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>
|
||||
)
|
||||
}
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
import { useCallback, useEffect, useState, type FormEvent } from 'react'
|
||||
import { preferencesApi, type UserPreferences } from '@/api/preferences'
|
||||
import { preferencesApi, type UserPreferences, type SummaryModelOption } from '@/api/preferences'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Label } from '@/components/ui/label'
|
||||
@ -7,6 +7,7 @@ import { Select } from '@/components/ui/select'
|
||||
import { Appearance } from '@/components/Appearance'
|
||||
|
||||
export function Preferences() {
|
||||
const [models, setModels] = useState<SummaryModelOption[]>([])
|
||||
const [preferences, setPreferences] = useState<UserPreferences | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [saving, setSaving] = useState(false)
|
||||
@ -14,8 +15,8 @@ export function Preferences() {
|
||||
const [saved, setSaved] = useState(false)
|
||||
|
||||
const load = useCallback(() => {
|
||||
return preferencesApi.get()
|
||||
.then(setPreferences)
|
||||
return Promise.all([preferencesApi.get(), preferencesApi.listSummaryModels()])
|
||||
.then(([value, catalog]) => { setPreferences(value); setModels(catalog ?? []) })
|
||||
.catch(() => setError('Impossible de charger vos préférences. Réessayez.'))
|
||||
.finally(() => setLoading(false))
|
||||
}, [])
|
||||
@ -49,6 +50,16 @@ export function Preferences() {
|
||||
{!loading && !preferences && <Button onClick={() => { setLoading(true); setError(''); void load() }}>Réessayer</Button>}
|
||||
{preferences && (
|
||||
<form onSubmit={save} aria-labelledby="preferences-title" aria-busy={saving} className="space-y-4">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="preferences-model">Modèle de synthèse</Label>
|
||||
<Select id="preferences-model" aria-describedby="model-help" value={preferences.summary_model_id ?? ''} disabled={saving} onChange={e => change({ summary_model_id: e.target.value || null })}>
|
||||
<option value="">Choisir un modèle de synthèse</option>
|
||||
{preferences.summary_model_id && !models.some(model => model.id === preferences.summary_model_id) && <option value={preferences.summary_model_id} disabled>Modèle sélectionné indisponible</option>}
|
||||
{models.map(model => <option key={model.id} value={model.id}>{model.provider} · {model.model}</option>)}
|
||||
</Select>
|
||||
<p id="model-help" className="text-sm text-muted-foreground">Ce choix personnel s’applique aux prochaines synthèses manuelles et planifiées. Aucun autre modèle ne sera choisi automatiquement.</p>
|
||||
{models.length === 0 ? <p role="status">Aucun modèle disponible. Contactez votre administrateur.</p> : !preferences.summary_model_id ? <p>Choisissez un modèle pour pouvoir générer une synthèse.</p> : !models.some(model => model.id === preferences.summary_model_id) && <p role="alert">Le modèle sélectionné n’est plus disponible. Choisissez un autre modèle.</p>}
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="preferences-language">Langue des synthèses</Label>
|
||||
<Select id="preferences-language" value={preferences.language} disabled={saving} onChange={e => change({ language: e.target.value as UserPreferences['language'] })}>
|
||||
|
||||
@ -1,258 +1,71 @@
|
||||
import { useState, useEffect, useCallback, useRef } from 'react'
|
||||
import { Trash2, FileText, Clock, Loader2, XCircle, AlertCircle, Send } from 'lucide-react'
|
||||
import { reportsApi, type Report, type ReportMessage } from '@/api/reports'
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { reportsApi, type ReportMessage } from '@/api/reports'
|
||||
import type { Report } from '@/api/reports'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { Markdown } from '@/components/ui/markdown'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Spinner } from '@/components/ui/spinner'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
|
||||
function StatusBadge({ status }: { status: Report['status'] }) {
|
||||
if (status === 'generating') return (
|
||||
<Badge variant="secondary" className="gap-1 text-xs">
|
||||
<Loader2 className="h-3 w-3 animate-spin" /> En cours
|
||||
</Badge>
|
||||
)
|
||||
if (status === 'error') return (
|
||||
<Badge variant="destructive" className="gap-1 text-xs">
|
||||
<AlertCircle className="h-3 w-3" /> Erreur
|
||||
</Badge>
|
||||
)
|
||||
return null
|
||||
}
|
||||
|
||||
function MessageBubble({ msg }: { msg: ReportMessage }) {
|
||||
const isUser = msg.role === 'user'
|
||||
return (
|
||||
<div className={`flex ${isUser ? 'justify-end' : 'justify-start'}`}>
|
||||
<div className={`max-w-[85%] rounded-lg px-3 py-2 text-sm ${
|
||||
isUser
|
||||
? 'bg-primary text-primary-foreground'
|
||||
: 'bg-muted'
|
||||
}`}>
|
||||
{msg.status === 'generating' ? (
|
||||
<div className="flex items-center gap-2 text-muted-foreground">
|
||||
<Loader2 className="h-3 w-3 animate-spin" />
|
||||
<span className="text-xs">Génération…</span>
|
||||
</div>
|
||||
) : msg.status === 'error' ? (
|
||||
<span className="text-destructive text-xs">{msg.content || 'Erreur lors de la génération.'}</span>
|
||||
) : isUser ? (
|
||||
<p>{msg.content}</p>
|
||||
) : (
|
||||
<Markdown content={msg.content} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ReportChat({ report }: { report: Report }) {
|
||||
function HistoricalConversation({ reportId }: { reportId: string }) {
|
||||
const [messages, setMessages] = useState<ReportMessage[]>([])
|
||||
const [input, setInput] = useState('')
|
||||
const [sending, setSending] = useState(false)
|
||||
const bottomRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
const loadMessages = useCallback(async () => {
|
||||
const msgs = await reportsApi.listMessages(report.id)
|
||||
setMessages(msgs ?? [])
|
||||
}, [report.id])
|
||||
|
||||
const [error, setError] = useState('')
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
void reportsApi.listMessages(report.id).then(msgs => {
|
||||
if (active) setMessages(msgs ?? [])
|
||||
})
|
||||
void reportsApi.listMessages(reportId).then(data => { if (active) setMessages(data ?? []) })
|
||||
.catch(() => { if (active) setError('Conversation historique indisponible.') })
|
||||
return () => { active = false }
|
||||
}, [report.id])
|
||||
|
||||
// Poll tant qu'un message assistant est en cours de génération
|
||||
useEffect(() => {
|
||||
const hasGenerating = messages.some(m => m.status === 'generating')
|
||||
if (!hasGenerating) return
|
||||
const interval = setInterval(loadMessages, 2000)
|
||||
return () => clearInterval(interval)
|
||||
}, [messages, loadMessages])
|
||||
|
||||
// Scroll vers le bas à chaque nouveau message
|
||||
useEffect(() => {
|
||||
bottomRef.current?.scrollIntoView({ behavior: 'smooth' })
|
||||
}, [messages])
|
||||
|
||||
async function send() {
|
||||
const content = input.trim()
|
||||
if (!content || sending) return
|
||||
setInput('')
|
||||
setSending(true)
|
||||
try {
|
||||
// Optimistic: ajouter le message user immédiatement
|
||||
const optimisticUser: ReportMessage = {
|
||||
id: `tmp-${Date.now()}`,
|
||||
report_id: report.id,
|
||||
role: 'user',
|
||||
content,
|
||||
status: 'done',
|
||||
created_at: new Date().toISOString(),
|
||||
}
|
||||
const optimisticAssistant: ReportMessage = {
|
||||
id: `tmp-assistant-${Date.now()}`,
|
||||
report_id: report.id,
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
status: 'generating',
|
||||
created_at: new Date().toISOString(),
|
||||
}
|
||||
setMessages(prev => [...prev, optimisticUser, optimisticAssistant])
|
||||
await reportsApi.createMessage(report.id, content)
|
||||
await loadMessages()
|
||||
} finally {
|
||||
setSending(false)
|
||||
}
|
||||
}
|
||||
|
||||
const hasGenerating = messages.some(m => m.status === 'generating')
|
||||
|
||||
return (
|
||||
<div className="border-t pt-3 space-y-3">
|
||||
<p className="text-xs font-medium text-muted-foreground uppercase tracking-wide">Conversation</p>
|
||||
|
||||
{messages.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
{messages.map(msg => (
|
||||
<MessageBubble key={msg.id} msg={msg} />
|
||||
))}
|
||||
<div ref={bottomRef} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={input}
|
||||
onChange={e => setInput(e.target.value)}
|
||||
onKeyDown={e => e.key === 'Enter' && !e.shiftKey && send()}
|
||||
placeholder="Posez une question sur cette réponse…"
|
||||
disabled={hasGenerating || sending}
|
||||
className="text-sm"
|
||||
/>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={send}
|
||||
disabled={!input.trim() || hasGenerating || sending}
|
||||
className="shrink-0"
|
||||
>
|
||||
{sending ? <Loader2 className="h-4 w-4 animate-spin" /> : <Send className="h-4 w-4" />}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}, [reportId])
|
||||
return <div className="space-y-3 border-t pt-3">
|
||||
<h2 className="text-sm font-medium">Conversation historique</h2>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
{messages.map(message => <div key={message.id} className="rounded-md bg-muted p-3 break-words">
|
||||
<p className="text-xs text-muted-foreground">{message.role === 'user' ? 'Vous' : 'Assistant'}</p>
|
||||
{message.content && <Markdown content={message.content} />}
|
||||
{message.status === 'generating' && <p>Réponse historique non finalisée. Le service de questions-réponses est suspendu.</p>}
|
||||
{message.status === 'error' && <p>Cette réponse historique a échoué.</p>}
|
||||
</div>)}
|
||||
</div>
|
||||
}
|
||||
|
||||
export function Reports() {
|
||||
const [reports, setReports] = useState<Report[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try { setReports((await reportsApi.list()) ?? []) }
|
||||
finally { setLoading(false) }
|
||||
}, [])
|
||||
|
||||
useEffect(() => { load() }, [load])
|
||||
|
||||
// Poll toutes les 3s tant qu'il y a des rapports en cours
|
||||
useEffect(() => {
|
||||
const hasGenerating = reports.some(r => r.status === 'generating')
|
||||
if (!hasGenerating) return
|
||||
const interval = setInterval(load, 3000)
|
||||
return () => clearInterval(interval)
|
||||
}, [reports, load])
|
||||
const [error, setError] = useState('')
|
||||
const [removing, setRemoving] = useState<string | null>(null)
|
||||
const [notice, setNotice] = useState('')
|
||||
const load = useCallback(() => reportsApi.list().then(data => setReports(data ?? []))
|
||||
.catch(() => setError('Impossible de charger les rapports historiques.'))
|
||||
.finally(() => setLoading(false)), [])
|
||||
useEffect(() => { void load() }, [load])
|
||||
|
||||
async function remove(id: string) {
|
||||
await reportsApi.delete(id)
|
||||
setReports(prev => prev.filter(r => r.id !== id))
|
||||
if (removing) return
|
||||
setRemoving(id); setError(''); setNotice('')
|
||||
try {
|
||||
await reportsApi.delete(id)
|
||||
setReports(current => current.filter(report => report.id !== id))
|
||||
setNotice('Rapport historique supprimé.')
|
||||
} catch { setError('Impossible de supprimer le rapport. Il est conservé.') }
|
||||
finally { setRemoving(null) }
|
||||
}
|
||||
|
||||
if (loading) return <div className="flex justify-center py-20"><Spinner /></div>
|
||||
|
||||
return (
|
||||
<div className="p-4 md:p-6 space-y-6">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">Rapports IA</h1>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Vos questions posées sur des extraits de résumés, avec les réponses de l'IA.
|
||||
</p>
|
||||
return <div className="p-4 md:p-6 space-y-6">
|
||||
<h1 className="text-2xl font-bold">Rapports historiques</h1>
|
||||
<p>Le service de questions-réponses est suspendu. Vos rapports et conversations existants restent consultables et supprimables.</p>
|
||||
{loading && <p role="status">Chargement des rapports…</p>}
|
||||
{error && <p role="alert">{error}</p>}
|
||||
{notice && <p role="status">{notice}</p>}
|
||||
{!loading && !error && reports.length === 0 && <p>Aucun rapport enregistré.</p>}
|
||||
{reports.map(report => <Card key={report.id}><CardContent className="space-y-3 py-4 break-words">
|
||||
<div className="flex flex-wrap justify-between items-center gap-3">
|
||||
<time className="text-xs text-muted-foreground">{new Date(report.created_at).toLocaleString('fr-FR')}</time>
|
||||
<Button variant="outline" title="Supprimer" aria-label="Supprimer le rapport" disabled={!!removing} onClick={() => void remove(report.id)}>Supprimer</Button>
|
||||
</div>
|
||||
|
||||
{reports.length === 0 ? (
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 text-center text-muted-foreground">
|
||||
<FileText className="h-8 w-8 mx-auto mb-3 opacity-50" />
|
||||
<p>Aucun rapport enregistré</p>
|
||||
<p className="text-xs mt-1">Sélectionnez du texte dans un résumé et posez une question à l'IA.</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{reports.map(r => (
|
||||
<Card key={r.id} className={r.status === 'generating' ? 'border-primary/30' : ''}>
|
||||
<CardContent className="pt-4 pb-4 space-y-3">
|
||||
{/* Meta */}
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<div className="flex items-center gap-1 text-xs text-muted-foreground">
|
||||
<Clock className="h-3 w-3" />
|
||||
{new Date(r.created_at).toLocaleString('fr-FR')}
|
||||
</div>
|
||||
<StatusBadge status={r.status} />
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0 text-muted-foreground hover:text-destructive shrink-0"
|
||||
onClick={() => remove(r.id)}
|
||||
title={r.status === 'generating' ? 'Annuler' : 'Supprimer'}
|
||||
>
|
||||
{r.status === 'generating'
|
||||
? <XCircle className="h-3 w-3" />
|
||||
: <Trash2 className="h-3 w-3" />}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Extraits de contexte */}
|
||||
{r.context_excerpt.split('\n\n---\n\n').map((excerpt, i) => (
|
||||
<div key={i} className="rounded bg-muted/60 px-3 py-2 text-xs text-muted-foreground italic">
|
||||
« {excerpt} »
|
||||
</div>
|
||||
))}
|
||||
|
||||
{/* Question */}
|
||||
<p className="text-sm font-medium">{r.question}</p>
|
||||
|
||||
{/* Réponse initiale */}
|
||||
{r.status === 'generating' && (
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 animate-spin text-primary" />
|
||||
L'IA génère la réponse…
|
||||
</div>
|
||||
)}
|
||||
{r.status === 'done' && (
|
||||
<div className="border-t pt-3">
|
||||
<Markdown content={r.answer} />
|
||||
</div>
|
||||
)}
|
||||
{r.status === 'error' && (
|
||||
<div className="text-sm text-destructive border-t pt-3">
|
||||
Erreur : {r.error_msg || 'Une erreur est survenue lors de la génération.'}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Chat de suivi (uniquement quand le rapport est terminé) */}
|
||||
{r.status === 'done' && <ReportChat report={r} />}
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
{report.context_excerpt && <blockquote className="text-sm text-muted-foreground whitespace-pre-wrap">{report.context_excerpt}</blockquote>}
|
||||
<p className="font-medium">{report.question}</p>
|
||||
{report.answer && <Markdown content={report.answer} />}
|
||||
{report.status === 'generating' && <p>Réponse historique non finalisée. Aucune génération n’est en cours.</p>}
|
||||
{report.status === 'error' && <p>Cette réponse historique a échoué.</p>}
|
||||
<HistoricalConversation reportId={report.id} />
|
||||
</CardContent></Card>)}
|
||||
</div>
|
||||
}
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { Plus, Trash2, Star, Download, HardDrive, Cpu, ChevronDown, ChevronUp, X } from 'lucide-react'
|
||||
import { adminApi, type AIProvider, type AIRoles, type OllamaModelInfo } from '@/api/admin'
|
||||
import { Plus, Trash2, Download, HardDrive, Cpu, ChevronUp, X } from 'lucide-react'
|
||||
import { AIModelCatalog } from '@/components/AIModelCatalog'
|
||||
import { adminApi, type AIProvider, type OllamaModelInfo } from '@/api/admin'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
@ -214,154 +215,6 @@ function ModelTag({ fullName, size, installed, isPulling, pulling, onRequest }:
|
||||
)
|
||||
}
|
||||
|
||||
// ── Cloud model picker (OpenAI / Anthropic / Gemini / …) ──────────────────
|
||||
|
||||
function CloudModelPicker({ value, providerName, apiKey, endpoint, onChange }: {
|
||||
value: string; providerName: string; apiKey: string; endpoint: string
|
||||
onChange: (model: string) => void
|
||||
}) {
|
||||
const [models, setModels] = useState<string[]>([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [loadError, setLoadError] = useState('')
|
||||
const noKeyNeeded = providerName === 'claudecode'
|
||||
|
||||
useEffect(() => {
|
||||
if (noKeyNeeded) loadModels()
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [providerName])
|
||||
|
||||
async function loadModels() {
|
||||
if (!noKeyNeeded && !apiKey) { setLoadError('Renseigne la clé API d\'abord'); return }
|
||||
setLoading(true); setLoadError('')
|
||||
try {
|
||||
const list = await adminApi.probeModels({ name: providerName, api_key: apiKey, endpoint })
|
||||
setModels(list ?? [])
|
||||
if ((list ?? []).length === 0) setLoadError('Aucun modèle trouvé')
|
||||
} catch (e) {
|
||||
setLoadError(e instanceof Error ? e.message : 'Erreur')
|
||||
} finally { setLoading(false) }
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-1.5">
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
placeholder="gpt-4o-mini, claude-sonnet-4-6…"
|
||||
value={value}
|
||||
onChange={e => onChange(e.target.value)}
|
||||
list="cloud-models-list"
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button type="button" variant="outline" size="sm" className="shrink-0" onClick={loadModels} disabled={loading}>
|
||||
{loading ? <Spinner className="h-3 w-3" /> : 'Charger'}
|
||||
</Button>
|
||||
</div>
|
||||
{models.length > 0 && (
|
||||
<datalist id="cloud-models-list">
|
||||
{models.map(m => <option key={m} value={m} />)}
|
||||
</datalist>
|
||||
)}
|
||||
{models.length > 0 && (
|
||||
<Select value={value} onChange={e => onChange(e.target.value)}>
|
||||
<option value="">— Sélectionner un modèle —</option>
|
||||
{models.map(m => <option key={m} value={m}>{m}</option>)}
|
||||
</Select>
|
||||
)}
|
||||
{loadError && <p className="text-xs text-destructive">{loadError}</p>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ── Ollama model picker (inside provider form) ─────────────────────────────
|
||||
|
||||
function OllamaModelPicker({ value, installedModels, onSelect, onRefresh }: {
|
||||
value: string
|
||||
installedModels: OllamaModelInfo[]
|
||||
onSelect: (name: string) => void
|
||||
onRefresh: () => Promise<OllamaModelInfo[]>
|
||||
}) {
|
||||
const [showCatalogue, setShowCatalogue] = useState(installedModels.length === 0)
|
||||
const [pulling, setPulling] = useState<string | null>(null)
|
||||
const installedNames = new Set(installedModels.map(m => m.name))
|
||||
|
||||
async function pull(fullName: string) {
|
||||
setPulling(fullName)
|
||||
try {
|
||||
await adminApi.pullOllamaModel(fullName)
|
||||
await new Promise<void>(resolve => {
|
||||
const iv = setInterval(async () => {
|
||||
try {
|
||||
const updated = await onRefresh()
|
||||
if (updated.some(m => m.name === fullName)) { clearInterval(iv); onSelect(fullName); setShowCatalogue(false); resolve() }
|
||||
} catch { /* ignore */ }
|
||||
}, 4000)
|
||||
setTimeout(() => { clearInterval(iv); resolve() }, 1800000)
|
||||
})
|
||||
} finally { setPulling(null) }
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<Select value={value} onChange={e => onSelect(e.target.value)}>
|
||||
<option value="">— Choisir un modèle installé —</option>
|
||||
{installedModels.map(m => (
|
||||
<option key={m.name} value={m.name}>
|
||||
{m.name}{m.details.parameter_size ? ` (${m.details.parameter_size})` : ''}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
<button type="button" className="flex items-center gap-1 text-xs text-primary hover:underline"
|
||||
onClick={() => setShowCatalogue(v => !v)}>
|
||||
{showCatalogue ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}
|
||||
{showCatalogue ? 'Masquer le catalogue' : 'Installer un nouveau modèle'}
|
||||
</button>
|
||||
{showCatalogue && (
|
||||
<div className="rounded-lg border bg-muted/30 p-3 max-h-72 overflow-y-auto">
|
||||
<ModelCatalogue installedNames={installedNames} pulling={pulling} onPull={pull} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ── Role Assignment ────────────────────────────────────────────────────────
|
||||
|
||||
const ROLE_LABELS: Record<string, { label: string; desc: string }> = {
|
||||
summary: { label: 'Résumés', desc: 'Génération du résumé quotidien (passe 2)' },
|
||||
report: { label: 'Rapports', desc: 'Réponses aux questions sur les résumés' },
|
||||
filter: { label: 'Filtre articles', desc: 'Sélection des articles pertinents (passe 1)' },
|
||||
}
|
||||
|
||||
function RoleCard({ role, providers, currentProviderID, onSave }: {
|
||||
role: string; providers: AIProvider[]; currentProviderID: string
|
||||
onSave: (providerID: string) => Promise<void>
|
||||
}) {
|
||||
const [providerID, setProviderID] = useState(currentProviderID)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [saved, setSaved] = useState(false)
|
||||
const { label, desc } = ROLE_LABELS[role]
|
||||
async function save() {
|
||||
setSaving(true)
|
||||
try { await onSave(providerID); setSaved(true); setTimeout(() => setSaved(false), 2000) }
|
||||
finally { setSaving(false) }
|
||||
}
|
||||
return (
|
||||
<div className="grid gap-3 sm:grid-cols-[1fr_auto] items-end">
|
||||
<div>
|
||||
<Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">{label}</Label>
|
||||
<p className="text-xs text-muted-foreground mb-2">{desc}</p>
|
||||
<Select value={providerID} onChange={e => setProviderID(e.target.value)}>
|
||||
<option value="">— Fournisseur par défaut —</option>
|
||||
{providers.map(p => <option key={p.id} value={p.id}>{p.name}{p.model ? ` — ${p.model}` : ''}</option>)}
|
||||
</Select>
|
||||
</div>
|
||||
<Button size="sm" onClick={save} disabled={saving} className="whitespace-nowrap">
|
||||
{saving ? <Spinner className="h-3 w-3" /> : saved ? '✓ Sauvegardé' : 'Appliquer'}
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ── Ollama model manager card ──────────────────────────────────────────────
|
||||
|
||||
function OllamaModelsCard({ installedModels, onRefresh, onDelete }: {
|
||||
@ -451,7 +304,6 @@ function OllamaModelsCard({ installedModels, onRefresh, onDelete }: {
|
||||
|
||||
export function AIProviders() {
|
||||
const [providers, setProviders] = useState<AIProvider[]>([])
|
||||
const [roles, setRoles] = useState<AIRoles | null>(null)
|
||||
const [ollamaModels, setOllamaModels] = useState<OllamaModelInfo[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [showForm, setShowForm] = useState(false)
|
||||
@ -465,10 +317,8 @@ export function AIProviders() {
|
||||
|
||||
const loadOllamaModels = useCallback(async (): Promise<OllamaModelInfo[]> => {
|
||||
try {
|
||||
console.log('[ollama] fetching installed models…')
|
||||
const m = await adminApi.listOllamaModels()
|
||||
const list = m ?? []
|
||||
console.log(`[ollama] ${list.length} model(s):`, list.map(x => x.name))
|
||||
setOllamaModels(list)
|
||||
return list
|
||||
} catch (e) {
|
||||
@ -477,13 +327,12 @@ export function AIProviders() {
|
||||
}
|
||||
}, [])
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
const [p, r] = await Promise.all([adminApi.listProviders(), adminApi.getRoles()])
|
||||
setProviders(p ?? [])
|
||||
setRoles(r)
|
||||
const load = useCallback(() => {
|
||||
return adminApi.listProviders().then(async providers => {
|
||||
setProviders(providers ?? [])
|
||||
await loadOllamaModels()
|
||||
} finally { setLoading(false) }
|
||||
}).catch(() => setError('Impossible de charger les fournisseurs.'))
|
||||
.finally(() => setLoading(false))
|
||||
}, [loadOllamaModels])
|
||||
|
||||
useEffect(() => { load() }, [load])
|
||||
@ -496,21 +345,19 @@ export function AIProviders() {
|
||||
setShowForm(false); setEditId(null)
|
||||
setForm({ name: 'openai', api_key: '', model: '', endpoint: '' })
|
||||
setLoading(true); await load()
|
||||
} catch (e) { setError(e instanceof Error ? e.message : 'Erreur') }
|
||||
} catch { setError('Impossible d’enregistrer le fournisseur.'); setForm(f => ({ ...f, api_key: '' })) }
|
||||
finally { setSaving(false) }
|
||||
}
|
||||
|
||||
async function setDefault(id: string) { await adminApi.activateProvider(id); setLoading(true); await load() }
|
||||
async function remove(id: string) {
|
||||
if (!confirm('Supprimer ce fournisseur ?')) return
|
||||
await adminApi.deleteProvider(id); setLoading(true); await load()
|
||||
setError('')
|
||||
try { await adminApi.deleteProvider(id); setLoading(true); await load() }
|
||||
catch { setError('Impossible de supprimer ce fournisseur. Vérifiez les modèles et comptes qui l’utilisent.') }
|
||||
}
|
||||
function startEdit(p: AIProvider) {
|
||||
setEditId(p.id); setForm({ name: p.name, api_key: '', model: p.model, endpoint: p.endpoint }); setShowForm(true)
|
||||
}
|
||||
async function saveRole(role: string, providerID: string) {
|
||||
await adminApi.updateRole(role, { provider_id: providerID, model: '' }); setLoading(true); await load()
|
||||
}
|
||||
async function deleteOllamaModel(name: string) {
|
||||
await adminApi.deleteOllamaModel(name); await loadOllamaModels()
|
||||
}
|
||||
@ -519,28 +366,22 @@ export function AIProviders() {
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">Fournisseurs IA</h1>
|
||||
<p className="text-muted-foreground text-sm">Configurez les fournisseurs et assignez un modèle à chaque tâche</p>
|
||||
<p className="text-muted-foreground text-sm">Gérez les connexions fournisseurs et le catalogue des modèles de synthèse. Chaque compte choisit son modèle dans Mes préférences.</p>
|
||||
</div>
|
||||
|
||||
{error && !showForm && <p role="alert">{error}</p>}
|
||||
{loading ? (
|
||||
<div className="flex justify-center py-12"><Spinner /></div>
|
||||
) : (
|
||||
<>
|
||||
{/* Role assignments */}
|
||||
{roles && providers.length > 0 && (
|
||||
<Card>
|
||||
<CardHeader><CardTitle className="text-base">Assignation des tâches</CardTitle></CardHeader>
|
||||
<CardContent className="space-y-5 divide-y">
|
||||
{(['summary', 'report', 'filter'] as const).map(role => (
|
||||
<div key={role} className={role !== 'summary' ? 'pt-5' : ''}>
|
||||
<RoleCard key={`${role}:${roles[role].provider_id}`} role={role} providers={providers}
|
||||
currentProviderID={roles[role].provider_id}
|
||||
onSave={pid => saveRole(role, pid)} />
|
||||
</div>
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
<Card>
|
||||
<CardHeader><CardTitle>Classement des articles</CardTitle></CardHeader>
|
||||
<CardContent className="space-y-2">
|
||||
<p className="font-medium">Laya, moteur fixe</p>
|
||||
<p>Laya classe les articles pertinents. Le classement est distinct du modèle de synthèse choisi par chaque compte ; aucun fournisseur de synthèse ne remplace Laya.</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<AIModelCatalog providers={providers} />
|
||||
|
||||
{/* Providers list */}
|
||||
<Card>
|
||||
@ -558,8 +399,8 @@ export function AIProviders() {
|
||||
<p className="font-medium text-sm">{editId ? 'Modifier le fournisseur' : 'Nouveau fournisseur'}</p>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<div className="space-y-1">
|
||||
<Label>Fournisseur</Label>
|
||||
<Select value={form.name} disabled={!!editId}
|
||||
<Label htmlFor="provider-name">Fournisseur</Label>
|
||||
<Select id="provider-name" value={form.name} disabled={!!editId}
|
||||
onChange={e => {
|
||||
const name = e.target.value
|
||||
setForm(f => ({ ...f, name, model: '', api_key: '', endpoint: name === 'ollama' ? 'http://ollama:11434' : '' }))
|
||||
@ -569,37 +410,21 @@ export function AIProviders() {
|
||||
</div>
|
||||
{!isOllamaForm && !isClaudeCodeForm && (
|
||||
<div className="space-y-1">
|
||||
<Label>Clé API {editId && <span className="text-muted-foreground text-xs">(vide = conserver)</span>}</Label>
|
||||
<Input type="password" placeholder="sk-…" value={form.api_key} onChange={e => setForm(f => ({ ...f, api_key: e.target.value }))} />
|
||||
<Label htmlFor="provider-key">Clé API {editId && <span className="text-muted-foreground text-xs">(vide = conserver)</span>}</Label>
|
||||
<Input id="provider-key" type="password" autoComplete="new-password" placeholder="sk-…" value={form.api_key} onChange={e => setForm(f => ({ ...f, api_key: e.target.value }))} />
|
||||
</div>
|
||||
)}
|
||||
{isOllamaForm && (
|
||||
<div className="space-y-1">
|
||||
<Label>Endpoint</Label>
|
||||
<Input value={form.endpoint || 'http://ollama:11434'} onChange={e => setForm(f => ({ ...f, endpoint: e.target.value }))} />
|
||||
<Label htmlFor="provider-endpoint">Endpoint</Label>
|
||||
<Input id="provider-endpoint" value={form.endpoint || 'http://ollama:11434'} onChange={e => setForm(f => ({ ...f, endpoint: e.target.value }))} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label>Modèle par défaut</Label>
|
||||
{isOllamaForm ? (
|
||||
<OllamaModelPicker value={form.model} installedModels={ollamaModels}
|
||||
onSelect={m => setForm(f => ({ ...f, model: m }))}
|
||||
onRefresh={loadOllamaModels} />
|
||||
) : (
|
||||
<CloudModelPicker
|
||||
value={form.model}
|
||||
providerName={form.name}
|
||||
apiKey={form.api_key}
|
||||
endpoint={form.endpoint}
|
||||
onChange={m => setForm(f => ({ ...f, model: m }))}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
{error && <p className="text-sm text-destructive">{error}</p>}
|
||||
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
|
||||
<div className="flex gap-2">
|
||||
<Button size="sm" onClick={save} disabled={saving}>{saving ? <Spinner className="h-4 w-4" /> : 'Enregistrer'}</Button>
|
||||
<Button size="sm" variant="outline" onClick={() => { setShowForm(false); setEditId(null) }}>Annuler</Button>
|
||||
<Button size="sm" variant="outline" onClick={() => { setShowForm(false); setEditId(null); setForm(f => ({ ...f, api_key: '' })) }}>Annuler</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
@ -609,25 +434,18 @@ export function AIProviders() {
|
||||
)}
|
||||
|
||||
{providers.map(p => (
|
||||
<div key={p.id} className={`flex flex-wrap items-center gap-3 rounded-md border px-3 py-2.5 ${p.is_active ? 'border-primary/50 bg-primary/5' : ''}`}>
|
||||
<div key={p.id} className="flex flex-wrap items-center gap-3 rounded-md border px-3 py-2.5">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<span className="font-semibold capitalize text-sm">{p.name}</span>
|
||||
{p.is_active && <Badge variant="default" className="text-xs">Défaut</Badge>}
|
||||
{!p.has_key && p.name !== 'ollama' && p.name !== 'claudecode' && <Badge variant="outline" className="text-yellow-500 border-yellow-500 text-xs">Sans clé</Badge>}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground flex gap-3 mt-0.5">
|
||||
{p.model && <span>Modèle : <strong>{p.model}</strong></span>}
|
||||
{p.endpoint && <span>{p.endpoint}</span>}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Button variant="ghost" size="sm" className="h-7 px-2 text-xs" onClick={() => startEdit(p)}>Modifier</Button>
|
||||
{!p.is_active && (
|
||||
<Button size="sm" variant="outline" className="h-7 px-2 text-xs" onClick={() => setDefault(p.id)}>
|
||||
<Star className="h-3 w-3 mr-1" /> Défaut
|
||||
</Button>
|
||||
)}
|
||||
<Button variant="ghost" size="sm" className="h-7 w-7 p-0 text-destructive hover:text-destructive" onClick={() => remove(p.id)}>
|
||||
<Trash2 className="h-3 w-3" />
|
||||
</Button>
|
||||
|
||||
Reference in New Issue
Block a user