merge: integrate AI provider connection test (#38)

This commit is contained in:
2026-11-24 16:22:06 +01:00
16 changed files with 599 additions and 18 deletions

View File

@ -4,6 +4,7 @@ import (
"bytes" "bytes"
"context" "context"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
@ -70,10 +71,34 @@ func (p *anthropicProvider) Summarize(ctx context.Context, prompt string, _ GenO
return result.Content[0].Text, nil return result.Content[0].Text, nil
} }
func (p *anthropicProvider) ListModels(_ context.Context) ([]string, error) { // ListModels checks API authentication using discovery, never generation.
return []string{ func (p *anthropicProvider) ListModels(ctx context.Context) ([]string, error) {
"claude-opus-4-7", req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://api.anthropic.com/v1/models", nil)
"claude-sonnet-4-6", if err != nil {
"claude-haiku-4-5-20251001", return nil, errors.New("model discovery request failed")
}, nil }
req.Header.Set("x-api-key", p.apiKey)
req.Header.Set("anthropic-version", "2023-06-01")
resp, err := p.client.Do(req)
if err != nil {
return nil, errors.New("model discovery unavailable")
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, &summaryHTTPError{status: resp.StatusCode, err: errors.New("model discovery failed")}
}
var result struct {
Data []struct {
ID string `json:"id"`
} `json:"data"`
}
// Discovery responses are bounded; malformed bodies never reach callers.
if err := json.NewDecoder(io.LimitReader(resp.Body, 2<<20)).Decode(&result); err != nil {
return nil, errors.New("model discovery response invalid")
}
names := make([]string, 0, len(result.Data))
for _, model := range result.Data {
names = append(names, model.ID)
}
return names, nil
} }

View File

@ -44,3 +44,6 @@ func (p *claudeCodeProvider) ListModels(_ context.Context) ([]string, error) {
"claude-haiku-4-5-20251001", "claude-haiku-4-5-20251001",
}, nil }, nil
} }
// SupportsAuthCheck is false because model discovery is a local static catalog.
func (p *claudeCodeProvider) SupportsAuthCheck() bool { return false }

View File

@ -0,0 +1,88 @@
package ai
import (
"context"
"database/sql"
"errors"
"time"
openai "github.com/sashabaranov/go-openai"
"github.com/tradarr/backend/internal/models"
)
var (
ErrConnectionUnsupported = errors.New("auth_check_unsupported")
ErrConnectionAuth = errors.New("auth_rejected")
ErrConnectionUnavailable = errors.New("unavailable")
ErrConnectionNotFound = errors.New("not_found")
ErrConnectionLocal = errors.New("internal_error")
)
type ConnectionRepository interface {
GetAIProviderByID(string) (*models.AIProvider, error)
}
type ConnectionDecryptor interface{ Decrypt(string) (string, error) }
type ConnectionTester struct {
repo ConnectionRepository
enc ConnectionDecryptor
build func(string, string, string) (Provider, error)
}
func NewConnectionTester(repo ConnectionRepository, enc ConnectionDecryptor, build func(string, string, string) (Provider, error)) *ConnectionTester {
return &ConnectionTester{repo, enc, build}
}
// Test never propagates provider/configuration errors or model names to callers.
func (t *ConnectionTester) Test(ctx context.Context, id string) error {
p, err := t.repo.GetAIProviderByID(id)
if errors.Is(err, sql.ErrNoRows) {
return ErrConnectionNotFound
}
if err != nil {
return ErrConnectionLocal
}
if p == nil {
return ErrConnectionNotFound
}
key := ""
if p.APIKeyEncrypted != "" {
if t.enc == nil {
return ErrConnectionLocal
}
key, err = t.enc.Decrypt(p.APIKeyEncrypted)
if err != nil {
return ErrConnectionLocal
}
}
provider, err := t.build(p.Name, key, p.Endpoint)
if err != nil || provider == nil {
return ErrConnectionLocal
}
// Static model catalogs do not prove authentication. Keep their discovery
// behavior available to other callers without claiming connection success.
if capability, ok := provider.(interface{ SupportsAuthCheck() bool }); ok && !capability.SupportsAuthCheck() {
return ErrConnectionUnsupported
}
ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
defer cancel()
_, err = provider.ListModels(ctx)
if err == nil {
return nil
}
var local *summaryHTTPError
var api *openai.APIError
var request *openai.RequestError
status := 0
switch {
case errors.As(err, &local):
status = local.status
case errors.As(err, &api):
status = api.HTTPStatusCode
case errors.As(err, &request):
status = request.HTTPStatusCode
}
if status == 401 || status == 403 {
return ErrConnectionAuth
}
return ErrConnectionUnavailable
}

