feat(ui): open synthesis Q&A from selected passage (#56)

This commit is contained in:
2026-11-25 21:57:19 +01:00
parent 287811184f
commit adf0ee2647
3 changed files with 161 additions and 52 deletions

View File

@ -1,14 +1,15 @@
import { expect, test } from '@playwright/test'
import { readStackManifest } from './stack-manifest.mjs'
for (const width of [1280, 375]) test(`ticket #54: passage and Q&A remain accessible at ${width}px`, async ({ page }) => {
for (const width of [1280, 375]) test(`ticket #56: fixed selection action and modal Q&A remain accessible at ${width}px`, async ({ page }) => {
const stack = readStackManifest()
await page.setViewportSize({ width, height: 850 })
await page.context().route('**/*', route => {
const host = new URL(route.request().url()).hostname
return host === '127.0.0.1' || host === '[::1]' ? route.continue() : route.abort('blockedbyclient')
})
const summary = { id: '00000000-0000-0000-0000-000000005401', user_id: 'reader', content: 'Passage de la synthèse pour poser une question.', ai_provider_id: null, generated_at: '2026-11-25T00:00:00Z' }
const excerpt = 'Passage de la synthèse pour poser une question. '.repeat(12).trim()
const summary = { id: '00000000-0000-0000-0000-000000005401', user_id: 'reader', content: excerpt + '\n\n' + Array.from({ length: 30 }, (_, i) => `Contexte ${i}. ` + 'Texte de contexte. '.repeat(20)).join('\n'), ai_provider_id: null, generated_at: '2026-11-25T00:00:00Z' }
const conversation = { id: 'c', summary_id: summary.id, 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: [] }
const questions = []
await page.route('**/api/**', async route => {
@ -31,8 +32,10 @@ for (const width of [1280, 375]) test(`ticket #54: passage and Q&A remain access
await page.getByLabel('Adresse email').fill(stack.bootstrapAdmin.email)
await page.getByLabel('Mot de passe').fill(stack.bootstrapAdmin.password)
await page.getByRole('button', { name: 'Se connecter' }).click()
const passage = page.getByText(summary.content, { exact: true })
const passage = page.getByText(excerpt, { exact: true })
await expect(passage).toBeVisible()
await expect(page.getByRole('button', { name: 'Interroger ce passage' })).toHaveCount(0)
await expect(page.getByRole('button', { name: 'Questions sur cette synthèse' })).toHaveCount(0)
await passage.evaluate(element => {
for (const name of ['contextmenu', 'selectstart', 'copy', 'touchstart']) {
if (!element.dispatchEvent(new Event(name, { bubbles: true, cancelable: true }))) throw new Error(`${name} blocked`)
@ -46,18 +49,45 @@ for (const width of [1280, 375]) test(`ticket #54: passage and Q&A remain access
document.dispatchEvent(new Event('selectionchange'))
})
await expect(page.getByRole('textbox', { name: 'Votre question' })).toHaveCount(0)
await page.getByRole('button', { name: 'Interroger ce passage' }).click()
const action = page.getByRole('button', { name: 'Interroger ce passage' })
await expect(action).toBeVisible()
const initialBox = await action.boundingBox()
await page.evaluate(() => { window.getSelection().removeAllRanges(); document.querySelector('main').scrollTop = 1100 })
await expect(action).toBeVisible()
expect((await action.boundingBox()).y).toBe(initialBox.y)
const beforeScroll = await page.locator('main').evaluate(element => element.scrollTop)
await action.click()
const dialog = page.getByRole('dialog', { name: 'Questions sur cette synthèse' })
await expect(dialog).toBeVisible()
await expect(dialog.getByRole('heading', { name: 'Questions sur cette synthèse' })).toBeFocused()
await expect(page.getByLabel('Passage sélectionné')).toHaveCSS('-webkit-line-clamp', '3')
await expect(page.getByLabel('Passage sélectionné')).toHaveText(excerpt)
const question = page.getByRole('textbox', { name: 'Votre question' })
await expect(question).toBeFocused()
await expect(page.getByText(/Les sources ont expiré/)).toBeVisible()
await question.fill('Que signifie ce passage ?')
await page.keyboard.press('Escape')
await expect(dialog).toHaveCount(0)
await expect(action).toBeFocused()
expect(await page.locator('main').evaluate(element => element.scrollTop)).toBe(beforeScroll)
await action.click()
await expect(question).toHaveValue('Que signifie ce passage ?')
// Keyboard navigation stays inside the modal, including after a smaller viewport.
await page.setViewportSize({ width, height: 450 })
const box = await dialog.boundingBox()
expect(box.y).toBeGreaterThanOrEqual(0)
expect(box.y + box.height).toBeLessThanOrEqual(450)
for (let i = 0; i < 10; i++) {
await page.keyboard.press('Tab')
expect(await dialog.evaluate(element => element.contains(document.activeElement))).toBe(true)
}
await page.getByRole('button', { name: 'Envoyer la question' }).click()
await expect(page.getByText('Réponse sur cette synthèse.', { exact: true })).toBeVisible()
expect(questions).toHaveLength(1)
expect(questions[0]).toMatchObject({ passage: summary.content, question: 'Que signifie ce passage ?', request_id: expect.stringMatching(/^[a-f0-9-]{36}$/) })
expect(questions[0]).toMatchObject({ passage: excerpt, question: 'Que signifie ce passage ?', request_id: expect.stringMatching(/^[a-f0-9-]{36}$/) })
expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true)
await page.getByRole('button', { name: 'Retour à la synthèse' }).click()
await page.getByRole('button', { name: 'Fermer', exact: true }).click()
await expect(page.getByRole('button', { name: 'Interroger ce passage' })).toBeFocused()
await page.getByRole('button', { name: 'Questions sur cette synthèse' }).click()
await page.getByRole('button', { name: 'Interroger ce passage' }).click()
await expect(page.getByText('Réponse sur cette synthèse.', { exact: true })).toBeVisible()
})

View File

@ -1,3 +1,4 @@
import * as Dialog from '@radix-ui/react-dialog'
import { useEffect, useId, useRef, useState, type FormEvent } from 'react'
import { summaryQAApi, type QAConversation, type QAQuestion } from '@/api/summaryQA'
import { ApiError } from '@/api/client'
@ -33,14 +34,15 @@ export function SummaryQA(props: { summaryId: string; content: string }) {
function Conversation({ summaryId, content }: { summaryId: string; content: string }) {
const id = useId()
const text = useRef<HTMLDivElement>(null)
const input = useRef<HTMLTextAreaElement>(null)
const title = useRef<HTMLHeadingElement>(null)
const returnButton = useRef<HTMLButtonElement>(null)
const position = useRef(0)
const position = useRef<{ target: HTMLElement | null; top: number; left: number }>({ target: null, top: 0, left: 0 })
const alive = useRef(true)
const pending = useRef(false)
const request = useRef<QAQuestion | null>(null)
const [selection, setSelection] = useState('')
const [passage, setPassage] = useState('')
const [expanded, setExpanded] = useState(false)
const [question, setQuestion] = useState('')
const [open, setOpen] = useState(false)
const [conversation, setConversation] = useState<QAConversation | null>(null)
@ -56,8 +58,9 @@ function Conversation({ summaryId, content }: { summaryId: string; content: stri
const selected = window.getSelection()
if (!selected || selected.isCollapsed) return
if (text.current?.contains(selected.anchorNode) && text.current.contains(selected.focusNode)) {
setSelection(selected.toString())
} else setSelection('')
const value = selected.toString()
if (value.trim() && [...value].length <= 8000 && !value.includes('\0')) setSelection(value)
}
}
document.addEventListener('selectionchange', observe)
return () => { alive.current = false; document.removeEventListener('selectionchange', observe) }
@ -78,8 +81,6 @@ function Conversation({ summaryId, content }: { summaryId: string; content: stri
// Refresh persisted pending turns without issuing another question.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open, conversation, sending])
const loaded = !!conversation
useEffect(() => { if (open && passage && loaded) input.current?.focus() }, [open, passage, loaded])
useEffect(() => {
if (!conversation || conversation.sources_expired || deadlinePassed) return
let timer: ReturnType<typeof setTimeout>
@ -92,16 +93,15 @@ function Conversation({ summaryId, content }: { summaryId: string; content: stri
return () => clearTimeout(timer)
}, [conversation, deadlinePassed])
function show(withSelection: boolean) {
position.current = window.scrollY
if (withSelection) { setPassage(selection); setValidation('') }
setOpen(true)
if (!conversation) void load()
}
function close() {
setOpen(false)
returnButton.current?.focus({ preventScroll: true })
window.scrollTo({ top: position.current, behavior: 'instant' })
function changeOpen(value: boolean) {
if (value) {
let target = text.current?.parentElement ?? null
while (target && !/(auto|scroll)/.test(getComputedStyle(target).overflowY)) target = target.parentElement
position.current = { target, top: target?.scrollTop ?? window.scrollY, left: target?.scrollLeft ?? window.scrollX }
if (selection !== passage) { setPassage(selection); setExpanded(false); setValidation('') }
if (!conversation && !loading) void load()
}
setOpen(value)
}
async function ask(event: FormEvent) {
event.preventDefault()
@ -132,18 +132,35 @@ function Conversation({ summaryId, content }: { summaryId: string; content: stri
return <div className="space-y-4 min-w-0">
<div ref={text} className="select-text"><Markdown content={content} /></div>
<p className="text-sm text-muted-foreground">Sélectionnez un passage normalement, puis utilisez « Interroger ce passage ». Les commandes du navigateur restent disponibles.</p>
<div className="flex flex-wrap gap-3">
<Button ref={returnButton} type="button" disabled={!selection.trim() || sending} onClick={() => show(true)} aria-controls={`${id}-panel`} aria-expanded={open}>Interroger ce passage</Button>
<Button type="button" variant="outline" onClick={() => show(false)} aria-controls={`${id}-panel`} aria-expanded={open}>Questions sur cette synthèse</Button>
</div>
{open && <section id={`${id}-panel`} aria-labelledby={`${id}-title`} className="space-y-4 border-t pt-4 min-w-0 break-words">
<div className="flex flex-wrap justify-between gap-3 items-center">
<h2 id={`${id}-title`} className="font-semibold">Questions sur cette synthèse</h2>
<Button type="button" variant="outline" onClick={close}>Retour à la synthèse</Button>
</div>
<Dialog.Root open={open} onOpenChange={changeOpen}>
{selection && <Dialog.Trigger asChild>
<Button ref={returnButton} type="button" className="fixed z-40 min-h-11 max-w-[calc(100vw-2rem)] top-[calc(env(safe-area-inset-top,0px)+1rem)] right-[calc(env(safe-area-inset-right,0px)+1rem)] shadow-lg">Interroger ce passage</Button>
</Dialog.Trigger>}
<Dialog.Portal>
<Dialog.Overlay className="fixed inset-0 z-[60] bg-black/50" />
<Dialog.Content
className="fixed z-[70] left-1/2 top-[calc((100dvh+env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px))/2)] -translate-x-1/2 -translate-y-1/2 w-[calc(100vw-2rem-env(safe-area-inset-left,0px)-env(safe-area-inset-right,0px))] max-w-2xl max-h-[calc(100dvh-2rem-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px))] overflow-y-auto overscroll-contain rounded-lg border bg-background p-4 sm:p-6 shadow-xl space-y-4 min-w-0 break-words"
onOpenAutoFocus={event => { event.preventDefault(); title.current?.focus({ preventScroll: true }) }}
onCloseAutoFocus={event => {
event.preventDefault()
returnButton.current?.focus({ preventScroll: true })
const { target, top, left } = position.current
if (target?.isConnected) target.scrollTo({ top, left, behavior: 'instant' })
else window.scrollTo({ top, left, behavior: 'instant' })
}}>
<div className="flex items-start justify-between gap-3">
<Dialog.Title ref={title} tabIndex={-1} className="font-semibold focus:outline-none">Questions sur cette synthèse</Dialog.Title>
<Dialog.Close asChild><Button type="button" variant="outline" className="min-h-11 shrink-0">Fermer</Button></Dialog.Close>
</div>
<Dialog.Description className="text-sm text-muted-foreground">Posez une question sur le passage sélectionné. Fermer cette fenêtre conserve votre brouillon et la réponse en cours.</Dialog.Description>
<div>
<p className="text-sm font-medium">Passage à interroger</p>
<blockquote id={`${id}-passage`} aria-label="Passage sélectionné" className={`whitespace-pre-wrap border-l-2 pl-3 ${expanded ? '' : 'line-clamp-3'}`}>{passage}</blockquote>
<Button type="button" variant="outline" className="min-h-11 mt-2" aria-expanded={expanded} aria-controls={`${id}-passage`} onClick={() => setExpanded(value => !value)}>{expanded ? 'Réduire le passage' : 'Développer le passage'}</Button>
</div>
{loading && <p role="status">Chargement de la conversation…</p>}
{error && <p role="alert">{error}</p>}
<Button type="button" variant="outline" onClick={() => void load()} disabled={loading || sending}>Actualiser la conversation</Button>
<Button type="button" variant="outline" className="min-h-11" onClick={() => void load()} disabled={loading || sending}>Actualiser la conversation</Button>
{conversation && <>
<p className="text-sm text-muted-foreground">Les réponses utilisent la synthèse et les échanges précédents, sans articles sources ni session fournisseur réutilisée. Aucune économie de tokens n’est garantie.</p>
{expired ? <p role="status">Les sources ont expiré. La conversation et les questions restent disponibles avec la synthèse et les échanges uniquement.</p> : <p>Expiration des sources : {new Date(conversation.source_expires_at).toLocaleString('fr-FR')}. Poser une question ne prolonge pas cette durée.</p>}
@ -158,14 +175,15 @@ function Conversation({ summaryId, content }: { summaryId: string; content: stri
</article>)}
</div>
<form onSubmit={ask} className="space-y-3" aria-label="Poser une question" aria-busy={sending}>
{passage ? <div><p className="text-sm font-medium">Passage à interroger</p><blockquote className="whitespace-pre-wrap border-l-2 pl-3 max-h-48 overflow-auto">{passage}</blockquote></div> : <p>Sélectionnez un passage dans la synthèse et utilisez « Interroger ce passage » pour poser une question.</p>}
<Label htmlFor={`${id}-question`}>Votre question</Label>
<textarea ref={input} id={`${id}-question`} className="w-full min-h-28 rounded-md border bg-transparent p-3 text-base" value={question} disabled={sending} aria-invalid={!!validation} aria-describedby={`${id}-help${validation ? ` ${id}-error` : ''}`} onChange={event => { setQuestion(event.target.value); setValidation('') }} />
<textarea id={`${id}-question`} className="w-full min-h-28 rounded-md border bg-transparent p-3 text-base" value={question} disabled={sending} aria-invalid={!!validation} aria-describedby={`${id}-help${validation ? ` ${id}-error` : ''}`} onChange={event => { setQuestion(event.target.value); setValidation('') }} />
<p id={`${id}-help`} className="text-sm text-muted-foreground">4 000 caractères maximum par question ; 8 000 par passage.</p>
{validation && <p id={`${id}-error`} role="alert">{validation}</p>}
<Button type="submit" disabled={sending || !!busy || !passage.trim()}>{sending ? 'Réponse en cours…' : 'Envoyer la question'}</Button>
<Button type="submit" className="min-h-11" disabled={sending || !!busy || !passage.trim()}>{sending ? 'Réponse en cours…' : 'Envoyer la question'}</Button>
</form>
</>}
</section>}
</Dialog.Content>
</Dialog.Portal>
</Dialog.Root>
</div>
}

View File

@ -13,8 +13,8 @@ function selectPassage() {
window.getSelection()!.addRange(range)
fireEvent(document, new Event('selectionchange'))
}
beforeEach(() => { 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() })
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(<SummaryQA summaryId="s" content="Un passage de synthèse." />)
const text = screen.getByText('Un passage de synthèse.')
@ -24,7 +24,7 @@ it('préserve les événements natifs et le focus ; seule une action explicite o
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(question).toHaveFocus()
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 ?')
@ -35,15 +35,14 @@ it('préserve les événements natifs et le focus ; seule une action explicite o
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(<SummaryQA summaryId="s" content="Un passage de synthèse." />)
await userEvent.click(screen.getByRole('button', { name: 'Questions sur cette synthèse' }))
expect(await screen.findByText('Ancienne réponse')).toBeInTheDocument()
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(<SummaryQA summaryId="other" content="Autre synthèse" />)
expect(screen.queryByText('Ancienne réponse')).not.toBeInTheDocument()
expect(screen.queryByRole('textbox')).not.toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Interroger ce passage' })).toBeDisabled()
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))
@ -84,12 +83,13 @@ it('bloque un second envoi pendant la réponse et annonce sa réception', async
it('reprend un chargement échoué sans afficher de détails techniques', async () => {
get.mockRejectedValueOnce(new ApiError('PRIVATE_PROVIDER_SECRET', 503))
render(<SummaryQA summaryId="s" content="Un passage de synthèse." />)
await userEvent.click(screen.getByRole('button', { name: 'Questions sur cette synthèse' }))
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('refuse les passages trop longs et les questions vides avant appel', async () => {
it('ne propose pas l’action pour un passage hors limite', () => {
const content = 'a'.repeat(8001)
render(<SummaryQA summaryId="s" content={content} />)
const range = document.createRange()
@ -97,12 +97,8 @@ it('refuse les passages trop longs et les questions vides avant appel', async ()
window.getSelection()!.removeAllRanges()
window.getSelection()!.addRange(range)
fireEvent(document, new Event('selectionchange'))
await userEvent.click(screen.getByRole('button', { name: 'Interroger ce passage' }))
await screen.findByRole('textbox')
await userEvent.click(screen.getByRole('button', { name: 'Envoyer la question' }))
expect(screen.getByRole('textbox')).toHaveAttribute('aria-invalid', 'true')
expect(screen.getByRole('alert')).toHaveTextContent('8 000')
expect(ask).not.toHaveBeenCalled()
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 }))
@ -116,3 +112,68 @@ it.each([45, undefined])('explique le quota Q&A avec délai %s et conserve la qu
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(<SummaryQA summaryId="s" content="Un passage de synthèse." />)
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(<SummaryQA summaryId="s" content="Un passage de synthèse." />)
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(<SummaryQA summaryId="s" content={content} />)
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(<SummaryQA summaryId="s" content="Un passage de synthèse." />)
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)
})