feat(ai): test saved summary model generation (#43)
This commit is contained in:
@ -6,6 +6,8 @@ export interface AIProvider {
|
||||
}
|
||||
export type ProviderConnectionStatus = 'success' | 'auth_rejected' | 'unavailable' | 'auth_check_unsupported'
|
||||
|
||||
export type AIModelTestStatus = 'success' | 'empty_response' | 'auth_rejected' | 'model_unavailable' | 'rate_limited' | 'timeout' | 'unavailable'
|
||||
|
||||
export interface AIModelCatalogEntry { id: string; provider_id: string; provider?: string; model: string; enabled: boolean }
|
||||
export interface OllamaModelInfo {
|
||||
name: string; size: number; modified_at: string
|
||||
@ -42,6 +44,7 @@ export const adminApi = {
|
||||
|
||||
// User-selectable synthesis model catalogue
|
||||
listAIModelCatalog: () => api.get<AIModelCatalogEntry[]>('/admin/ai-models'),
|
||||
testAIModelCatalogEntry: (id: string) => api.post<{ status: AIModelTestStatus }>(`/admin/ai-models/${encodeURIComponent(id)}/test`),
|
||||
createAIModelCatalogEntry: (data: { provider_id: string; model: string }) => api.post<AIModelCatalogEntry>('/admin/ai-models', data),
|
||||
updateAIModelCatalogEntry: (id: string, data: { enabled: boolean }) => api.put<AIModelCatalogEntry>(`/admin/ai-models/${encodeURIComponent(id)}`, data),
|
||||
deleteAIModelCatalogEntry: (id: string) => api.delete<void>(`/admin/ai-models/${encodeURIComponent(id)}`),
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
import { useEffect, useState, useCallback, type FormEvent } from 'react'
|
||||
import { adminApi, type AIProvider, type AIModelCatalogEntry } from '@/api/admin'
|
||||
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'
|
||||
@ -16,7 +17,39 @@ function isCatalogEntry(value: unknown): value is AIModelCatalogEntry {
|
||||
&& (entry.provider === undefined || typeof entry.provider === 'string')
|
||||
}
|
||||
|
||||
export function AIModelCatalog({ providers }: { providers: AIProvider[] }) {
|
||||
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)
|
||||
@ -39,9 +72,49 @@ export function AIModelCatalog({ providers }: { providers: AIProvider[] }) {
|
||||
.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()) return
|
||||
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() })
|
||||
@ -52,11 +125,12 @@ export function AIModelCatalog({ providers }: { providers: AIProvider[] }) {
|
||||
}
|
||||
|
||||
async function change(entry: AIModelCatalogEntry, remove: boolean) {
|
||||
if (busy || loadFailed) return
|
||||
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
|
||||
@ -69,19 +143,35 @@ export function AIModelCatalog({ providers }: { providers: AIProvider[] }) {
|
||||
<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 => <li key={entry.id} className="rounded-md border p-3 space-y-2 break-words">
|
||||
<p>{entry.provider ?? providers.find(provider => provider.id === entry.provider_id)?.name ?? 'Fournisseur indisponible'} · {entry.model}</p>
|
||||
<p>{entry.enabled ? 'Proposé aux comptes' : 'Désactivé'}</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button variant="outline" disabled={busy || loadFailed} onClick={() => void change(entry, false)}>{entry.enabled ? 'Désactiver' : 'Activer'}</Button>
|
||||
<Button variant="outline" disabled={busy || loadFailed} onClick={() => void change(entry, true)}>Supprimer le modèle</Button>
|
||||
</div>
|
||||
</li>)}</ul>
|
||||
<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)}>
|
||||
@ -89,9 +179,9 @@ export function AIModelCatalog({ providers }: { providers: AIProvider[] }) {
|
||||
{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} onChange={event => setModel(event.target.value)} />
|
||||
<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()}>{busy ? 'Enregistrement…' : 'Ajouter au catalogue'}</Button>
|
||||
<Button type="submit" disabled={busy || !providerId || !model.trim() || providerBusy(providerId)}>{busy ? 'Enregistrement…' : 'Ajouter au catalogue'}</Button>
|
||||
</div>
|
||||
</form>}
|
||||
</>}
|
||||
|
||||
@ -321,6 +321,7 @@ export function AIProviders() {
|
||||
const [editId, setEditId] = useState<string | null>(null)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const [modelTestingProviders, setModelTestingProviders] = useState<string[]>([])
|
||||
const [connectionStates, setConnectionStates] = useState<Record<string, ConnectionState>>({})
|
||||
|
||||
const isOllamaForm = form.name === 'ollama'
|
||||
@ -361,6 +362,7 @@ export function AIProviders() {
|
||||
}
|
||||
|
||||
async function save() {
|
||||
if (editId && modelTestingProviders.includes(editId)) return
|
||||
setSaving(true); setError('')
|
||||
try {
|
||||
if (editId) { await adminApi.updateProvider(editId, form) }
|
||||
@ -405,7 +407,9 @@ export function AIProviders() {
|
||||
<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} />
|
||||
<AIModelCatalog providers={providers}
|
||||
busyProviderIds={[...modelTestingProviders, ...Object.keys(connectionStates).filter(id => connectionStates[id] === 'testing'), ...(saving && editId ? [editId] : [])]}
|
||||
onTestingChange={(id, testing) => setModelTestingProviders(current => testing ? [...new Set([...current, id])] : current.filter(value => value !== id))} />
|
||||
|
||||
{/* Providers list */}
|
||||
<Card>
|
||||
@ -447,7 +451,7 @@ export function AIProviders() {
|
||||
</div>
|
||||
{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" onClick={save} disabled={saving || !!(editId && modelTestingProviders.includes(editId))}>{saving ? <Spinner className="h-4 w-4" /> : 'Enregistrer'}</Button>
|
||||
<Button size="sm" variant="outline" onClick={() => { setShowForm(false); setEditId(null); setForm(f => ({ ...f, api_key: '' })) }}>Annuler</Button>
|
||||
</div>
|
||||
</div>
|
||||
@ -474,12 +478,12 @@ export function AIProviders() {
|
||||
<Button variant="outline" size="sm" className="h-7 px-2 text-xs"
|
||||
aria-label={`Tester la connexion ${p.name}`}
|
||||
aria-describedby={`connection-${p.id}`}
|
||||
disabled={connectionStates[p.id] === 'testing' || (!p.has_key && p.name !== 'ollama' && p.name !== 'claudecode')}
|
||||
disabled={modelTestingProviders.includes(p.id) || connectionStates[p.id] === 'testing' || (!p.has_key && p.name !== 'ollama' && p.name !== 'claudecode')}
|
||||
onClick={() => testConnection(p)}>
|
||||
{connectionStates[p.id] === 'testing' ? 'Test en cours…' : 'Tester'}
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" className="h-7 px-2 text-xs" disabled={connectionStates[p.id] === 'testing'} onClick={() => startEdit(p)}>Modifier</Button>
|
||||
<Button variant="ghost" size="sm" className="h-7 w-7 p-0 text-destructive hover:text-destructive" disabled={connectionStates[p.id] === 'testing'} onClick={() => remove(p.id)}>
|
||||
<Button variant="ghost" size="sm" className="h-7 px-2 text-xs" disabled={modelTestingProviders.includes(p.id) || connectionStates[p.id] === 'testing'} onClick={() => startEdit(p)}>Modifier</Button>
|
||||
<Button variant="ghost" size="sm" className="h-7 w-7 p-0 text-destructive hover:text-destructive" disabled={modelTestingProviders.includes(p.id) || connectionStates[p.id] === 'testing'} onClick={() => remove(p.id)}>
|
||||
<Trash2 className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
51
frontend/tests/catalog-provider-lock-ticket43.test.tsx
Normal file
51
frontend/tests/catalog-provider-lock-ticket43.test.tsx
Normal file
@ -0,0 +1,51 @@
|
||||
import { cleanup, render, screen, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
|
||||
import { AIProviders } from '../src/pages/admin/AIProviders'
|
||||
|
||||
const fetchMock = vi.fn()
|
||||
const response = (data: unknown) => new Response(JSON.stringify({ data }), { status: 200 })
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
fetchMock.mockReset().mockImplementation((url: string) => Promise.resolve(response(
|
||||
url === '/api/admin/ai-providers' ? [
|
||||
{ id: 'p0', name: 'openai', endpoint: '', model: '', has_key: true, is_active: true },
|
||||
{ id: 'p1', name: 'ollama', endpoint: '', model: '', has_key: false, is_active: true },
|
||||
] : url === '/api/admin/ai-models' ? [
|
||||
{ id: 'a', provider_id: 'p0', model: 'exact-model', enabled: false },
|
||||
{ id: 'b', provider_id: 'p1', model: 'local-model', enabled: true },
|
||||
] : [],
|
||||
)))
|
||||
})
|
||||
afterEach(() => { cleanup(); vi.unstubAllGlobals() })
|
||||
|
||||
it('bloque la configuration et la découverte du même fournisseur pendant le test réel du modèle', async () => {
|
||||
render(<AIProviders />)
|
||||
const test = await screen.findByRole('button', { name: 'Tester le modèle exact-model chez openai' })
|
||||
const provider = document.querySelector<HTMLElement>('[data-provider-id="p0"]')!
|
||||
await userEvent.click(within(provider).getByRole('button', { name: 'Modifier', exact: true }))
|
||||
let complete!: (value: Response) => void
|
||||
fetchMock.mockImplementationOnce(() => new Promise<Response>(resolve => { complete = resolve }))
|
||||
await userEvent.click(test)
|
||||
for (const button of within(provider).getAllByRole('button')) expect(button).toBeDisabled()
|
||||
expect(screen.getByRole('button', { name: 'Enregistrer', exact: true })).toBeDisabled()
|
||||
const other = document.querySelector<HTMLElement>('[data-provider-id="p1"]')!
|
||||
expect(within(other).getByRole('button', { name: 'Modifier', exact: true })).toBeEnabled()
|
||||
complete(response({ status: 'success' }))
|
||||
expect(await screen.findByText('Test réussi : le modèle a renvoyé une réponse non vide.')).toBeInTheDocument()
|
||||
expect(within(provider).getByRole('button', { name: 'Modifier', exact: true })).toBeEnabled()
|
||||
})
|
||||
|
||||
it('ne démarre pas un test modèle lorsque la découverte de ce fournisseur est déjà en cours', async () => {
|
||||
render(<AIProviders />)
|
||||
const test = await screen.findByRole('button', { name: 'Tester le modèle exact-model chez openai' })
|
||||
let complete!: (value: Response) => void
|
||||
fetchMock.mockImplementationOnce(() => new Promise<Response>(resolve => { complete = resolve }))
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Tester la connexion openai' }))
|
||||
expect(test).toBeDisabled()
|
||||
expect(screen.getByRole('status', { name: 'Test du modèle exact-model chez openai' })).toHaveTextContent('Un test est déjà en cours chez openai.')
|
||||
expect(screen.getByRole('button', { name: 'Tester le modèle local-model chez ollama' })).toBeEnabled()
|
||||
complete(response({ status: 'success' }))
|
||||
expect(await screen.findByText('Connexion et authentification vérifiées.')).toBeInTheDocument()
|
||||
expect(test).toBeEnabled()
|
||||
})
|
||||
181
frontend/tests/model-generation-test-ticket43.test.tsx
Normal file
181
frontend/tests/model-generation-test-ticket43.test.tsx
Normal file
@ -0,0 +1,181 @@
|
||||
import { cleanup, render, screen, within, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
|
||||
import { AIModelCatalog } from '../src/components/AIModelCatalog'
|
||||
import type { AIProvider } from '../src/api/admin'
|
||||
|
||||
const providers: AIProvider[] = ['openai', 'ollama', 'claudecode'].map((name, index) => ({ id: `p${index}`, name, model: '', endpoint: '', has_key: index === 0, is_active: true }))
|
||||
let entries: { id: string; provider_id: string; model: string; enabled: boolean }[]
|
||||
const fetchMock = vi.fn()
|
||||
const response = (body: unknown) => new Response(JSON.stringify({ data: body }), { status: 200 })
|
||||
const testButton = (name = 'exact-model', provider = 'openai') => screen.getByRole('button', { name: `Tester le modèle ${name} chez ${provider}`, exact: true })
|
||||
const result = (name = 'exact-model', provider = 'openai') => screen.getByRole('status', { name: `Test du modèle ${name} chez ${provider}` })
|
||||
beforeEach(() => {
|
||||
entries = [
|
||||
{ id: 'model/a', provider_id: 'p0', model: 'exact-model', enabled: true },
|
||||
{ id: 'disabled', provider_id: 'p0', model: 'disabled-model', enabled: false },
|
||||
{ id: 'local', provider_id: 'p1', model: 'local-model', enabled: true },
|
||||
{ id: 'code', provider_id: 'p2', model: 'code-model', enabled: false },
|
||||
]
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
fetchMock.mockReset().mockImplementation(() => Promise.resolve(response(entries)))
|
||||
})
|
||||
afterEach(() => { cleanup(); vi.unstubAllGlobals() })
|
||||
|
||||
it('envoie uniquement le POST du modèle exact et avertit du coût, sans afficher de réponse', async () => {
|
||||
render(<AIModelCatalog providers={providers} />)
|
||||
await screen.findByText('openai · exact-model')
|
||||
expect(screen.getByText(/tokens facturés/)).toBeInTheDocument()
|
||||
expect(screen.getByText(/réponse n’est pas affichée/)).toBeInTheDocument()
|
||||
fetchMock.mockResolvedValueOnce(response({ status: 'success', response: 'PRIVATE_GENERATED_TEXT', prompt: 'PRIVATE_PROMPT', secret: 'PRIVATE_SECRET' }))
|
||||
const button = testButton()
|
||||
await userEvent.click(button)
|
||||
expect(fetchMock).toHaveBeenLastCalledWith('/api/admin/ai-models/model%2Fa/test', expect.objectContaining({ method: 'POST', body: undefined }))
|
||||
expect(result()).toHaveTextContent('Test réussi : le modèle a renvoyé une réponse non vide.')
|
||||
expect(button).toHaveFocus()
|
||||
expect(document.body.innerHTML).not.toMatch(/PRIVATE_/)
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it.each([
|
||||
['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.'],
|
||||
['unknown', 'Impossible de tester le modèle. Réessayez.'],
|
||||
])('affiche un statut borné et accessible pour %s, sans relance automatique', async (status, message) => {
|
||||
render(<AIModelCatalog providers={providers} />)
|
||||
await screen.findByText('openai · exact-model')
|
||||
fetchMock.mockResolvedValueOnce(response({ status, error: 'PRIVATE_ERROR', response: 'PRIVATE_GENERATED_TEXT' }))
|
||||
await userEvent.click(testButton())
|
||||
expect(result()).toHaveTextContent(message)
|
||||
expect(result('disabled-model')).toBeEmptyDOMElement()
|
||||
expect(testButton()).toBeEnabled()
|
||||
expect(document.body.innerHTML).not.toMatch(/PRIVATE_/)
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('permet les modèles désactivés et les fournisseurs sans clé Ollama/Claude Code sans les activer', async () => {
|
||||
render(<AIModelCatalog providers={providers} />)
|
||||
await screen.findByText('openai · exact-model')
|
||||
for (const [model, provider] of [['disabled-model', 'openai'], ['local-model', 'ollama'], ['code-model', 'claudecode']]) {
|
||||
fetchMock.mockResolvedValueOnce(response({ status: 'success' }))
|
||||
await userEvent.click(testButton(model, provider))
|
||||
expect(result(model, provider)).toHaveTextContent('réponse non vide')
|
||||
}
|
||||
const disabledRow = testButton('disabled-model').closest('li')!
|
||||
expect(within(disabledRow).getByRole('button', { name: 'Activer', exact: true })).toBeEnabled()
|
||||
expect(within(disabledRow).getByText('Désactivé', { exact: true })).toBeInTheDocument()
|
||||
expect(fetchMock.mock.calls.slice(1).every(([, options]) => options.method === 'POST' && options.body === undefined)).toBe(true)
|
||||
expect(fetchMock).toHaveBeenCalledTimes(4)
|
||||
})
|
||||
|
||||
it('annonce le fournisseur occupé, bloque ses actions et garde les fournisseurs distincts indépendants', async () => {
|
||||
render(<AIModelCatalog providers={providers} />)
|
||||
await screen.findByText('openai · exact-model')
|
||||
await userEvent.selectOptions(screen.getByLabelText('Connexion fournisseur'), 'p0')
|
||||
await userEvent.type(screen.getByLabelText('Identifiant du modèle'), 'another-model')
|
||||
let complete!: (value: Response) => void
|
||||
fetchMock.mockImplementationOnce(() => new Promise<Response>(resolve => { complete = resolve }))
|
||||
await userEvent.click(testButton())
|
||||
expect(result()).toHaveTextContent('Test du modèle en cours…')
|
||||
expect(result('disabled-model')).toHaveTextContent('Un test est déjà en cours chez openai.')
|
||||
const sameRow = testButton('disabled-model').closest('li')!
|
||||
for (const button of within(sameRow).getAllByRole('button')) expect(button).toBeDisabled()
|
||||
const ownRow = testButton().closest('li')!
|
||||
for (const button of within(ownRow).getAllByRole('button')) expect(button).toBeDisabled()
|
||||
expect(screen.getByRole('button', { name: 'Ajouter au catalogue' })).toBeDisabled()
|
||||
expect(testButton('local-model', 'ollama')).toBeEnabled()
|
||||
fetchMock.mockResolvedValueOnce(response({ status: 'success' }))
|
||||
await userEvent.click(testButton('local-model', 'ollama'))
|
||||
expect(result('local-model', 'ollama')).toHaveTextContent('réponse non vide')
|
||||
expect(result()).toHaveTextContent('Test du modèle en cours…')
|
||||
complete(response({ status: 'empty_response' }))
|
||||
expect(await within(result()).findByText('Le modèle a renvoyé une réponse vide.')).toBeInTheDocument()
|
||||
expect(testButton('disabled-model')).toBeEnabled()
|
||||
})
|
||||
|
||||
it('assainit les erreurs réseau et permet une reprise manuelle', async () => {
|
||||
render(<AIModelCatalog providers={providers} />)
|
||||
await screen.findByText('openai · exact-model')
|
||||
fetchMock.mockRejectedValueOnce(new Error('PRIVATE_ERROR https://private.invalid'))
|
||||
await userEvent.click(testButton())
|
||||
expect(result()).toHaveTextContent('Impossible de tester le modèle. Réessayez.')
|
||||
expect(document.body.innerHTML).not.toMatch(/PRIVATE_|private.invalid/)
|
||||
fetchMock.mockResolvedValueOnce(response({ status: 'success' }))
|
||||
await userEvent.click(testButton())
|
||||
expect(result()).toHaveTextContent('réponse non vide')
|
||||
expect(fetchMock).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
|
||||
it('efface un résultat lorsque la configuration du fournisseur change, sans refaire de test', async () => {
|
||||
const view = render(<AIModelCatalog providers={providers} />)
|
||||
await screen.findByText('openai · exact-model')
|
||||
fetchMock.mockResolvedValueOnce(response({ status: 'success' }))
|
||||
await userEvent.click(testButton())
|
||||
expect(result()).toHaveTextContent('réponse non vide')
|
||||
view.rerender(<AIModelCatalog providers={providers.map(provider => ({ ...provider, endpoint: 'changed-endpoint' }))} />)
|
||||
expect(result()).toBeEmptyDOMElement()
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('efface un résultat après modification du modèle au catalogue', async () => {
|
||||
render(<AIModelCatalog providers={providers} />)
|
||||
await screen.findByText('openai · exact-model')
|
||||
fetchMock.mockResolvedValueOnce(response({ status: 'success' }))
|
||||
await userEvent.click(testButton())
|
||||
entries = entries.map(entry => entry.id === 'model/a' ? { ...entry, enabled: false } : entry)
|
||||
const row = testButton().closest('li')!
|
||||
await userEvent.click(within(row).getByRole('button', { name: 'Désactiver', exact: true }))
|
||||
expect(await within(row).findByText('Désactivé', { exact: true })).toBeInTheDocument()
|
||||
expect(result()).toBeEmptyDOMElement()
|
||||
})
|
||||
|
||||
it('assainit aussi les échecs HTTP sans afficher la réponse du fournisseur', async () => {
|
||||
render(<AIModelCatalog providers={providers} />)
|
||||
await screen.findByText('openai · exact-model')
|
||||
fetchMock.mockResolvedValueOnce(new Response(JSON.stringify({ error: 'PRIVATE_EXCEPTION', response: 'PRIVATE_GENERATED_TEXT' }), { status: 500 }))
|
||||
await userEvent.click(testButton())
|
||||
expect(result()).toHaveTextContent('Impossible de tester le modèle. Réessayez.')
|
||||
expect(document.body.innerHTML).not.toMatch(/PRIVATE_/)
|
||||
})
|
||||
|
||||
it.each([[409, 'Un test est déjà en cours chez ce fournisseur. Attendez sa fin avant de lancer un nouveau test.'], [404, 'Modèle inaccessible chez ce fournisseur.']])('affiche le refus HTTP %s du handler sans texte brut', async (status, message) => {
|
||||
render(<AIModelCatalog providers={providers} />)
|
||||
await screen.findByText('openai · exact-model')
|
||||
fetchMock.mockResolvedValueOnce(new Response(JSON.stringify({ status: 'unavailable', error: 'PRIVATE_EXCEPTION' }), { status }))
|
||||
await userEvent.click(testButton())
|
||||
expect(result()).toHaveTextContent(message)
|
||||
expect(document.body.innerHTML).not.toMatch(/PRIVATE_/)
|
||||
})
|
||||
|
||||
it('ignore le résultat devenu périmé si la configuration change pendant le test', async () => {
|
||||
const view = render(<AIModelCatalog providers={providers} />)
|
||||
await screen.findByText('openai · exact-model')
|
||||
let complete!: (value: Response) => void
|
||||
fetchMock.mockImplementationOnce(() => new Promise<Response>(resolve => { complete = resolve }))
|
||||
await userEvent.click(testButton())
|
||||
view.rerender(<AIModelCatalog providers={providers.map(provider => ({ ...provider, endpoint: 'changed-endpoint' }))} />)
|
||||
expect(result()).toHaveTextContent('Test du modèle en cours…')
|
||||
view.rerender(<AIModelCatalog providers={providers} />)
|
||||
complete(response({ status: 'success' }))
|
||||
await within(testButton().closest('li')!).findByRole('button', { name: 'Tester le modèle exact-model chez openai' })
|
||||
await waitFor(() => expect(testButton()).toBeEnabled())
|
||||
expect(result()).toBeEmptyDOMElement()
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('ne réaffiche pas un ancien succès si la configuration revient à sa valeur précédente', async () => {
|
||||
const view = render(<AIModelCatalog providers={providers} />)
|
||||
await screen.findByText('openai · exact-model')
|
||||
fetchMock.mockResolvedValueOnce(response({ status: 'success' }))
|
||||
await userEvent.click(testButton())
|
||||
expect(result()).toHaveTextContent('réponse non vide')
|
||||
view.rerender(<AIModelCatalog providers={providers.map(provider => ({ ...provider, endpoint: 'changed-endpoint' }))} />)
|
||||
expect(result()).toBeEmptyDOMElement()
|
||||
view.rerender(<AIModelCatalog providers={providers} />)
|
||||
expect(result()).toBeEmptyDOMElement()
|
||||
})
|
||||
Reference in New Issue
Block a user