View File

@ -0,0 +1,41 @@
package ai
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"strings"
"testing"
)
type connectionTransport func(*http.Request) (*http.Response, error)
func (f connectionTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
func TestConnectionDiscoveryHTTPStatus(t *testing.T) {
for _, code := range []int{401, 403, 429, 500} {
for _, name := range []string{"gemini", "ollama"} {
t.Run(fmt.Sprintf("%s/%d", name, code), func(t *testing.T) {
client := &http.Client{Transport: connectionTransport(func(*http.Request) (*http.Response, error) {
return &http.Response{StatusCode: code, Body: io.NopCloser(strings.NewReader(`{"secret":"private response"}`)), Header: make(http.Header)}, nil
})}
var p Provider
if name == "gemini" {
g := newGemini("secret", "")
g.client = client
p = g
} else {
o := newOllama("https://private.invalid", "")
o.client = client
p = o
}
_, err := p.ListModels(context.Background())
var status *summaryHTTPError
if !errors.As(err, &status) || status.status != code || strings.Contains(err.Error(), "private") {
t.Fatalf("unsafe or unclassified error: %v", err)
}
})
}
}
}

View File

@ -0,0 +1,95 @@
package ai
import (
"context"
"errors"
"io"
"net/http"
"strings"
"testing"
"github.com/tradarr/backend/internal/models"
)
func TestConnectionClaudeCodeDoesNotClaimAuthSuccess(t *testing.T) {
tester := NewConnectionTester(connectionRepo{p: &models.AIProvider{Name: "claudecode"}}, nil, func(string, string, string) (Provider, error) { return newClaudeCode(""), nil })
err := tester.Test(context.Background(), "id")
if err == nil || err.Error() != "auth_check_unsupported" {
t.Fatalf("want unsupported auth check; got %v", err)
}
}
func TestConnectionAnthropicChecksAuthentication(t *testing.T) {
for _, code := range []int{200, 401, 403, 503} {
t.Run(http.StatusText(code), func(t *testing.T) {
calls := 0
p := newAnthropic("saved-secret", "")
p.client = &http.Client{Transport: connectionTransport(func(r *http.Request) (*http.Response, error) {
calls++
if r.Method != "GET" || r.URL.String() != "https://api.anthropic.com/v1/models" || r.Header.Get("x-api-key") != "saved-secret" || r.Header.Get("anthropic-version") == "" || r.Body != nil {
t.Fatal("expected authenticated, bodyless model discovery")
}
body := `{"data":[{"id":"model-id"}]}`
if code != 200 {
body = `private body saved-secret https://private.invalid`
}
return &http.Response{StatusCode: code, Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header)}, nil
})}
tester := NewConnectionTester(connectionRepo{p: &models.AIProvider{Name: "anthropic"}}, nil, func(string, string, string) (Provider, error) { return p, nil })
err := tester.Test(context.Background(), "id")
if calls != 1 {
t.Fatalf("auth requests=%d", calls)
}
var want error
if code == 401 || code == 403 {
want = ErrConnectionAuth
} else if code != 200 {
want = ErrConnectionUnavailable
}
if !errors.Is(err, want) {
t.Fatalf("got %v want %v", err, want)
}
})
}
}
func TestConnectionAnthropicDiscoverySanitizesFailures(t *testing.T) {
for _, tc := range []struct {
name string
code int
body string
transportErr error
}{
{name: "auth", code: 401, body: "saved-secret https://private.invalid private body"},
{name: "malformed", code: 200, body: "saved-secret https://private.invalid private body"},
{name: "transport", transportErr: errors.New("saved-secret https://private.invalid private body")},
} {
t.Run(tc.name, func(t *testing.T) {
p := newAnthropic("saved-secret", "")
p.client = &http.Client{Transport: connectionTransport(func(*http.Request) (*http.Response, error) {
if tc.transportErr != nil {
return nil, tc.transportErr
}
return &http.Response{StatusCode: tc.code, Body: io.NopCloser(strings.NewReader(tc.body)), Header: make(http.Header)}, nil
})}
_, err := p.ListModels(context.Background())
if err == nil {
t.Fatal("expected discovery error")
}
for _, s := range []string{"saved-secret", "https://", "private body"} {
if strings.Contains(err.Error(), s) {
t.Fatalf("discovery error leaked sensitive detail")
}
}
})
}
}
func TestConnectionAnthropicReturnsDiscoveredModels(t *testing.T) {
p := newAnthropic("saved-secret", "")
p.client = &http.Client{Transport: connectionTransport(func(*http.Request) (*http.Response, error) {
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(`{"data":[{"id":"discovered-model"}]}`)), Header: make(http.Header)}, nil
})}
models, err := p.ListModels(context.Background())
if err != nil || len(models) != 1 || models[0] != "discovered-model" {
t.Fatal("expected discovered models")
}
}

