feat(qa): add synthesis conversations with source retention (#52)

This commit is contained in:
2026-11-25 19:46:06 +01:00
parent 90dd2a65d2
commit 287811184f
49 changed files with 2636 additions and 47 deletions

View File

@ -0,0 +1,63 @@
import { expect, test } from '@playwright/test'
import { readStackManifest } from './stack-manifest.mjs'
for (const width of [1280, 375]) test(`ticket #54: passage and Q&A remain accessible at ${width}px`, async ({ page }) => {
const stack = readStackManifest()
await page.setViewportSize({ width, height: 850 })
await page.context().route('**/*', route => {
const host = new URL(route.request().url()).hostname
return host === '127.0.0.1' || host === '[::1]' ? route.continue() : route.abort('blockedbyclient')
})
const summary = { id: '00000000-0000-0000-0000-000000005401', user_id: 'reader', content: 'Passage de la synthèse pour poser une question.', ai_provider_id: null, generated_at: '2026-11-25T00:00:00Z' }
const conversation = { id: 'c', summary_id: summary.id, mode: 'stateless', uses_source_articles: false, provider_session_supported: false, source_expires_at: '2026-01-01T00:00:00Z', sources_expired: true, source_count: 0, messages: [] }
const questions = []
await page.route('**/api/**', async route => {
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/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', answer: 'Réponse 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()
})
await page.goto(new URL('/login', stack.frontendUrl).href)
await page.getByLabel('Adresse email').fill(stack.bootstrapAdmin.email)
await page.getByLabel('Mot de passe').fill(stack.bootstrapAdmin.password)
await page.getByRole('button', { name: 'Se connecter' }).click()
const passage = page.getByText(summary.content, { exact: true })
await expect(passage).toBeVisible()
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)
await page.getByRole('button', { name: 'Interroger ce passage' }).click()
const question = page.getByRole('textbox', { name: 'Votre question' })
await expect(question).toBeFocused()
await expect(page.getByText(/Les sources ont expiré/)).toBeVisible()
await question.fill('Que signifie ce passage ?')
await page.getByRole('button', { name: 'Envoyer la question' }).click()
await expect(page.getByText('Réponse sur cette synthèse.', { exact: true })).toBeVisible()
expect(questions).toHaveLength(1)
expect(questions[0]).toMatchObject({ passage: summary.content, question: 'Que signifie ce passage ?', request_id: expect.stringMatching(/^[a-f0-9-]{36}$/) })
expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true)
await page.getByRole('button', { name: 'Retour à la synthèse' }).click()
await expect(page.getByRole('button', { name: 'Interroger ce passage' })).toBeFocused()
await page.getByRole('button', { name: 'Questions sur cette synthèse' }).click()
await expect(page.getByText('Réponse sur cette synthèse.', { exact: true })).toBeVisible()
})

View File

@ -1,12 +1,27 @@
const BASE = '/api'
export class ApiError extends Error {
constructor(message: string, public readonly status: number) {
constructor(message: string, public readonly status: number, public readonly retryAfterSeconds?: number) {
super(message)
this.name = 'ApiError'
}
}
// Expose only a validated delay, never the raw server header.
function retryAfterSeconds(header: string | null): number | undefined {
if (header === null) return undefined
const value = header.trim()
if (/^[0-9]+$/.test(value)) {
const seconds = Number(value)
return Number.isSafeInteger(seconds) ? seconds : undefined
}
// HTTP-date (IMF-fixdate); reject permissive Date.parse inputs and invalid dates.
if (!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), [0-9]{2} (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) [0-9]{4} [0-9]{2}:[0-9]{2}:[0-9]{2} GMT$/.test(value)) return undefined
const date = new Date(value)
if (!Number.isFinite(date.getTime()) || date.toUTCString() !== value) return undefined
return Math.max(0, Math.ceil((date.getTime() - Date.now()) / 1000))
}
function getToken() {
return localStorage.getItem('token')
}
@ -29,7 +44,7 @@ async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
}
if (!res.ok) {
const err = await res.json().catch(() => ({ error: res.statusText }))
throw new ApiError(err.error || res.statusText, res.status)
throw new ApiError(err.error || res.statusText, res.status, retryAfterSeconds(res.headers.get('Retry-After')))
}
if (res.status === 204) return undefined as T
const json = await res.json()

View File

