import { useState, useEffect, useCallback } from 'react' import { Plus, Trash2, Download, HardDrive, Cpu, ChevronUp, X } from 'lucide-react' import { AIModelCatalog } from '@/components/AIModelCatalog' import { adminApi, type AIProvider, type OllamaModelInfo, type ProviderConnectionStatus } from '@/api/admin' 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' import { Badge } from '@/components/ui/badge' import { Spinner } from '@/components/ui/spinner' const PROVIDER_NAMES = ['openai', 'anthropic', 'gemini', 'ollama', 'claudecode'] as const type ConnectionState = ProviderConnectionStatus | 'testing' | 'error' const CONNECTION_MESSAGES: Record = { testing: 'Test en cours…', success: 'Connexion et authentification vérifiées.', auth_check_unsupported: 'Authentification non vérifiée. Aucune synthèse n’a été générée.', auth_rejected: 'Authentification refusée. Vérifiez les identifiants du fournisseur.', unavailable: 'Fournisseur indisponible. Réessayez plus tard.', error: 'Impossible de tester la connexion. Réessayez.', } const CUSTOM_MODELS_KEY = 'ollama_custom_models' const KNOWN_OLLAMA_MODELS: { name: string; family: string; tags: { tag: string; size: string }[] }[] = [ { name: 'qwen3', family: 'Qwen3', tags: [{ tag: '0.6b', size: '~0.4 GB' }, { tag: '1.7b', size: '~1.1 GB' }, { tag: '4b', size: '~2.6 GB' }, { tag: '8b', size: '~5.2 GB' }, { tag: '14b', size: '~9.3 GB' }, { tag: '32b', size: '~20 GB' }] }, { name: 'qwen2.5', family: 'Qwen2.5', tags: [{ tag: '0.5b', size: '~0.4 GB' }, { tag: '1.5b', size: '~1 GB' }, { tag: '3b', size: '~2 GB' }, { tag: '7b', size: '~4.7 GB' }, { tag: '14b', size: '~9 GB' }, { tag: '32b', size: '~20 GB' }] }, { name: 'llama3.2', family: 'Llama 3.2', tags: [{ tag: '1b', size: '~1.3 GB' }, { tag: '3b', size: '~2 GB' }] }, { name: 'llama3.1', family: 'Llama 3.1', tags: [{ tag: '8b', size: '~4.9 GB' }, { tag: '70b', size: '~40 GB' }] }, { name: 'gemma3', family: 'Gemma 3', tags: [{ tag: '1b', size: '~0.8 GB' }, { tag: '4b', size: '~3.3 GB' }, { tag: '12b', size: '~8 GB' }, { tag: '27b', size: '~17 GB' }] }, { name: 'mistral', family: 'Mistral', tags: [{ tag: '7b', size: '~4.1 GB' }] }, { name: 'phi4', family: 'Phi-4', tags: [{ tag: 'latest', size: '~9 GB' }] }, { name: 'phi4-mini', family: 'Phi-4 Mini', tags: [{ tag: 'latest', size: '~2.5 GB' }] }, { name: 'deepseek-r1', family: 'DeepSeek-R1', tags: [{ tag: '1.5b', size: '~1.1 GB' }, { tag: '7b', size: '~4.7 GB' }, { tag: '8b', size: '~4.9 GB' }, { tag: '14b', size: '~9 GB' }, { tag: '32b', size: '~20 GB' }] }, ] function formatSize(bytes: number): string { if (bytes >= 1e9) return `${(bytes / 1e9).toFixed(1)} GB` if (bytes >= 1e6) return `${(bytes / 1e6).toFixed(0)} MB` return `${bytes} B` } function loadCustomModels(): string[] { try { return JSON.parse(localStorage.getItem(CUSTOM_MODELS_KEY) ?? '[]') } catch { return [] } } function saveCustomModels(models: string[]) { localStorage.setItem(CUSTOM_MODELS_KEY, JSON.stringify(models)) } // ── Confirmation dialog ──────────────────────────────────────────────────── function ConfirmDownloadDialog({ modelName, onConfirm, onCancel }: { modelName: string onConfirm: () => void onCancel: () => void }) { return (

Télécharger ce modèle ?

{modelName} sera téléchargé depuis Ollama Hub. Le téléchargement peut prendre plusieurs minutes.

) } // ── Shared model catalogue ───────────────────────────────────────────────── function ModelCatalogue({ installedNames, pulling, onPull, }: { installedNames: Set pulling: string | null onPull: (name: string) => void }) { const [customName, setCustomName] = useState('') const [pendingModel, setPendingModel] = useState(null) const [customModels, setCustomModels] = useState(loadCustomModels) // All model names in the hardcoded catalogue const knownNames = new Set( KNOWN_OLLAMA_MODELS.flatMap(f => f.tags.map(t => `${f.name}:${t.tag}`)) ) function requestPull(name: string) { setPendingModel(name) } function confirmPull() { if (!pendingModel) return // If not in hardcoded catalogue, add to custom list if (!knownNames.has(pendingModel)) { const updated = [...new Set([...customModels, pendingModel])] setCustomModels(updated) saveCustomModels(updated) } onPull(pendingModel) setPendingModel(null) } function submitCustom() { const name = customName.trim() if (!name) return const fullName = name.includes(':') ? name : `${name}:latest` setCustomName('') requestPull(fullName) } // Families to display: hardcoded + custom entries const customEntries = customModels.filter(m => !knownNames.has(m)) return ( <> {pendingModel && ( setPendingModel(null)} /> )}
{/* Free-text input */}

Nom personnalisé

