import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { SummaryQA } from '../src/components/SummaryQA'
import { ApiError } from '../src/api/client'
const { get, ask } = vi.hoisted(() => ({ get: vi.fn(), ask: vi.fn() }))
vi.mock('@/api/summaryQA', () => ({ summaryQAApi: { get, ask } }))
const conversation = { id: 'c', summary_id: 's', mode: 'stateless', uses_source_articles: false, provider_session_supported: false, source_expires_at: '2026-01-01T00:00:00Z', sources_expired: true, source_count: 0, messages: [] }
function selectPassage() {
const range = document.createRange()
range.selectNodeContents(screen.getByText('Un passage de synthèse.'))
window.getSelection()!.removeAllRanges()
window.getSelection()!.addRange(range)
fireEvent(document, new Event('selectionchange'))
}
beforeEach(() => { vi.spyOn(window, 'scrollTo').mockImplementation(() => {}); get.mockResolvedValue(conversation); ask.mockResolvedValue({ id: 't', request_id: 'r', passage: 'Un passage de synthèse.', question: 'Pourquoi ?', answer: 'Une réponse.', status: 'answered', created_at: '', replayed: false }) })
afterEach(() => { cleanup(); window.getSelection()?.removeAllRanges(); vi.restoreAllMocks() })
it('préserve les événements natifs et le focus ; seule une action explicite ouvre la question', async () => {
render()
const text = screen.getByText('Un passage de synthèse.')
for (const type of ['contextmenu', 'selectstart', 'touchstart', 'copy']) expect(fireEvent(text, new Event(type, { bubbles: true, cancelable: true }))).toBe(true)
selectPassage()
expect(get).not.toHaveBeenCalled()
expect(screen.queryByRole('textbox')).not.toBeInTheDocument()
await userEvent.click(screen.getByRole('button', { name: 'Interroger ce passage' }))
const question = await screen.findByRole('textbox', { name: 'Votre question' })
expect(screen.getByRole('heading', { name: 'Questions sur cette synthèse' })).toHaveFocus()
expect(await screen.findByText(/Les sources ont expiré/)).toBeInTheDocument()
expect(screen.getByText(/sans articles sources ni session fournisseur réutilisée/)).toBeInTheDocument()
await userEvent.type(question, 'Pourquoi ?')
await userEvent.click(screen.getByRole('button', { name: 'Envoyer la question' }))
expect(await screen.findByText('Une réponse.')).toBeInTheDocument()
expect(ask).toHaveBeenCalledWith('s', expect.objectContaining({ passage: 'Un passage de synthèse.', question: 'Pourquoi ?', request_id: expect.stringMatching(/^[a-f0-9-]{36}$/) }))
})
it('reprend la conversation et efface les données temporaires au changement de synthèse', async () => {
get.mockResolvedValueOnce({ ...conversation, messages: [{ id: 'old', passage: 'Ancien extrait', question: 'Ancienne question', answer: 'Ancienne réponse', status: 'answered' }] })
const view = render()
selectPassage()
await userEvent.click(screen.getByRole('button', { name: 'Interroger ce passage' }))
expect(await screen.findByText('Ancienne réponse')).toBeInTheDocument()
await userEvent.type(screen.getByRole('textbox'), 'Brouillon')
view.rerender()
expect(screen.queryByText('Ancienne réponse')).not.toBeInTheDocument()
expect(screen.queryByRole('textbox')).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Interroger ce passage' })).not.toBeInTheDocument()
})
it('explique le modèle indisponible en conservant la question', async () => {
ask.mockRejectedValueOnce(new ApiError('qa_model_unavailable', 409))
render()
selectPassage()
await userEvent.click(screen.getByRole('button', { name: 'Interroger ce passage' }))
await userEvent.type(await screen.findByRole('textbox'), 'Pourquoi ?')
await userEvent.click(screen.getByRole('button', { name: 'Envoyer la question' }))
expect(await screen.findByRole('alert')).toHaveTextContent(/modèle.*indisponible/)
expect(screen.getByRole('textbox')).toHaveValue('Pourquoi ?')
})
it('réutilise le request_id après une erreur réseau', async () => {
ask.mockRejectedValueOnce(new Error('network'))
render()
selectPassage()
await userEvent.click(screen.getByRole('button', { name: 'Interroger ce passage' }))
await userEvent.type(await screen.findByRole('textbox'), 'Pourquoi ?')
await userEvent.click(screen.getByRole('button', { name: 'Envoyer la question' }))
await screen.findByRole('alert')
const first = ask.mock.calls.at(-1)![1]
await userEvent.click(screen.getByRole('button', { name: 'Envoyer la question' }))
await waitFor(() => expect(ask.mock.calls.at(-1)![1]).toEqual(first))
})
it('bloque un second envoi pendant la réponse et annonce sa réception', async () => {
let finish!: (value: unknown) => void
ask.mockImplementationOnce(() => new Promise(resolve => { finish = resolve }))
render()
selectPassage()
await userEvent.click(screen.getByRole('button', { name: 'Interroger ce passage' }))
await userEvent.type(await screen.findByRole('textbox'), 'Pourquoi ?')
await userEvent.click(screen.getByRole('button', { name: 'Envoyer la question' }))
expect(screen.getByRole('button', { name: 'Réponse en cours…' })).toBeDisabled()
expect(screen.getByRole('textbox')).toBeDisabled()
expect(ask).toHaveBeenCalledTimes(1)
finish({ id: 't', request_id: 'r', passage: 'Un passage de synthèse.', question: 'Pourquoi ?', answer: 'Réponse terminale', status: 'answered' })
expect(await screen.findByRole('log')).toHaveTextContent('Réponse terminale')
})
it('reprend un chargement échoué sans afficher de détails techniques', async () => {
get.mockRejectedValueOnce(new ApiError('PRIVATE_PROVIDER_SECRET', 503))
render()
selectPassage()
await userEvent.click(screen.getByRole('button', { name: 'Interroger ce passage' }))
expect(await screen.findByRole('alert')).not.toHaveTextContent('PRIVATE_PROVIDER_SECRET')
await userEvent.click(screen.getByRole('button', { name: 'Actualiser la conversation' }))
expect(await screen.findByRole('textbox', { name: 'Votre question' })).toBeInTheDocument()
})
it('ne propose pas l’action pour un passage hors limite', () => {
const content = 'a'.repeat(8001)
render()
const range = document.createRange()
range.selectNodeContents(screen.getByText(content))
window.getSelection()!.removeAllRanges()
window.getSelection()!.addRange(range)
fireEvent(document, new Event('selectionchange'))
expect(screen.queryByRole('button', { name: 'Interroger ce passage' })).not.toBeInTheDocument()
expect(get).not.toHaveBeenCalled()
})
it.each([45, undefined])('explique le quota Q&A avec délai %s et conserve la question', async seconds => {
ask.mockRejectedValueOnce(Object.assign(new ApiError('qa_rate_limited', 429), { retryAfterSeconds: seconds }))
render()
selectPassage()
await userEvent.click(screen.getByRole('button', { name: 'Interroger ce passage' }))
await userEvent.type(await screen.findByRole('textbox'), 'Pourquoi ?')
await userEvent.click(screen.getByRole('button', { name: 'Envoyer la question' }))
const alert = await screen.findByRole('alert')
expect(alert).toHaveTextContent('Trop de questions en peu de temps.')
expect(alert).toHaveTextContent(seconds === undefined ? 'Réessayez dans quelques instants.' : 'Réessayez dans 45 secondes.')
expect(screen.getByRole('textbox')).toHaveValue('Pourquoi ?')
})
it('affiche seulement le bouton fixe après sélection valide et la mémorise au scroll/collapse', () => {
render()
expect(screen.queryByRole('button', { name: 'Interroger ce passage' })).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Questions sur cette synthèse' })).not.toBeInTheDocument()
selectPassage()
const action = screen.getByRole('button', { name: 'Interroger ce passage' })
expect(action).toHaveClass('fixed')
window.getSelection()?.removeAllRanges()
fireEvent(document, new Event('selectionchange'))
fireEvent.scroll(window)
expect(action).toBeVisible()
expect(get).not.toHaveBeenCalled()
})
it('ouvre une modale accessible, conserve le brouillon et restaure le focus après Échap', async () => {
render()
selectPassage()
const action = screen.getByRole('button', { name: 'Interroger ce passage' })
await userEvent.click(action)
expect(await screen.findByRole('dialog', { name: 'Questions sur cette synthèse' })).toBeInTheDocument()
await userEvent.type(await screen.findByRole('textbox'), 'Brouillon conservé')
await userEvent.keyboard('{Escape}')
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
expect(action).toHaveFocus()
await userEvent.click(action)
expect(await screen.findByRole('textbox')).toHaveValue('Brouillon conservé')
expect(get).toHaveBeenCalledTimes(1)
})
it('croppe visuellement le passage mais transmet son intégralité', async () => {
const content = Array.from({ length: 6 }, (_, i) => `Ligne ${i + 1} du passage.`).join('\n')
render()
const range = document.createRange()
range.setStart(screen.getByText('Ligne 1 du passage.').firstChild!, 0)
range.setEndAfter(screen.getByText('Ligne 6 du passage.'))
window.getSelection()!.removeAllRanges()
window.getSelection()!.addRange(range)
fireEvent(document, new Event('selectionchange'))
const fullPassage = window.getSelection()!.toString()
await userEvent.click(screen.getByRole('button', { name: 'Interroger ce passage' }))
const preview = await screen.findByLabelText('Passage sélectionné')
expect(preview).toHaveClass('line-clamp-3')
expect(preview.textContent).toBe(fullPassage)
await userEvent.click(screen.getByRole('button', { name: 'Développer le passage' }))
expect(preview).not.toHaveClass('line-clamp-3')
await userEvent.type(screen.getByRole('textbox'), 'Pourquoi ?')
await userEvent.click(screen.getByRole('button', { name: 'Envoyer la question' }))
expect(ask).toHaveBeenCalledWith('s', expect.objectContaining({ passage: fullPassage }))
})
it('garde la requête et son request_id lors de fermeture puis reprise après erreur réseau', async () => {
let fail!: (error: Error) => void
ask.mockImplementationOnce(() => new Promise((_, reject) => { fail = reject }))
render()
selectPassage()
await userEvent.click(screen.getByRole('button', { name: 'Interroger ce passage' }))
await userEvent.type(await screen.findByRole('textbox'), 'Pourquoi ?')
await userEvent.click(screen.getByRole('button', { name: 'Envoyer la question' }))
const first = ask.mock.calls.at(-1)![1]
await userEvent.keyboard('{Escape}')
await userEvent.click(screen.getByRole('button', { name: 'Interroger ce passage' }))
expect(screen.getByRole('button', { name: 'Réponse en cours…' })).toBeDisabled()
expect(ask).toHaveBeenCalledTimes(1)
fail(new Error('network'))
await screen.findByRole('alert')
await userEvent.click(screen.getByRole('button', { name: 'Envoyer la question' }))
expect(ask.mock.calls.at(-1)![1]).toEqual(first)
})