@ -10,6 +10,7 @@ export interface PromptCapacity {
export interface SummaryModelOption { id: string; provider: string; model: string; label?: string; prompt_capacity?: PromptCapacity | null }
export interface UserPreferences {
source_article_retention_days?: number
summary_prompt_token_budget?: number
ranking_model_id?: string | null
summary_model_id?: string | null

View File

@ -0,0 +1,27 @@
import { api } from './client'
export interface QAQuestion { request_id: string; passage: string; question: string }
export interface QATurn extends QAQuestion {
id: string
answer: string
status: 'pending' | 'answered' | 'failed'
failure_code?: string
created_at: string
replayed: boolean
}
export interface QAConversation {
id: string
summary_id: string
mode: string
uses_source_articles: boolean
provider_session_supported: boolean
source_expires_at: string
sources_expired: boolean
source_count: number
messages: QATurn[]
}
const path = (id: string) => `/summaries/${encodeURIComponent(id)}/conversation`
export const summaryQAApi = {
get: (id: string) => api.get<QAConversation>(path(id)),
ask: (id: string, question: QAQuestion) => api.post<QATurn>(`${path(id)}/messages`, question),
}

View File

@ -83,7 +83,7 @@ export function GenerationDetails({ outcome }: { outcome: GenerationOutcome }) {
))}</tbody>
</table>
</div>
<p className="text-sm text-muted-foreground">Les articles sont utilisés temporairement pour la génération. Seuls la synthèse et le bilan agrégé sont conservés.</p>
<p className="text-sm text-muted-foreground">Les articles sources sont conservés temporairement selon votre préférence (7 jours par défaut), à compter de la génération. Poser une question ne prolonge pas cette durée. La synthèse, le bilan agrégé et les échanges restent consultables.</p>
</details>
</section>
)

View File

