feat(ai): add provider connection test (#38)

This commit is contained in:
2026-11-24 16:21:48 +01:00
parent 2e865204c8
commit 54fced1ffb
16 changed files with 599 additions and 18 deletions

View File

@ -4,6 +4,8 @@ export interface AIProvider {
id: string; name: string; model: string; endpoint: string
is_active: boolean; has_key: boolean
}
export type ProviderConnectionStatus = 'success' | 'auth_rejected' | 'unavailable' | 'auth_check_unsupported'
export interface AIModelCatalogEntry { id: string; provider_id: string; provider?: string; model: string; enabled: boolean }
export interface OllamaModelInfo {
name: string; size: number; modified_at: string
@ -31,6 +33,8 @@ export const adminApi = {
updateProvider: (id: string, data: { name: string; api_key?: string; model?: string; endpoint?: string }) =>
api.put<void>(`/admin/ai-providers/${id}`, data),
deleteProvider: (id: string) => api.delete<void>(`/admin/ai-providers/${id}`),
testProvider: (id: string) =>
api.post<{ status: ProviderConnectionStatus }>(`/admin/ai-providers/${encodeURIComponent(id)}/test`),
listModels: (id: string) => api.get<string[]>(`/admin/ai-providers/${id}/models`),
probeModels: (data: { name: string; api_key?: string; endpoint?: string }) =>
api.post<string[]>('/admin/ai-providers/probe-models', data),

View File

@ -1,7 +1,7 @@
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 } from '@/api/admin'
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'
@ -12,6 +12,16 @@ 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<ConnectionState, string> = {
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 }[] }[] = [
@ -311,6 +321,7 @@ export function AIProviders() {
const [editId, setEditId] = useState<string | null>(null)
const [saving, setSaving] = useState(false)
const [error, setError] = useState('')
const [connectionStates, setConnectionStates] = useState<Record<string, ConnectionState>>({})
const isOllamaForm = form.name === 'ollama'
const isClaudeCodeForm = form.name === 'claudecode'
@ -337,11 +348,24 @@ export function AIProviders() {
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()
@ -433,8 +457,10 @@ export function AIProviders() {
<p className="text-sm text-muted-foreground text-center py-4">Aucun fournisseur configuré</p>
)}
<p className="text-sm text-muted-foreground">Le test vérifie la connexion avec les identifiants enregistrés. Aucune synthèse n’est générée.</p>
{providers.map(p => (
<div key={p.id} className="flex flex-wrap items-center gap-3 rounded-md border px-3 py-2.5">
<div key={p.id} data-provider-id={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>
@ -445,11 +471,23 @@ export function AIProviders() {
</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>
<Button variant="ghost" size="sm" className="h-7 w-7 p-0 text-destructive hover:text-destructive" onClick={() => remove(p.id)}>
<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')}
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)}>
<Trash2 className="h-3 w-3" />
</Button>
</div>
<p id={`connection-${p.id}`} role="status" aria-label={`Connexion ${p.name}`} aria-live="polite" aria-atomic="true"
className="w-full text-sm">
{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.' : '')}
</p>
</div>
))}
</CardContent>

View File

@ -0,0 +1,111 @@
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'
vi.mock('@/components/AIModelCatalog', () => ({ AIModelCatalog: () => null }))
const fetchMock = vi.fn()
const providers = ['openai', 'anthropic', 'ollama', 'claudecode'].map((name, i) => ({
id: `provider-${i}`, name, has_key: i === 0, model: '', endpoint: '', is_active: true,
}))
const response = (body: unknown) => new Response(JSON.stringify(body), { status: 200 })
beforeEach(() => {
vi.stubGlobal('fetch', fetchMock)
fetchMock.mockReset().mockImplementation((url: string) => Promise.resolve(response(
url.endsWith('/ai-providers') ? providers : [],
)))
})
afterEach(() => { cleanup(); vi.unstubAllGlobals() })
it('désactive uniquement les fournisseurs nécessitant une clé absente et explique la portée du test', async () => {
render(<AIProviders />)
expect(await screen.findByRole('button', { name: 'Tester la connexion openai' })).toBeEnabled()
expect(screen.getByRole('button', { name: 'Tester la connexion anthropic' })).toBeDisabled()
expect(screen.getByRole('button', { name: 'Tester la connexion ollama' })).toBeEnabled()
expect(screen.getByRole('button', { name: 'Tester la connexion claudecode' })).toBeEnabled()
expect(screen.getByText(/Aucune synthèse n’est générée/)).toBeInTheDocument()
})
it('envoie un POST vide, présente la progression sous la ligne ciblée et permet de retester', async () => {
const user = userEvent.setup()
render(<AIProviders />)
const button = await screen.findByRole('button', { name: 'Tester la connexion openai' })
let complete!: (value: Response) => void
fetchMock.mockImplementationOnce(() => new Promise<Response>(resolve => { complete = resolve }))
await user.click(button)
expect(button).toBeDisabled()
const result = screen.getByRole('status', { name: 'Connexion openai' })
expect(result).toHaveTextContent('Test en cours…')
expect(button.closest('[data-provider-id]')).toContainElement(result)
expect(screen.getByRole('button', { name: 'Tester la connexion ollama' })).toBeEnabled()
expect(fetchMock).toHaveBeenLastCalledWith('/api/admin/ai-providers/provider-0/test', expect.objectContaining({ method: 'POST', body: undefined }))
complete(response({ status: 'success' }))
expect(await within(result).findByText('Connexion et authentification vérifiées.')).toBeInTheDocument()
expect(button).toBeEnabled()
fetchMock.mockResolvedValueOnce(response({ status: 'auth_rejected' }))
await user.click(button)
expect(await within(result).findByText('Authentification refusée. Vérifiez les identifiants du fournisseur.')).toBeInTheDocument()
expect(fetchMock.mock.calls.filter(([, options]) => options?.method === 'POST')).toHaveLength(2)
})
it.each([
['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.'],
['unexpected', 'Impossible de tester la connexion. Réessayez.'],
])('présente un résultat accessible pour %s sans données brutes', async (status, message) => {
render(<AIProviders />)
const button = await screen.findByRole('button', { name: 'Tester la connexion openai' })
fetchMock.mockResolvedValueOnce(response({ status, error: 'secret-never-display' }))
await userEvent.click(button)
expect(await screen.findByRole('status', { name: 'Connexion openai' })).toHaveTextContent(message)
expect(screen.queryByText(/secret-never-display/)).not.toBeInTheDocument()
})
it('assainit les erreurs réseau et permet de réessayer', async () => {
render(<AIProviders />)
const button = await screen.findByRole('button', { name: 'Tester la connexion openai' })
fetchMock.mockRejectedValueOnce(new Error('secret-never-display'))
await userEvent.click(button)
expect(await screen.findByRole('status', { name: 'Connexion openai' })).toHaveTextContent('Impossible de tester la connexion. Réessayez.')
expect(button).toBeEnabled()
expect(screen.queryByText(/secret-never-display/)).not.toBeInTheDocument()
})
it('conserve les résultats indépendants de deux fournisseurs testés en parallèle', async () => {
render(<AIProviders />)
const openai = await screen.findByRole('button', { name: 'Tester la connexion openai' })
let complete!: (value: Response) => void
fetchMock.mockImplementationOnce(() => new Promise<Response>(resolve => { complete = resolve }))
await userEvent.click(openai)
fetchMock.mockResolvedValueOnce(response({ status: 'unavailable' }))
await userEvent.click(screen.getByRole('button', { name: 'Tester la connexion ollama' }))
expect(screen.getByRole('status', { name: 'Connexion ollama' })).toHaveTextContent('Fournisseur indisponible.')
expect(screen.getByRole('status', { name: 'Connexion openai' })).toHaveTextContent('Test en cours…')
complete(response({ status: 'success' }))
expect(await within(screen.getByRole('status', { name: 'Connexion openai' })).findByText('Connexion et authentification vérifiées.')).toBeInTheDocument()
expect(screen.getByRole('status', { name: 'Connexion ollama' })).toHaveTextContent('Fournisseur indisponible.')
})
it('affiche une erreur générique pour un échec HTTP sans exposer la réponse', async () => {
render(<AIProviders />)
const button = await screen.findByRole('button', { name: 'Tester la connexion openai' })
fetchMock.mockResolvedValueOnce(new Response(JSON.stringify({ error: 'secret-never-display' }), { status: 500 }))
await userEvent.click(button)
expect(screen.getByRole('status', { name: 'Connexion openai' })).toHaveTextContent('Impossible de tester la connexion. Réessayez.')
expect(screen.queryByText(/secret-never-display/)).not.toBeInTheDocument()
})
it('présente une vérification non supportée comme un état neutre sans suggérer de réessayer', async () => {
render(<AIProviders />)
const button = await screen.findByRole('button', { name: 'Tester la connexion claudecode' })
fetchMock.mockResolvedValueOnce(response({ status: 'auth_check_unsupported', error: 'secret-never-display' }))
await userEvent.click(button)
const result = screen.getByRole('status', { name: 'Connexion claudecode' })
expect(result).toHaveTextContent('Authentification non vérifiée')
expect(result).toHaveTextContent('Aucune synthèse n’a été générée.')
expect(result).not.toHaveTextContent(/réessay|réussie|vérifiées|impossible|refusée/i)
expect(screen.queryByText(/secret-never-display/)).not.toBeInTheDocument()
})