View File

@ -0,0 +1,81 @@
package ai
import (
"context"
"errors"
"fmt"
openai "github.com/sashabaranov/go-openai"
"github.com/tradarr/backend/internal/models"
"testing"
)
type connectionRepo struct {
p *models.AIProvider
err error
}
func (r connectionRepo) GetAIProviderByID(string) (*models.AIProvider, error) { return r.p, r.err }
type connectionKey struct{ err error }
func (k connectionKey) Decrypt(s string) (string, error) {
if s != "cipher" {
panic("wrong cipher")
}
return "secret", k.err
}
type connectionProvider struct {
err error
calls int
}
func (*connectionProvider) Name() string { return "fake" }
func (*connectionProvider) Summarize(context.Context, string, GenOptions) (string, error) {
panic("must not generate")
}
func (p *connectionProvider) ListModels(context.Context) ([]string, error) {
p.calls++
return []string{"private-model"}, p.err
}
func TestConnectionSavedCredentials(t *testing.T) {
for _, tt := range []struct {
name string
upstream, want error
}{
{"success", nil, nil}, {"auth", fmt.Errorf("wrapped: %w", &openai.APIError{HTTPStatusCode: 401}), ErrConnectionAuth}, {"forbidden", &openai.RequestError{HTTPStatusCode: 403}, ErrConnectionAuth}, {"rate limit", &openai.APIError{HTTPStatusCode: 429}, ErrConnectionUnavailable}, {"untrusted text", errors.New("401 secret endpoint"), ErrConnectionUnavailable},
} {
t.Run(tt.name, func(t *testing.T) {
p := &connectionProvider{err: tt.upstream}
tester := NewConnectionTester(connectionRepo{p: &models.AIProvider{Name: "fake", APIKeyEncrypted: "cipher", Endpoint: "private"}}, connectionKey{}, func(name, key, endpoint string) (Provider, error) {
if name != "fake" || key != "secret" || endpoint != "private" {
t.Fatal("saved config not used")
}
return p, nil
})
if got := tester.Test(context.Background(), "id"); !errors.Is(got, tt.want) {
t.Fatalf("got %v want %v", got, tt.want)
}
if p.calls != 1 {
t.Fatal("ListModels calls")
}
})
}
}
func TestConnectionLocalFailures(t *testing.T) {
for _, tt := range []struct {
name string
repo connectionRepo
key connectionKey
buildErr, want error
}{
{name: "missing", want: ErrConnectionNotFound}, {name: "database", repo: connectionRepo{err: errors.New("secret")}, want: ErrConnectionLocal}, {name: "decrypt", repo: connectionRepo{p: &models.AIProvider{APIKeyEncrypted: "cipher"}}, key: connectionKey{errors.New("secret")}, want: ErrConnectionLocal}, {name: "factory", repo: connectionRepo{p: &models.AIProvider{}}, buildErr: errors.New("secret"), want: ErrConnectionLocal},
} {
t.Run(tt.name, func(t *testing.T) {
tester := NewConnectionTester(tt.repo, tt.key, func(string, string, string) (Provider, error) { return nil, tt.buildErr })
if got := tester.Test(context.Background(), "id"); !errors.Is(got, tt.want) {
t.Fatalf("got %v", got)
}
})
}
}

View File