setCustomName(e.target.value)} onKeyDown={e => e.key === 'Enter' && submitCustom()} disabled={pulling !== null} />
{/* Custom models section */} {customEntries.length > 0 && (

Personnalisés

{customEntries.map(fullName => { const installed = installedNames.has(fullName) const isPulling = pulling === fullName return })}
)} {/* Hardcoded catalogue */}
{KNOWN_OLLAMA_MODELS.map(family => (

{family.family}

{family.tags.map(({ tag, size }) => { const fullName = `${family.name}:${tag}` const installed = installedNames.has(fullName) const isPulling = pulling === fullName return })}
))}
) } function ModelTag({ fullName, size, installed, isPulling, pulling, onRequest }: { fullName: string; size: string installed: boolean; isPulling: boolean; pulling: string | null onRequest: (name: string) => void }) { return ( ) } // ── Ollama model manager card ────────────────────────────────────────────── function OllamaModelsCard({ installedModels, onRefresh, onDelete }: { installedModels: OllamaModelInfo[] onRefresh: () => Promise onDelete: (name: string) => Promise }) { const [showCatalogue, setShowCatalogue] = useState(false) const [pulling, setPulling] = useState(null) const [deleting, setDeleting] = useState(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(resolve => { const iv = setInterval(async () => { try { const updated = await onRefresh() if (updated.some(m => m.name === fullName)) { clearInterval(iv); resolve() } } catch { /* ignore */ } }, 4000) setTimeout(() => { clearInterval(iv); resolve() }, 1800000) }) } finally { setPulling(null) } } async function remove(name: string) { setDeleting(name) try { await onDelete(name) } finally { setDeleting(null) } } return (
Modèles Ollama

Installés ({installedModels.length})

{installedModels.length === 0 ? (

Aucun modèle installé

) : (
{installedModels.map(m => (
{m.name} {formatSize(m.size)} {m.details.parameter_size && <> · {m.details.parameter_size}} {m.details.quantization_level && <> · {m.details.quantization_level}}
))}
)}
{showCatalogue && (

Catalogue

)}
) } // ── Main Page ────────────────────────────────────────────────────────────── export function AIProviders() { const [providers, setProviders] = useState([]) const [ollamaModels, setOllamaModels] = useState([]) const [loading, setLoading] = useState(true) const [showForm, setShowForm] = useState(false) const [form, setForm] = useState({ name: 'openai', api_key: '', model: '', endpoint: '' }) const [editId, setEditId] = useState(null) const [saving, setSaving] = useState(false) const [error, setError] = useState('') const [connectionStates, setConnectionStates] = useState>({}) const isOllamaForm = form.name === 'ollama' const isClaudeCodeForm = form.name === 'claudecode' const loadOllamaModels = useCallback(async (): Promise => { try { const m = await adminApi.listOllamaModels() const list = m ?? [] setOllamaModels(list) return list } catch (e) { console.error('[ollama] error:', e) return [] } }, []) const load = useCallback(() => { return adminApi.listProviders().then(async providers => { setProviders(providers ?? []) await loadOllamaModels() }).catch(() => setError('Impossible de charger les fournisseurs.')) .finally(() => setLoading(false)) }, [loadOllamaModels]) useEffect(() => { load() }, [load]) async function testConnection(provider: AIProvider) { setConnectionStates(states => ({ ...states, [provider.id]: 'testing' })) try { const result = await adminApi.testProvider(provider.id) const status = result?.status const state = status === 'success' || status === 'auth_rejected' || status === 'unavailable' || status === 'auth_check_unsupported' ? status : 'error' setConnectionStates(states => ({ ...states, [provider.id]: state })) } catch { setConnectionStates(states => ({ ...states, [provider.id]: 'error' })) } } async function save() { setSaving(true); setError('') try { if (editId) { await adminApi.updateProvider(editId, form) } else { await adminApi.createProvider(form) } setConnectionStates({}) setShowForm(false); setEditId(null) setForm({ name: 'openai', api_key: '', model: '', endpoint: '' }) setLoading(true); await load() } catch { setError('Impossible d’enregistrer le fournisseur.'); setForm(f => ({ ...f, api_key: '' })) } finally { setSaving(false) } } async function remove(id: string) { if (!confirm('Supprimer ce fournisseur ?')) return 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 deleteOllamaModel(name: string) { await adminApi.deleteOllamaModel(name); await loadOllamaModels() } return (

Fournisseurs IA

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.

{error && !showForm &&

{error}

} {loading ? (
) : ( <> Classement des articles

Laya, moteur fixe

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.

{/* Providers list */}
Fournisseurs configurés
{showForm && (

{editId ? 'Modifier le fournisseur' : 'Nouveau fournisseur'}

{!isOllamaForm && !isClaudeCodeForm && (
setForm(f => ({ ...f, api_key: e.target.value }))} />
)} {isOllamaForm && (
setForm(f => ({ ...f, endpoint: e.target.value }))} />
)}
{error &&

{error}

}
)} {providers.length === 0 && !showForm && (

Aucun fournisseur configuré

)}

Le test vérifie la connexion avec les identifiants enregistrés. Aucune synthèse n’est générée.

{providers.map(p => (
{p.name} {!p.has_key && p.name !== 'ollama' && p.name !== 'claudecode' && Sans clé}
{p.endpoint && {p.endpoint}}

{connectionStates[p.id] ? CONNECTION_MESSAGES[connectionStates[p.id]] : (!p.has_key && p.name !== 'ollama' && p.name !== 'claudecode' ? 'Ajoutez une clé API pour tester la connexion.' : '')}

))}
{/* Ollama model manager — always shown so user can install even without provider configured */} )}
) }