diff --git a/frontend/e2e/ticket54-summary-qa.spec.mjs b/frontend/e2e/ticket54-summary-qa.spec.mjs index d404b38..2c4ac80 100644 --- a/frontend/e2e/ticket54-summary-qa.spec.mjs +++ b/frontend/e2e/ticket54-summary-qa.spec.mjs @@ -1,7 +1,7 @@ import { expect, test } from '@playwright/test' 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() await page.setViewportSize({ width, height: 850 }) 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') }) 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', 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 secondExcerpt = 'Autre passage à joindre explicitement.' + 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 = [] await page.route('**/api/**', async route => { const path = new URL(route.request().url()).pathname 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/generation-jobs/recent') return respond(null) - if (path === `/api/summaries/${summary.id}/conversation`) return respond(conversation) - if (path === `/api/summaries/${summary.id}/conversation/messages`) { - const question = route.request().postDataJSON() - questions.push(question) - 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' } - conversation.messages.push(turn) - return respond(turn) + for (const [id, conversation] of conversations) { + if (path === `/api/summaries/${id}/conversation`) return respond(conversation) + if (path === `/api/summaries/${id}/conversation/messages`) { + const question = route.request().postDataJSON() + questions.push(question) + 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' } + conversation.messages.push(turn) + return respond(turn) + } } 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() 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`) - } - 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' }) + const action = page.getByRole('button', { name: 'Ouvrir le chat de cette synthèse' }) + const generate = page.getByRole('button', { name: 'Générer une synthèse' }) 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 expect(action).toHaveAttribute('title', 'Ouvrir le chat de cette synthèse') + expect(await action.evaluate(element => element.parentElement.nextElementSibling === [...element.parentElement.parentElement.querySelectorAll('button')].find(button => button.textContent.includes('Générer')))).toBe(true) + const actionBox = await action.boundingBox() + const generateBox = await generate.boundingBox() + 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() 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(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) - 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.' }) + const question = dialog.getByRole('textbox', { name: 'Votre question' }) + 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é.' }) + const add = dialog.getByRole('button', { name: 'Ajouter le passage sélectionné à la question' }) + await expect(dialog.getByRole('heading')).toBeFocused() + await expect(question).toHaveValue('') + await expect(add).toHaveCount(0) + expect(questions).toHaveLength(0) await expect(webSearch).toBeChecked() 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 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 selectText(page.getByText(secondExcerpt, { exact: true })) await action.click() await expect(question).toHaveValue('Que signifie ce passage ?') - await expect(webSearch).not.toBeChecked() - // Keyboard navigation stays inside the modal, including after a smaller viewport. + await expect(dialog.getByLabel('Passage joint', { exact: true })).toHaveText(excerpt) + 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 }) const box = await dialog.boundingBox() 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') 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: 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() + await dialog.getByRole('button', { name: 'Envoyer la question' }).click() + await expect(dialog.getByText('Réponse avec recherche simulée.', { exact: true })).toBeVisible() 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) - 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('target', '_blank') 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) - await page.getByRole('button', { name: 'Fermer', exact: true }).click() - await expect(page.getByRole('button', { name: 'Interroger ce passage' })).toBeFocused() - await page.getByRole('button', { name: 'Interroger ce passage' }).click() - await expect(page.getByText('Réponse sur cette synthèse.', { exact: true })).toBeVisible() + await add.click() + await question.fill('Brouillon non envoyé') + await webSearch.uncheck() + 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() }) diff --git a/frontend/src/api/summaryQA.ts b/frontend/src/api/summaryQA.ts index fde0071..bc4588b 100644 --- a/frontend/src/api/summaryQA.ts +++ b/frontend/src/api/summaryQA.ts @@ -1,6 +1,12 @@ 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 { id: string web_search_performed: boolean diff --git a/frontend/src/components/SummaryQA.tsx b/frontend/src/components/SummaryQA.tsx index d0eb9f0..ae5d383 100644 --- a/frontend/src/components/SummaryQA.tsx +++ b/frontend/src/components/SummaryQA.tsx @@ -1,4 +1,6 @@ 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 { summaryQAApi, type QAConversation, type QAQuestion, type QATurn } from '@/api/summaryQA' import { ApiError } from '@/api/client' @@ -44,11 +46,26 @@ function Citations({ turn }: { turn: QATurn }) { } -// Reset all transient selection/draft/request state when the displayed summary changes. -export function SummaryQA(props: { summaryId: string; content: string }) { +// Dashboard keeps these snapshots only for the lifetime of the page. +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 } -function Conversation({ summaryId, content }: { summaryId: string; content: string }) { +function Conversation({ summaryId, content, launcherHost, initialDraft, onDraftChange }: SummaryQAProps) { const id = useId() const text = useRef(null) const title = useRef(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 alive = useRef(true) const pending = useRef(false) - const request = useRef(null) + const request = useRef(initialDraft?.request ?? null) + const draftVersion = useRef(initialDraft?.draftVersion ?? 0) + const requestVersion = useRef(initialDraft?.requestVersion ?? 0) const [selection, setSelection] = useState('') - const [passage, setPassage] = useState('') - const [question, setQuestion] = useState('') - const [useWebSearch, setUseWebSearch] = useState(true) + const [passage, setPassage] = useState(initialDraft?.passage ?? '') + const [question, setQuestion] = useState(initialDraft?.question ?? '') + const [useWebSearch, setUseWebSearch] = useState(initialDraft?.useWebSearch ?? true) const [open, setOpen] = useState(false) const [conversation, setConversation] = useState(null) const [needsSync, setNeedsSync] = useState(false) @@ -69,6 +88,15 @@ function Conversation({ summaryId, content }: { summaryId: string; content: stri const [error, setError] = 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(() => { alive.current = true const observe = () => { @@ -76,13 +104,22 @@ function Conversation({ summaryId, content }: { summaryId: string; content: stri if (!selected || selected.isCollapsed) return if (text.current?.contains(selected.anchorNode) && text.current.contains(selected.focusNode)) { 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) 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() { setLoading(true); setError('') try { @@ -90,7 +127,7 @@ function Conversation({ summaryId, content }: { summaryId: string; content: stri if (alive.current) { setConversation(value); setNeedsSync(false) 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 } } 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 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); setValidation('') } if (!conversation && !loading) void load() } setOpen(value) @@ -117,19 +153,20 @@ function Conversation({ summaryId, content }: { summaryId: string; content: stri async function ask(event: FormEvent) { event.preventDefault() 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) { - setValidation('Sélectionnez un passage de 1 à 8 000 caractères et saisissez une question de 1 à 4 000 caractères.'); return + if (!question.trim() || [...passage].length > 8000 || [...question].length > 4000) { + 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 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 + requestVersion.current = draftVersion.current pending.current = true; setSending(true); setError(''); setValidation('') try { const turn = await summaryQAApi.ask(summaryId, body) 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) - 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 } } catch (error) { if (alive.current) { @@ -141,12 +178,15 @@ function Conversation({ summaryId, content }: { summaryId: string; content: stri } finally { pending.current = false; if (alive.current) setSending(false) } } const busy = conversation?.messages.some(turn => turn.status === 'pending') + const launcher = + + return
- {selection && - - } + {launcherHost === undefined ? launcher : launcherHost ? createPortal(launcher, launcherHost) : null} -
+
Questions sur cette synthèse
-
-

Passage à interroger

-
{passage}
-
{loading &&

Chargement de la conversation…

} {error &&

{error}

} {conversation && <> -
+
{conversation.messages.length === 0 &&

Aucune question pour cette synthèse.

} - {conversation.messages.map(turn =>
-
{turn.passage}
-

Votre question : {turn.question}

- {turn.status === 'answered' && <>} - {turn.status === 'pending' &&

Réponse en cours…

} - {turn.status === 'failed' &&

{errorMessage(new ApiError(turn.failure_code ?? 'qa_provider_failed', 502))}

} -
)} + {conversation.messages.map(turn =>
+
+

Vous

+ {turn.passage &&
{turn.passage}
} +

{turn.question}

+
+
+

Assistant

+ {turn.status === 'answered' && <>} + {turn.status === 'pending' &&

Réponse en cours…

} + {turn.status === 'failed' &&

{errorMessage(new ApiError(turn.failure_code ?? 'qa_provider_failed', 502))}

} +
+
)}
+ {selection && selection !== passage && } + {passage &&
+

Passage joint

+
{passage}
+ +
} -