From 54fced1ffb3c35a37930485df98c55e87c9fec28 Mon Sep 17 00:00:00 2001 From: Blomios Date: Tue, 24 Nov 2026 16:21:48 +0100 Subject: [PATCH] feat(ai): add provider connection test (#38) --- backend/internal/ai/anthropic.go | 37 +++++- backend/internal/ai/claudecode.go | 3 + backend/internal/ai/connection.go | 88 ++++++++++++++ backend/internal/ai/connection_http_test.go | 41 +++++++ backend/internal/ai/connection_qa_test.go | 95 +++++++++++++++ backend/internal/ai/connection_test.go | 81 +++++++++++++ backend/internal/ai/gemini.go | 3 +- backend/internal/ai/ollama.go | 3 + .../api/ai_connection_ticket38_test.go | 28 +++++ backend/internal/api/handlers/admin.go | 19 +++ .../api/handlers/ai_connection_test.go | 37 ++++++ backend/internal/api/handlers/handler.go | 20 ++-- backend/internal/api/router.go | 1 + frontend/src/api/admin.ts | 4 + frontend/src/pages/admin/AIProviders.tsx | 46 +++++++- .../tests/ai-provider-connection.test.tsx | 111 ++++++++++++++++++ 16 files changed, 599 insertions(+), 18 deletions(-) create mode 100644 backend/internal/ai/connection.go create mode 100644 backend/internal/ai/connection_http_test.go create mode 100644 backend/internal/ai/connection_qa_test.go create mode 100644 backend/internal/ai/connection_test.go create mode 100644 backend/internal/api/ai_connection_ticket38_test.go create mode 100644 backend/internal/api/handlers/ai_connection_test.go create mode 100644 frontend/tests/ai-provider-connection.test.tsx diff --git a/backend/internal/ai/anthropic.go b/backend/internal/ai/anthropic.go index 9ec0ea9..97c06fd 100644 --- a/backend/internal/ai/anthropic.go +++ b/backend/internal/ai/anthropic.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -70,10 +71,34 @@ func (p *anthropicProvider) Summarize(ctx context.Context, prompt string, _ GenO return result.Content[0].Text, nil } -func (p *anthropicProvider) ListModels(_ context.Context) ([]string, error) { - return []string{ - "claude-opus-4-7", - "claude-sonnet-4-6", - "claude-haiku-4-5-20251001", - }, nil +// ListModels checks API authentication using discovery, never generation. +func (p *anthropicProvider) ListModels(ctx context.Context) ([]string, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://api.anthropic.com/v1/models", nil) + if err != nil { + return nil, errors.New("model discovery request failed") + } + 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 } diff --git a/backend/internal/ai/claudecode.go b/backend/internal/ai/claudecode.go index 5f98070..598e12f 100644 --- a/backend/internal/ai/claudecode.go +++ b/backend/internal/ai/claudecode.go @@ -44,3 +44,6 @@ func (p *claudeCodeProvider) ListModels(_ context.Context) ([]string, error) { "claude-haiku-4-5-20251001", }, nil } + +// SupportsAuthCheck is false because model discovery is a local static catalog. +func (p *claudeCodeProvider) SupportsAuthCheck() bool { return false } diff --git a/backend/internal/ai/connection.go b/backend/internal/ai/connection.go new file mode 100644 index 0000000..b0aea53 --- /dev/null +++ b/backend/internal/ai/connection.go @@ -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 +} diff --git a/backend/internal/ai/connection_http_test.go b/backend/internal/ai/connection_http_test.go new file mode 100644 index 0000000..323cee9 --- /dev/null +++ b/backend/internal/ai/connection_http_test.go @@ -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) + } + }) + } + } +} diff --git a/backend/internal/ai/connection_qa_test.go b/backend/internal/ai/connection_qa_test.go new file mode 100644 index 0000000..c47d2a6 --- /dev/null +++ b/backend/internal/ai/connection_qa_test.go @@ -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") + } +} diff --git a/backend/internal/ai/connection_test.go b/backend/internal/ai/connection_test.go new file mode 100644 index 0000000..d3e8aeb --- /dev/null +++ b/backend/internal/ai/connection_test.go @@ -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) + } + }) + } +} diff --git a/backend/internal/ai/gemini.go b/backend/internal/ai/gemini.go index d6d1e3d..fb9c144 100644 --- a/backend/internal/ai/gemini.go +++ b/backend/internal/ai/gemini.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -87,7 +88,7 @@ func (p *geminiProvider) ListModels(ctx context.Context) ([]string, error) { defer resp.Body.Close() raw, _ := io.ReadAll(resp.Body) 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 { Models []struct { diff --git a/backend/internal/ai/ollama.go b/backend/internal/ai/ollama.go index c340fb9..f78af62 100644 --- a/backend/internal/ai/ollama.go +++ b/backend/internal/ai/ollama.go @@ -116,6 +116,9 @@ func (p *OllamaProvider) ListModelsDetailed(ctx context.Context) ([]OllamaModelI return nil, err } 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) var result struct { diff --git a/backend/internal/api/ai_connection_ticket38_test.go b/backend/internal/api/ai_connection_ticket38_test.go new file mode 100644 index 0000000..1e1b19a --- /dev/null +++ b/backend/internal/api/ai_connection_ticket38_test.go @@ -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) + } +} diff --git a/backend/internal/api/handlers/admin.go b/backend/internal/api/handlers/admin.go index c130837..128fc80 100644 --- a/backend/internal/api/handlers/admin.go +++ b/backend/internal/api/handlers/admin.go @@ -551,3 +551,22 @@ func (h *Handler) CreateAdminUser(c *gin.Context) { } 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"}) + } +} diff --git a/backend/internal/api/handlers/ai_connection_test.go b/backend/internal/api/handlers/ai_connection_test.go new file mode 100644 index 0000000..751215b --- /dev/null +++ b/backend/internal/api/handlers/ai_connection_test.go @@ -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) + } + } +} diff --git a/backend/internal/api/handlers/handler.go b/backend/internal/api/handlers/handler.go index adad436..0f8246c 100644 --- a/backend/internal/api/handlers/handler.go +++ b/backend/internal/api/handlers/handler.go @@ -16,6 +16,9 @@ import ( ) type Handler struct { + connectionTester interface { + Test(context.Context, string) error + } companyCatalog CompanyCatalog indexSearcher indices.IndexSearcher generationJobs interface { @@ -44,13 +47,16 @@ func New( } return &Handler{ companyCatalog: catalog, - repo: repo, - cfg: cfg, - enc: enc, - registry: registry, - pipeline: pipeline, - scheduler: sched, - reportManager: ai.NewReportManager(), + connectionTester: ai.NewConnectionTester(repo, enc, func(name, key, endpoint string) (ai.Provider, error) { + return ai.NewProvider(name, key, "", endpoint) + }), + repo: repo, + cfg: cfg, + enc: enc, + registry: registry, + pipeline: pipeline, + scheduler: sched, + reportManager: ai.NewReportManager(), } } diff --git a/backend/internal/api/router.go b/backend/internal/api/router.go index b0b66f3..2c2e001 100644 --- a/backend/internal/api/router.go +++ b/backend/internal/api/router.go @@ -73,6 +73,7 @@ func SetupRouter(h *handlers.Handler, jwtSecret string) *gin.Engine { admin.POST("/ai-providers/:id/activate", h.SetActiveAIProvider) admin.DELETE("/ai-providers/:id", h.DeleteAIProvider) 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.GET("/sources", h.ListSources) diff --git a/frontend/src/api/admin.ts b/frontend/src/api/admin.ts index bd6cad5..c44d928 100644 --- a/frontend/src/api/admin.ts +++ b/frontend/src/api/admin.ts @@ -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(`/admin/ai-providers/${id}`, data), deleteProvider: (id: string) => api.delete(`/admin/ai-providers/${id}`), + testProvider: (id: string) => + api.post<{ status: ProviderConnectionStatus }>(`/admin/ai-providers/${encodeURIComponent(id)}/test`), listModels: (id: string) => api.get(`/admin/ai-providers/${id}/models`), probeModels: (data: { name: string; api_key?: string; endpoint?: string }) => api.post('/admin/ai-providers/probe-models', data), diff --git a/frontend/src/pages/admin/AIProviders.tsx b/frontend/src/pages/admin/AIProviders.tsx index f86a58d..74759ea 100644 --- a/frontend/src/pages/admin/AIProviders.tsx +++ b/frontend/src/pages/admin/AIProviders.tsx @@ -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 = { + 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(null) const [saving, setSaving] = useState(false) const [error, setError] = useState('') + const [connectionStates, setConnectionStates] = useState>({}) 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() {

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} @@ -445,11 +471,23 @@ export function AIProviders() {
- - + +
+

+ {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.' : '')} +

))} diff --git a/frontend/tests/ai-provider-connection.test.tsx b/frontend/tests/ai-provider-connection.test.tsx new file mode 100644 index 0000000..d6ec98d --- /dev/null +++ b/frontend/tests/ai-provider-connection.test.tsx @@ -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() + 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() + const button = await screen.findByRole('button', { name: 'Tester la connexion openai' }) + let complete!: (value: Response) => void + fetchMock.mockImplementationOnce(() => new Promise(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() + 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() + 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() + const openai = await screen.findByRole('button', { name: 'Tester la connexion openai' }) + let complete!: (value: Response) => void + fetchMock.mockImplementationOnce(() => new Promise(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() + 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() + 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() +})