feat(ai): add personal summary models and retire Q&A
Add an admin-managed provider model catalog with per-user summary selection, migration backfill, and generation snapshots. Retire report creation and messaging while preserving owner-scoped history. Refs #15 #16 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@ -1,9 +1,8 @@
|
||||
import { useState, useEffect, useRef, useCallback } from 'react'
|
||||
import { TrendingUp, Clock, Sparkles, MessageSquarePlus, Loader2, Plus, X, Send, ChevronDown, ChevronUp } from 'lucide-react'
|
||||
import { TrendingUp, Clock, Sparkles, Loader2 } from 'lucide-react'
|
||||
import { summariesApi, type Summary, type GenerationOutcome, type GenerationHistory } from '@/api/summaries'
|
||||
import { preferencesApi, type UserPreferences } from '@/api/preferences'
|
||||
import { preferencesApi, type UserPreferences, type SummaryModelOption } from '@/api/preferences'
|
||||
import { GenerationDetails } from '@/components/GenerationDetails'
|
||||
import { reportsApi } from '@/api/reports'
|
||||
import { assetsApi, type Asset } from '@/api/assets'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Markdown } from '@/components/ui/markdown'
|
||||
@ -12,135 +11,6 @@ import { Badge } from '@/components/ui/badge'
|
||||
import { Spinner } from '@/components/ui/spinner'
|
||||
import { useAuth } from '@/lib/auth'
|
||||
|
||||
// ── Text-selection floating button ─────────────────────────────────────────
|
||||
|
||||
function useTextSelection(containerRef: React.RefObject<HTMLElement>) {
|
||||
const [selection, setSelection] = useState<{ text: string; x: number; y: number } | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
function readSelection() {
|
||||
const sel = window.getSelection()
|
||||
const text = sel?.toString().trim()
|
||||
if (!text || !containerRef.current) { setSelection(null); return }
|
||||
const range = sel!.getRangeAt(0)
|
||||
const rect = range.getBoundingClientRect()
|
||||
const containerRect = containerRef.current.getBoundingClientRect()
|
||||
setSelection({
|
||||
text,
|
||||
x: rect.left - containerRect.left + rect.width / 2,
|
||||
y: rect.top - containerRect.top - 8,
|
||||
})
|
||||
}
|
||||
function onMouseUp() { readSelection() }
|
||||
// On mobile, selectionchange fires after the user lifts their finger
|
||||
function onSelectionChange() {
|
||||
const sel = window.getSelection()
|
||||
if (!sel?.toString().trim()) setSelection(null)
|
||||
else readSelection()
|
||||
}
|
||||
function onPointerDown(e: PointerEvent) {
|
||||
if (!(e.target as Element).closest('[data-context-action]')) setSelection(null)
|
||||
}
|
||||
document.addEventListener('mouseup', onMouseUp)
|
||||
document.addEventListener('selectionchange', onSelectionChange)
|
||||
document.addEventListener('pointerdown', onPointerDown)
|
||||
return () => {
|
||||
document.removeEventListener('mouseup', onMouseUp)
|
||||
document.removeEventListener('selectionchange', onSelectionChange)
|
||||
document.removeEventListener('pointerdown', onPointerDown)
|
||||
}
|
||||
}, [containerRef])
|
||||
|
||||
return selection
|
||||
}
|
||||
|
||||
// ── Context panel (extraits + question) ────────────────────────────────────
|
||||
|
||||
function ContextPanel({
|
||||
excerpts,
|
||||
onRemove,
|
||||
onClear,
|
||||
onSubmit,
|
||||
}: {
|
||||
excerpts: string[]
|
||||
onRemove: (i: number) => void
|
||||
onClear: () => void
|
||||
onSubmit: (question: string) => Promise<void>
|
||||
}) {
|
||||
const [question, setQuestion] = useState('')
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
const [submitted, setSubmitted] = useState(false)
|
||||
const [showExcerpts, setShowExcerpts] = useState(false)
|
||||
|
||||
async function submit() {
|
||||
if (!question.trim() || submitting) return
|
||||
setSubmitting(true)
|
||||
try {
|
||||
await onSubmit(question)
|
||||
setSubmitted(true)
|
||||
setQuestion('')
|
||||
setTimeout(() => setSubmitted(false), 2000)
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="fixed bottom-16 left-0 right-0 z-40 flex flex-col bg-card border-t shadow-2xl overflow-hidden md:bottom-4 md:left-auto md:right-4 md:w-96 md:rounded-xl md:border">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between px-4 py-3 border-b bg-primary/5">
|
||||
<button
|
||||
className="text-sm font-semibold flex items-center gap-2 hover:text-primary transition-colors"
|
||||
onClick={() => setShowExcerpts(v => !v)}
|
||||
>
|
||||
<MessageSquarePlus className="h-4 w-4 text-primary" />
|
||||
Contexte ({excerpts.length} extrait{excerpts.length > 1 ? 's' : ''})
|
||||
<span className="md:hidden">{showExcerpts ? <ChevronDown className="h-3 w-3" /> : <ChevronUp className="h-3 w-3" />}</span>
|
||||
</button>
|
||||
<button onClick={onClear} className="text-xs text-muted-foreground hover:text-destructive transition-colors">
|
||||
Tout effacer
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Extraits — toujours visible sur desktop, togglable sur mobile */}
|
||||
<div className={`flex-1 overflow-y-auto px-4 py-3 space-y-2 min-h-0 max-h-[25vh] ${showExcerpts ? 'block' : 'hidden'} md:block`}>
|
||||
{excerpts.map((e, i) => (
|
||||
<div key={i} className="flex items-start gap-2 group">
|
||||
<div className="flex-1 rounded bg-muted/60 px-2 py-1.5 text-xs text-muted-foreground italic line-clamp-3">
|
||||
« {e} »
|
||||
</div>
|
||||
<button
|
||||
onClick={() => onRemove(i)}
|
||||
className="mt-1 shrink-0 text-muted-foreground hover:text-destructive md:opacity-0 md:group-hover:opacity-100 transition-opacity"
|
||||
>
|
||||
<X className="h-3 w-3" />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Question */}
|
||||
<div className="border-t px-4 py-3 space-y-2">
|
||||
<textarea
|
||||
className="w-full rounded border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-ring resize-none"
|
||||
rows={2}
|
||||
placeholder="Votre question…"
|
||||
value={question}
|
||||
onChange={e => setQuestion(e.target.value)}
|
||||
onKeyDown={e => { if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) submit() }}
|
||||
/>
|
||||
<Button size="sm" className="w-full" onClick={submit} disabled={!question.trim() || submitting || submitted}>
|
||||
{submitting
|
||||
? <><Loader2 className="h-3 w-3 animate-spin" /> Envoi…</>
|
||||
: submitted
|
||||
? 'Envoyé !'
|
||||
: <><Send className="h-3 w-3" /> Envoyer (Ctrl+Entrée)</>}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ── Summary content renderer ────────────────────────────────────────────────
|
||||
|
||||
function SummaryContent({ content }: { content: string }) {
|
||||
@ -156,8 +26,8 @@ export function Dashboard() {
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [generating, setGenerating] = useState(false)
|
||||
const [current, setCurrent] = useState<Summary | null>(null)
|
||||
const [excerpts, setExcerpts] = useState<string[]>([])
|
||||
|
||||
const [models, setModels] = useState<SummaryModelOption[]>([])
|
||||
const [preferences, setPreferences] = useState<UserPreferences | null>(null)
|
||||
const [history, setHistory] = useState<GenerationHistory[]>([])
|
||||
const [outcome, setOutcome] = useState<GenerationOutcome | null>(null)
|
||||
@ -166,20 +36,18 @@ export function Dashboard() {
|
||||
const [loadError, setLoadError] = useState('')
|
||||
const requestPending = useRef(false)
|
||||
|
||||
const summaryRef = useRef<HTMLDivElement>(null)
|
||||
const textSel = useTextSelection(summaryRef as React.RefObject<HTMLElement>)
|
||||
|
||||
const load = useCallback(() => {
|
||||
return Promise.allSettled([
|
||||
summariesApi.list(5), assetsApi.list(), preferencesApi.get(), summariesApi.generations(),
|
||||
summariesApi.list(5), assetsApi.list(), preferencesApi.get(), summariesApi.generations(), preferencesApi.listSummaryModels(),
|
||||
]).then(results => {
|
||||
const [summaryResult, assetResult, preferenceResult, historyResult] = results
|
||||
const [summaryResult, assetResult, preferenceResult, historyResult, modelResult] = results
|
||||
if (summaryResult.status === 'fulfilled') {
|
||||
setSummaries(summaryResult.value ?? [])
|
||||
setCurrent(previous => summaryResult.value?.[0] ?? previous)
|
||||
}
|
||||
if (assetResult.status === 'fulfilled') setAssets(assetResult.value ?? [])
|
||||
if (preferenceResult.status === 'fulfilled') setPreferences(preferenceResult.value)
|
||||
if (modelResult.status === 'fulfilled') setModels(modelResult.value ?? [])
|
||||
if (historyResult.status === 'fulfilled') setHistory(historyResult.value ?? [])
|
||||
setLoadError(results.some(result => result.status === 'rejected') ? 'Certaines données n’ont pas pu être chargées. Réessayez.' : '')
|
||||
setLoading(false)
|
||||
@ -203,7 +71,7 @@ export function Dashboard() {
|
||||
}, [generating, load])
|
||||
|
||||
async function generate() {
|
||||
if (requestPending.current || generating || assets.length === 0 || !preferences) return
|
||||
if (requestPending.current || generating || assets.length === 0 || !selectedModel) return
|
||||
requestPending.current = true
|
||||
setGenerating(true); setMessage(''); setFailed(false); setOutcome(null)
|
||||
try {
|
||||
@ -215,7 +83,6 @@ export function Dashboard() {
|
||||
const summary = result.summary
|
||||
setSummaries(previous => [summary, ...previous.filter(item => item.id !== summary.id)])
|
||||
setCurrent(summary)
|
||||
setExcerpts([])
|
||||
setHistory(previous => [{ id: result.outcome.id, summary_id: summary.id, outcome: result.outcome, created_at: summary.generated_at }, ...previous])
|
||||
setMessage('Nouvelle synthèse disponible.')
|
||||
} else {
|
||||
@ -228,20 +95,7 @@ export function Dashboard() {
|
||||
|
||||
const currentOutcome = history.find(item => item.summary_id === current?.id)?.outcome
|
||||
|
||||
const addExcerpt = useCallback(() => {
|
||||
if (!textSel) return
|
||||
setExcerpts(prev => [...prev, textSel.text])
|
||||
window.getSelection()?.removeAllRanges()
|
||||
}, [textSel])
|
||||
|
||||
async function submitQuestion(question: string) {
|
||||
await reportsApi.create({
|
||||
summary_id: current?.id,
|
||||
excerpts,
|
||||
question,
|
||||
})
|
||||
setExcerpts([])
|
||||
}
|
||||
const selectedModel = models.find(model => model.id === preferences?.summary_model_id)
|
||||
|
||||
return (
|
||||
<div className="p-4 md:p-6 space-y-6">
|
||||
@ -259,18 +113,19 @@ export function Dashboard() {
|
||||
<h1 className="text-2xl font-bold">Bonjour 👋</h1>
|
||||
<p className="text-muted-foreground text-sm">{user?.email}</p>
|
||||
</div>
|
||||
<Button onClick={generate} disabled={generating || loading || assets.length === 0 || !preferences}>
|
||||
<Button onClick={generate} disabled={generating || loading || assets.length === 0 || !selectedModel}>
|
||||
{generating ? <><Spinner className="h-4 w-4" /> Génération en cours</> : <><Sparkles className="h-4 w-4" /> Générer une synthèse</>}
|
||||
</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>}
|
||||
<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>}
|
||||
{message && <p role={failed ? 'alert' : 'status'}>{message}</p>}
|
||||
{(failed || outcome?.status === 'no_results') && <Button onClick={generate} disabled={generating || !preferences || assets.length === 0}>Réessayer</Button>}
|
||||
{(failed || outcome?.status === 'no_results') && <Button onClick={generate} disabled={generating || !selectedModel || assets.length === 0}>Réessayer</Button>}
|
||||
{outcome && <GenerationDetails outcome={outcome} />}
|
||||
|
||||
{assets.length === 0 && !loading && (
|
||||
@ -312,37 +167,8 @@ 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>
|
||||
<div ref={summaryRef} className="relative">
|
||||
<SummaryContent content={current.content} />
|
||||
{/* Desktop: floating button above selection */}
|
||||
{textSel && (
|
||||
<button
|
||||
data-context-action
|
||||
onClick={addExcerpt}
|
||||
className="absolute z-10 hidden md:flex items-center gap-1 rounded-full bg-primary text-primary-foreground text-xs px-2 py-1 shadow-lg hover:bg-primary/90 transition-colors"
|
||||
style={{ left: textSel.x, top: textSel.y, transform: 'translate(-50%, -100%)' }}
|
||||
>
|
||||
<Plus className="h-3 w-3" />
|
||||
Ajouter au contexte
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{/* Mobile: fixed bottom bar — avoids conflict with native selection menu */}
|
||||
{textSel && (
|
||||
<div className="md:hidden fixed bottom-16 left-0 right-0 z-50 flex justify-center px-4 pointer-events-none">
|
||||
<button
|
||||
data-context-action
|
||||
onClick={addExcerpt}
|
||||
className="pointer-events-auto flex items-center gap-2 rounded-full bg-primary text-primary-foreground text-sm px-4 py-2.5 shadow-xl"
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
Ajouter au contexte
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<p className="text-xs text-muted-foreground mt-4 italic">
|
||||
Sélectionnez du texte pour l'ajouter au contexte, puis posez une question dans le panneau qui apparaît.
|
||||
</p>
|
||||
<SummaryContent 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>
|
||||
) : (
|
||||
@ -370,7 +196,7 @@ 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); setExcerpts([]); setOutcome(null); setMessage('') }}>{s.content.slice(0, 120)}…</button>
|
||||
<button className="text-sm text-left line-clamp-3" onClick={() => { setCurrent(s); setOutcome(null); setMessage('') }}>{s.content.slice(0, 120)}…</button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
@ -380,15 +206,6 @@ export function Dashboard() {
|
||||
|
||||
{!outcome && currentOutcome && <GenerationDetails outcome={currentOutcome} />}
|
||||
|
||||
{/* Panneau contexte flottant */}
|
||||
{excerpts.length > 0 && (
|
||||
<ContextPanel
|
||||
excerpts={excerpts}
|
||||
onRemove={i => setExcerpts(prev => prev.filter((_, idx) => idx !== i))}
|
||||
onClear={() => setExcerpts([])}
|
||||
onSubmit={submitQuestion}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user