@ -0,0 +1,171 @@
import { useEffect, useId, useRef, useState, type FormEvent } from 'react'
import { summaryQAApi, type QAConversation, type QAQuestion } from '@/api/summaryQA'
import { ApiError } from '@/api/client'
import { Markdown } from '@/components/ui/markdown'
import { Button } from '@/components/ui/button'
import { Label } from '@/components/ui/label'
function errorMessage(error: unknown) {
if (error instanceof ApiError && error.status === 429) {
const seconds = error.retryAfterSeconds
const timing = seconds !== undefined && Number.isSafeInteger(seconds) && seconds >= 0
? seconds === 0 ? 'Vous pouvez réessayer maintenant.' : `Réessayez dans ${seconds} ${seconds === 1 ? 'seconde' : 'secondes'}.`
: 'Réessayez dans quelques instants.'
return `Trop de questions en peu de temps. ${timing} Votre question est conservée.`
}
const code = error instanceof ApiError ? error.message : ''
switch (code) {
case 'qa_not_found': return 'Cette conversation n’est pas disponible pour cette synthèse.'
case 'qa_model_unavailable': return 'Le modèle de cette synthèse est indisponible. Contactez votre administrateur.'
case 'qa_context_limit': return 'La conversation a atteint sa limite de contexte. Aucune réponse supplémentaire ne peut être produite.'
case 'qa_invalid_request': return 'Vérifiez le passage (8 000 caractères maximum) et la question (4 000 caractères maximum).'
case 'qa_question_in_progress': return 'Une réponse est déjà en cours. Actualisez la conversation avant de réessayer.'
case 'qa_idempotency_conflict': return 'Cette demande a déjà été utilisée avec un autre contenu. Actualisez la conversation.'
case 'qa_provider_failed': return 'La réponse a échoué chez le fournisseur. Votre question est conservée ; vous pouvez réessayer.'
default: return 'Impossible de vérifier la réponse. Votre question est conservée. Réessayez pour vérifier la même demande.'
}
}
// 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} />
}
function Conversation({ summaryId, content }: { summaryId: string; content: string }) {
const id = useId()
const text = useRef<HTMLDivElement>(null)
const input = useRef<HTMLTextAreaElement>(null)
const returnButton = useRef<HTMLButtonElement>(null)
const position = useRef(0)
const alive = useRef(true)
const pending = useRef(false)
const request = useRef<QAQuestion | null>(null)
const [selection, setSelection] = useState('')
const [passage, setPassage] = useState('')
const [question, setQuestion] = useState('')
const [open, setOpen] = useState(false)
const [conversation, setConversation] = useState<QAConversation | null>(null)
const [deadlinePassed, setDeadlinePassed] = useState(false)
const [loading, setLoading] = useState(false)
const [sending, setSending] = useState(false)
const [error, setError] = useState('')
const [validation, setValidation] = useState('')
useEffect(() => {
alive.current = true
const observe = () => {
const selected = window.getSelection()
if (!selected || selected.isCollapsed) return
if (text.current?.contains(selected.anchorNode) && text.current.contains(selected.focusNode)) {
setSelection(selected.toString())
} else setSelection('')
}
document.addEventListener('selectionchange', observe)
return () => { alive.current = false; document.removeEventListener('selectionchange', observe) }
}, [])
async function load() {
setLoading(true); setError('')
try {
const value = await summaryQAApi.get(summaryId)
if (alive.current) { setConversation(value); setDeadlinePassed(Date.parse(value.source_expires_at) <= Date.now()) }
} catch (error) { if (alive.current) setError(errorMessage(error)) }
finally { if (alive.current) setLoading(false) }
}
useEffect(() => {
if (!open || !conversation?.messages.some(turn => turn.status === 'pending') || sending) return
const timer = setTimeout(() => { void load() }, 3000)
return () => clearTimeout(timer)
// Refresh persisted pending turns without issuing another question.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open, conversation, sending])
const loaded = !!conversation
useEffect(() => { if (open && passage && loaded) input.current?.focus() }, [open, passage, loaded])
useEffect(() => {
if (!conversation || conversation.sources_expired || deadlinePassed) return
let timer: ReturnType<typeof setTimeout>
const schedule = () => {
const remaining = Date.parse(conversation.source_expires_at) - Date.now()
if (remaining <= 0) { setDeadlinePassed(true); return }
timer = setTimeout(schedule, Math.min(2147483647, remaining))
}
schedule()
return () => clearTimeout(timer)
}, [conversation, deadlinePassed])
function show(withSelection: boolean) {
position.current = window.scrollY
if (withSelection) { setPassage(selection); setValidation('') }
setOpen(true)
if (!conversation) void load()
}
function close() {
setOpen(false)
returnButton.current?.focus({ preventScroll: true })
window.scrollTo({ top: position.current, behavior: 'instant' })
}
async function ask(event: FormEvent) {
event.preventDefault()
if (pending.current || !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
}
const previous = request.current
const body = previous?.passage === passage && previous.question === question ? previous : { request_id: crypto.randomUUID(), passage, question }
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 }
else if (turn.status === 'failed') { setError(errorMessage(new ApiError(turn.failure_code ?? 'qa_provider_failed', 502))); request.current = null }
} catch (error) {
if (alive.current) {
setError(errorMessage(error))
// Transport errors keep the UUID for a safe replay. Terminal server failures require a new attempt.
if (error instanceof ApiError && error.message !== 'qa_question_in_progress') request.current = null
}
} finally { pending.current = false; if (alive.current) setSending(false) }
}
const expired = conversation && (conversation.sources_expired || deadlinePassed)
const busy = conversation?.messages.some(turn => turn.status === 'pending')
return <div className="space-y-4 min-w-0">
<div ref={text} className="select-text"><Markdown content={content} /></div>
<p className="text-sm text-muted-foreground">Sélectionnez un passage normalement, puis utilisez « Interroger ce passage ». Les commandes du navigateur restent disponibles.</p>
<div className="flex flex-wrap gap-3">
<Button ref={returnButton} type="button" disabled={!selection.trim() || sending} onClick={() => show(true)} aria-controls={`${id}-panel`} aria-expanded={open}>Interroger ce passage</Button>
<Button type="button" variant="outline" onClick={() => show(false)} aria-controls={`${id}-panel`} aria-expanded={open}>Questions sur cette synthèse</Button>
</div>
{open && <section id={`${id}-panel`} aria-labelledby={`${id}-title`} className="space-y-4 border-t pt-4 min-w-0 break-words">
<div className="flex flex-wrap justify-between gap-3 items-center">
<h2 id={`${id}-title`} className="font-semibold">Questions sur cette synthèse</h2>
<Button type="button" variant="outline" onClick={close}>Retour à la synthèse</Button>
</div>
{loading && <p role="status">Chargement de la conversation…</p>}
{error && <p role="alert">{error}</p>}
<Button type="button" variant="outline" onClick={() => void load()} disabled={loading || sending}>Actualiser la conversation</Button>
{conversation && <>
<p className="text-sm text-muted-foreground">Les réponses utilisent la synthèse et les échanges précédents, sans articles sources ni session fournisseur réutilisée. Aucune économie de tokens n’est garantie.</p>
{expired ? <p role="status">Les sources ont expiré. La conversation et les questions restent disponibles avec la synthèse et les échanges uniquement.</p> : <p>Expiration des sources : {new Date(conversation.source_expires_at).toLocaleString('fr-FR')}. Poser une question ne prolonge pas cette durée.</p>}
<div className="space-y-4" 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.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 === '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>
<form onSubmit={ask} className="space-y-3" aria-label="Poser une question" aria-busy={sending}>
{passage ? <div><p className="text-sm font-medium">Passage à interroger</p><blockquote className="whitespace-pre-wrap border-l-2 pl-3 max-h-48 overflow-auto">{passage}</blockquote></div> : <p>Sélectionnez un passage dans la synthèse et utilisez « Interroger ce passage » pour poser une question.</p>}
<Label htmlFor={`${id}-question`}>Votre question</Label>
<textarea ref={input} id={`${id}-question`} className="w-full min-h-28 rounded-md border bg-transparent p-3 text-base" value={question} disabled={sending} aria-invalid={!!validation} aria-describedby={`${id}-help${validation ? ` ${id}-error` : ''}`} onChange={event => { setQuestion(event.target.value); setValidation('') }} />
<p id={`${id}-help`} className="text-sm text-muted-foreground">4 000 caractères maximum par question ; 8 000 par passage.</p>
{validation && <p id={`${id}-error`} role="alert">{validation}</p>}
<Button type="submit" disabled={sending || !!busy || !passage.trim()}>{sending ? 'Réponse en cours…' : 'Envoyer la question'}</Button>
</form>
</>}
</section>}
</div>
}