@ -4,6 +4,7 @@ import (
"bytes" "bytes"
"context" "context"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
@ -87,7 +88,7 @@ func (p *geminiProvider) ListModels(ctx context.Context) ([]string, error) {
defer resp.Body.Close() defer resp.Body.Close()
raw, _ := io.ReadAll(resp.Body) raw, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("gemini list models error %d: %s", resp.StatusCode, raw) return nil, &summaryHTTPError{status: resp.StatusCode, err: errors.New("model discovery failed")}
} }
var result struct { var result struct {
Models []struct { Models []struct {

View File

@ -116,6 +116,9 @@ func (p *OllamaProvider) ListModelsDetailed(ctx context.Context) ([]OllamaModelI
return nil, err return nil, err
} }
defer resp.Body.Close() defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, &summaryHTTPError{status: resp.StatusCode, err: fmt.Errorf("model discovery failed")}
}
raw, _ := io.ReadAll(resp.Body) raw, _ := io.ReadAll(resp.Body)
var result struct { var result struct {

View File

@ -0,0 +1,28 @@
package api_test
import (
"github.com/tradarr/backend/internal/api"
"github.com/tradarr/backend/internal/api/handlers"
"github.com/tradarr/backend/internal/config"
"net/http/httptest"
"testing"
)
func TestAIProviderConnectionRequiresAuthentication(t *testing.T) {
h := handlers.New(nil, &config.Config{}, nil, nil, nil, nil)
r := api.SetupRouter(h, "test-secret")
found := false
for _, route := range r.Routes() {
if route.Method == "POST" && route.Path == "/api/admin/ai-providers/:id/test" {
found = true
}
}
if !found {
t.Fatal("test route missing")
}
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("POST", "/api/admin/ai-providers/saved/test", nil))
if w.Code != 401 {
t.Fatalf("unauthenticated status=%d", w.Code)
}
}

View File

@ -551,3 +551,22 @@ func (h *Handler) CreateAdminUser(c *gin.Context) {
} }
httputil.Created(c, user) httputil.Created(c, user)
} }
// TestAIProvider returns only bounded outcomes from saved configuration.
func (h *Handler) TestAIProvider(c *gin.Context) {
err := h.connectionTester.Test(c.Request.Context(), c.Param("id"))
switch {
case err == nil:
c.JSON(200, gin.H{"status": "success"})
case errors.Is(err, ai.ErrConnectionAuth):
c.JSON(200, gin.H{"status": "auth_rejected"})
case errors.Is(err, ai.ErrConnectionUnavailable):
c.JSON(200, gin.H{"status": "unavailable"})
case errors.Is(err, ai.ErrConnectionUnsupported):
c.JSON(200, gin.H{"status": "auth_check_unsupported"})
case errors.Is(err, ai.ErrConnectionNotFound):
c.JSON(404, gin.H{"error": "not found"})
default:
c.JSON(500, gin.H{"error": "internal server error"})
}
}

View File

@ -0,0 +1,37 @@
package handlers
import (
"context"
"errors"
"github.com/gin-gonic/gin"
"github.com/tradarr/backend/internal/ai"
"net/http/httptest"
"testing"
)
type fakeConnection struct {
err error
id string
}
func (f *fakeConnection) Test(_ context.Context, id string) error { f.id = id; return f.err }
func TestAIProviderConnectionHandler(t *testing.T) {
gin.SetMode(gin.TestMode)
for _, tt := range []struct {
err error
code int
body string
}{
{nil, 200, `{"status":"success"}`}, {ai.ErrConnectionAuth, 200, `{"status":"auth_rejected"}`}, {ai.ErrConnectionUnavailable, 200, `{"status":"unavailable"}`}, {ai.ErrConnectionUnsupported, 200, `{"status":"auth_check_unsupported"}`}, {ai.ErrConnectionNotFound, 404, `{"error":"not found"}`}, {errors.New("secret endpoint raw error"), 500, `{"error":"internal server error"}`},
} {
f := &fakeConnection{err: tt.err}
h := &Handler{connectionTester: f}
r := gin.New()
r.POST("/api/admin/ai-providers/:id/test", h.TestAIProvider)
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("POST", "/api/admin/ai-providers/saved-id/test", nil))
if w.Code != tt.code || w.Body.String() != tt.body || f.id != "saved-id" {
t.Fatalf("code=%d body=%s id=%s", w.Code, w.Body, f.id)
}
}
}

View File

