feat(generation): enforce prompt budget with whole article eviction (#47)
This commit is contained in:
@ -2,16 +2,13 @@ import { useState, useEffect, useRef, useCallback } from 'react'
|
||||
import { TrendingUp, Clock, Sparkles, Loader2 } from 'lucide-react'
|
||||
import { summariesApi, type Summary, type GenerationOutcome, type GenerationHistory, type GenerationJob } from '@/api/summaries'
|
||||
import { preferencesApi, type UserPreferences, type SummaryModelOption } from '@/api/preferences'
|
||||
import { GenerationDetails } from '@/components/GenerationDetails'
|
||||
import { assetsApi, type Asset } from '@/api/assets'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Markdown } from '@/components/ui/markdown'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Spinner } from '@/components/ui/spinner'
|
||||
import { useAuth } from '@/lib/auth'
|
||||
import { PromptCapacityDetails } from '@/components/PromptCapacityDetails'
|
||||
import { generationCopy, generationLimitMessage } from '@/i18n/generation'
|
||||
import { generationCopy, generationLimitMessage, generationFailureMessage } from '@/i18n/generation'
|
||||
|
||||
// ── Summary content renderer ────────────────────────────────────────────────
|
||||
|
||||
@ -19,6 +16,14 @@ 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
|
||||
return <p className="text-xs text-muted-foreground mt-1">{count === 1
|
||||
? '1 article ancien a été retiré pour respecter le plafond du prompt.'
|
||||
: `${count} articles parmi les plus anciens ont été retirés pour respecter le plafond du prompt.`}</p>
|
||||
}
|
||||
|
||||
// ── Dashboard ───────────────────────────────────────────────────────────────
|
||||
|
||||
export function Dashboard() {
|
||||
@ -33,10 +38,9 @@ export function Dashboard() {
|
||||
const [models, setModels] = useState<SummaryModelOption[]>([])
|
||||
const [preferences, setPreferences] = useState<UserPreferences | null>(null)
|
||||
const [history, setHistory] = useState<GenerationHistory[]>([])
|
||||
const [outcomeSummaryId, setOutcomeSummaryId] = useState<string | null>(null)
|
||||
const [outcome, setOutcome] = useState<GenerationOutcome | null>(null)
|
||||
const [message, setMessage] = useState('')
|
||||
const [failed, setFailed] = useState(false)
|
||||
const [failureCode, setFailureCode] = useState<string | undefined>()
|
||||
const [completedJob, setCompletedJob] = useState<GenerationJob | null>(null)
|
||||
const [loadError, setLoadError] = useState('')
|
||||
const requestPending = useRef(false)
|
||||
const jobRef = useRef<GenerationJob | null>(null)
|
||||
@ -74,12 +78,8 @@ export function Dashboard() {
|
||||
setUncertain(false)
|
||||
setGenerating(job?.status === 'running')
|
||||
setOutcome(job?.outcome ?? null)
|
||||
setFailed(job?.status === 'failed')
|
||||
setFailureCode(job?.outcome?.failure_code ?? job?.failure_code)
|
||||
setMessage(!job || job.status === 'running' ? '' : generationLimitMessage(job.outcome?.failure_code ?? job.failure_code) ?? (job.status === 'failed'
|
||||
? copy.failed
|
||||
: job.status === 'no_results' ? copy.empty
|
||||
: copy.succeeded))
|
||||
setOutcomeSummaryId(job?.summary_id ?? null)
|
||||
if (job?.status !== 'running') setCompletedJob(job)
|
||||
if (job && job.status !== 'running') await load()
|
||||
}
|
||||
const verify = async (accepted?: GenerationJob) => {
|
||||
@ -92,7 +92,7 @@ export function Dashboard() {
|
||||
? summariesApi.getJob(jobRef.current.id) : summariesApi.recentJob())
|
||||
if (!disposed) await apply(job)
|
||||
} catch {
|
||||
if (!disposed) { setUncertain(true); setGenerating(false); setMessage('') }
|
||||
if (!disposed) { setUncertain(true); setGenerating(false) }
|
||||
} finally {
|
||||
busy = false
|
||||
if (!disposed) {
|
||||
@ -102,7 +102,7 @@ export function Dashboard() {
|
||||
}
|
||||
}
|
||||
verifyRef.current = () => { void verify() }
|
||||
const visible = () => { if (document.visibilityState === 'visible') void verify() }
|
||||
const visible = () => { if (document.visibilityState === 'visible') { void load(); void verify() } }
|
||||
acceptRef.current = job => { void verify(job) }
|
||||
window.addEventListener('focus', visible)
|
||||
document.addEventListener('visibilitychange', visible)
|
||||
@ -119,7 +119,7 @@ export function Dashboard() {
|
||||
async function generate() {
|
||||
if (requestPending.current || generating || checking || uncertain || assets.length === 0 || !selectedModel) return
|
||||
requestPending.current = true
|
||||
setGenerating(true); setMessage(''); setFailed(false); setFailureCode(undefined); setOutcome(null)
|
||||
setGenerating(true); setOutcome(null)
|
||||
try {
|
||||
const job = await summariesApi.generate()
|
||||
requestPending.current = false
|
||||
@ -131,11 +131,26 @@ export function Dashboard() {
|
||||
}
|
||||
|
||||
const currentOutcome = history.find(item => item.summary_id === current?.id)?.outcome
|
||||
?? (current && outcomeSummaryId === current.id ? outcome : null)
|
||||
|
||||
const newestHistory = history[0]
|
||||
const historyIsNewer = newestHistory && (!completedJob ||
|
||||
Date.parse(newestHistory.created_at) > Date.parse(completedJob.finished_at ?? completedJob.created_at))
|
||||
const latest = historyIsNewer ? newestHistory.outcome : completedJob
|
||||
const latestOutcome = historyIsNewer ? newestHistory.outcome : completedJob?.outcome
|
||||
const latestSummaryId = historyIsNewer ? newestHistory.summary_id : completedJob?.summary_id
|
||||
const failureCode = latest?.failure_code ?? latestOutcome?.failure_code
|
||||
const failed = latest?.status === 'failed'
|
||||
const lastFailure = failed ? failureCode ?? '' : null
|
||||
const message = !latest || generating || uncertain ? '' : generationLimitMessage(failureCode)
|
||||
?? (latest.status === 'no_results' ? copy.empty : copy.succeeded)
|
||||
|
||||
const selectedModel = models.find(model => model.id === preferences?.summary_model_id)
|
||||
|
||||
return (
|
||||
<div className="p-4 md:p-6 space-y-6">
|
||||
{lastFailure !== null && <p role="alert">{generationFailureMessage(lastFailure)}</p>}
|
||||
{latestOutcome && latestSummaryId && latestSummaryId !== current?.id && <PromptBudgetRemoval outcome={latestOutcome} />}
|
||||
{/* Generating banner */}
|
||||
{generating && !uncertain && (
|
||||
<div role="status" className="flex items-center gap-3 rounded-md bg-primary/10 border border-primary/20 px-4 py-3 text-sm text-primary">
|
||||
@ -155,18 +170,10 @@ export function Dashboard() {
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
{preferences ? <p>Prochaine synthèse : {preferences.language === 'fr' ? 'Français' : 'English'} · Classement par {preferences.ranking_mode === 'title_content' ? 'titre et contenu disponible' : 'titre uniquement'}</p> : <p>Chargement des préférences…</p>}
|
||||
{selectedModel ? <p>Modèle de synthèse : {selectedModel.provider} · {selectedModel.model}</p> : <p>Aucun modèle de synthèse disponible sélectionné. Choisissez un modèle dans Mes préférences avant de générer.</p>}
|
||||
{preferences && <p>Budget souhaité : {(preferences.summary_prompt_token_budget ?? 250000).toLocaleString('fr-FR')} tokens par génération</p>}
|
||||
{preferences && <PromptCapacityDetails model={selectedModel} requested={preferences.summary_prompt_token_budget ?? 250000} />}
|
||||
<a href="/preferences" className="text-primary underline">Modifier mes préférences</a>
|
||||
</div>
|
||||
{loadError && <div role="alert"><p>{loadError}</p><Button onClick={() => void load()}>Recharger</Button></div>}
|
||||
{uncertain && <div role="status"><p>{copy.uncertain}</p><Button onClick={() => verifyRef.current()} disabled={checking}>{copy.verify}</Button></div>}
|
||||
{message && <p role={failed ? 'alert' : 'status'}>{message}</p>}
|
||||
{(failed || outcome?.status === 'no_results') && !['summary_capacity_unknown', 'summary_prompt_budget_exceeded'].includes(failureCode ?? '') && <Button onClick={generate} disabled={generating || checking || uncertain || !selectedModel || assets.length === 0}>{copy.retry}</Button>}
|
||||
{outcome && <GenerationDetails outcome={outcome} />}
|
||||
{message && !failed && <p role="status">{message}</p>}
|
||||
{(failed || latest?.status === 'no_results') && !['summary_capacity_unknown', 'summary_prompt_budget_exceeded'].includes(failureCode ?? '') && <Button onClick={generate} disabled={generating || checking || uncertain || !selectedModel || assets.length === 0}>{copy.retry}</Button>}
|
||||
|
||||
{assets.length === 0 && !loading && (
|
||||
<Card className="border-dashed">
|
||||
@ -179,14 +186,6 @@ export function Dashboard() {
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{assets.length > 0 && (
|
||||
<div aria-label="Indices actuellement suivis" className="flex flex-wrap gap-2">
|
||||
{assets.map(a => (
|
||||
<Badge key={a.id} variant="secondary"><span>{a.name}</span><span className="ml-2 font-mono">{a.symbol}</span></Badge>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Résumé actuel */}
|
||||
<div className="grid gap-6 lg:grid-cols-3">
|
||||
<div className="lg:col-span-2 space-y-4">
|
||||
@ -199,9 +198,12 @@ export function Dashboard() {
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Sparkles className="h-5 w-5 text-primary" /> Synthèse
|
||||
</CardTitle>
|
||||
<div className="flex items-center gap-1 text-xs text-muted-foreground">
|
||||
<Clock className="h-3 w-3" />
|
||||
{new Date(current.generated_at).toLocaleString('fr-FR')}
|
||||
<div>
|
||||
<div className="flex items-center gap-1 text-xs text-muted-foreground">
|
||||
<Clock className="h-3 w-3" />
|
||||
{new Date(current.generated_at).toLocaleString('fr-FR')}
|
||||
</div>
|
||||
<PromptBudgetRemoval outcome={currentOutcome} />
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
@ -223,9 +225,20 @@ export function Dashboard() {
|
||||
</div>
|
||||
|
||||
{/* Historique résumés */}
|
||||
{summaries.length > 1 && (
|
||||
{(summaries.length > 1 || history.some(item => !item.summary_id)) && (
|
||||
<div className="space-y-3">
|
||||
<h2 className="font-semibold text-sm text-muted-foreground uppercase tracking-wider">Historique</h2>
|
||||
{history.filter(item => !item.summary_id).map(item => (
|
||||
<Card key={item.id}>
|
||||
<CardContent className="py-3">
|
||||
<div className="text-xs text-muted-foreground">{new Date(item.created_at).toLocaleString('fr-FR')}</div>
|
||||
<PromptBudgetRemoval outcome={item.outcome} />
|
||||
<p className="text-sm">{item.outcome.status === 'failed'
|
||||
? generationFailureMessage(item.outcome.failure_code)
|
||||
: generationLimitMessage(item.outcome.failure_code) ?? copy.empty}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
{summaries.slice(1).map(s => (
|
||||
<Card
|
||||
key={s.id}
|
||||
@ -236,7 +249,8 @@ export function Dashboard() {
|
||||
<Clock className="h-3 w-3" />
|
||||
{new Date(s.generated_at).toLocaleString('fr-FR')}
|
||||
</div>
|
||||
<button className="text-sm text-left line-clamp-3" onClick={() => { setCurrent(s); setOutcome(null); setMessage('') }}>{s.content.slice(0, 120)}…</button>
|
||||
<PromptBudgetRemoval outcome={history.find(item => item.summary_id === s.id)?.outcome} />
|
||||
<button className="text-sm text-left line-clamp-3" onClick={() => { setCurrent(s) }}>{s.content.slice(0, 120)}…</button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
@ -244,7 +258,6 @@ export function Dashboard() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!outcome && currentOutcome && <GenerationDetails outcome={currentOutcome} />}
|
||||
|
||||
</div>
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user