View File

@ -4,7 +4,7 @@ import { summariesApi, type Summary, type GenerationOutcome, type GenerationHist
import { preferencesApi, type UserPreferences, type SummaryModelOption } from '@/api/preferences'
import { assetsApi, type Asset } from '@/api/assets'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Markdown } from '@/components/ui/markdown'
import { SummaryQA } from '@/components/SummaryQA'
import { Button } from '@/components/ui/button'
import { Spinner } from '@/components/ui/spinner'
import { useAuth } from '@/lib/auth'
@ -12,10 +12,6 @@ import { generationCopy, generationLimitMessage, generationFailureMessage } from
// ── Summary content renderer ────────────────────────────────────────────────
function SummaryContent({ content }: { content: string }) {
return <Markdown content={content} />
}
function PromptBudgetRemoval({ outcome }: { outcome?: GenerationOutcome | null }) {
const count = outcome?.articles_removed_for_prompt_budget
if (!outcome || !Number.isSafeInteger(count) || !count || count < 1) return null
@ -210,7 +206,7 @@ export function Dashboard() {
</CardHeader>
<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>
<SummaryContent content={current.content} />
<SummaryQA summaryId={current.id} content={current.content} />
<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>
</Card>

View File

@ -15,13 +15,15 @@ export function Preferences() {
const [loading, setLoading] = useState(true)
const [saving, setSaving] = useState(false)
const [error, setError] = useState('')
const [retention, setRetention] = useState('7')
const [retentionError, setRetentionError] = useState('')
const [budget, setBudget] = useState('250000')
const [budgetError, setBudgetError] = useState('')
const [saved, setSaved] = useState(false)
const load = useCallback(() => {
return Promise.all([preferencesApi.get(), preferencesApi.listSummaryModels(), preferencesApi.listRankingModels()])
.then(([value, catalog, rankingCatalog]) => { setPreferences(value); setBudget(String(value.summary_prompt_token_budget ?? 250000)); setModels(catalog ?? []); setRankingModels(rankingCatalog ?? []) })
.then(([value, catalog, rankingCatalog]) => { setPreferences(value); setRetention(String(value.source_article_retention_days ?? 7)); setBudget(String(value.summary_prompt_token_budget ?? 250000)); setModels(catalog ?? []); setRankingModels(rankingCatalog ?? []) })
.catch(() => setError('Impossible de charger vos préférences. Réessayez.'))
.finally(() => setLoading(false))
}, [])
@ -31,6 +33,11 @@ export function Preferences() {
async function save(event: FormEvent) {
event.preventDefault()
if (!preferences || saving) return
const days = Number(retention)
if (!retention.trim() || !Number.isInteger(days) || days < 1 || days > 30) {
setRetentionError('Saisissez un nombre entier entre 1 et 30 jours.'); setSaved(false); return
}
setRetentionError('')
const tokens = Number(budget)
if (!budget.trim() || !Number.isInteger(tokens) || tokens < 1 || tokens > 2000000) {
setBudgetError('Saisissez un entier entre 1 et 2 000 000 tokens.'); setSaved(false); return
@ -38,10 +45,12 @@ export function Preferences() {
setBudgetError('')
setSaving(true); setError(''); setSaved(false)
try {
setPreferences(await preferencesApi.update({ ...preferences, summary_prompt_token_budget: tokens }))
setPreferences(await preferencesApi.update({ ...preferences, summary_prompt_token_budget: tokens, source_article_retention_days: days }))
setSaved(true)
} catch (error) {
if (error instanceof ApiError && error.message === 'ranking_model_incompatible') {
if (error instanceof ApiError && error.message === 'invalid_source_article_retention_days') {
setRetentionError('Saisissez un nombre entier entre 1 et 30 jours.')
} else if (error instanceof ApiError && error.message === 'ranking_model_incompatible') {
setError('Ce modèle est incompatible avec le classement : sa sortie JSON structurée n’est pas prise en charge. Choisissez un modèle compatible. Il reste disponible pour la synthèse. Vos choix sont conservés.')
} else if (error instanceof ApiError && error.message === 'ranking_model_unavailable') {
setError('Le modèle de classement sélectionné n’est plus disponible. Choisissez un autre modèle. Vos choix sont conservés.')
@ -114,6 +123,13 @@ export function Preferences() {
</Select>
<p id="ranking-help" className="text-sm text-muted-foreground">Laya utilise le titre et le contenu réellement disponible pour le classement. En mode titre et contenu, seuls les articles dont le corps complet est disponible peuvent alimenter la synthèse. Les contenus partiels et absents sont signalés dans le bilan ; aucune synthèse n’est générée si aucun contenu complet n’est disponible.</p>
</div>
<div className="space-y-1.5">
<Label htmlFor="preferences-retention">Conservation des articles sources (jours)</Label>
<Input id="preferences-retention" type="number" min={1} max={30} step={1} inputMode="numeric" value={retention} disabled={saving} aria-invalid={!!retentionError} aria-describedby={retentionError ? 'retention-help retention-error' : 'retention-help'} onChange={event => { setRetention(event.target.value); setRetentionError(''); setSaved(false) }} />
<div className="flex flex-wrap gap-2">{[1, 7, 30].map(days => <Button key={days} type="button" variant="outline" disabled={saving} onClick={() => { setRetention(String(days)); setRetentionError(''); setSaved(false) }}>{days} {days === 1 ? 'jour' : 'jours'}</Button>)}</div>
<p id="retention-help" className="text-sm text-muted-foreground">De 1 à 30 jours, 7 par défaut, à compter de la génération. Une question ne prolonge pas la conservation. Réduire la durée peut avancer l’expiration des sources existantes ; l’augmenter ne restaure pas les sources supprimées. Les échanges restent consultables. Actuellement, les réponses utilisent la synthèse et les échanges uniquement, sans les articles sources.</p>
{retentionError && <p id="retention-error" role="alert">{retentionError}</p>}
</div>
<Button type="submit" disabled={saving}>{saving ? 'Enregistrement…' : 'Enregistrer'}</Button>
{saved && <p role="status">Préférences enregistrées.</p>}
</form>

View File

@ -38,6 +38,20 @@ describe('Mes préférences', () => {
updatePreferences.mockResolvedValue({ language: 'en', ranking_mode: 'title_content' })
})
it('configure la rétention 1–30 jours avec défaut 7 et refuse les valeurs hors limites', async () => {
render(<Preferences />)
const retention = await screen.findByLabelText('Conservation des articles sources (jours)')
expect(retention).toHaveValue(7)
await userEvent.clear(retention)
await userEvent.type(retention, '31')
await userEvent.click(screen.getByRole('button', { name: 'Enregistrer' }))
expect(retention).toHaveAttribute('aria-invalid', 'true')
expect(updatePreferences).not.toHaveBeenCalled()
await userEvent.clear(retention)
await userEvent.type(retention, '30')
await userEvent.click(screen.getByRole('button', { name: 'Enregistrer' }))
expect(updatePreferences).toHaveBeenCalledWith(expect.objectContaining({ source_article_retention_days: 30 }))
})
it('réserve le catalogue compatible au classement et garde le catalogue complet pour la synthèse', async () => {
listModels.mockResolvedValueOnce([{ id: 'summary-only', provider: 'Other', model: 'summary-only' }])
render(<Preferences />)
@ -105,6 +119,7 @@ describe('Mes préférences', () => {
language: 'en',
ranking_mode: 'title_content',
summary_prompt_token_budget: 250000,
source_article_retention_days: 7,
}))
})
it('charge les valeurs françaises et affiche les libellés et l’aide', async () => {
@ -129,7 +144,7 @@ describe('Mes préférences', () => {
await user.selectOptions(screen.getByLabelText(/informations utilisées par Laya/i), 'title')
await user.click(screen.getByRole('button', { name: 'Enregistrer' }))
expect(await screen.findByRole('status')).toHaveTextContent('Préférences enregistrées.')
expect(updatePreferences).toHaveBeenLastCalledWith({ language: 'fr', ranking_mode: 'title', summary_prompt_token_budget: 250000 })
expect(updatePreferences).toHaveBeenLastCalledWith({ language: 'fr', ranking_mode: 'title', summary_prompt_token_budget: 250000, source_article_retention_days: 7 })
view.unmount()
render(<Preferences />)
expect(await screen.findByLabelText(/langue/i)).toHaveValue('fr')

View File

@ -29,7 +29,7 @@ it('charge le budget et décrit sa portée sans capacité du modèle', async ()
expect(screen.queryByText(/Réserve de sortie/)).not.toBeInTheDocument()
expect(screen.queryByText(/taille estimée conservative/i)).not.toBeInTheDocument()
await userEvent.click(screen.getByRole('button', { name: 'Enregistrer' }))
expect(update).toHaveBeenCalledWith(preferences)
expect(update).toHaveBeenCalledWith({ ...preferences, source_article_retention_days: 7 })
})
it('utilise 250000 en absence de champ historique et sauvegarde une valeur personnalisée', async () => {
@ -74,7 +74,7 @@ it('conserve le catalogue et le budget en cas de rejet serveur sans diagnostic c
update.mockRejectedValueOnce(new ApiError('invalid_prompt_budget', 400))
await userEvent.click(screen.getByRole('button', { name: 'Enregistrer' }))
expect(screen.getByRole('alert')).toHaveTextContent(/entier entre 1 et 2\s?000\s?000 tokens/)
expect(screen.getByRole('spinbutton')).toHaveValue(250000)
expect(screen.getByRole('spinbutton', { name: 'Budget maximal du prompt de synthèse' })).toHaveValue(250000)
})
const outcome = {

View File

@ -49,7 +49,7 @@ describe('choix personnel du modèle de synthèse — ticket #14', () => {
expect(within(selector).getByRole('option', { name: 'Ollama · qwen-summary' })).toBeInTheDocument()
await user.selectOptions(selector, 'model-b')
await user.click(screen.getByRole('button', { name: 'Enregistrer' }))
expect(updatePreferences).toHaveBeenCalledWith({ language: 'fr', ranking_mode: 'title_content', summary_model_id: 'model-b', summary_prompt_token_budget: 250000 })
expect(updatePreferences).toHaveBeenCalledWith({ language: 'fr', ranking_mode: 'title_content', summary_model_id: 'model-b', summary_prompt_token_budget: 250000, source_article_retention_days: 7 })
expect(listSummaryModels).toHaveBeenCalledOnce()
})

View File

@ -0,0 +1,28 @@
import { afterEach, expect, it, vi } from 'vitest'
import { summaryQAApi } from '../src/api/summaryQA'
afterEach(() => { vi.unstubAllGlobals(); localStorage.clear() })
it('utilise les nouvelles routes owner-scoped et le DTO Question exact de #53', async () => {
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 question = { request_id: '00000000-0000-0000-0000-000000005401', passage: 'Passage', question: 'Pourquoi ?' }
const turn = { ...question, id: 't', 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 })))
vi.stubGlobal('fetch', fetchMock)
expect(await summaryQAApi.get('s')).toEqual(conversation)
expect(await summaryQAApi.ask('s', question)).toEqual(turn)
expect(fetchMock).toHaveBeenNthCalledWith(1, '/api/summaries/s/conversation', { headers: { 'Content-Type': 'application/json', Authorization: 'Bearer user-token' } })
expect(fetchMock).toHaveBeenNthCalledWith(2, '/api/summaries/s/conversation/messages', { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: 'Bearer user-token' }, body: JSON.stringify(question) })
})
it.each([
['45', 45], ['0', 0], [null, undefined], ['', undefined], ['-1', undefined], ['1.5', undefined],
['Infinity', undefined], ['999999999999999999999999', undefined], ['PRIVATE_HEADER', undefined],
['Wed, 25 Nov 2026 12:00:30 GMT', 30], ['Wed, 25 Nov 2026 11:59:00 GMT', 0],
])('capture Retry-After %s comme délai sûr %s', async (header, seconds) => {
vi.spyOn(Date, 'now').mockReturnValue(Date.parse('2026-11-25T12:00:00Z'))
try {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ error: 'qa_rate_limited' }), {
status: 429, headers: header === null ? {} : { 'Retry-After': header },
})))
await expect(summaryQAApi.get('s')).rejects.toMatchObject({ message: 'qa_rate_limited', status: 429, retryAfterSeconds: seconds })
} finally { vi.restoreAllMocks() }
})

View File

@ -0,0 +1,118 @@
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { SummaryQA } from '../src/components/SummaryQA'
import { ApiError } from '../src/api/client'
const { get, ask } = vi.hoisted(() => ({ get: vi.fn(), ask: vi.fn() }))
vi.mock('@/api/summaryQA', () => ({ summaryQAApi: { get, ask } }))
const conversation = { id: 'c', summary_id: 's', mode: 'stateless', uses_source_articles: false, provider_session_supported: false, source_expires_at: '2026-01-01T00:00:00Z', sources_expired: true, source_count: 0, messages: [] }
function selectPassage() {
const range = document.createRange()
range.selectNodeContents(screen.getByText('Un passage de synthèse.'))
window.getSelection()!.removeAllRanges()
window.getSelection()!.addRange(range)
fireEvent(document, new Event('selectionchange'))
}
beforeEach(() => { get.mockResolvedValue(conversation); ask.mockResolvedValue({ id: 't', request_id: 'r', passage: 'Un passage de synthèse.', question: 'Pourquoi ?', answer: 'Une réponse.', status: 'answered', created_at: '', replayed: false }) })
afterEach(() => { cleanup(); window.getSelection()?.removeAllRanges() })
it('préserve les événements natifs et le focus ; seule une action explicite ouvre la question', async () => {
render(<SummaryQA summaryId="s" content="Un passage de synthèse." />)
const text = screen.getByText('Un passage de synthèse.')
for (const type of ['contextmenu', 'selectstart', 'touchstart', 'copy']) expect(fireEvent(text, new Event(type, { bubbles: true, cancelable: true }))).toBe(true)
selectPassage()
expect(get).not.toHaveBeenCalled()
expect(screen.queryByRole('textbox')).not.toBeInTheDocument()
await userEvent.click(screen.getByRole('button', { name: 'Interroger ce passage' }))
const question = await screen.findByRole('textbox', { name: 'Votre question' })
expect(question).toHaveFocus()
expect(await screen.findByText(/Les sources ont expiré/)).toBeInTheDocument()
expect(screen.getByText(/sans articles sources ni session fournisseur réutilisée/)).toBeInTheDocument()
await userEvent.type(question, 'Pourquoi ?')
await userEvent.click(screen.getByRole('button', { name: 'Envoyer la question' }))
expect(await screen.findByText('Une réponse.')).toBeInTheDocument()
expect(ask).toHaveBeenCalledWith('s', expect.objectContaining({ passage: 'Un passage de synthèse.', question: 'Pourquoi ?', request_id: expect.stringMatching(/^[a-f0-9-]{36}$/) }))
})
it('reprend la conversation et efface les données temporaires au changement de synthèse', async () => {
get.mockResolvedValueOnce({ ...conversation, messages: [{ id: 'old', passage: 'Ancien extrait', question: 'Ancienne question', answer: 'Ancienne réponse', status: 'answered' }] })
const view = render(<SummaryQA summaryId="s" content="Un passage de synthèse." />)
await userEvent.click(screen.getByRole('button', { name: 'Questions sur cette synthèse' }))
expect(await screen.findByText('Ancienne réponse')).toBeInTheDocument()
selectPassage()
await userEvent.click(screen.getByRole('button', { name: 'Interroger ce passage' }))
await userEvent.type(screen.getByRole('textbox'), 'Brouillon')
view.rerender(<SummaryQA summaryId="other" content="Autre synthèse" />)
expect(screen.queryByText('Ancienne réponse')).not.toBeInTheDocument()
expect(screen.queryByRole('textbox')).not.toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Interroger ce passage' })).toBeDisabled()
})
it('explique le modèle indisponible en conservant la question', async () => {
ask.mockRejectedValueOnce(new ApiError('qa_model_unavailable', 409))
render(<SummaryQA summaryId="s" content="Un passage de synthèse." />)
selectPassage()
await userEvent.click(screen.getByRole('button', { name: 'Interroger ce passage' }))
await userEvent.type(await screen.findByRole('textbox'), 'Pourquoi ?')
await userEvent.click(screen.getByRole('button', { name: 'Envoyer la question' }))
expect(await screen.findByRole('alert')).toHaveTextContent(/modèle.*indisponible/)
expect(screen.getByRole('textbox')).toHaveValue('Pourquoi ?')
})
it('réutilise le request_id après une erreur réseau', async () => {
ask.mockRejectedValueOnce(new Error('network'))
render(<SummaryQA summaryId="s" content="Un passage de synthèse." />)
selectPassage()
await userEvent.click(screen.getByRole('button', { name: 'Interroger ce passage' }))
await userEvent.type(await screen.findByRole('textbox'), 'Pourquoi ?')
await userEvent.click(screen.getByRole('button', { name: 'Envoyer la question' }))
await screen.findByRole('alert')
const first = ask.mock.calls.at(-1)![1]
await userEvent.click(screen.getByRole('button', { name: 'Envoyer la question' }))
await waitFor(() => expect(ask.mock.calls.at(-1)![1]).toEqual(first))
})
it('bloque un second envoi pendant la réponse et annonce sa réception', async () => {
let finish!: (value: unknown) => void
ask.mockImplementationOnce(() => new Promise(resolve => { finish = resolve }))
render(<SummaryQA summaryId="s" content="Un passage de synthèse." />)
selectPassage()
await userEvent.click(screen.getByRole('button', { name: 'Interroger ce passage' }))
await userEvent.type(await screen.findByRole('textbox'), 'Pourquoi ?')
await userEvent.click(screen.getByRole('button', { name: 'Envoyer la question' }))
expect(screen.getByRole('button', { name: 'Réponse en cours…' })).toBeDisabled()
expect(screen.getByRole('textbox')).toBeDisabled()
expect(ask).toHaveBeenCalledTimes(1)
finish({ id: 't', request_id: 'r', passage: 'Un passage de synthèse.', question: 'Pourquoi ?', answer: 'Réponse terminale', status: 'answered' })
expect(await screen.findByRole('log')).toHaveTextContent('Réponse terminale')
})
it('reprend un chargement échoué sans afficher de détails techniques', async () => {
get.mockRejectedValueOnce(new ApiError('PRIVATE_PROVIDER_SECRET', 503))
render(<SummaryQA summaryId="s" content="Un passage de synthèse." />)
await userEvent.click(screen.getByRole('button', { name: 'Questions sur cette synthèse' }))
expect(await screen.findByRole('alert')).not.toHaveTextContent('PRIVATE_PROVIDER_SECRET')
await userEvent.click(screen.getByRole('button', { name: 'Actualiser la conversation' }))
expect(await screen.findByRole('textbox', { name: 'Votre question' })).toBeInTheDocument()
})
it('refuse les passages trop longs et les questions vides avant appel', async () => {
const content = 'a'.repeat(8001)
render(<SummaryQA summaryId="s" content={content} />)
const range = document.createRange()
range.selectNodeContents(screen.getByText(content))
window.getSelection()!.removeAllRanges()
window.getSelection()!.addRange(range)
fireEvent(document, new Event('selectionchange'))
await userEvent.click(screen.getByRole('button', { name: 'Interroger ce passage' }))
await screen.findByRole('textbox')
await userEvent.click(screen.getByRole('button', { name: 'Envoyer la question' }))
expect(screen.getByRole('textbox')).toHaveAttribute('aria-invalid', 'true')
expect(screen.getByRole('alert')).toHaveTextContent('8 000')
expect(ask).not.toHaveBeenCalled()
})
it.each([45, undefined])('explique le quota Q&A avec délai %s et conserve la question', async seconds => {
ask.mockRejectedValueOnce(Object.assign(new ApiError('qa_rate_limited', 429), { retryAfterSeconds: seconds }))
render(<SummaryQA summaryId="s" content="Un passage de synthèse." />)
selectPassage()
await userEvent.click(screen.getByRole('button', { name: 'Interroger ce passage' }))
await userEvent.type(await screen.findByRole('textbox'), 'Pourquoi ?')
await userEvent.click(screen.getByRole('button', { name: 'Envoyer la question' }))
const alert = await screen.findByRole('alert')
expect(alert).toHaveTextContent('Trop de questions en peu de temps.')
expect(alert).toHaveTextContent(seconds === undefined ? 'Réessayez dans quelques instants.' : 'Réessayez dans 45 secondes.')
expect(screen.getByRole('textbox')).toHaveValue('Pourquoi ?')
})