@ -16,6 +16,9 @@ import (
) )
type Handler struct { type Handler struct {
connectionTester interface {
Test(context.Context, string) error
}
companyCatalog CompanyCatalog companyCatalog CompanyCatalog
indexSearcher indices.IndexSearcher indexSearcher indices.IndexSearcher
generationJobs interface { generationJobs interface {
@ -44,6 +47,9 @@ func New(
} }
return &Handler{ return &Handler{
companyCatalog: catalog, companyCatalog: catalog,
connectionTester: ai.NewConnectionTester(repo, enc, func(name, key, endpoint string) (ai.Provider, error) {
return ai.NewProvider(name, key, "", endpoint)
}),
repo: repo, repo: repo,
cfg: cfg, cfg: cfg,
enc: enc, enc: enc,

View File

@ -73,6 +73,7 @@ func SetupRouter(h *handlers.Handler, jwtSecret string) *gin.Engine {
admin.POST("/ai-providers/:id/activate", h.SetActiveAIProvider) admin.POST("/ai-providers/:id/activate", h.SetActiveAIProvider)
admin.DELETE("/ai-providers/:id", h.DeleteAIProvider) admin.DELETE("/ai-providers/:id", h.DeleteAIProvider)
admin.GET("/ai-providers/:id/models", h.ListAIModels) admin.GET("/ai-providers/:id/models", h.ListAIModels)
admin.POST("/ai-providers/:id/test", h.TestAIProvider)
admin.POST("/ai-providers/probe-models", h.ProbeAIModels) admin.POST("/ai-providers/probe-models", h.ProbeAIModels)
admin.GET("/sources", h.ListSources) admin.GET("/sources", h.ListSources)

View File

@ -4,6 +4,8 @@ export interface AIProvider {
id: string; name: string; model: string; endpoint: string id: string; name: string; model: string; endpoint: string
is_active: boolean; has_key: boolean 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 AIModelCatalogEntry { id: string; provider_id: string; provider?: string; model: string; enabled: boolean }
export interface OllamaModelInfo { export interface OllamaModelInfo {
name: string; size: number; modified_at: string 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 }) => updateProvider: (id: string, data: { name: string; api_key?: string; model?: string; endpoint?: string }) =>
api.put<void>(`/admin/ai-providers/${id}`, data), api.put<void>(`/admin/ai-providers/${id}`, data),
deleteProvider: (id: string) => api.delete<void>(`/admin/ai-providers/${id}`), 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`), listModels: (id: string) => api.get<string[]>(`/admin/ai-providers/${id}/models`),
probeModels: (data: { name: string; api_key?: string; endpoint?: string }) => probeModels: (data: { name: string; api_key?: string; endpoint?: string }) =>
api.post<string[]>('/admin/ai-providers/probe-models', data), api.post<string[]>('/admin/ai-providers/probe-models', data),

View File

@ -1,7 +1,7 @@
import { useState, useEffect, useCallback } from 'react' import { useState, useEffect, useCallback } from 'react'
import { Plus, Trash2, Download, HardDrive, Cpu, ChevronUp, X } from 'lucide-react' import { Plus, Trash2, Download, HardDrive, Cpu, ChevronUp, X } from 'lucide-react'
import { AIModelCatalog } from '@/components/AIModelCatalog' 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 { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input' 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 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 CUSTOM_MODELS_KEY = 'ollama_custom_models'
const KNOWN_OLLAMA_MODELS: { name: string; family: string; tags: { tag: string; size: string }[] }[] = [ 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 [editId, setEditId] = useState<string | null>(null)
const [saving, setSaving] = useState(false) const [saving, setSaving] = useState(false)
const [error, setError] = useState('') const [error, setError] = useState('')
const [connectionStates, setConnectionStates] = useState<Record<string, ConnectionState>>({})
const isOllamaForm = form.name === 'ollama' const isOllamaForm = form.name === 'ollama'
const isClaudeCodeForm = form.name === 'claudecode' const isClaudeCodeForm = form.name === 'claudecode'
@ -337,11 +348,24 @@ export function AIProviders() {
useEffect(() => { load() }, [load]) 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() { async function save() {
setSaving(true); setError('') setSaving(true); setError('')
try { try {
if (editId) { await adminApi.updateProvider(editId, form) } if (editId) { await adminApi.updateProvider(editId, form) }
else { await adminApi.createProvider(form) } else { await adminApi.createProvider(form) }
setConnectionStates({})
setShowForm(false); setEditId(null) setShowForm(false); setEditId(null)
setForm({ name: 'openai', api_key: '', model: '', endpoint: '' }) setForm({ name: 'openai', api_key: '', model: '', endpoint: '' })
setLoading(true); await load() 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 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 => ( {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-1 min-w-0">
<div className="flex items-center gap-2 flex-wrap"> <div className="flex items-center gap-2 flex-wrap">
<span className="font-semibold capitalize text-sm">{p.name}</span> <span className="font-semibold capitalize text-sm">{p.name}</span>
@ -445,11 +471,23 @@ export function AIProviders() {
</div> </div>
</div> </div>
<div className="flex items-center gap-1.5"> <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="outline" size="sm" className="h-7 px-2 text-xs"
<Button variant="ghost" size="sm" className="h-7 w-7 p-0 text-destructive hover:text-destructive" onClick={() => remove(p.id)}> 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" /> <Trash2 className="h-3 w-3" />
</Button> </Button>
</div> </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> </div>
))} ))}
</CardContent> </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()
})