feat(ui): turn synthesis Q&A into persistent chat (#64)

This commit is contained in:
2026-11-26 14:56:13 +01:00
parent 0a19d1c617
commit f75de489cc
9 changed files with 458 additions and 131 deletions

View File

@ -1,7 +1,7 @@
import { expect, test } from '@playwright/test' import { expect, test } from '@playwright/test'
import { readStackManifest } from './stack-manifest.mjs' import { readStackManifest } from './stack-manifest.mjs'
for (const width of [1280, 375]) test(`ticket #61: web search choice and citations remain accessible at ${width}px`, async ({ page }) => { for (const width of [1280, 375]) test(`ticket #64: synthesis chat, attachments and web citations at ${width}px`, async ({ page }) => {
const stack = readStackManifest() const stack = readStackManifest()
await page.setViewportSize({ width, height: 850 }) await page.setViewportSize({ width, height: 850 })
await page.context().route('**/*', route => { await page.context().route('**/*', route => {
@ -9,22 +9,26 @@ for (const width of [1280, 375]) test(`ticket #61: web search choice and citatio
return host === '127.0.0.1' || host === '[::1]' ? route.continue() : route.abort('blockedbyclient') return host === '127.0.0.1' || host === '[::1]' ? route.continue() : route.abort('blockedbyclient')
}) })
const excerpt = 'Passage de la synthèse pour poser une question. '.repeat(12).trim() 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 secondExcerpt = 'Autre passage à joindre explicitement.'
const conversation = { id: 'c', web_search_supported: true, 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 summary = { id: '00000000-0000-0000-0000-000000005401', user_id: 'reader', content: excerpt + '\n\n' + secondExcerpt + '\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 other = { ...summary, id: '00000000-0000-0000-0000-000000005402', content: 'Autre synthèse de test.' }
const conversations = new Map([summary, other].map(item => [item.id, { id: `c-${item.id}`, web_search_supported: true, summary_id: item.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 = [] const questions = []
await page.route('**/api/**', async route => { await page.route('**/api/**', async route => {
const path = new URL(route.request().url()).pathname const path = new URL(route.request().url()).pathname
const respond = data => route.fulfill({ json: { data } }) const respond = data => route.fulfill({ json: { data } })
if (path === '/api/summaries') return respond([summary]) if (path === '/api/summaries') return respond([summary, other])
if (path === '/api/summaries/generations' || path === '/api/me/assets') return respond([]) if (path === '/api/summaries/generations' || path === '/api/me/assets') return respond([])
if (path === '/api/summaries/generation-jobs/recent') return respond(null) if (path === '/api/summaries/generation-jobs/recent') return respond(null)
if (path === `/api/summaries/${summary.id}/conversation`) return respond(conversation) for (const [id, conversation] of conversations) {
if (path === `/api/summaries/${summary.id}/conversation/messages`) { if (path === `/api/summaries/${id}/conversation`) return respond(conversation)
const question = route.request().postDataJSON() if (path === `/api/summaries/${id}/conversation/messages`) {
questions.push(question) const question = route.request().postDataJSON()
const turn = { ...question, id: `t-${questions.length}`, web_search_performed: question.use_web_search, citations: question.use_web_search ? [{ title: 'Source de test', url: 'https://example.test/source' }] : [], answer: question.use_web_search ? 'Réponse avec recherche simulée.' : 'Réponse sur cette synthèse.', status: 'answered', replayed: false, created_at: '2026-11-25T00:00:00Z' } questions.push(question)
conversation.messages.push(turn) const turn = { ...question, id: `t-${questions.length}`, web_search_performed: question.use_web_search, citations: question.use_web_search ? [{ title: 'Source de test', url: 'https://example.test/source' }] : [], answer: question.use_web_search ? 'Réponse avec recherche simulée.' : 'Réponse globale sur cette synthèse.', status: 'answered', replayed: false, created_at: '2026-11-25T00:00:00Z' }
return respond(turn) conversation.messages.push(turn)
return respond(turn)
}
} }
return route.continue() return route.continue()
}) })
@ -34,50 +38,67 @@ for (const width of [1280, 375]) test(`ticket #61: web search choice and citatio
await page.getByRole('button', { name: 'Se connecter' }).click() await page.getByRole('button', { name: 'Se connecter' }).click()
const passage = page.getByText(excerpt, { exact: true }) const passage = page.getByText(excerpt, { exact: true })
await expect(passage).toBeVisible() await expect(passage).toBeVisible()
await expect(page.getByRole('button', { name: 'Interroger ce passage' })).toHaveCount(0) const action = page.getByRole('button', { name: 'Ouvrir le chat de cette synthèse' })
await expect(page.getByRole('button', { name: 'Questions sur cette synthèse' })).toHaveCount(0) const generate = page.getByRole('button', { name: 'Générer une synthèse' })
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`)
}
if (getComputedStyle(element).userSelect === 'none') throw new Error('selection disabled')
const range = document.createRange()
range.selectNodeContents(element)
const selection = window.getSelection()
selection.removeAllRanges()
selection.addRange(range)
document.dispatchEvent(new Event('selectionchange'))
})
await expect(page.getByRole('textbox', { name: 'Votre question' })).toHaveCount(0)
const action = page.getByRole('button', { name: 'Interroger ce passage' })
await expect(action).toBeVisible() await expect(action).toBeVisible()
const initialBox = await action.boundingBox() await expect(action).toHaveAttribute('title', 'Ouvrir le chat de cette synthèse')
await page.evaluate(() => { window.getSelection().removeAllRanges(); document.querySelector('main').scrollTop = 1100 }) expect(await action.evaluate(element => element.parentElement.nextElementSibling === [...element.parentElement.parentElement.querySelectorAll('button')].find(button => button.textContent.includes('Générer')))).toBe(true)
await expect(action).toBeVisible() const actionBox = await action.boundingBox()
expect((await action.boundingBox()).y).toBe(initialBox.y) const generateBox = await generate.boundingBox()
const beforeScroll = await page.locator('main').evaluate(element => element.scrollTop) expect(actionBox.y + actionBox.height).toBeLessThanOrEqual(generateBox.y)
expect(await action.evaluate(element => getComputedStyle(element).position)).not.toBe('fixed')
// Global question is possible without selecting or attaching any text.
await action.click() await action.click()
const dialog = page.getByRole('dialog', { name: 'Questions sur cette synthèse' }) const dialog = page.getByRole('dialog', { name: 'Questions sur cette synthèse' })
await expect(dialog).toBeVisible() const question = dialog.getByRole('textbox', { name: 'Votre question' })
await expect(dialog.getByRole('heading', { name: 'Questions sur cette synthèse' })).toBeFocused() const webSearch = dialog.getByRole('checkbox', { name: 'Utiliser la recherche Web si nécessaire pour répondre ; la synthèse complète, les échanges précédents, votre question et tout passage joint seront transmis au fournisseur du modèle sélectionné.' })
await expect(page.getByLabel('Passage sélectionné')).toHaveCSS('-webkit-line-clamp', '3') const add = dialog.getByRole('button', { name: 'Ajouter le passage sélectionné à la question' })
await expect(page.getByLabel('Passage sélectionné')).toHaveText(excerpt) await expect(dialog.getByRole('heading')).toBeFocused()
const question = page.getByRole('textbox', { name: 'Votre question' }) await expect(question).toHaveValue('')
await expect(add).toHaveCount(0)
await expect(dialog.getByText(/Les sources ont expiré|Expiration des sources|Posez une question sur le passage sélectionné|sans articles sources ni session fournisseur/)).toHaveCount(0) expect(questions).toHaveLength(0)
await expect(dialog.getByRole('button', { name: /Actualiser|Développer|Réduire/ })).toHaveCount(0)
const webSearch = dialog.getByRole('checkbox', { name: 'Utiliser la recherche Web si nécessaire pour répondre, en transmettant au fournisseur de recherche les termes et éléments de contexte utiles.' })
await expect(webSearch).toBeChecked() await expect(webSearch).toBeChecked()
await webSearch.uncheck() await webSearch.uncheck()
await question.fill('Que signifie cette synthèse ?')
await dialog.getByRole('button', { name: 'Envoyer la question' }).click()
await expect(dialog.getByText('Réponse globale sur cette synthèse.', { exact: true })).toBeVisible()
expect(questions[0]).toMatchObject({ passage: '', question: 'Que signifie cette synthèse ?', use_web_search: false })
await expect(dialog.getByRole('link')).toHaveCount(0)
await expect(webSearch).toBeChecked()
await expect(question).toHaveValue('')
await page.keyboard.press('Escape')
await expect(action).toBeFocused()
async function selectText(element) {
await element.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`)
}
if (getComputedStyle(element).userSelect === 'none') throw new Error('selection disabled')
const range = document.createRange(); range.selectNodeContents(element)
const selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(range)
document.dispatchEvent(new Event('selectionchange'))
})
}
await selectText(passage)
await action.click()
await expect(dialog.getByLabel('Passage joint', { exact: true })).toHaveCount(0)
await add.click()
await expect(dialog.getByLabel('Passage joint', { exact: true })).toHaveText(excerpt)
await expect(dialog.getByLabel('Passage joint', { exact: true })).toHaveCSS('-webkit-line-clamp', '3')
await question.fill('Que signifie ce passage ?') await question.fill('Que signifie ce passage ?')
await page.keyboard.press('Escape') await page.keyboard.press('Escape')
await expect(dialog).toHaveCount(0) await selectText(page.getByText(secondExcerpt, { exact: true }))
await expect(action).toBeFocused()
expect(await page.locator('main').evaluate(element => element.scrollTop)).toBe(beforeScroll)
await action.click() await action.click()
await expect(question).toHaveValue('Que signifie ce passage ?') await expect(question).toHaveValue('Que signifie ce passage ?')
await expect(webSearch).not.toBeChecked() await expect(dialog.getByLabel('Passage joint', { exact: true })).toHaveText(excerpt)
// Keyboard navigation stays inside the modal, including after a smaller viewport. await add.click()
await expect(dialog.getByLabel('Passage joint', { exact: true })).toHaveText(secondExcerpt)
await dialog.getByRole('button', { name: 'Retirer le passage joint' }).click()
await expect(dialog.getByLabel('Passage joint', { exact: true })).toHaveCount(0)
await add.click()
await page.setViewportSize({ width, height: 450 }) await page.setViewportSize({ width, height: 450 })
const box = await dialog.boundingBox() const box = await dialog.boundingBox()
expect(box.y).toBeGreaterThanOrEqual(0) expect(box.y).toBeGreaterThanOrEqual(0)
@ -86,27 +107,50 @@ for (const width of [1280, 375]) test(`ticket #61: web search choice and citatio
await page.keyboard.press('Tab') await page.keyboard.press('Tab')
expect(await dialog.evaluate(element => element.contains(document.activeElement))).toBe(true) expect(await dialog.evaluate(element => element.contains(document.activeElement))).toBe(true)
} }
await page.getByRole('button', { name: 'Envoyer la question' }).click() await dialog.getByRole('button', { name: 'Envoyer la question' }).click()
await expect(page.getByText('Réponse sur cette synthèse.', { exact: true })).toBeVisible() await expect(dialog.getByText('Réponse avec recherche simulée.', { exact: true })).toBeVisible()
expect(questions).toHaveLength(1)
expect(questions[0]).toMatchObject({ passage: excerpt, question: 'Que signifie ce passage ?', use_web_search: false, request_id: expect.stringMatching(/^[a-f0-9-]{36}$/) })
await expect(dialog.getByRole('link')).toHaveCount(0)
await expect(dialog.getByRole('list', { name: 'Sources de la réponse' })).toHaveCount(0)
await expect(webSearch).toBeChecked()
await expect(question).toHaveValue('')
await question.fill('Quels éléments récents ?')
await page.getByRole('button', { name: 'Envoyer la question' }).click()
await expect(page.getByText('Réponse avec recherche simulée.', { exact: true })).toBeVisible()
expect(questions).toHaveLength(2) expect(questions).toHaveLength(2)
expect(questions[1].use_web_search).toBe(true) expect(questions[1]).toMatchObject({ passage: secondExcerpt, question: 'Que signifie ce passage ?', use_web_search: true })
expect(questions[1].request_id).not.toBe(questions[0].request_id) expect(questions[1].request_id).not.toBe(questions[0].request_id)
const source = dialog.getByRole('link', { name: 'Source de test (nouvel onglet)' }) await expect(dialog.getByRole('article', { name: 'Vous', exact: true }).first()).toHaveCSS('align-self', 'flex-end')
const assistant = dialog.getByRole('article', { name: 'Assistant', exact: true }).last()
await expect(assistant).toHaveCSS('align-self', 'flex-start')
const source = assistant.getByRole('link', { name: 'Source de test (nouvel onglet)' })
await expect(source).toHaveAttribute('href', 'https://example.test/source') await expect(source).toHaveAttribute('href', 'https://example.test/source')
await expect(source).toHaveAttribute('target', '_blank') await expect(source).toHaveAttribute('target', '_blank')
await expect(source).toHaveAttribute('rel', 'noopener noreferrer') await expect(source).toHaveAttribute('rel', 'noopener noreferrer')
await expect(question).toHaveValue('')
await expect(dialog.getByLabel('Passage joint', { exact: true })).toHaveCount(0)
expect(await dialog.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true)
expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true) expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true)
await page.getByRole('button', { name: 'Fermer', exact: true }).click() await add.click()
await expect(page.getByRole('button', { name: 'Interroger ce passage' })).toBeFocused() await question.fill('Brouillon non envoyé')
await page.getByRole('button', { name: 'Interroger ce passage' }).click() await webSearch.uncheck()
await expect(page.getByText('Réponse sur cette synthèse.', { exact: true })).toBeVisible() await page.keyboard.press('Escape')
await expect(action).toBeFocused()
await action.click()
await expect(question).toHaveValue('Brouillon non envoyé')
await expect(webSearch).not.toBeChecked()
await page.keyboard.press('Escape')
await page.getByRole('button', { name: 'Autre synthèse de test.…' }).click()
await action.click()
await expect(question).toHaveValue('')
await expect(webSearch).toBeChecked()
await expect(dialog.getByText('Aucune question pour cette synthèse.')).toBeVisible()
await expect(dialog.getByText('Réponse globale sur cette synthèse.', { exact: true })).toHaveCount(0)
await question.fill('Brouillon autre synthèse')
await page.keyboard.press('Escape')
await page.getByRole('button', { name: summary.content.slice(0, 120) + '…', exact: true }).click()
await action.click()
await expect(question).toHaveValue('Brouillon non envoyé')
await expect(dialog.getByLabel('Passage joint', { exact: true })).toHaveText(secondExcerpt)
await expect(webSearch).not.toBeChecked()
await expect(dialog.getByText('Réponse globale sur cette synthèse.', { exact: true })).toBeVisible()
await page.keyboard.press('Escape')
await page.getByRole('button', { name: 'Autre synthèse de test.…' }).click()
await action.click()
await expect(question).toHaveValue('Brouillon autre synthèse')
await expect(webSearch).toBeChecked()
await expect(dialog.getByLabel('Passage joint', { exact: true })).toHaveCount(0)
await expect(dialog.getByText('Aucune question pour cette synthèse.')).toBeVisible()
}) })

View File

@ -1,6 +1,12 @@
import { api } from './client' import { api } from './client'
export interface QAQuestion { request_id: string; passage: string; question: string; use_web_search: boolean } export interface QAQuestion {
request_id: string
// Empty passage asks about the whole summary; attachments remain separate from the question.
passage: string
question: string
use_web_search: boolean
}
export interface QATurn extends QAQuestion { export interface QATurn extends QAQuestion {
id: string id: string
web_search_performed: boolean web_search_performed: boolean

View File

@ -1,4 +1,6 @@
import * as Dialog from '@radix-ui/react-dialog' import * as Dialog from '@radix-ui/react-dialog'
import { createPortal } from 'react-dom'
import { MessageCircleQuestion, Plus } from 'lucide-react'
import { useEffect, useId, useRef, useState, type FormEvent } from 'react' import { useEffect, useId, useRef, useState, type FormEvent } from 'react'
import { summaryQAApi, type QAConversation, type QAQuestion, type QATurn } from '@/api/summaryQA' import { summaryQAApi, type QAConversation, type QAQuestion, type QATurn } from '@/api/summaryQA'
import { ApiError } from '@/api/client' import { ApiError } from '@/api/client'
@ -44,11 +46,26 @@ function Citations({ turn }: { turn: QATurn }) {
</ul> </ul>
} }
// Reset all transient selection/draft/request state when the displayed summary changes. // Dashboard keeps these snapshots only for the lifetime of the page.
export function SummaryQA(props: { summaryId: string; content: string }) { export interface SummaryQADraft {
question: string
passage: string
useWebSearch: boolean
request: QAQuestion | null
draftVersion: number
requestVersion: number
}
type SummaryQAProps = {
summaryId: string
content: string
launcherHost?: HTMLElement | null
initialDraft?: SummaryQADraft
onDraftChange?: (summaryId: string, draft: SummaryQADraft) => void
}
export function SummaryQA(props: SummaryQAProps) {
return <Conversation key={props.summaryId} {...props} /> return <Conversation key={props.summaryId} {...props} />
} }
function Conversation({ summaryId, content }: { summaryId: string; content: string }) { function Conversation({ summaryId, content, launcherHost, initialDraft, onDraftChange }: SummaryQAProps) {
const id = useId() const id = useId()
const text = useRef<HTMLDivElement>(null) const text = useRef<HTMLDivElement>(null)
const title = useRef<HTMLHeadingElement>(null) const title = useRef<HTMLHeadingElement>(null)
@ -56,11 +73,13 @@ function Conversation({ summaryId, content }: { summaryId: string; content: stri
const position = useRef<{ target: HTMLElement | null; top: number; left: number }>({ target: null, top: 0, left: 0 }) const position = useRef<{ target: HTMLElement | null; top: number; left: number }>({ target: null, top: 0, left: 0 })
const alive = useRef(true) const alive = useRef(true)
const pending = useRef(false) const pending = useRef(false)
const request = useRef<QAQuestion | null>(null) const request = useRef<QAQuestion | null>(initialDraft?.request ?? null)
const draftVersion = useRef(initialDraft?.draftVersion ?? 0)
const requestVersion = useRef(initialDraft?.requestVersion ?? 0)
const [selection, setSelection] = useState('') const [selection, setSelection] = useState('')
const [passage, setPassage] = useState('') const [passage, setPassage] = useState(initialDraft?.passage ?? '')
const [question, setQuestion] = useState('') const [question, setQuestion] = useState(initialDraft?.question ?? '')
const [useWebSearch, setUseWebSearch] = useState(true) const [useWebSearch, setUseWebSearch] = useState(initialDraft?.useWebSearch ?? true)
const [open, setOpen] = useState(false) const [open, setOpen] = useState(false)
const [conversation, setConversation] = useState<QAConversation | null>(null) const [conversation, setConversation] = useState<QAConversation | null>(null)
const [needsSync, setNeedsSync] = useState(false) const [needsSync, setNeedsSync] = useState(false)
@ -69,6 +88,15 @@ function Conversation({ summaryId, content }: { summaryId: string; content: stri
const [error, setError] = useState('') const [error, setError] = useState('')
const [validation, setValidation] = useState('') const [validation, setValidation] = useState('')
// Save after each commit, including request/ref changes; identical snapshots are ignored by Dashboard.
// Dialog, loading and server history remain local to the keyed conversation.
useEffect(() => {
onDraftChange?.(summaryId, {
question, passage, useWebSearch, request: request.current,
draftVersion: draftVersion.current, requestVersion: requestVersion.current,
})
})
useEffect(() => { useEffect(() => {
alive.current = true alive.current = true
const observe = () => { const observe = () => {
@ -76,13 +104,22 @@ function Conversation({ summaryId, content }: { summaryId: string; content: stri
if (!selected || selected.isCollapsed) return if (!selected || selected.isCollapsed) return
if (text.current?.contains(selected.anchorNode) && text.current.contains(selected.focusNode)) { if (text.current?.contains(selected.anchorNode) && text.current.contains(selected.focusNode)) {
const value = selected.toString() const value = selected.toString()
if (value.trim() && [...value].length <= 8000 && !value.includes('\0')) setSelection(value) setSelection(value.trim() && [...value].length <= 8000 && !value.includes('\0') ? value : '')
} }
} }
document.addEventListener('selectionchange', observe) document.addEventListener('selectionchange', observe)
return () => { alive.current = false; document.removeEventListener('selectionchange', observe) } return () => { alive.current = false; document.removeEventListener('selectionchange', observe) }
}, []) }, [])
function completeRequest() {
// A persisted answer may arrive after the user has started another draft.
if (requestVersion.current === draftVersion.current) {
setQuestion(''); setPassage(''); setUseWebSearch(true)
draftVersion.current++
}
request.current = null
}
async function load() { async function load() {
setLoading(true); setError('') setLoading(true); setError('')
try { try {
@ -90,7 +127,7 @@ function Conversation({ summaryId, content }: { summaryId: string; content: stri
if (alive.current) { if (alive.current) {
setConversation(value); setNeedsSync(false) setConversation(value); setNeedsSync(false)
const ownTurn = request.current && value.messages.find(turn => turn.request_id === request.current?.request_id) const ownTurn = request.current && value.messages.find(turn => turn.request_id === request.current?.request_id)
if (ownTurn?.status === 'answered') { setQuestion(''); setUseWebSearch(true); request.current = null } if (ownTurn?.status === 'answered') completeRequest()
else if (ownTurn?.status === 'failed') request.current = null else if (ownTurn?.status === 'failed') request.current = null
} }
} catch { if (alive.current) { setNeedsSync(true); setError('Impossible de charger la conversation. Une nouvelle tentative aura lieu automatiquement.') } } } catch { if (alive.current) { setNeedsSync(true); setError('Impossible de charger la conversation. Une nouvelle tentative aura lieu automatiquement.') } }
@ -109,7 +146,6 @@ function Conversation({ summaryId, content }: { summaryId: string; content: stri
let target = text.current?.parentElement ?? null let target = text.current?.parentElement ?? null
while (target && !/(auto|scroll)/.test(getComputedStyle(target).overflowY)) target = target.parentElement while (target && !/(auto|scroll)/.test(getComputedStyle(target).overflowY)) target = target.parentElement
position.current = { target, top: target?.scrollTop ?? window.scrollY, left: target?.scrollLeft ?? window.scrollX } position.current = { target, top: target?.scrollTop ?? window.scrollY, left: target?.scrollLeft ?? window.scrollX }
if (selection !== passage) { setPassage(selection); setValidation('') }
if (!conversation && !loading) void load() if (!conversation && !loading) void load()
} }
setOpen(value) setOpen(value)
@ -117,19 +153,20 @@ function Conversation({ summaryId, content }: { summaryId: string; content: stri
async function ask(event: FormEvent) { async function ask(event: FormEvent) {
event.preventDefault() event.preventDefault()
if (pending.current || loading || needsSync || conversation?.messages.some(turn => turn.status === 'pending') || !conversation) return if (pending.current || loading || needsSync || conversation?.messages.some(turn => turn.status === 'pending') || !conversation) return
if (!passage.trim() || !question.trim() || [...passage].length > 8000 || [...question].length > 4000) { if (!question.trim() || [...passage].length > 8000 || [...question].length > 4000) {
setValidation('Sélectionnez un passage de 1 à 8 000 caractères et saisissez une question de 1 à 4 000 caractères.'); return setValidation('Saisissez une question de 1 à 4 000 caractères. Le passage joint est facultatif et limité à 8 000 caractères.'); return
} }
const use_web_search = conversation.web_search_supported === true && useWebSearch const use_web_search = conversation.web_search_supported === true && useWebSearch
const previous = request.current const previous = request.current
const body = previous?.passage === passage && previous.question === question && previous.use_web_search === use_web_search ? previous : { request_id: crypto.randomUUID(), passage, question, use_web_search } const body = requestVersion.current === draftVersion.current && previous?.passage === passage && previous.question === question && previous.use_web_search === use_web_search ? previous : { request_id: crypto.randomUUID(), passage, question, use_web_search }
request.current = body request.current = body
requestVersion.current = draftVersion.current
pending.current = true; setSending(true); setError(''); setValidation('') pending.current = true; setSending(true); setError(''); setValidation('')
try { try {
const turn = await summaryQAApi.ask(summaryId, body) const turn = await summaryQAApi.ask(summaryId, body)
if (!alive.current) return if (!alive.current) return
setConversation(current => current ? { ...current, messages: [...current.messages.filter(item => item.request_id !== turn.request_id && item.id !== turn.id), turn] } : current) setConversation(current => current ? { ...current, messages: [...current.messages.filter(item => item.request_id !== turn.request_id && item.id !== turn.id), turn] } : current)
if (turn.status === 'answered') { setQuestion(''); setUseWebSearch(true); request.current = null } if (turn.status === 'answered') completeRequest()
else if (turn.status === 'failed') { setError(errorMessage(new ApiError(turn.failure_code ?? 'qa_provider_failed', 502))); request.current = null } else if (turn.status === 'failed') { setError(errorMessage(new ApiError(turn.failure_code ?? 'qa_provider_failed', 502))); request.current = null }
} catch (error) { } catch (error) {
if (alive.current) { if (alive.current) {
@ -141,12 +178,15 @@ function Conversation({ summaryId, content }: { summaryId: string; content: stri
} finally { pending.current = false; if (alive.current) setSending(false) } } finally { pending.current = false; if (alive.current) setSending(false) }
} }
const busy = conversation?.messages.some(turn => turn.status === 'pending') const busy = conversation?.messages.some(turn => turn.status === 'pending')
const launcher = <Dialog.Trigger asChild>
<Button ref={returnButton} type="button" variant="outline" size="icon" className="min-h-11 min-w-11" aria-label="Ouvrir le chat de cette synthèse" title="Ouvrir le chat de cette synthèse">
<MessageCircleQuestion className="h-5 w-5" aria-hidden="true" />
</Button>
</Dialog.Trigger>
return <div className="space-y-4 min-w-0"> return <div className="space-y-4 min-w-0">
<div ref={text} className="select-text"><Markdown content={content} /></div> <div ref={text} className="select-text"><Markdown content={content} /></div>
<Dialog.Root open={open} onOpenChange={changeOpen}> <Dialog.Root open={open} onOpenChange={changeOpen}>
{selection && <Dialog.Trigger asChild> {launcherHost === undefined ? launcher : launcherHost ? createPortal(launcher, launcherHost) : null}
<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.Portal>
<Dialog.Overlay className="fixed inset-0 z-[60] bg-black/50" /> <Dialog.Overlay className="fixed inset-0 z-[60] bg-black/50" />
<Dialog.Content <Dialog.Content
@ -160,39 +200,49 @@ function Conversation({ summaryId, content }: { summaryId: string; content: stri
if (target?.isConnected) target.scrollTo({ top, left, behavior: 'instant' }) if (target?.isConnected) target.scrollTo({ top, left, behavior: 'instant' })
else window.scrollTo({ top, left, behavior: 'instant' }) else window.scrollTo({ top, left, behavior: 'instant' })
}}> }}>
<div className="flex items-start justify-between gap-3"> <div className="sticky top-0 z-10 bg-background 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.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> <Dialog.Close asChild><Button type="button" variant="outline" className="min-h-11 shrink-0">Fermer</Button></Dialog.Close>
</div> </div>
<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 line-clamp-3">{passage}</blockquote>
</div>
{loading && <p role="status">Chargement de la conversation…</p>} {loading && <p role="status">Chargement de la conversation…</p>}
{error && <p role="alert">{error}</p>} {error && <p role="alert">{error}</p>}
{conversation && <> {conversation && <>
<div className="space-y-4" role="log" aria-live="polite" aria-label="Échanges de cette synthèse"> <div className="flex flex-col gap-4 min-w-0" role="log" aria-live="polite" aria-label="Échanges de cette synthèse">
{conversation.messages.length === 0 && <p>Aucune question pour cette synthèse.</p>} {conversation.messages.length === 0 && <p>Aucune question pour cette synthèse.</p>}
{conversation.messages.map(turn => <article key={turn.id} className="space-y-2 rounded-md bg-muted p-3 min-w-0"> {conversation.messages.map(turn => <div key={turn.id} className="flex flex-col gap-2 min-w-0">
<blockquote className="whitespace-pre-wrap border-l-2 pl-3">{turn.passage}</blockquote> <article aria-label="Vous" className="self-end max-w-[90%] min-w-0 rounded-lg bg-primary/10 p-3 space-y-2 [overflow-wrap:anywhere]">
<p className="whitespace-pre-wrap"><strong>Votre question : </strong>{turn.question}</p> <p className="text-xs font-semibold">Vous</p>
{turn.status === 'answered' && <><Markdown content={turn.answer} /><Citations turn={turn} /></>} {turn.passage && <blockquote className="whitespace-pre-wrap border-l-2 pl-3">{turn.passage}</blockquote>}
{turn.status === 'pending' && <p role="status">Réponse en cours…</p>} <p className="whitespace-pre-wrap">{turn.question}</p>
{turn.status === 'failed' && <p>{errorMessage(new ApiError(turn.failure_code ?? 'qa_provider_failed', 502))}</p>} </article>
</article>)} <article aria-label="Assistant" className="self-start max-w-[90%] min-w-0 rounded-lg bg-muted p-3 space-y-2 [overflow-wrap:anywhere]">
<p className="text-xs font-semibold">Assistant</p>
{turn.status === 'answered' && <><Markdown content={turn.answer} /><Citations turn={turn} /></>}
{turn.status === 'pending' && <p role="status">Réponse en cours…</p>}
{turn.status === 'failed' && <p>{errorMessage(new ApiError(turn.failure_code ?? 'qa_provider_failed', 502))}</p>}
</article>
</div>)}
</div> </div>
<form onSubmit={ask} className="space-y-3" aria-label="Poser une question" aria-busy={sending}> <form onSubmit={ask} className="space-y-3" aria-label="Poser une question" aria-busy={sending}>
{selection && selection !== passage && <Button type="button" variant="outline" className="min-h-11 h-auto whitespace-normal text-left" disabled={sending} onClick={() => { draftVersion.current++; setPassage(selection); setValidation('') }}>
<Plus className="h-4 w-4 shrink-0" aria-hidden="true" />Ajouter le passage sélectionné à la question
</Button>}
{passage && <div className="rounded-md border p-3 space-y-2">
<p className="text-sm font-medium">Passage joint</p>
<blockquote aria-label="Passage joint" className="whitespace-pre-wrap border-l-2 pl-3 line-clamp-3">{passage}</blockquote>
<Button type="button" variant="outline" className="min-h-11" disabled={sending} onClick={() => { draftVersion.current++; setPassage(''); setValidation('') }}>Retirer le passage joint</Button>
</div>}
<Label htmlFor={`${id}-question`}>Votre question</Label> <Label htmlFor={`${id}-question`}>Votre question</Label>
<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('') }} /> <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 => { draftVersion.current++; 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> <p id={`${id}-help`} className="text-sm text-muted-foreground">4 000 caractères maximum par question ; 8 000 par passage.</p>
{typeof conversation.web_search_supported === 'boolean' && <label className="flex min-h-11 items-start gap-3 py-2 text-sm" htmlFor={`${id}-web-search`}> {typeof conversation.web_search_supported === 'boolean' && <label className="flex min-h-11 items-start gap-3 py-2 text-sm" htmlFor={`${id}-web-search`}>
<input id={`${id}-web-search`} type="checkbox" className="mt-1 shrink-0" checked={conversation.web_search_supported && useWebSearch} disabled={!conversation.web_search_supported || sending || loading || needsSync || !!busy} onChange={event => setUseWebSearch(event.target.checked)} /> <input id={`${id}-web-search`} type="checkbox" className="mt-1 shrink-0" checked={conversation.web_search_supported && useWebSearch} disabled={!conversation.web_search_supported || sending || loading || needsSync || !!busy} onChange={event => { draftVersion.current++; setUseWebSearch(event.target.checked) }} />
<span>{conversation.web_search_supported <span>{conversation.web_search_supported
? 'Utiliser la recherche Web si nécessaire pour répondre, en transmettant au fournisseur de recherche les termes et éléments de contexte utiles.' ? 'Utiliser la recherche Web si nécessaire pour répondre ; la synthèse complète, les échanges précédents, votre question et tout passage joint seront transmis au fournisseur du modèle sélectionné.'
: 'La recherche Web n’est pas disponible avec le modèle de cette synthèse.'}</span> : 'La recherche Web n’est pas disponible avec le modèle de cette synthèse.'}</span>
</label>} </label>}
{validation && <p id={`${id}-error`} role="alert">{validation}</p>} {validation && <p id={`${id}-error`} role="alert">{validation}</p>}
<Button type="submit" className="min-h-11" disabled={sending || loading || needsSync || !!busy || !passage.trim()}>{sending ? 'Réponse en cours…' : 'Envoyer la question'}</Button> <Button type="submit" className="min-h-11" disabled={sending || loading || needsSync || !!busy}>{sending ? 'Réponse en cours…' : 'Envoyer la question'}</Button>
</form> </form>
</>} </>}
</Dialog.Content> </Dialog.Content>

View File

@ -4,7 +4,7 @@ import { summariesApi, type Summary, type GenerationOutcome, type GenerationHist
import { preferencesApi, type UserPreferences, type SummaryModelOption } from '@/api/preferences' import { preferencesApi, type UserPreferences, type SummaryModelOption } from '@/api/preferences'
import { assetsApi, type Asset } from '@/api/assets' import { assetsApi, type Asset } from '@/api/assets'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { SummaryQA } from '@/components/SummaryQA' import { SummaryQA, type SummaryQADraft } from '@/components/SummaryQA'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { Spinner } from '@/components/ui/spinner' import { Spinner } from '@/components/ui/spinner'
import { useAuth } from '@/lib/auth' import { useAuth } from '@/lib/auth'
@ -29,6 +29,17 @@ export function Dashboard() {
const [assets, setAssets] = useState<Asset[]>([]) const [assets, setAssets] = useState<Asset[]>([])
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true)
const [generating, setGenerating] = useState(false) const [generating, setGenerating] = useState(false)
const [chatLauncherHost, setChatLauncherHost] = useState<HTMLDivElement | null>(null)
const [chatDrafts, setChatDrafts] = useState(() => new Map<string, SummaryQADraft>())
const saveChatDraft = useCallback((summaryId: string, draft: SummaryQADraft) => {
setChatDrafts(currentDrafts => {
const previous = currentDrafts.get(summaryId)
if (previous && previous.question === draft.question && previous.passage === draft.passage
&& previous.useWebSearch === draft.useWebSearch && previous.request === draft.request
&& previous.draftVersion === draft.draftVersion && previous.requestVersion === draft.requestVersion) return currentDrafts
return new Map(currentDrafts).set(summaryId, draft)
})
}, [])
const [current, setCurrent] = useState<Summary | null>(null) const [current, setCurrent] = useState<Summary | null>(null)
const [models, setModels] = useState<SummaryModelOption[]>([]) const [models, setModels] = useState<SummaryModelOption[]>([])
@ -162,9 +173,12 @@ export function Dashboard() {
<h1 className="text-2xl font-bold">Bonjour 👋</h1> <h1 className="text-2xl font-bold">Bonjour 👋</h1>
<p className="text-muted-foreground text-sm">{user?.email}</p> <p className="text-muted-foreground text-sm">{user?.email}</p>
</div> </div>
<div className="flex flex-col items-end gap-2">
<div ref={setChatLauncherHost} />
<Button onClick={generate} disabled={generating || checking || uncertain || loading || assets.length === 0 || !selectedModel}> <Button onClick={generate} disabled={generating || checking || uncertain || loading || assets.length === 0 || !selectedModel}>
{generating && !uncertain ? <><Spinner className="h-4 w-4" /> {copy.pending}</> : <><Sparkles className="h-4 w-4" /> {copy.generate}</>} {generating && !uncertain ? <><Spinner className="h-4 w-4" /> {copy.pending}</> : <><Sparkles className="h-4 w-4" /> {copy.generate}</>}
</Button> </Button>
</div>
</div> </div>
{loadError && <div role="alert"><p>{loadError}</p><Button onClick={() => void load()}>Recharger</Button></div>} {loadError && <div role="alert"><p>{loadError}</p><Button onClick={() => void load()}>Recharger</Button></div>}
@ -206,7 +220,7 @@ export function Dashboard() {
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<p className="text-sm text-muted-foreground mb-3">Langue de cette synthèse : {currentOutcome ? (currentOutcome.language === 'fr' ? 'Français' : 'English') : 'non renseignée'}</p> <p className="text-sm text-muted-foreground mb-3">Langue de cette synthèse : {currentOutcome ? (currentOutcome.language === 'fr' ? 'Français' : 'English') : 'non renseignée'}</p>
<SummaryQA summaryId={current.id} content={current.content} /> <SummaryQA summaryId={current.id} content={current.content} launcherHost={chatLauncherHost} initialDraft={chatDrafts.get(current.id)} onDraftChange={saveChatDraft} />
<p className="mt-3 text-sm text-muted-foreground">Modèle utilisé : {current.provider_name && current.model_name ? `${current.provider_name} · ${current.model_name}` : 'non renseigné pour cette synthèse historique'}</p> <p className="mt-3 text-sm text-muted-foreground">Modèle utilisé : {current.provider_name && current.model_name ? `${current.provider_name} · ${current.model_name}` : 'non renseigné pour cette synthèse historique'}</p>
</CardContent> </CardContent>
</Card> </Card>
@ -236,7 +250,7 @@ export function Dashboard() {
</CardContent> </CardContent>
</Card> </Card>
))} ))}
{summaries.slice(1).map(s => ( {summaries.filter((s, index) => index > 0 || s.id !== current?.id).map(s => (
<Card <Card
key={s.id} key={s.id}
className={`cursor-pointer transition-colors hover:border-primary/50 ${current?.id === s.id ? 'border-primary/50' : ''}`} className={`cursor-pointer transition-colors hover:border-primary/50 ${current?.id === s.id ? 'border-primary/50' : ''}`}

View File

@ -1,6 +1,7 @@
import { act, cleanup, render, screen, waitFor } from '@testing-library/react' import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event' import userEvent from '@testing-library/user-event'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { summaryQAApi } from '../src/api/summaryQA'
import { Dashboard } from '../src/pages/Dashboard' import { Dashboard } from '../src/pages/Dashboard'
const { const {
@ -113,6 +114,74 @@ describe('Dashboard — génération de synthèses éphémères', () => {
createReport.mockResolvedValue({ id: 'report-1' }) createReport.mockResolvedValue({ id: 'report-1' })
}) })
it('restaure indépendamment question, passage joint et Web après A → B → A → B', async () => {
const a = { ...previousSummary, id: 'summary-a', content: 'Passage synthèse A.' }
const b = { ...previousSummary, id: 'summary-b', content: 'Passage synthèse B.' }
listSummaries.mockResolvedValue([generatedSummary, a, b])
const getChat = vi.spyOn(summaryQAApi, 'get').mockImplementation(async id => ({
id: `chat-${id}`, summary_id: id, mode: 'stateless', web_search_supported: true,
uses_source_articles: false, provider_session_supported: false, source_expires_at: '', sources_expired: true, source_count: 0,
messages: [{ id: `turn-${id}`, request_id: `request-${id}`, passage: '', question: `Historique ${id}`, answer: `Réponse ${id}`, status: 'answered', created_at: '', replayed: false, use_web_search: false, web_search_performed: false, citations: [] }],
}))
vi.spyOn(window, 'scrollTo').mockImplementation(() => {})
const select = (content: string) => {
const range = document.createRange(); range.selectNodeContents(screen.getByText(content, { exact: true }))
window.getSelection()!.removeAllRanges(); window.getSelection()!.addRange(range)
fireEvent(document, new Event('selectionchange'))
}
const open = async () => {
await userEvent.click(screen.getByRole('button', { name: 'Ouvrir le chat de cette synthèse' }))
return screen.findByRole('textbox')
}
try {
renderDashboard(); await screen.findByText(generatedSummary.content)
await userEvent.click(screen.getByRole('button', { name: /Passage synthèse A/ }))
select(a.content)
const questionA = await open()
expect(questionA).toHaveValue('')
await userEvent.type(questionA, 'Brouillon A')
await userEvent.click(screen.getByRole('button', { name: 'Ajouter le passage sélectionné à la question' }))
await userEvent.click(screen.getByRole('checkbox'))
await userEvent.keyboard('{Escape}')
await userEvent.click(screen.getByRole('button', { name: /Passage synthèse B/ }))
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
const questionB = await open()
expect(questionB).toHaveValue('')
expect(screen.queryByLabelText('Passage joint')).not.toBeInTheDocument()
expect(screen.getByRole('checkbox')).toBeChecked()
expect(screen.getByText('Historique summary-b')).toBeInTheDocument()
expect(screen.queryByText('Historique summary-a')).not.toBeInTheDocument()
await userEvent.type(questionB, 'Brouillon B')
await userEvent.keyboard('{Escape}')
select(b.content); await open()
await userEvent.click(screen.getByRole('button', { name: 'Ajouter le passage sélectionné à la question' }))
await userEvent.keyboard('{Escape}')
await userEvent.click(screen.getByRole('button', { name: /Passage synthèse A/ }))
expect(await open()).toHaveValue('Brouillon A')
expect(screen.getByLabelText('Passage joint')).toHaveTextContent(a.content)
expect(screen.getByRole('checkbox')).not.toBeChecked()
expect(screen.getByText('Historique summary-a')).toBeInTheDocument()
expect(screen.queryByText('Historique summary-b')).not.toBeInTheDocument()
await userEvent.keyboard('{Escape}')
await userEvent.click(screen.getByRole('button', { name: /Passage synthèse B/ }))
expect(await open()).toHaveValue('Brouillon B')
expect(screen.getByLabelText('Passage joint')).toHaveTextContent(b.content)
expect(screen.getByRole('checkbox')).toBeChecked()
expect(getChat.mock.calls.map(([id]) => id)).toEqual(['summary-a', 'summary-b', 'summary-a', 'summary-b'])
} finally { window.getSelection()?.removeAllRanges(); vi.restoreAllMocks() }
})
it('place le launcher chat dans le header directement au-dessus de Générer', async () => {
renderDashboard()
const launcher = await screen.findByRole('button', { name: 'Ouvrir le chat de cette synthèse' })
const generate = screen.getByRole('button', { name: 'Générer une synthèse' })
expect(launcher.parentElement?.nextElementSibling).toBe(generate)
expect(launcher.parentElement?.parentElement).toBe(generate.parentElement)
expect(generate.parentElement).toHaveClass('flex-col')
expect(launcher).not.toHaveClass('fixed')
expect(launcher.querySelector('svg')).toBeInTheDocument()
})
it.each(['ranking_model_unavailable', 'ranking_model_incompatible'])('guide vers les préférences pour %s', async (failure_code) => { it.each(['ranking_model_unavailable', 'ranking_model_incompatible'])('guide vers les préférences pour %s', async (failure_code) => {
generationStatus.mockResolvedValueOnce({ id: 'failed', status: 'failed', failure_code }) generationStatus.mockResolvedValueOnce({ id: 'failed', status: 'failed', failure_code })
renderDashboard() renderDashboard()
@ -163,7 +232,8 @@ describe('Dashboard — génération de synthèses éphémères', () => {
expect(screen.getByText('2 articles parmi les plus anciens ont été retirés pour respecter le plafond du prompt.')).toBeInTheDocument() expect(screen.getByText('2 articles parmi les plus anciens ont été retirés pour respecter le plafond du prompt.')).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: /Ancienne synthèse/ })) await user.click(screen.getByRole('button', { name: /Ancienne synthèse/ }))
expect(screen.getAllByText('2 articles parmi les plus anciens ont été retirés pour respecter le plafond du prompt.')).toHaveLength(2) expect(screen.getAllByText('2 articles parmi les plus anciens ont été retirés pour respecter le plafond du prompt.')).toHaveLength(2)
if (count) expect(screen.getAllByText(expected)).toHaveLength(1) // The newest summary is now selectable in history as well as shown in the latest-result notice.
if (count) expect(screen.getAllByText(expected)).toHaveLength(2)
}) })
it('affiche le compteur du résultat récent lié à la synthèse sans historique disponible', async () => { it('affiche le compteur du résultat récent lié à la synthèse sans historique disponible', async () => {

View File

@ -1,11 +1,11 @@
import { afterEach, expect, it, vi } from 'vitest' import { afterEach, expect, it, vi } from 'vitest'
import { summaryQAApi } from '../src/api/summaryQA' import { summaryQAApi } from '../src/api/summaryQA'
afterEach(() => { vi.unstubAllGlobals(); localStorage.clear() }) afterEach(() => { vi.unstubAllGlobals(); localStorage.clear() })
it('utilise les nouvelles routes owner-scoped et le DTO Question exact de #53', async () => { it.each(['', 'Passage'])('transmet passage %s et le DTO Web sans altération via les routes owner-scoped', async passage => {
localStorage.setItem('token', 'user-token') localStorage.setItem('token', 'user-token')
const conversation = { id: 'c', summary_id: 's', mode: 'stateless', uses_source_articles: false, provider_session_supported: false, source_expires_at: '2026-12-01T00:00:00Z', sources_expired: false, source_count: 2, messages: [] } const conversation = { id: 'c', summary_id: 's', web_search_supported: true, mode: 'stateless', uses_source_articles: false, provider_session_supported: false, source_expires_at: '2026-12-01T00:00:00Z', sources_expired: false, source_count: 2, messages: [] }
const question = { request_id: '00000000-0000-0000-0000-000000005401', passage: 'Passage', question: 'Pourquoi ?' } const question = { request_id: '00000000-0000-0000-0000-000000005401', passage, question: 'Pourquoi ?', use_web_search: true }
const turn = { ...question, id: 't', answer: 'Réponse', status: 'answered', created_at: '2026-11-25T00:00:00Z', replayed: false } const turn = { ...question, id: 't', web_search_performed: true, citations: [{ title: 'Source', url: 'https://example.test/source' }], answer: 'Réponse', status: 'answered', created_at: '2026-11-25T00:00:00Z', replayed: false }
const fetchMock = vi.fn().mockResolvedValueOnce(new Response(JSON.stringify({ data: conversation }))).mockResolvedValueOnce(new Response(JSON.stringify({ data: turn }))) const fetchMock = vi.fn().mockResolvedValueOnce(new Response(JSON.stringify({ data: conversation }))).mockResolvedValueOnce(new Response(JSON.stringify({ data: turn })))
vi.stubGlobal('fetch', fetchMock) vi.stubGlobal('fetch', fetchMock)
expect(await summaryQAApi.get('s')).toEqual(conversation) expect(await summaryQAApi.get('s')).toEqual(conversation)

View File

@ -22,11 +22,12 @@ it('préserve les événements natifs et le focus ; seule une action explicite o
selectPassage() selectPassage()
expect(get).not.toHaveBeenCalled() expect(get).not.toHaveBeenCalled()
expect(screen.queryByRole('textbox')).not.toBeInTheDocument() expect(screen.queryByRole('textbox')).not.toBeInTheDocument()
await userEvent.click(screen.getByRole('button', { name: 'Interroger ce passage' })) await userEvent.click(screen.getByRole('button', { name: 'Ouvrir le chat de cette synthèse' }))
const question = await screen.findByRole('textbox', { name: 'Votre question' }) const question = await screen.findByRole('textbox', { name: 'Votre question' })
expect(screen.getByRole('heading', { name: 'Questions sur cette synthèse' })).toHaveFocus() expect(screen.getByRole('heading', { name: 'Questions sur cette synthèse' })).toHaveFocus()
expect(screen.queryAllByText(/Les sources ont expiré|Expiration des sources|sans articles sources ni session fournisseur réutilisée|Sélectionnez un passage normalement|Posez une question sur le passage sélectionné/)).toHaveLength(0) expect(screen.queryAllByText(/Les sources ont expiré|Expiration des sources|sans articles sources ni session fournisseur réutilisée|Sélectionnez un passage normalement|Posez une question sur le passage sélectionné/)).toHaveLength(0)
expect(screen.queryByRole('button', { name: /Actualiser|Développer|Réduire/ })).not.toBeInTheDocument() expect(screen.queryByRole('button', { name: /Actualiser|Développer|Réduire/ })).not.toBeInTheDocument()
await userEvent.click(screen.getByRole('button', { name: 'Ajouter le passage sélectionné à la question' }))
await userEvent.type(question, 'Pourquoi ?') await userEvent.type(question, 'Pourquoi ?')
await userEvent.click(screen.getByRole('button', { name: 'Envoyer la question' })) await userEvent.click(screen.getByRole('button', { name: 'Envoyer la question' }))
expect(await screen.findByText('Une réponse.')).toBeInTheDocument() expect(await screen.findByText('Une réponse.')).toBeInTheDocument()
@ -36,19 +37,19 @@ it('reprend la conversation et efface les données temporaires au changement de
get.mockResolvedValueOnce({ ...conversation, messages: [{ id: 'old', passage: 'Ancien extrait', question: 'Ancienne question', answer: 'Ancienne réponse', status: 'answered' }] }) 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." />) const view = render(<SummaryQA summaryId="s" content="Un passage de synthèse." />)
selectPassage() selectPassage()
await userEvent.click(screen.getByRole('button', { name: 'Interroger ce passage' })) await userEvent.click(screen.getByRole('button', { name: 'Ouvrir le chat de cette synthèse' }))
expect(await screen.findByText('Ancienne réponse')).toBeInTheDocument() expect(await screen.findByText('Ancienne réponse')).toBeInTheDocument()
await userEvent.type(screen.getByRole('textbox'), 'Brouillon') await userEvent.type(screen.getByRole('textbox'), 'Brouillon')
view.rerender(<SummaryQA summaryId="other" content="Autre synthèse" />) view.rerender(<SummaryQA summaryId="other" content="Autre synthèse" />)
expect(screen.queryByText('Ancienne réponse')).not.toBeInTheDocument() expect(screen.queryByText('Ancienne réponse')).not.toBeInTheDocument()
expect(screen.queryByRole('textbox')).not.toBeInTheDocument() expect(screen.queryByRole('textbox')).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Interroger ce passage' })).not.toBeInTheDocument() expect(screen.getByRole('button', { name: 'Ouvrir le chat de cette synthèse' })).toBeInTheDocument()
}) })
it('explique le modèle indisponible en conservant la question', async () => { it('explique le modèle indisponible en conservant la question', async () => {
ask.mockRejectedValueOnce(new ApiError('qa_model_unavailable', 409)) ask.mockRejectedValueOnce(new ApiError('qa_model_unavailable', 409))
render(<SummaryQA summaryId="s" content="Un passage de synthèse." />) render(<SummaryQA summaryId="s" content="Un passage de synthèse." />)
selectPassage() selectPassage()
await userEvent.click(screen.getByRole('button', { name: 'Interroger ce passage' })) await userEvent.click(screen.getByRole('button', { name: 'Ouvrir le chat de cette synthèse' }))
await userEvent.type(await screen.findByRole('textbox'), 'Pourquoi ?') await userEvent.type(await screen.findByRole('textbox'), 'Pourquoi ?')
await userEvent.click(screen.getByRole('button', { name: 'Envoyer la question' })) await userEvent.click(screen.getByRole('button', { name: 'Envoyer la question' }))
expect(await screen.findByRole('alert')).toHaveTextContent(/modèle.*indisponible/) expect(await screen.findByRole('alert')).toHaveTextContent(/modèle.*indisponible/)
@ -58,7 +59,7 @@ it('réutilise le request_id après une erreur réseau', async () => {
ask.mockRejectedValueOnce(new Error('network')) ask.mockRejectedValueOnce(new Error('network'))
render(<SummaryQA summaryId="s" content="Un passage de synthèse." />) render(<SummaryQA summaryId="s" content="Un passage de synthèse." />)
selectPassage() selectPassage()
await userEvent.click(screen.getByRole('button', { name: 'Interroger ce passage' })) await userEvent.click(screen.getByRole('button', { name: 'Ouvrir le chat de cette synthèse' }))
await userEvent.type(await screen.findByRole('textbox'), 'Pourquoi ?') await userEvent.type(await screen.findByRole('textbox'), 'Pourquoi ?')
await userEvent.click(screen.getByRole('button', { name: 'Envoyer la question' })) await userEvent.click(screen.getByRole('button', { name: 'Envoyer la question' }))
await screen.findByRole('alert') await screen.findByRole('alert')
@ -71,7 +72,7 @@ it('bloque un second envoi pendant la réponse et annonce sa réception', async
ask.mockImplementationOnce(() => new Promise(resolve => { finish = resolve })) ask.mockImplementationOnce(() => new Promise(resolve => { finish = resolve }))
render(<SummaryQA summaryId="s" content="Un passage de synthèse." />) render(<SummaryQA summaryId="s" content="Un passage de synthèse." />)
selectPassage() selectPassage()
await userEvent.click(screen.getByRole('button', { name: 'Interroger ce passage' })) await userEvent.click(screen.getByRole('button', { name: 'Ouvrir le chat de cette synthèse' }))
await userEvent.type(await screen.findByRole('textbox'), 'Pourquoi ?') await userEvent.type(await screen.findByRole('textbox'), 'Pourquoi ?')
await userEvent.click(screen.getByRole('button', { name: 'Envoyer la question' })) await userEvent.click(screen.getByRole('button', { name: 'Envoyer la question' }))
expect(screen.getByRole('button', { name: 'Réponse en cours…' })).toBeDisabled() expect(screen.getByRole('button', { name: 'Réponse en cours…' })).toBeDisabled()
@ -84,12 +85,12 @@ it('reprend un chargement échoué sans afficher de détails techniques', async
get.mockRejectedValueOnce(new ApiError('PRIVATE_PROVIDER_SECRET', 503)) get.mockRejectedValueOnce(new ApiError('PRIVATE_PROVIDER_SECRET', 503))
render(<SummaryQA summaryId="s" content="Un passage de synthèse." />) render(<SummaryQA summaryId="s" content="Un passage de synthèse." />)
selectPassage() selectPassage()
await userEvent.click(screen.getByRole('button', { name: 'Interroger ce passage' })) await userEvent.click(screen.getByRole('button', { name: 'Ouvrir le chat de cette synthèse' }))
expect(await screen.findByRole('alert')).not.toHaveTextContent('PRIVATE_PROVIDER_SECRET') expect(await screen.findByRole('alert')).not.toHaveTextContent('PRIVATE_PROVIDER_SECRET')
await waitFor(() => expect(get).toHaveBeenCalledTimes(2), { timeout: 4500 }) await waitFor(() => expect(get).toHaveBeenCalledTimes(2), { timeout: 4500 })
expect(await screen.findByRole('textbox', { name: 'Votre question' })).toBeInTheDocument() expect(await screen.findByRole('textbox', { name: 'Votre question' })).toBeInTheDocument()
}) })
it('ne propose pas l’action pour un passage hors limite', () => { it('permet le chat sans joindre un passage hors limite', async () => {
const content = 'a'.repeat(8001) const content = 'a'.repeat(8001)
render(<SummaryQA summaryId="s" content={content} />) render(<SummaryQA summaryId="s" content={content} />)
const range = document.createRange() const range = document.createRange()
@ -97,14 +98,16 @@ it('ne propose pas l’action pour un passage hors limite', () => {
window.getSelection()!.removeAllRanges() window.getSelection()!.removeAllRanges()
window.getSelection()!.addRange(range) window.getSelection()!.addRange(range)
fireEvent(document, new Event('selectionchange')) fireEvent(document, new Event('selectionchange'))
expect(screen.queryByRole('button', { name: 'Interroger ce passage' })).not.toBeInTheDocument()
expect(get).not.toHaveBeenCalled() expect(get).not.toHaveBeenCalled()
await userEvent.click(screen.getByRole('button', { name: 'Ouvrir le chat de cette synthèse' }))
await screen.findByRole('textbox')
expect(screen.queryByRole('button', { name: 'Ajouter le passage sélectionné à la question' })).not.toBeInTheDocument()
}) })
it.each([45, undefined])('explique le quota Q&A avec délai %s et conserve la question', async seconds => { 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 })) ask.mockRejectedValueOnce(Object.assign(new ApiError('qa_rate_limited', 429), { retryAfterSeconds: seconds }))
render(<SummaryQA summaryId="s" content="Un passage de synthèse." />) render(<SummaryQA summaryId="s" content="Un passage de synthèse." />)
selectPassage() selectPassage()
await userEvent.click(screen.getByRole('button', { name: 'Interroger ce passage' })) await userEvent.click(screen.getByRole('button', { name: 'Ouvrir le chat de cette synthèse' }))
await userEvent.type(await screen.findByRole('textbox'), 'Pourquoi ?') await userEvent.type(await screen.findByRole('textbox'), 'Pourquoi ?')
await userEvent.click(screen.getByRole('button', { name: 'Envoyer la question' })) await userEvent.click(screen.getByRole('button', { name: 'Envoyer la question' }))
const alert = await screen.findByRole('alert') const alert = await screen.findByRole('alert')
@ -112,13 +115,11 @@ 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(alert).toHaveTextContent(seconds === undefined ? 'Réessayez dans quelques instants.' : 'Réessayez dans 45 secondes.')
expect(screen.getByRole('textbox')).toHaveValue('Pourquoi ?') expect(screen.getByRole('textbox')).toHaveValue('Pourquoi ?')
}) })
it('affiche seulement le bouton fixe après sélection valide et la mémorise au scroll/collapse', () => { it('garde le launcher dans le flux et mémorise une sélection au scroll/collapse sans ouvrir', () => {
render(<SummaryQA summaryId="s" content="Un passage de synthèse." />) render(<SummaryQA summaryId="s" content="Un passage de synthèse." />)
expect(screen.queryByRole('button', { name: 'Interroger ce passage' })).not.toBeInTheDocument() const action = screen.getByRole('button', { name: 'Ouvrir le chat de cette synthèse' })
expect(screen.queryByRole('button', { name: 'Questions sur cette synthèse' })).not.toBeInTheDocument() expect(action).not.toHaveClass('fixed')
selectPassage() selectPassage()
const action = screen.getByRole('button', { name: 'Interroger ce passage' })
expect(action).toHaveClass('fixed')
window.getSelection()?.removeAllRanges() window.getSelection()?.removeAllRanges()
fireEvent(document, new Event('selectionchange')) fireEvent(document, new Event('selectionchange'))
fireEvent.scroll(window) fireEvent.scroll(window)
@ -128,7 +129,7 @@ it('affiche seulement le bouton fixe après sélection valide et la mémorise au
it('ouvre une modale accessible, conserve le brouillon et restaure le focus après Échap', async () => { 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." />) render(<SummaryQA summaryId="s" content="Un passage de synthèse." />)
selectPassage() selectPassage()
const action = screen.getByRole('button', { name: 'Interroger ce passage' }) const action = screen.getByRole('button', { name: 'Ouvrir le chat de cette synthèse' })
await userEvent.click(action) await userEvent.click(action)
expect(await screen.findByRole('dialog', { name: 'Questions sur cette synthèse' })).toBeInTheDocument() expect(await screen.findByRole('dialog', { name: 'Questions sur cette synthèse' })).toBeInTheDocument()
await userEvent.type(await screen.findByRole('textbox'), 'Brouillon conservé') await userEvent.type(await screen.findByRole('textbox'), 'Brouillon conservé')
@ -149,8 +150,9 @@ it('croppe visuellement le passage mais transmet son intégralité', async () =>
window.getSelection()!.addRange(range) window.getSelection()!.addRange(range)
fireEvent(document, new Event('selectionchange')) fireEvent(document, new Event('selectionchange'))
const fullPassage = window.getSelection()!.toString() const fullPassage = window.getSelection()!.toString()
await userEvent.click(screen.getByRole('button', { name: 'Interroger ce passage' })) await userEvent.click(screen.getByRole('button', { name: 'Ouvrir le chat de cette synthèse' }))
const preview = await screen.findByLabelText('Passage sélectionné') await userEvent.click(screen.getByRole('button', { name: 'Ajouter le passage sélectionné à la question' }))
const preview = await screen.findByLabelText('Passage joint')
expect(preview).toHaveClass('line-clamp-3') expect(preview).toHaveClass('line-clamp-3')
expect(preview.textContent).toBe(fullPassage) expect(preview.textContent).toBe(fullPassage)
expect(preview).not.toHaveAttribute('aria-hidden', 'true') expect(preview).not.toHaveAttribute('aria-hidden', 'true')
@ -164,12 +166,12 @@ it('garde la requête et son request_id lors de fermeture puis reprise après er
ask.mockImplementationOnce(() => new Promise((_, reject) => { fail = reject })) ask.mockImplementationOnce(() => new Promise((_, reject) => { fail = reject }))
render(<SummaryQA summaryId="s" content="Un passage de synthèse." />) render(<SummaryQA summaryId="s" content="Un passage de synthèse." />)
selectPassage() selectPassage()
await userEvent.click(screen.getByRole('button', { name: 'Interroger ce passage' })) await userEvent.click(screen.getByRole('button', { name: 'Ouvrir le chat de cette synthèse' }))
await userEvent.type(await screen.findByRole('textbox'), 'Pourquoi ?') await userEvent.type(await screen.findByRole('textbox'), 'Pourquoi ?')
await userEvent.click(screen.getByRole('button', { name: 'Envoyer la question' })) await userEvent.click(screen.getByRole('button', { name: 'Envoyer la question' }))
const first = ask.mock.calls.at(-1)![1] const first = ask.mock.calls.at(-1)![1]
await userEvent.keyboard('{Escape}') await userEvent.keyboard('{Escape}')
await userEvent.click(screen.getByRole('button', { name: 'Interroger ce passage' })) await userEvent.click(screen.getByRole('button', { name: 'Ouvrir le chat de cette synthèse' }))
expect(screen.getByRole('button', { name: 'Réponse en cours…' })).toBeDisabled() expect(screen.getByRole('button', { name: 'Réponse en cours…' })).toBeDisabled()
expect(ask).toHaveBeenCalledTimes(1) expect(ask).toHaveBeenCalledTimes(1)
fail(new Error('network')) fail(new Error('network'))
@ -182,7 +184,7 @@ it('reprend après conflit, erreur de lecture et réponse pending sans perdre le
ask.mockRejectedValueOnce(new ApiError('qa_question_in_progress', 409)) ask.mockRejectedValueOnce(new ApiError('qa_question_in_progress', 409))
render(<SummaryQA summaryId="s" content="Un passage de synthèse." />) render(<SummaryQA summaryId="s" content="Un passage de synthèse." />)
selectPassage() selectPassage()
await userEvent.click(screen.getByRole('button', { name: 'Interroger ce passage' })) await userEvent.click(screen.getByRole('button', { name: 'Ouvrir le chat de cette synthèse' }))
await userEvent.type(await screen.findByRole('textbox'), 'Mon brouillon') await userEvent.type(await screen.findByRole('textbox'), 'Mon brouillon')
await userEvent.click(screen.getByRole('button', { name: 'Envoyer la question' })) await userEvent.click(screen.getByRole('button', { name: 'Envoyer la question' }))
expect(await screen.findByRole('alert')).not.toHaveTextContent(/actualis/i) expect(await screen.findByRole('alert')).not.toHaveTextContent(/actualis/i)

View File

@ -4,7 +4,7 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { SummaryQA } from '../src/components/SummaryQA' import { SummaryQA } from '../src/components/SummaryQA'
const { get, ask } = vi.hoisted(() => ({ get: vi.fn(), ask: vi.fn() })) const { get, ask } = vi.hoisted(() => ({ get: vi.fn(), ask: vi.fn() }))
vi.mock('@/api/summaryQA', () => ({ summaryQAApi: { get, ask } })) vi.mock('@/api/summaryQA', () => ({ summaryQAApi: { get, ask } }))
const label = 'Utiliser la recherche Web si nécessaire pour répondre, en transmettant au fournisseur de recherche les termes et éléments de contexte utiles.' const label = 'Utiliser la recherche Web si nécessaire pour répondre ; la synthèse complète, les échanges précédents, votre question et tout passage joint seront transmis au fournisseur du modèle sélectionné.'
const unavailable = 'La recherche Web n’est pas disponible avec le modèle de cette synthèse.' const unavailable = 'La recherche Web n’est pas disponible avec le modèle de cette synthèse.'
const conversation = { id: 'c', web_search_supported: true, messages: [] } const conversation = { id: 'c', web_search_supported: true, messages: [] }
const answered = { id: 't', status: 'answered', answer: 'Réponse', citations: [], web_search_performed: false } const answered = { id: 't', status: 'answered', answer: 'Réponse', citations: [], web_search_performed: false }
@ -13,7 +13,7 @@ async function open() {
const range = document.createRange(); range.selectNodeContents(screen.getByText('Passage sélectionnable')) const range = document.createRange(); range.selectNodeContents(screen.getByText('Passage sélectionnable'))
window.getSelection()!.removeAllRanges(); window.getSelection()!.addRange(range) window.getSelection()!.removeAllRanges(); window.getSelection()!.addRange(range)
fireEvent(document, new Event('selectionchange')) fireEvent(document, new Event('selectionchange'))
await userEvent.click(screen.getByRole('button', { name: 'Interroger ce passage' })) await userEvent.click(screen.getByRole('button', { name: 'Ouvrir le chat de cette synthèse' }))
} }
async function send() { await userEvent.click(screen.getByRole('button', { name: 'Envoyer la question' })) } async function send() { await userEvent.click(screen.getByRole('button', { name: 'Envoyer la question' })) }
beforeEach(() => { beforeEach(() => {
@ -46,7 +46,7 @@ it('conserve choix fermé et après erreur, rejoue le même UUID puis change UUI
await open(); await userEvent.click(await screen.findByRole('checkbox', { name: label })) await open(); await userEvent.click(await screen.findByRole('checkbox', { name: label }))
await userEvent.type(screen.getByRole('textbox'), 'Pourquoi ?') await userEvent.type(screen.getByRole('textbox'), 'Pourquoi ?')
await userEvent.keyboard('{Escape}') await userEvent.keyboard('{Escape}')
await userEvent.click(screen.getByRole('button', { name: 'Interroger ce passage' })) await userEvent.click(screen.getByRole('button', { name: 'Ouvrir le chat de cette synthèse' }))
expect(screen.getByRole('checkbox')).not.toBeChecked() expect(screen.getByRole('checkbox')).not.toBeChecked()
await send(); await screen.findByRole('alert') await send(); await screen.findByRole('alert')
const first = ask.mock.calls[0][1]; expect(first.use_web_search).toBe(false) const first = ask.mock.calls[0][1]; expect(first.use_web_search).toBe(false)

View File

@ -0,0 +1,141 @@
import { cleanup, fireEvent, render, screen, waitFor, within } 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'
const { get, ask } = vi.hoisted(() => ({ get: vi.fn(), ask: vi.fn() }))
vi.mock('@/api/summaryQA', () => ({ summaryQAApi: { get, ask } }))
const launcher = 'Ouvrir le chat de cette synthèse'
const attach = 'Ajouter le passage sélectionné à la question'
const conversation = { id: 'c', web_search_supported: true, messages: [] }
const answered = { id: 't', status: 'answered', answer: 'Réponse complète', citations: [], web_search_performed: false }
function select(value = 'Premier passage.') {
const range = document.createRange(); range.selectNodeContents(screen.getByText(value))
window.getSelection()!.removeAllRanges(); window.getSelection()!.addRange(range)
fireEvent(document, new Event('selectionchange'))
}
function view() { return render(<SummaryQA summaryId="s" content={'Premier passage.\n\nSecond passage.'} />) }
async function open() { await userEvent.click(screen.getByRole('button', { name: launcher })); await screen.findByRole('textbox') }
async function send() { await userEvent.click(screen.getByRole('button', { name: 'Envoyer la question' })) }
beforeEach(() => {
vi.spyOn(window, 'scrollTo').mockImplementation(() => {})
get.mockResolvedValue(conversation)
ask.mockImplementation(async (_id, body) => ({ ...body, ...answered }))
})
afterEach(() => { cleanup(); window.getSelection()?.removeAllRanges(); vi.restoreAllMocks() })
it('ouvre sans sélection ni envoi automatique et transmet passage vide pour la synthèse entière', async () => {
view()
const button = screen.getByRole('button', { name: launcher })
expect(button).toHaveAttribute('title', launcher)
expect(button).not.toHaveClass('fixed')
expect(get).not.toHaveBeenCalled()
await open()
expect(ask).not.toHaveBeenCalled()
expect(screen.getByRole('textbox')).toHaveValue('')
expect(screen.queryByText('Passage joint')).not.toBeInTheDocument()
await userEvent.type(screen.getByRole('textbox'), 'Question globale ?'); await send()
expect(ask).toHaveBeenCalledWith('s', expect.objectContaining({ passage: '', question: 'Question globale ?', use_web_search: true }))
expect(await screen.findByText('Réponse complète')).toBeInTheDocument()
})
it('attache seulement via +, conserve puis remplace explicitement et retire le passage', async () => {
view(); select(); await open()
expect(screen.queryByText('Passage joint')).not.toBeInTheDocument()
expect(screen.getByRole('button', { name: attach }).querySelector('svg')).not.toBeNull()
await userEvent.click(screen.getByRole('button', { name: attach }))
expect(screen.getByLabelText('Passage joint')).toHaveTextContent('Premier passage.')
expect(screen.getByLabelText('Passage joint')).toHaveClass('line-clamp-3')
await userEvent.type(screen.getByRole('textbox'), 'Brouillon')
await userEvent.click(screen.getByRole('checkbox'))
await userEvent.keyboard('{Escape}'); select('Second passage.'); await open()
expect(screen.getByRole('textbox')).toHaveValue('Brouillon')
expect(screen.getByRole('checkbox')).not.toBeChecked()
expect(screen.getByLabelText('Passage joint')).toHaveTextContent('Premier passage.')
await userEvent.click(screen.getByRole('button', { name: attach }))
expect(screen.getByLabelText('Passage joint')).toHaveTextContent('Second passage.')
await userEvent.click(screen.getByRole('button', { name: 'Retirer le passage joint' }))
expect(screen.queryByLabelText('Passage joint')).not.toBeInTheDocument()
await send()
expect(ask.mock.calls[0][1]).toMatchObject({ passage: '', use_web_search: false })
})
it('isole nouveau summaryId, historique serveur, brouillon et pièce jointe', async () => {
const current = view(); select(); await open()
await userEvent.click(screen.getByRole('button', { name: attach }))
await userEvent.type(screen.getByRole('textbox'), 'Ancien brouillon')
get.mockResolvedValueOnce({ ...conversation, id: 'other', messages: [{ ...answered, passage: '', question: 'Question autre synthèse', request_id: 'other' }] })
current.rerender(<SummaryQA summaryId="other" content="Autre synthèse" />)
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
await open()
expect(get).toHaveBeenLastCalledWith('other')
expect(screen.getByRole('textbox')).toHaveValue('')
expect(screen.queryByLabelText('Passage joint')).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: attach })).not.toBeInTheDocument()
expect(screen.getByText('Question autre synthèse')).toBeInTheDocument()
expect(screen.getByRole('checkbox')).toBeChecked()
})
it('bulles auteur accessibles à droite/gauche et citations sous assistant y compris états non terminés', async () => {
get.mockResolvedValue({ ...conversation, messages: [
{ ...answered, id: 'a', passage: 'Extrait', question: 'Pourquoi', request_id: 'a', web_search_performed: true, citations: [{ title: 'Source', url: 'https://example.test/source' }] },
{ ...answered, id: 'p', question: 'En cours', request_id: 'p', passage: '', status: 'pending' },
{ ...answered, id: 'f', question: 'Erreur', request_id: 'f', passage: '', status: 'failed' },
] })
view(); await open()
for (const user of screen.getAllByRole('article', { name: 'Vous' })) expect(user).toHaveClass('self-end')
const assistants = screen.getAllByRole('article', { name: 'Assistant' })
for (const assistant of assistants) expect(assistant).toHaveClass('self-start')
expect(within(assistants[0]).getByRole('link', { name: 'Source (nouvel onglet)' })).toBeInTheDocument()
expect(within(assistants[1]).getByRole('status')).toHaveTextContent('Réponse en cours')
expect(assistants[2]).toHaveTextContent('La réponse a échoué')
})
it('change UUID pour question et passage, réutilise seulement la demande inchangée après transport', async () => {
ask.mockRejectedValue(new Error('network'))
view(); select(); await open()
await userEvent.type(screen.getByRole('textbox'), 'Question'); await send(); await screen.findByRole('alert')
const first = ask.mock.calls[0][1]
await send(); await screen.findByRole('alert')
expect(ask.mock.calls[1][1]).toEqual(first)
await userEvent.click(screen.getByRole('button', { name: attach })); await send(); await screen.findByRole('alert')
expect(ask.mock.calls[2][1].passage).toBe('Premier passage.')
expect(ask.mock.calls[2][1].request_id).not.toBe(first.request_id)
const attached = ask.mock.calls[2][1]
await userEvent.type(screen.getByRole('textbox'), ' différente'); await send(); await screen.findByRole('alert')
expect(ask.mock.calls[3][1].request_id).not.toBe(attached.request_id)
})
it('efface le brouillon envoyé et sa pièce jointe après succès direct', async () => {
view(); select(); await open(); await userEvent.click(screen.getByRole('button', { name: attach }))
await userEvent.click(screen.getByRole('checkbox'))
await userEvent.type(screen.getByRole('textbox'), 'Question'); await send()
await screen.findByText('Réponse complète')
expect(screen.getByRole('textbox')).toHaveValue('')
expect(screen.queryByLabelText('Passage joint')).not.toBeInTheDocument()
expect(screen.getByRole('checkbox')).toBeChecked()
})
it('le polling ne supprime jamais le nouveau brouillon rédigé après envoi pending', async () => {
ask.mockImplementationOnce(async (_id, body) => ({ ...body, ...answered, status: 'pending' }))
view(); select(); await open(); await userEvent.click(screen.getByRole('button', { name: attach }))
await userEvent.type(screen.getByRole('textbox'), 'Question envoyée'); await send()
await userEvent.clear(screen.getByRole('textbox')); await userEvent.type(screen.getByRole('textbox'), 'Nouveau brouillon')
get.mockResolvedValue({ ...conversation, messages: [{ ...ask.mock.calls[0][1], ...answered }] })
await waitFor(() => expect(screen.getByText('Réponse complète')).toBeInTheDocument(), { timeout: 4500 })
expect(screen.getByRole('textbox')).toHaveValue('Nouveau brouillon')
expect(screen.getByLabelText('Passage joint')).toHaveTextContent('Premier passage.')
})
it('le launcher est rendu dans le host header sans déplacer le lecteur de synthèse', async () => {
const host = document.createElement('div'); document.body.append(host)
try {
const result = render(<SummaryQA summaryId="s" content="Contenu" launcherHost={host} />)
expect(within(host).getByRole('button', { name: launcher })).toBeInTheDocument()
expect(within(result.container).getByText('Contenu')).toBeInTheDocument()
expect(within(result.container).queryByRole('button', { name: launcher })).not.toBeInTheDocument()
await open()
} finally { host.remove() }
})
it('valide question vide/plus de 4000 caractères et accepte une question d’un caractère sans passage', async () => {
view(); await open(); await send()
expect(screen.getByRole('alert')).toHaveTextContent('1 à 4 000')
expect(ask).not.toHaveBeenCalled()
fireEvent.change(screen.getByRole('textbox'), { target: { value: 'a'.repeat(4001) } })
await send(); expect(ask).not.toHaveBeenCalled()
fireEvent.change(screen.getByRole('textbox'), { target: { value: '?' } })
await send()
expect(ask.mock.calls[0][1]).toMatchObject({ question: '?', passage: '' })
})