feat(ui): add web citations to synthesis Q&A (#61)
This commit is contained in:
@ -1,7 +1,7 @@
|
||||
import { expect, test } from '@playwright/test'
|
||||
import { readStackManifest } from './stack-manifest.mjs'
|
||||
|
||||
for (const width of [1280, 375]) test(`ticket #57: simplified modal Q&A remains accessible at ${width}px`, async ({ page }) => {
|
||||
for (const width of [1280, 375]) test(`ticket #61: web search choice and citations remain accessible at ${width}px`, async ({ page }) => {
|
||||
const stack = readStackManifest()
|
||||
await page.setViewportSize({ width, height: 850 })
|
||||
await page.context().route('**/*', route => {
|
||||
@ -10,7 +10,7 @@ for (const width of [1280, 375]) test(`ticket #57: simplified modal Q&A remains
|
||||
})
|
||||
const excerpt = 'Passage de la synthèse pour poser une question. '.repeat(12).trim()
|
||||
const summary = { id: '00000000-0000-0000-0000-000000005401', user_id: 'reader', content: excerpt + '\n\n' + Array.from({ length: 30 }, (_, i) => `Contexte ${i}. ` + 'Texte de contexte. '.repeat(20)).join('\n'), ai_provider_id: null, generated_at: '2026-11-25T00:00:00Z' }
|
||||
const conversation = { id: 'c', summary_id: summary.id, mode: 'stateless', uses_source_articles: false, provider_session_supported: false, source_expires_at: '2026-01-01T00:00:00Z', sources_expired: true, source_count: 0, messages: [] }
|
||||
const 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 questions = []
|
||||
await page.route('**/api/**', async route => {
|
||||
const path = new URL(route.request().url()).pathname
|
||||
@ -22,7 +22,7 @@ for (const width of [1280, 375]) test(`ticket #57: simplified modal Q&A remains
|
||||
if (path === `/api/summaries/${summary.id}/conversation/messages`) {
|
||||
const question = route.request().postDataJSON()
|
||||
questions.push(question)
|
||||
const turn = { ...question, id: 't', answer: 'Réponse sur cette synthèse.', status: 'answered', replayed: false, created_at: '2026-11-25T00:00:00Z' }
|
||||
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)
|
||||
}
|
||||
@ -66,6 +66,9 @@ for (const width of [1280, 375]) test(`ticket #57: simplified modal Q&A remains
|
||||
|
||||
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.' })
|
||||
await expect(webSearch).toBeChecked()
|
||||
await webSearch.uncheck()
|
||||
await question.fill('Que signifie ce passage ?')
|
||||
await page.keyboard.press('Escape')
|
||||
await expect(dialog).toHaveCount(0)
|
||||
@ -73,6 +76,7 @@ for (const width of [1280, 375]) test(`ticket #57: simplified modal Q&A remains
|
||||
expect(await page.locator('main').evaluate(element => element.scrollTop)).toBe(beforeScroll)
|
||||
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 page.setViewportSize({ width, height: 450 })
|
||||
const box = await dialog.boundingBox()
|
||||
@ -85,7 +89,21 @@ for (const width of [1280, 375]) test(`ticket #57: simplified modal Q&A remains
|
||||
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 ?', request_id: expect.stringMatching(/^[a-f0-9-]{36}$/) })
|
||||
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[1].use_web_search).toBe(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(source).toHaveAttribute('href', 'https://example.test/source')
|
||||
await expect(source).toHaveAttribute('target', '_blank')
|
||||
await expect(source).toHaveAttribute('rel', 'noopener noreferrer')
|
||||
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()
|
||||
|
||||
@ -1,8 +1,10 @@
|
||||
import { api } from './client'
|
||||
|
||||
export interface QAQuestion { request_id: string; passage: string; question: string }
|
||||
export interface QAQuestion { request_id: string; passage: string; question: string; use_web_search: boolean }
|
||||
export interface QATurn extends QAQuestion {
|
||||
id: string
|
||||
web_search_performed: boolean
|
||||
citations: { title: string; url: string }[]
|
||||
answer: string
|
||||
status: 'pending' | 'answered' | 'failed'
|
||||
failure_code?: string
|
||||
@ -12,6 +14,7 @@ export interface QATurn extends QAQuestion {
|
||||
export interface QAConversation {
|
||||
id: string
|
||||
summary_id: string
|
||||
web_search_supported: boolean
|
||||
mode: string
|
||||
uses_source_articles: boolean
|
||||
provider_session_supported: boolean
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import * as Dialog from '@radix-ui/react-dialog'
|
||||
import { useEffect, useId, useRef, useState, type FormEvent } from 'react'
|
||||
import { summaryQAApi, type QAConversation, type QAQuestion } from '@/api/summaryQA'
|
||||
import { summaryQAApi, type QAConversation, type QAQuestion, type QATurn } from '@/api/summaryQA'
|
||||
import { ApiError } from '@/api/client'
|
||||
import { Markdown } from '@/components/ui/markdown'
|
||||
import { Button } from '@/components/ui/button'
|
||||
@ -27,6 +27,23 @@ function errorMessage(error: unknown) {
|
||||
}
|
||||
}
|
||||
|
||||
// Links come exclusively from structured backend citations, never answer text.
|
||||
function Citations({ turn }: { turn: QATurn }) {
|
||||
const citations = (turn.citations ?? []).flatMap(citation => {
|
||||
try {
|
||||
const url = new URL(citation.url)
|
||||
if (url.protocol !== 'https:' || url.username || url.password) return []
|
||||
return [{ url: url.href, title: citation.title.trim() || url.hostname }]
|
||||
} catch { return [] }
|
||||
})
|
||||
if (!turn.web_search_performed || citations.length === 0) return null
|
||||
return <ul aria-label="Sources de la réponse" className="space-y-1 text-sm min-w-0">
|
||||
{citations.map((citation, index) => <li key={`${citation.url}-${index}`}>
|
||||
<a href={citation.url} target="_blank" rel="noopener noreferrer" className="underline break-words [overflow-wrap:anywhere]" aria-label={`${citation.title} (nouvel onglet)`}>{citation.title}</a>
|
||||
</li>)}
|
||||
</ul>
|
||||
}
|
||||
|
||||
// Reset all transient selection/draft/request state when the displayed summary changes.
|
||||
export function SummaryQA(props: { summaryId: string; content: string }) {
|
||||
return <Conversation key={props.summaryId} {...props} />
|
||||
@ -43,6 +60,7 @@ function Conversation({ summaryId, content }: { summaryId: string; content: stri
|
||||
const [selection, setSelection] = useState('')
|
||||
const [passage, setPassage] = useState('')
|
||||
const [question, setQuestion] = useState('')
|
||||
const [useWebSearch, setUseWebSearch] = useState(true)
|
||||
const [open, setOpen] = useState(false)
|
||||
const [conversation, setConversation] = useState<QAConversation | null>(null)
|
||||
const [needsSync, setNeedsSync] = useState(false)
|
||||
@ -69,7 +87,12 @@ function Conversation({ summaryId, content }: { summaryId: string; content: stri
|
||||
setLoading(true); setError('')
|
||||
try {
|
||||
const value = await summaryQAApi.get(summaryId)
|
||||
if (alive.current) { setConversation(value); setNeedsSync(false) }
|
||||
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 }
|
||||
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.') } }
|
||||
finally { if (alive.current) setLoading(false) }
|
||||
}
|
||||
@ -97,15 +120,16 @@ function Conversation({ summaryId, content }: { summaryId: string; content: stri
|
||||
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
|
||||
}
|
||||
const use_web_search = conversation.web_search_supported === true && useWebSearch
|
||||
const previous = request.current
|
||||
const body = previous?.passage === passage && previous.question === question ? previous : { request_id: crypto.randomUUID(), passage, question }
|
||||
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 }
|
||||
request.current = body
|
||||
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(''); request.current = null }
|
||||
if (turn.status === 'answered') { setQuestion(''); setUseWebSearch(true); request.current = null }
|
||||
else if (turn.status === 'failed') { setError(errorMessage(new ApiError(turn.failure_code ?? 'qa_provider_failed', 502))); request.current = null }
|
||||
} catch (error) {
|
||||
if (alive.current) {
|
||||
@ -152,7 +176,7 @@ function Conversation({ summaryId, content }: { summaryId: string; content: stri
|
||||
{conversation.messages.map(turn => <article key={turn.id} className="space-y-2 rounded-md bg-muted p-3 min-w-0">
|
||||
<blockquote className="whitespace-pre-wrap border-l-2 pl-3">{turn.passage}</blockquote>
|
||||
<p className="whitespace-pre-wrap"><strong>Votre question : </strong>{turn.question}</p>
|
||||
{turn.status === 'answered' && <Markdown content={turn.answer} />}
|
||||
{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>)}
|
||||
@ -161,6 +185,12 @@ function Conversation({ summaryId, content }: { summaryId: string; content: stri
|
||||
<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('') }} />
|
||||
<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`}>
|
||||
<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)} />
|
||||
<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.'
|
||||
: 'La recherche Web n’est pas disponible avec le modèle de cette synthèse.'}</span>
|
||||
</label>}
|
||||
{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>
|
||||
</form>
|
||||
|
||||
94
frontend/tests/summary-qa-ticket61.test.tsx
Normal file
94
frontend/tests/summary-qa-ticket61.test.tsx
Normal file
@ -0,0 +1,94 @@
|
||||
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
|
||||
import { SummaryQA } from '../src/components/SummaryQA'
|
||||
const { get, ask } = vi.hoisted(() => ({ get: vi.fn(), ask: vi.fn() }))
|
||||
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 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 answered = { id: 't', status: 'answered', answer: 'Réponse', citations: [], web_search_performed: false }
|
||||
async function open() {
|
||||
render(<SummaryQA summaryId="s" content="Passage sélectionnable" />)
|
||||
const range = document.createRange(); range.selectNodeContents(screen.getByText('Passage sélectionnable'))
|
||||
window.getSelection()!.removeAllRanges(); window.getSelection()!.addRange(range)
|
||||
fireEvent(document, new Event('selectionchange'))
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Interroger ce passage' }))
|
||||
}
|
||||
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('attend la capacité avant de présenter une case native cochée', async () => {
|
||||
let resolve!: (value: unknown) => void
|
||||
get.mockImplementationOnce(() => new Promise(r => { resolve = r }))
|
||||
await open()
|
||||
expect(screen.queryByRole('checkbox')).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('form')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText(unavailable)).not.toBeInTheDocument()
|
||||
await act(async () => resolve(conversation))
|
||||
const checkbox = await screen.findByRole('checkbox', { name: label })
|
||||
expect(checkbox.tagName).toBe('INPUT'); expect(checkbox).toBeChecked()
|
||||
})
|
||||
it('envoie false pour un modèle incompatible mais permet la question classique', async () => {
|
||||
get.mockResolvedValue({ ...conversation, web_search_supported: false })
|
||||
await open()
|
||||
const checkbox = await screen.findByRole('checkbox', { name: unavailable })
|
||||
expect(checkbox).toBeDisabled(); expect(checkbox).not.toBeChecked()
|
||||
await userEvent.type(screen.getByRole('textbox'), 'Pourquoi ?'); await send()
|
||||
expect(ask.mock.calls[0][1].use_web_search).toBe(false)
|
||||
})
|
||||
it('conserve choix fermé et après erreur, rejoue le même UUID puis change UUID si option modifiée', async () => {
|
||||
ask.mockRejectedValue(new Error('network'))
|
||||
await open(); await userEvent.click(await screen.findByRole('checkbox', { name: label }))
|
||||
await userEvent.type(screen.getByRole('textbox'), 'Pourquoi ?')
|
||||
await userEvent.keyboard('{Escape}')
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Interroger ce passage' }))
|
||||
expect(screen.getByRole('checkbox')).not.toBeChecked()
|
||||
await send(); await screen.findByRole('alert')
|
||||
const first = ask.mock.calls[0][1]; expect(first.use_web_search).toBe(false)
|
||||
await send(); await screen.findByRole('alert'); expect(ask.mock.calls[1][1]).toEqual(first)
|
||||
await userEvent.click(screen.getByRole('checkbox')); await send(); await screen.findByRole('alert')
|
||||
expect(ask.mock.calls[2][1]).toEqual({ ...first, request_id: expect.any(String), use_web_search: true })
|
||||
expect(ask.mock.calls[2][1].request_id).not.toBe(first.request_id)
|
||||
})
|
||||
it('désactive pendant envoi et réinitialise après réponse', async () => {
|
||||
let resolve!: (value: unknown) => void
|
||||
ask.mockImplementationOnce(() => new Promise(r => { resolve = r }))
|
||||
await open(); await userEvent.click(await screen.findByRole('checkbox'))
|
||||
await userEvent.type(screen.getByRole('textbox'), 'Pourquoi ?'); await send()
|
||||
expect(screen.getByRole('checkbox')).toBeDisabled()
|
||||
await act(async () => resolve({ ...ask.mock.calls[0][1], ...answered }))
|
||||
expect(screen.getByRole('checkbox')).toBeChecked(); expect(screen.getByRole('checkbox')).toBeEnabled()
|
||||
expect(screen.getByRole('textbox')).toHaveValue('')
|
||||
})
|
||||
it('réinitialise aussi après polling de sa propre demande', async () => {
|
||||
ask.mockImplementationOnce(async (_id, body) => ({ ...body, ...answered, status: 'pending' }))
|
||||
await open(); await userEvent.click(await screen.findByRole('checkbox'))
|
||||
await userEvent.type(screen.getByRole('textbox'), 'Pourquoi ?'); await send()
|
||||
expect(screen.getByRole('checkbox')).toBeDisabled()
|
||||
get.mockResolvedValue({ ...conversation, messages: [{ ...ask.mock.calls[0][1], ...answered }] })
|
||||
await waitFor(() => expect(screen.getByRole('textbox')).toHaveValue(''), { timeout: 4500 })
|
||||
expect(screen.getByRole('checkbox')).toBeChecked()
|
||||
})
|
||||
it('affiche seulement citations DTO HTTPS avec titre ou hostname et nouvel onglet annoncé', async () => {
|
||||
get.mockResolvedValue({ ...conversation, messages: [{ ...answered, passage: 'Extrait', question: 'Question', web_search_performed: true, answer: '[Faux lien](https://model.invalid) https://raw.invalid', citations: [
|
||||
{ title: 'Source fiable', url: 'https://example.com/article' }, { title: '', url: 'https://fallback.example/path' },
|
||||
{ title: 'HTTP', url: 'http://unsafe.example' }, { title: 'Script', url: 'javascript:alert(1)' }, { title: 'Invalide', url: 'not a url' },
|
||||
] }] })
|
||||
await open()
|
||||
const link = await screen.findByRole('link', { name: 'Source fiable (nouvel onglet)' })
|
||||
expect(link).toHaveAttribute('href', 'https://example.com/article')
|
||||
expect(link).toHaveAttribute('target', '_blank'); expect(link).toHaveAttribute('rel', 'noopener noreferrer')
|
||||
expect(screen.getByRole('link', { name: 'fallback.example (nouvel onglet)' })).toBeInTheDocument()
|
||||
expect(screen.getAllByRole('link')).toHaveLength(2)
|
||||
})
|
||||
it.each([undefined, [], [{ title: 'Interdit', url: 'http://unsafe.example' }]])('aucun panneau vide ni lien pour citations absentes ou invalides %s', async citations => {
|
||||
get.mockResolvedValue({ ...conversation, messages: [{ ...answered, passage: 'Extrait', question: 'Question', citations, web_search_performed: true }] })
|
||||
await open(); await screen.findByRole('textbox')
|
||||
expect(screen.queryByRole('link')).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('list', { name: 'Sources de la réponse' })).not.toBeInTheDocument()
|
||||
})
|
||||
Reference in New Issue
Block a user