191 lines
12 KiB
TypeScript
191 lines
12 KiB
TypeScript
import { useEffect, useState, useCallback, useRef, type FormEvent } from 'react'
|
||
import { adminApi, type AIProvider, type AIModelCatalogEntry, type AIModelTestStatus } from '@/api/admin'
|
||
import { ApiError } from '@/api/client'
|
||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||
import { Button } from '@/components/ui/button'
|
||
import { Input } from '@/components/ui/input'
|
||
import { Label } from '@/components/ui/label'
|
||
import { Select } from '@/components/ui/select'
|
||
|
||
function isCatalogEntry(value: unknown): value is AIModelCatalogEntry {
|
||
if (!value || typeof value !== 'object') return false
|
||
const entry = value as Record<string, unknown>
|
||
return typeof entry.id === 'string' && entry.id.length > 0
|
||
&& typeof entry.provider_id === 'string' && entry.provider_id.length > 0
|
||
&& typeof entry.model === 'string' && entry.model.length > 0
|
||
&& typeof entry.enabled === 'boolean'
|
||
&& (entry.provider === undefined || typeof entry.provider === 'string')
|
||
}
|
||
|
||
type ModelTestOutcome = AIModelTestStatus | 'testing' | 'busy'
|
||
const MODEL_TEST_MESSAGES: Record<ModelTestOutcome, string> = {
|
||
testing: 'Test du modèle en cours…',
|
||
success: 'Test réussi : le modèle a renvoyé une réponse non vide.',
|
||
empty_response: 'Le modèle a renvoyé une réponse vide.',
|
||
auth_rejected: 'Authentification refusée par le fournisseur.',
|
||
model_unavailable: 'Modèle inaccessible chez ce fournisseur.',
|
||
rate_limited: 'Limite de requêtes atteinte. Réessayez plus tard.',
|
||
timeout: 'Le test a dépassé le délai autorisé.',
|
||
unavailable: 'Impossible de tester le modèle. Réessayez.',
|
||
busy: 'Un test est déjà en cours chez ce fournisseur. Attendez sa fin avant de lancer un nouveau test.',
|
||
}
|
||
function boundedTestStatus(value: unknown): AIModelTestStatus {
|
||
switch (value) {
|
||
case 'success': case 'empty_response': case 'auth_rejected': case 'model_unavailable':
|
||
case 'rate_limited': case 'timeout': case 'unavailable': return value
|
||
default: return 'unavailable'
|
||
}
|
||
}
|
||
|
||
interface CatalogProps {
|
||
providers: AIProvider[]
|
||
busyProviderIds?: readonly string[]
|
||
onTestingChange?: (providerId: string, testing: boolean) => void
|
||
}
|
||
|
||
export function AIModelCatalog({ providers, busyProviderIds = [], onTestingChange }: CatalogProps) {
|
||
const providerConfiguration = JSON.stringify(providers.map(provider => [provider.id, provider.name, provider.endpoint, provider.model, provider.has_key, provider.is_active]))
|
||
const [testConfiguration, setTestConfiguration] = useState({ key: providerConfiguration, revision: 0 })
|
||
const [testResults, setTestResults] = useState<Record<string, { status: ModelTestOutcome; config: string; revision: number }>>({})
|
||
const [testingByProvider, setTestingByProvider] = useState<Record<string, string>>({})
|
||
const testLocks = useRef(new Set<string>())
|
||
const testButtons = useRef(new Map<string, HTMLButtonElement>())
|
||
const [entries, setEntries] = useState<AIModelCatalogEntry[]>([])
|
||
const [loading, setLoading] = useState(true)
|
||
const [loadFailed, setLoadFailed] = useState(false)
|
||
const [error, setError] = useState('')
|
||
const [notice, setNotice] = useState('')
|
||
const [busy, setBusy] = useState(false)
|
||
const [providerId, setProviderId] = useState('')
|
||
const [model, setModel] = useState('')
|
||
const load = useCallback(() => adminApi.listAIModelCatalog().then(data => {
|
||
// Missing catalogues remain compatible with the existing empty response.
|
||
// Reject malformed payloads in full; never silently discard individual rows.
|
||
const catalog: unknown = data ?? []
|
||
if (!Array.isArray(catalog) || !Array.from(catalog).every(isCatalogEntry)) {
|
||
throw new Error('Invalid model catalogue')
|
||
}
|
||
setEntries(catalog); setLoadFailed(false); setError('')
|
||
return true
|
||
})
|
||
.catch(() => { setLoadFailed(true); setNotice(''); setError('Impossible de charger le catalogue de modèles.'); return false })
|
||
.finally(() => setLoading(false)), [])
|
||
useEffect(() => { void load() }, [load])
|
||
|
||
// Discard results permanently on configuration changes, including late replies.
|
||
if (testConfiguration.key !== providerConfiguration) {
|
||
setTestConfiguration({ key: providerConfiguration, revision: testConfiguration.revision + 1 })
|
||
setTestResults({})
|
||
}
|
||
|
||
function providerBusy(id: string) {
|
||
return !!testingByProvider[id] || busyProviderIds.includes(id)
|
||
}
|
||
function configuration(entry: AIModelCatalogEntry) {
|
||
const provider = providers.find(provider => provider.id === entry.provider_id)
|
||
return JSON.stringify([entry.provider_id, entry.model, entry.enabled, provider?.name, provider?.endpoint, provider?.model, provider?.has_key, provider?.is_active])
|
||
}
|
||
async function test(entry: AIModelCatalogEntry) {
|
||
if (busy || loadFailed || providerBusy(entry.provider_id) || testLocks.current.has(entry.provider_id)) return
|
||
const trigger = testButtons.current.get(entry.id)
|
||
const keepFocus = document.activeElement === trigger
|
||
const config = configuration(entry)
|
||
const revision = testConfiguration.revision
|
||
const remember = (status: ModelTestOutcome) => setTestResults(current => ({ ...current, [entry.id]: { status, config, revision } }))
|
||
testLocks.current.add(entry.provider_id)
|
||
setTestingByProvider(current => ({ ...current, [entry.provider_id]: entry.id }))
|
||
remember('testing')
|
||
onTestingChange?.(entry.provider_id, true)
|
||
try {
|
||
const result = await adminApi.testAIModelCatalogEntry(entry.id)
|
||
remember(boundedTestStatus(result?.status))
|
||
} catch (error) {
|
||
remember(error instanceof ApiError && error.status === 409 ? 'busy'
|
||
: error instanceof ApiError && error.status === 404 ? 'model_unavailable' : 'unavailable')
|
||
} finally {
|
||
testLocks.current.delete(entry.provider_id)
|
||
setTestingByProvider(current => { const next = { ...current }; delete next[entry.provider_id]; return next })
|
||
onTestingChange?.(entry.provider_id, false)
|
||
if (keepFocus) setTimeout(() => {
|
||
if (trigger?.isConnected && !trigger.disabled && document.activeElement === document.body) trigger.focus()
|
||
}, 0)
|
||
}
|
||
}
|
||
|
||
async function save(event: FormEvent) {
|
||
event.preventDefault()
|
||
if (busy || loadFailed || !providerId || !model.trim() || providerBusy(providerId) || testLocks.current.has(providerId)) return
|
||
setBusy(true); setError(''); setNotice('')
|
||
try {
|
||
await adminApi.createAIModelCatalogEntry({ provider_id: providerId, model: model.trim() })
|
||
setModel(''); setProviderId('')
|
||
if (await load()) setNotice('Catalogue enregistré. Chaque compte choisit son modèle dans Mes préférences.')
|
||
} catch { setError('Impossible d’enregistrer ce modèle. Vos saisies sont conservées.') }
|
||
finally { setBusy(false) }
|
||
}
|
||
|
||
async function change(entry: AIModelCatalogEntry, remove: boolean) {
|
||
if (busy || loadFailed || providerBusy(entry.provider_id) || testLocks.current.has(entry.provider_id)) return
|
||
setBusy(true); setError(''); setNotice('')
|
||
try {
|
||
if (remove) await adminApi.deleteAIModelCatalogEntry(entry.id)
|
||
else await adminApi.updateAIModelCatalogEntry(entry.id, { enabled: !entry.enabled })
|
||
setTestResults(current => { const next = { ...current }; delete next[entry.id]; return next })
|
||
if (await load()) setNotice(remove ? 'Modèle supprimé du catalogue.' : 'Disponibilité du modèle mise à jour.')
|
||
} catch (error) {
|
||
setError(error && typeof error === 'object' && 'status' in error && error.status === 409
|
||
? 'Ce modèle est encore sélectionné par un compte et ne peut pas être supprimé.'
|
||
: 'Impossible de modifier le catalogue. Le modèle est conservé.')
|
||
} finally { setBusy(false) }
|
||
}
|
||
|
||
return <Card>
|
||
<CardHeader><CardTitle>Catalogue des modèles de synthèse</CardTitle></CardHeader>
|
||
<CardContent className="space-y-4">
|
||
<p>Les modèles activés sont proposés à tous les comptes. Chaque utilisateur choisit sa configuration personnelle ; aucun choix global ne remplace cette sélection.</p>
|
||
<p id="model-test-help" className="text-sm text-muted-foreground">Le test envoie une courte demande au modèle exact et vérifie qu’une réponse non vide est reçue. Il peut consommer des tokens facturés. La réponse n’est pas affichée. Un modèle désactivé peut être testé sans être activé.</p>
|
||
{loading && <p role="status">Chargement du catalogue…</p>}
|
||
{error && <div><p role="alert">{error}</p><Button disabled={busy} variant="outline" onClick={() => { setLoading(true); setError(''); void load() }}>Recharger le catalogue</Button></div>}
|
||
{notice && <p role="status">{notice}</p>}
|
||
{!loading && <>
|
||
{!loadFailed && entries.length === 0 && <p>Aucun modèle configuré.</p>}
|
||
<ul className="space-y-3">{entries.map(entry => {
|
||
const provider = entry.provider ?? providers.find(provider => provider.id === entry.provider_id)?.name ?? 'Fournisseur indisponible'
|
||
const storedResult = testResults[entry.id]
|
||
const result = storedResult?.config === configuration(entry) && storedResult.revision === testConfiguration.revision ? storedResult : undefined
|
||
const providerTesting = providerBusy(entry.provider_id)
|
||
const message = providerTesting
|
||
? testingByProvider[entry.provider_id] === entry.id ? MODEL_TEST_MESSAGES.testing : `Un test est déjà en cours chez ${provider}.`
|
||
: result ? MODEL_TEST_MESSAGES[result.status] : ''
|
||
return <li key={entry.id} className="rounded-md border p-3 space-y-2 break-words">
|
||
<p>{provider} · {entry.model}</p>
|
||
<p>{entry.enabled ? 'Proposé aux comptes' : 'Désactivé'}</p>
|
||
<div className="flex flex-wrap gap-2" aria-busy={providerTesting}>
|
||
<Button variant="outline" disabled={busy || loadFailed || providerTesting}
|
||
ref={element => { if (element) testButtons.current.set(entry.id, element); else testButtons.current.delete(entry.id) }}
|
||
aria-label={`Tester le modèle ${entry.model} chez ${provider}`}
|
||
aria-describedby={`model-test-help model-test-${entry.id}`}
|
||
onClick={() => void test(entry)}>{testingByProvider[entry.provider_id] === entry.id ? 'Test en cours…' : 'Tester'}</Button>
|
||
<Button variant="outline" disabled={busy || loadFailed || providerTesting} onClick={() => void change(entry, false)}>{entry.enabled ? 'Désactiver' : 'Activer'}</Button>
|
||
<Button variant="outline" disabled={busy || loadFailed || providerTesting} onClick={() => void change(entry, true)}>Supprimer le modèle</Button>
|
||
</div>
|
||
<p id={`model-test-${entry.id}`} role="status" aria-label={`Test du modèle ${entry.model} chez ${provider}`} aria-live="polite" aria-atomic="true">{message}</p>
|
||
</li>
|
||
})}</ul>
|
||
{!loadFailed && <form aria-label="Ajouter un modèle" onSubmit={save} className="space-y-3">
|
||
<Label htmlFor="catalog-provider">Connexion fournisseur</Label>
|
||
<Select id="catalog-provider" required disabled={busy} value={providerId} onChange={event => setProviderId(event.target.value)}>
|
||
<option value="">Choisir une connexion</option>
|
||
{providers.map(provider => <option key={provider.id} value={provider.id}>{provider.name}</option>)}
|
||
</Select>
|
||
<Label htmlFor="catalog-model">Identifiant du modèle</Label>
|
||
<Input id="catalog-model" required maxLength={256} value={model} disabled={busy || providerBusy(providerId)} onChange={event => setModel(event.target.value)} />
|
||
<div className="flex flex-wrap gap-2">
|
||
<Button type="submit" disabled={busy || !providerId || !model.trim() || providerBusy(providerId)}>{busy ? 'Enregistrement…' : 'Ajouter au catalogue'}</Button>
|
||
</div>
|
||
</form>}
|
||
</>}
|
||
</CardContent>
|
||
</Card>
|
||
}
|