feat(ai): test saved summary model generation (#43)
This commit is contained in:
@ -26,6 +26,7 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/tradarr/backend/internal/ai"
|
||||
"github.com/tradarr/backend/internal/config"
|
||||
"github.com/tradarr/backend/internal/crypto"
|
||||
"github.com/tradarr/backend/internal/database"
|
||||
"github.com/tradarr/backend/internal/e2estack"
|
||||
"github.com/tradarr/backend/internal/generation"
|
||||
@ -113,7 +114,12 @@ func run(ctx context.Context) error {
|
||||
provider := e2estack.FakeProvider{URL: fakeURL, Client: client}
|
||||
gin.SetMode(gin.TestMode)
|
||||
gin.DefaultWriter = io.Discard
|
||||
app := server.New(repo, cfg, server.Dependencies{CompanyCatalog: e2estack.FakeCompanyCatalog{Fakes: fakes}, Feeds: feeds, IndexSearcher: openfigi.New(openfigi.Config{BaseURL: fakeURL}, client), EnableScheduler: false, GenerationFactory: func(p *ai.Pipeline) generation.UseCase {
|
||||
probe := ai.NewModelTester(repo, crypto.New(cfg.EncryptionKey), func(_, _, model, _ string) (ai.Provider, error) {
|
||||
selected := provider
|
||||
selected.Model = model
|
||||
return selected, nil
|
||||
})
|
||||
app := server.New(repo, cfg, server.Dependencies{ModelTester: probe, CompanyCatalog: e2estack.FakeCompanyCatalog{Fakes: fakes}, Feeds: feeds, IndexSearcher: openfigi.New(openfigi.Config{BaseURL: fakeURL}, client), EnableScheduler: false, GenerationFactory: func(p *ai.Pipeline) generation.UseCase {
|
||||
return p.NewGenerationUseCaseWithFactory(feeds, e2estack.FakeLayaRanker{Provider: provider}, func(m models.ResolvedSummaryModel) (ai.Provider, error) {
|
||||
selected := provider
|
||||
selected.Model = m.Model
|
||||
|
||||
@ -5,7 +5,6 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
)
|
||||
@ -56,9 +55,9 @@ func (p *anthropicProvider) Summarize(ctx context.Context, prompt string, opts G
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
raw, _ := io.ReadAll(resp.Body)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", &summaryHTTPError{status: resp.StatusCode, err: fmt.Errorf("anthropic API error %d: %s", resp.StatusCode, raw)}
|
||||
raw, err := readGenerationResponse(resp)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
var result struct {
|
||||
|
||||
@ -3,9 +3,14 @@ package ai
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type claudeCodeProvider struct {
|
||||
@ -21,20 +26,76 @@ func newClaudeCode(model string) *claudeCodeProvider {
|
||||
|
||||
func (p *claudeCodeProvider) Name() string { return "claudecode" }
|
||||
|
||||
func (p *claudeCodeProvider) Summarize(ctx context.Context, prompt string, _ GenOptions) (string, error) {
|
||||
var stdout, stderr bytes.Buffer
|
||||
cmd := exec.CommandContext(ctx, "claude", "-p", prompt, "--model", p.model)
|
||||
cmd.Stdout = &stdout
|
||||
cmd.Stderr = &stderr
|
||||
// boundedCLICapture never writes model output to the process console and never
|
||||
// returns silently truncated content as a successful generation.
|
||||
type boundedCLICapture struct {
|
||||
buffer bytes.Buffer
|
||||
overflow bool
|
||||
}
|
||||
|
||||
err := cmd.Run()
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return "", ctx.Err()
|
||||
func (b *boundedCLICapture) Write(p []byte) (int, error) {
|
||||
remaining := maxGenerationResponseBytes - b.buffer.Len()
|
||||
if len(p) > remaining {
|
||||
b.overflow = true
|
||||
}
|
||||
if remaining > 0 {
|
||||
b.buffer.Write(p[:min(len(p), remaining)])
|
||||
}
|
||||
return len(p), nil
|
||||
}
|
||||
func (p *claudeCodeProvider) Summarize(ctx context.Context, prompt string, opts GenOptions) (string, error) {
|
||||
var stdout boundedCLICapture
|
||||
testMode, _ := ctx.Value(modelTestContextKey{}).(bool)
|
||||
args := []string{"-p", prompt, "--model", p.model}
|
||||
if testMode {
|
||||
args = append(args, "--output-format", "json", "--no-session-persistence")
|
||||
}
|
||||
cmd := exec.CommandContext(ctx, "claude", args...)
|
||||
cmd.Stdout = &stdout
|
||||
cmd.Stderr = io.Discard
|
||||
cmd.WaitDelay = 250 * time.Millisecond
|
||||
if testMode {
|
||||
overrides := map[string]string{"CLAUDE_CODE_MAX_OUTPUT_TOKENS": strconv.Itoa(opts.MaxOutputTokens), "CLAUDE_CODE_MAX_RETRIES": "0", "CLAUDE_CODE_RETRY_WATCHDOG": "", "MAX_THINKING_TOKENS": "0"}
|
||||
cmd.Env = []string{}
|
||||
for _, entry := range os.Environ() {
|
||||
key, _, _ := strings.Cut(entry, "=")
|
||||
if _, replace := overrides[key]; !replace {
|
||||
cmd.Env = append(cmd.Env, entry)
|
||||
}
|
||||
}
|
||||
for key, value := range overrides {
|
||||
cmd.Env = append(cmd.Env, key+"="+value)
|
||||
}
|
||||
}
|
||||
err := cmd.Run()
|
||||
if ctx.Err() != nil {
|
||||
return "", ctx.Err()
|
||||
}
|
||||
if stdout.overflow {
|
||||
return "", errors.New("claude cli: response unavailable")
|
||||
}
|
||||
if testMode {
|
||||
raw := stdout.buffer.Bytes()
|
||||
code := generationErrorCode(raw)
|
||||
if code != "" {
|
||||
return "", &summaryHTTPError{code: code, err: errors.New("claude cli: generation rejected")}
|
||||
}
|
||||
if err != nil {
|
||||
return "", errors.New("claude cli: execution failed")
|
||||
}
|
||||
var envelope struct {
|
||||
Type, Subtype, Result string
|
||||
IsError *bool `json:"is_error"`
|
||||
}
|
||||
if json.Unmarshal(raw, &envelope) != nil || envelope.Type != "result" || envelope.Subtype != "success" || envelope.IsError == nil || *envelope.IsError {
|
||||
return "", errors.New("claude cli: generation unavailable")
|
||||
}
|
||||
return strings.TrimSpace(envelope.Result), nil
|
||||
}
|
||||
if err != nil {
|
||||
return "", errors.New("claude cli: execution failed")
|
||||
}
|
||||
return strings.TrimSpace(stdout.String()), nil
|
||||
return strings.TrimSpace(stdout.buffer.String()), nil
|
||||
}
|
||||
|
||||
func (p *claudeCodeProvider) ListModels(_ context.Context) ([]string, error) {
|
||||
|
||||
@ -8,6 +8,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
neturl "net/url"
|
||||
)
|
||||
|
||||
type geminiProvider struct {
|
||||
@ -32,7 +33,7 @@ func (p *geminiProvider) Name() string { return "gemini" }
|
||||
func (p *geminiProvider) Summarize(ctx context.Context, prompt string, opts GenOptions) (string, error) {
|
||||
url := fmt.Sprintf(
|
||||
"https://generativelanguage.googleapis.com/v1beta/models/%s:generateContent?key=%s",
|
||||
p.model, p.apiKey,
|
||||
neturl.PathEscape(p.model), neturl.QueryEscape(p.apiKey),
|
||||
)
|
||||
body := map[string]interface{}{
|
||||
"contents": []map[string]interface{}{
|
||||
@ -55,9 +56,9 @@ func (p *geminiProvider) Summarize(ctx context.Context, prompt string, opts GenO
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
raw, _ := io.ReadAll(resp.Body)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", &summaryHTTPError{status: resp.StatusCode, err: fmt.Errorf("gemini API error %d: %s", resp.StatusCode, raw)}
|
||||
raw, err := readGenerationResponse(resp)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
var result struct {
|
||||
@ -79,7 +80,7 @@ func (p *geminiProvider) Summarize(ctx context.Context, prompt string, opts GenO
|
||||
}
|
||||
|
||||
func (p *geminiProvider) ListModels(ctx context.Context) ([]string, error) {
|
||||
url := fmt.Sprintf("https://generativelanguage.googleapis.com/v1beta/models?key=%s", p.apiKey)
|
||||
url := fmt.Sprintf("https://generativelanguage.googleapis.com/v1beta/models?key=%s", neturl.QueryEscape(p.apiKey))
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
64
backend/internal/ai/generation_response.go
Normal file
64
backend/internal/ai/generation_response.go
Normal file
@ -0,0 +1,64 @@
|
||||
package ai
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const maxGenerationResponseBytes = 2 << 20
|
||||
|
||||
type generationReadError struct{ cause error }
|
||||
|
||||
func (e *generationReadError) Error() string { return "provider generation response unavailable" }
|
||||
func (e *generationReadError) Unwrap() error { return e.cause }
|
||||
|
||||
// Preserve only structured HTTP status and allowlisted error identifiers. Error
|
||||
// messages and response bodies never become error strings or log arguments.
|
||||
func readGenerationResponse(resp *http.Response) ([]byte, error) {
|
||||
maximum := maxGenerationResponseBytes
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
maximum = 64 << 10
|
||||
}
|
||||
raw, err := io.ReadAll(io.LimitReader(resp.Body, int64(maximum)+1))
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
code := ""
|
||||
if err == nil && len(raw) <= maximum {
|
||||
code = generationErrorCode(raw)
|
||||
}
|
||||
return nil, &summaryHTTPError{status: resp.StatusCode, code: code, err: errors.New("provider generation rejected")}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, &generationReadError{cause: err}
|
||||
}
|
||||
if len(raw) > maximum {
|
||||
return nil, errors.New("provider generation response unavailable")
|
||||
}
|
||||
return raw, nil
|
||||
}
|
||||
func generationErrorCode(raw []byte) string {
|
||||
var payload struct {
|
||||
Error struct {
|
||||
Code any `json:"code"`
|
||||
Type, Status string
|
||||
Details []struct{ Reason string }
|
||||
}
|
||||
}
|
||||
if json.Unmarshal(raw, &payload) != nil {
|
||||
return ""
|
||||
}
|
||||
code, _ := payload.Error.Code.(string)
|
||||
values := []string{code, payload.Error.Type, payload.Error.Status}
|
||||
for _, detail := range payload.Error.Details {
|
||||
values = append(values, detail.Reason)
|
||||
}
|
||||
for _, value := range values {
|
||||
switch code := strings.ToLower(value); code {
|
||||
case "invalid_api_key", "authentication_error", "permission_denied", "unauthenticated", "api_key_invalid", "api_key_expired", "model_not_found", "not_found_error", "not_found", "rate_limit_error", "rate_limit_exceeded", "resource_exhausted", "deadline_exceeded", "timeout_error":
|
||||
return code
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
127
backend/internal/ai/model_probe_adapters_ticket43_test.go
Normal file
127
backend/internal/ai/model_probe_adapters_ticket43_test.go
Normal file
@ -0,0 +1,127 @@
|
||||
package ai
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
openai "github.com/sashabaranov/go-openai"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTicket43OllamaSmallGenerationHasExplicitOutputLimit(t *testing.T) {
|
||||
p := newOllama("https://fixture.invalid", "exact-saved-model")
|
||||
calls := 0
|
||||
p.client = &http.Client{Transport: ticket31Transport(func(r *http.Request) (*http.Response, error) {
|
||||
calls++
|
||||
var body struct {
|
||||
Model, Prompt string
|
||||
Options map[string]int
|
||||
}
|
||||
if json.NewDecoder(r.Body).Decode(&body) != nil || body.Model != "exact-saved-model" || body.Prompt != modelTestPrompt || body.Options["num_predict"] != modelTestMaxOutputTokens {
|
||||
t.Error("Ollama test call omitted the fixed output cap or exact saved model")
|
||||
}
|
||||
return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"response":"OK"}`))}, nil
|
||||
})}
|
||||
if _, err := p.Summarize(context.Background(), modelTestPrompt, GenOptions{MaxOutputTokens: modelTestMaxOutputTokens}); err != nil || calls != 1 {
|
||||
t.Fatal("small generation retried or failed")
|
||||
}
|
||||
}
|
||||
func TestTicket43AdapterStructuredErrorCodesAndRawBodiesAreNotExposed(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, body string
|
||||
want error
|
||||
}{
|
||||
{"anthropic", `{"error":{"type":"authentication_error","message":"PRIVATE_BODY"}}`, ErrModelTestAuth},
|
||||
{"gemini", `{"error":{"status":"RESOURCE_EXHAUSTED","message":"PRIVATE_BODY"}}`, ErrModelTestRateLimited},
|
||||
{"ollama", `{"error":{"code":"model_not_found","message":"PRIVATE_BODY"}}`, ErrModelTestModelUnavailable},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
client := &http.Client{Transport: ticket31Transport(func(*http.Request) (*http.Response, error) {
|
||||
return &http.Response{StatusCode: 400, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(tc.body))}, nil
|
||||
})}
|
||||
var provider Provider
|
||||
switch tc.name {
|
||||
case "anthropic":
|
||||
p := newAnthropic("PRIVATE_KEY", "exact")
|
||||
p.client = client
|
||||
provider = p
|
||||
case "gemini":
|
||||
p := newGemini("PRIVATE_KEY", "exact")
|
||||
p.client = client
|
||||
provider = p
|
||||
case "ollama":
|
||||
p := newOllama("https://PRIVATE_ENDPOINT", "exact")
|
||||
p.client = client
|
||||
provider = p
|
||||
}
|
||||
_, err := provider.Summarize(context.Background(), modelTestPrompt, GenOptions{MaxOutputTokens: modelTestMaxOutputTokens})
|
||||
if err == nil || strings.Contains(err.Error(), "PRIVATE") || classifyModelTestError(err) != tc.want {
|
||||
t.Error("structured adapter rejection lost its category or exposed raw response")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTicket43HTTPGenerationAdaptersUseExactModelCredentialsAndSmallOutput(t *testing.T) {
|
||||
for _, name := range []string{"openai", "anthropic", "gemini", "ollama"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
const key = "PRIVATE_KEY+&"
|
||||
calls := 0
|
||||
client := &http.Client{Transport: ticket31Transport(func(r *http.Request) (*http.Response, error) {
|
||||
calls++
|
||||
var body map[string]any
|
||||
if r.Method != "POST" || json.NewDecoder(r.Body).Decode(&body) != nil {
|
||||
t.Error("generation was replaced by discovery")
|
||||
}
|
||||
response := ""
|
||||
switch name {
|
||||
case "openai":
|
||||
if body["model"] != "exact-saved-model" || body["max_tokens"] != float64(modelTestMaxOutputTokens) || r.Header.Get("Authorization") != "Bearer "+key {
|
||||
t.Error("OpenAI generation configuration changed")
|
||||
}
|
||||
response = `{"choices":[{"message":{"role":"assistant","content":"OK"}}]}`
|
||||
case "anthropic":
|
||||
if body["model"] != "exact-saved-model" || body["max_tokens"] != float64(modelTestMaxOutputTokens) || r.Header.Get("x-api-key") != key {
|
||||
t.Error("Anthropic generation configuration changed")
|
||||
}
|
||||
response = `{"content":[{"type":"text","text":"OK"}]}`
|
||||
case "gemini":
|
||||
config, _ := body["generationConfig"].(map[string]any)
|
||||
if !strings.HasSuffix(r.URL.Path, "/models/exact-saved-model:generateContent") || r.URL.Query().Get("key") != key || config["maxOutputTokens"] != float64(modelTestMaxOutputTokens) {
|
||||
t.Error("Gemini generation configuration changed")
|
||||
}
|
||||
response = `{"candidates":[{"content":{"parts":[{"text":"OK"}]}}]}`
|
||||
case "ollama":
|
||||
config, _ := body["options"].(map[string]any)
|
||||
if body["model"] != "exact-saved-model" || r.URL.Host != "saved-fixture.invalid" || config["num_predict"] != float64(modelTestMaxOutputTokens) {
|
||||
t.Error("Ollama generation configuration changed")
|
||||
}
|
||||
response = `{"response":"OK"}`
|
||||
}
|
||||
return &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(response))}, nil
|
||||
})}
|
||||
provider, err := NewProvider(name, key, "exact-saved-model", "https://saved-fixture.invalid")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
switch p := provider.(type) {
|
||||
case *openAIProvider:
|
||||
cfg := openai.DefaultConfig(key)
|
||||
cfg.HTTPClient = client
|
||||
p.client = openai.NewClientWithConfig(cfg)
|
||||
case *anthropicProvider:
|
||||
p.client = client
|
||||
case *geminiProvider:
|
||||
p.client = client
|
||||
case *OllamaProvider:
|
||||
p.client = client
|
||||
}
|
||||
response, err := provider.Summarize(context.Background(), modelTestPrompt, GenOptions{MaxOutputTokens: modelTestMaxOutputTokens, NumCtx: 2048})
|
||||
if err != nil || response != "OK" || calls != 1 {
|
||||
t.Fatal("exact-model generation failed or retried")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
51
backend/internal/ai/model_probe_cli_ticket43_test.go
Normal file
51
backend/internal/ai/model_probe_cli_ticket43_test.go
Normal file
@ -0,0 +1,51 @@
|
||||
package ai
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTicket43ClaudeModelTestUsesStructuredNonemptyResultAndBoundedChildOptions(t *testing.T) {
|
||||
directory := t.TempDir()
|
||||
script := `#!/bin/sh
|
||||
[ "$CLAUDE_CODE_MAX_OUTPUT_TOKENS" = 16 ] || exit 1
|
||||
[ "$CLAUDE_CODE_MAX_RETRIES" = 0 ] || exit 1
|
||||
[ -z "$CLAUDE_CODE_RETRY_WATCHDOG" ] || exit 1
|
||||
case " $* " in *" --output-format json "*) ;; *) exit 1;; esac
|
||||
case " $* " in *" --no-session-persistence "*) ;; *) exit 1;; esac
|
||||
printf '%s' '{"type":"result","subtype":"success","is_error":false,"result":"PRIVATE_GENERATED_RESULT"}'
|
||||
printf '%s' 'PRIVATE_STDERR' >&2
|
||||
`
|
||||
if err := os.WriteFile(filepath.Join(directory, "claude"), []byte(script), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("PATH", directory+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||
t.Setenv("CLAUDE_CODE_MAX_OUTPUT_TOKENS", "9999")
|
||||
t.Setenv("CLAUDE_CODE_MAX_RETRIES", "10")
|
||||
t.Setenv("CLAUDE_CODE_RETRY_WATCHDOG", "1")
|
||||
// Use the same marked context as the admin test service.
|
||||
ctx := context.WithValue(context.Background(), modelTestContextKey{}, true)
|
||||
response, err := newClaudeCode("exact-saved-model").Summarize(ctx, modelTestPrompt, GenOptions{MaxOutputTokens: modelTestMaxOutputTokens})
|
||||
if err != nil || response != "PRIVATE_GENERATED_RESULT" {
|
||||
t.Fatal("CLI test options or structured generation result missing")
|
||||
}
|
||||
}
|
||||
func TestTicket43ClaudeErrorEnvelopeCannotBecomeSuccessfulGeneratedText(t *testing.T) {
|
||||
directory := t.TempDir()
|
||||
script := `#!/bin/sh
|
||||
printf '%s' '{"type":"result","subtype":"error_during_execution","is_error":true,"result":"PRIVATE_ERROR_TEXT"}'
|
||||
printf '%s' 'PRIVATE_STDERR' >&2
|
||||
`
|
||||
if err := os.WriteFile(filepath.Join(directory, "claude"), []byte(script), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("PATH", directory+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||
ctx := context.WithValue(context.Background(), modelTestContextKey{}, true)
|
||||
response, err := newClaudeCode("exact").Summarize(ctx, modelTestPrompt, GenOptions{MaxOutputTokens: modelTestMaxOutputTokens})
|
||||
if err == nil || response != "" || strings.Contains(err.Error(), "PRIVATE") {
|
||||
t.Fatal("CLI error envelope leaked or became generated content")
|
||||
}
|
||||
}
|
||||
121
backend/internal/ai/model_test_lock_ticket43_test.go
Normal file
121
backend/internal/ai/model_test_lock_ticket43_test.go
Normal file
@ -0,0 +1,121 @@
|
||||
package ai
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestTicket43ProviderLockSpansModelsAndDifferentProvidersRemainIndependent(t *testing.T) {
|
||||
started, finish := make(chan struct{}), make(chan struct{})
|
||||
provider := &model43Provider{generate: func(context.Context, string, GenOptions) (string, error) { close(started); <-finish; return "OK", nil }}
|
||||
repo := model43Repo(func(_ context.Context, id string) (models.ResolvedSummaryModel, error) {
|
||||
pid := "shared"
|
||||
if id == "other" {
|
||||
pid = "independent"
|
||||
}
|
||||
return models.ResolvedSummaryModel{ID: id, ProviderID: pid, Provider: "ollama", Model: id}, nil
|
||||
})
|
||||
builds := 0
|
||||
service := NewModelTester(repo, nil, func(_, _, model, _ string) (Provider, error) {
|
||||
builds++
|
||||
if model == "other" {
|
||||
return &model43Provider{generate: func(context.Context, string, GenOptions) (string, error) { return "OK", nil }}, nil
|
||||
}
|
||||
return provider, nil
|
||||
})
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- service.Test(context.Background(), "first") }()
|
||||
select {
|
||||
case <-started:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("first generation did not start")
|
||||
}
|
||||
if err := service.Test(context.Background(), "second"); !errors.Is(err, ErrModelTestBusy) {
|
||||
t.Error("same-provider model test was not rejected")
|
||||
}
|
||||
if err := service.Test(context.Background(), "other"); err != nil {
|
||||
t.Error("independent provider was blocked")
|
||||
}
|
||||
close(finish)
|
||||
if err := <-done; err != nil || builds != 2 {
|
||||
t.Fatal("provider lock retried or failed")
|
||||
}
|
||||
if err := service.Test(context.Background(), "other"); err != nil {
|
||||
t.Fatal("completed lock was retained")
|
||||
}
|
||||
}
|
||||
func TestTicket43TimeoutReturnsPromptlyButKeepsProviderLockedUntilCallExits(t *testing.T) {
|
||||
started, finish := make(chan struct{}), make(chan struct{})
|
||||
service := NewModelTester(model43Repo(func(_ context.Context, id string) (models.ResolvedSummaryModel, error) {
|
||||
return models.ResolvedSummaryModel{ID: id, ProviderID: "p", Provider: "ollama", Model: id}, nil
|
||||
}), nil, func(string, string, string, string) (Provider, error) {
|
||||
return &model43Provider{generate: func(context.Context, string, GenOptions) (string, error) {
|
||||
close(started)
|
||||
<-finish
|
||||
return "late output", nil
|
||||
}}, nil
|
||||
})
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
|
||||
defer cancel()
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- service.Test(ctx, "m") }()
|
||||
select {
|
||||
case <-started:
|
||||
case <-time.After(time.Second):
|
||||
close(finish)
|
||||
t.Fatal("generation did not start")
|
||||
}
|
||||
select {
|
||||
case err := <-done:
|
||||
if !errors.Is(err, ErrModelTestTimeout) {
|
||||
t.Error("deadline not classified")
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
close(finish)
|
||||
t.Fatal("HTTP-level call ignored deadline")
|
||||
}
|
||||
if err := service.Test(context.Background(), "other-model"); !errors.Is(err, ErrModelTestBusy) {
|
||||
t.Error("timeout released a still-running provider")
|
||||
}
|
||||
close(finish)
|
||||
// Wait on the lock itself, without launching another generation or retry.
|
||||
deadline := time.Now().Add(time.Second)
|
||||
for {
|
||||
service.mu.Lock()
|
||||
busy := service.busy["p"]
|
||||
service.mu.Unlock()
|
||||
if !busy {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("finished provider lock leaked")
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
}
|
||||
func TestTicket43FailuresAndPanicsReleaseProviderLockWithoutLeakingMessages(t *testing.T) {
|
||||
for _, failure := range []string{"decrypt", "factory", "provider panic"} {
|
||||
t.Run(failure, func(t *testing.T) {
|
||||
service := NewModelTester(model43Repo(func(_ context.Context, id string) (models.ResolvedSummaryModel, error) {
|
||||
cipher := ""
|
||||
if failure == "decrypt" {
|
||||
cipher = "PRIVATE_CIPHER"
|
||||
}
|
||||
return models.ResolvedSummaryModel{ID: id, ProviderID: "p", Provider: "ollama", Model: id, APIKeyEncrypted: cipher}, nil
|
||||
}), model43Decrypt(func(string) (string, error) { return "", errors.New("PRIVATE_DECRYPT") }), func(string, string, string, string) (Provider, error) {
|
||||
if failure == "factory" {
|
||||
return nil, errors.New("PRIVATE_FACTORY")
|
||||
}
|
||||
return &model43Provider{generate: func(context.Context, string, GenOptions) (string, error) { panic("PRIVATE_PANIC") }}, nil
|
||||
})
|
||||
for i := 0; i < 2; i++ {
|
||||
if err := service.Test(context.Background(), "m"); !errors.Is(err, ErrModelTestLocal) {
|
||||
t.Fatal("local failure leaked or lock was retained")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
193
backend/internal/ai/model_test_service.go
Normal file
193
backend/internal/ai/model_test_service.go
Normal file
@ -0,0 +1,193 @@
|
||||
package ai
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
openai "github.com/sashabaranov/go-openai"
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrModelTestEmpty = errors.New("empty_response")
|
||||
ErrModelTestAuth = errors.New("auth_rejected")
|
||||
ErrModelTestModelUnavailable = errors.New("model_unavailable")
|
||||
ErrModelTestRateLimited = errors.New("rate_limited")
|
||||
ErrModelTestTimeout = errors.New("timeout")
|
||||
ErrModelTestUnavailable = errors.New("unavailable")
|
||||
ErrModelTestNotFound = errors.New("catalog_model_not_found")
|
||||
ErrModelTestBusy = errors.New("provider_test_busy")
|
||||
ErrModelTestLocal = errors.New("model_test_local_failure")
|
||||
)
|
||||
|
||||
const modelTestPrompt = "Reply with OK."
|
||||
const modelTestMaxOutputTokens = 16
|
||||
const modelTestTimeout = 30 * time.Second
|
||||
|
||||
type modelTestContextKey struct{}
|
||||
|
||||
type ModelTestRepository interface {
|
||||
GetSummaryModelForTest(context.Context, string) (models.ResolvedSummaryModel, error)
|
||||
}
|
||||
type ModelProviderFactory func(name, key, model, endpoint string) (Provider, error)
|
||||
type ModelTester struct {
|
||||
repo ModelTestRepository
|
||||
enc ConnectionDecryptor
|
||||
build ModelProviderFactory
|
||||
mu sync.Mutex
|
||||
busy map[string]bool
|
||||
}
|
||||
|
||||
func NewModelTester(repo ModelTestRepository, enc ConnectionDecryptor, build ModelProviderFactory) *ModelTester {
|
||||
if build == nil {
|
||||
build = NewProvider
|
||||
}
|
||||
return &ModelTester{repo: repo, enc: enc, build: build, busy: map[string]bool{}}
|
||||
}
|
||||
|
||||
// Test runs against a saved catalogue snapshot, never user test parameters.
|
||||
// It is a single shared service per HTTP server; locks are keyed by provider ID.
|
||||
func (t *ModelTester) Test(parent context.Context, id string) (err error) {
|
||||
defer func() {
|
||||
if recover() != nil {
|
||||
err = ErrModelTestLocal
|
||||
}
|
||||
}()
|
||||
ctx, cancel := context.WithTimeout(parent, modelTestTimeout)
|
||||
defer cancel()
|
||||
ctx = context.WithValue(ctx, modelTestContextKey{}, true)
|
||||
model, err := t.repo.GetSummaryModelForTest(ctx, id)
|
||||
if ctx.Err() != nil {
|
||||
return modelTestContextError(ctx.Err())
|
||||
}
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return ErrModelTestNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return ErrModelTestLocal
|
||||
}
|
||||
if model.ID == "" || model.ProviderID == "" || strings.TrimSpace(model.Provider) == "" || strings.TrimSpace(model.Model) == "" {
|
||||
return ErrModelTestLocal
|
||||
}
|
||||
t.mu.Lock()
|
||||
if t.busy[model.ProviderID] {
|
||||
t.mu.Unlock()
|
||||
return ErrModelTestBusy
|
||||
}
|
||||
t.busy[model.ProviderID] = true
|
||||
t.mu.Unlock()
|
||||
var once sync.Once
|
||||
release := func() { once.Do(func() { t.mu.Lock(); delete(t.busy, model.ProviderID); t.mu.Unlock() }) }
|
||||
handedOff := false
|
||||
defer func() {
|
||||
if !handedOff {
|
||||
release()
|
||||
}
|
||||
}()
|
||||
key := ""
|
||||
if model.APIKeyEncrypted != "" {
|
||||
if t.enc == nil {
|
||||
return ErrModelTestLocal
|
||||
}
|
||||
key, err = t.enc.Decrypt(model.APIKeyEncrypted)
|
||||
if err != nil {
|
||||
return ErrModelTestLocal
|
||||
}
|
||||
}
|
||||
provider, err := t.build(model.Provider, key, model.Model, model.Endpoint)
|
||||
if err != nil || provider == nil {
|
||||
return ErrModelTestLocal
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return modelTestContextError(ctx.Err())
|
||||
}
|
||||
done := make(chan error, 1)
|
||||
handedOff = true
|
||||
go func() {
|
||||
outcome := runModelTestGeneration(ctx, provider)
|
||||
// Keep a timed-out provider locked until its actual call exits. A provider
|
||||
// ignoring cancellation must not permit a second concurrent generation.
|
||||
release()
|
||||
done <- outcome
|
||||
}()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return modelTestContextError(ctx.Err())
|
||||
case outcome := <-done:
|
||||
if ctx.Err() != nil {
|
||||
return modelTestContextError(ctx.Err())
|
||||
}
|
||||
return outcome
|
||||
}
|
||||
}
|
||||
func runModelTestGeneration(ctx context.Context, provider Provider) (err error) {
|
||||
defer func() {
|
||||
if recover() != nil {
|
||||
err = ErrModelTestLocal
|
||||
}
|
||||
}()
|
||||
response, err := provider.Summarize(ctx, modelTestPrompt, GenOptions{MaxOutputTokens: modelTestMaxOutputTokens, NumCtx: 2048})
|
||||
if ctx.Err() != nil {
|
||||
return modelTestContextError(ctx.Err())
|
||||
}
|
||||
if err != nil {
|
||||
return classifyModelTestError(err)
|
||||
}
|
||||
if strings.TrimSpace(response) == "" {
|
||||
return ErrModelTestEmpty
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func modelTestContextError(err error) error {
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
return ErrModelTestTimeout
|
||||
}
|
||||
return ErrModelTestUnavailable
|
||||
}
|
||||
func classifyModelTestError(err error) error {
|
||||
var timeout interface{ Timeout() bool }
|
||||
if errors.Is(err, context.DeadlineExceeded) || (errors.As(err, &timeout) && timeout.Timeout()) {
|
||||
return ErrModelTestTimeout
|
||||
}
|
||||
status, code := 0, ""
|
||||
var local *summaryHTTPError
|
||||
var api *openai.APIError
|
||||
var request *openai.RequestError
|
||||
switch {
|
||||
case errors.As(err, &local):
|
||||
status = local.status
|
||||
code = local.code
|
||||
case errors.As(err, &api):
|
||||
status = api.HTTPStatusCode
|
||||
code, _ = api.Code.(string)
|
||||
if code == "" {
|
||||
code = api.Type
|
||||
}
|
||||
case errors.As(err, &request):
|
||||
status = request.HTTPStatusCode
|
||||
}
|
||||
switch status {
|
||||
case 401, 403:
|
||||
return ErrModelTestAuth
|
||||
case 404, 410:
|
||||
return ErrModelTestModelUnavailable
|
||||
case 429:
|
||||
return ErrModelTestRateLimited
|
||||
case 408, 504:
|
||||
return ErrModelTestTimeout
|
||||
}
|
||||
switch strings.ToLower(code) {
|
||||
case "invalid_api_key", "authentication_error", "permission_denied", "unauthenticated", "api_key_invalid", "api_key_expired":
|
||||
return ErrModelTestAuth
|
||||
case "model_not_found", "not_found_error", "not_found":
|
||||
return ErrModelTestModelUnavailable
|
||||
case "rate_limit_error", "rate_limit_exceeded", "resource_exhausted":
|
||||
return ErrModelTestRateLimited
|
||||
case "deadline_exceeded", "timeout_error":
|
||||
return ErrModelTestTimeout
|
||||
}
|
||||
return ErrModelTestUnavailable
|
||||
}
|
||||
117
backend/internal/ai/model_test_service_ticket43_test.go
Normal file
117
backend/internal/ai/model_test_service_ticket43_test.go
Normal file
@ -0,0 +1,117 @@
|
||||
package ai
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
openai "github.com/sashabaranov/go-openai"
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
)
|
||||
|
||||
type model43Repo func(context.Context, string) (models.ResolvedSummaryModel, error)
|
||||
|
||||
func (f model43Repo) GetSummaryModelForTest(ctx context.Context, id string) (models.ResolvedSummaryModel, error) {
|
||||
return f(ctx, id)
|
||||
}
|
||||
|
||||
type model43Decrypt func(string) (string, error)
|
||||
|
||||
func (f model43Decrypt) Decrypt(value string) (string, error) { return f(value) }
|
||||
|
||||
type model43Provider struct {
|
||||
generate func(context.Context, string, GenOptions) (string, error)
|
||||
calls, discoveries int
|
||||
}
|
||||
|
||||
func (*model43Provider) Name() string { return "fixture" }
|
||||
func (p *model43Provider) ListModels(context.Context) ([]string, error) {
|
||||
p.discoveries++
|
||||
return nil, errors.New("discovery must not run")
|
||||
}
|
||||
func (p *model43Provider) Summarize(ctx context.Context, prompt string, opts GenOptions) (string, error) {
|
||||
p.calls++
|
||||
return p.generate(ctx, prompt, opts)
|
||||
}
|
||||
func TestTicket43ModelTestUsesExactSavedConfigurationAndStructuredOutcomes(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, response string
|
||||
upstream, want error
|
||||
}{
|
||||
{name: "success", response: " PRIVATE_GENERATED_TEXT "},
|
||||
{name: "empty", response: " \t\n\u2003", want: ErrModelTestEmpty},
|
||||
{name: "auth", upstream: &openai.APIError{HTTPStatusCode: 401, Message: "PRIVATE_BODY"}, want: ErrModelTestAuth},
|
||||
{name: "forbidden", upstream: &openai.RequestError{HTTPStatusCode: 403}, want: ErrModelTestAuth},
|
||||
{name: "missing", upstream: &openai.APIError{HTTPStatusCode: 404}, want: ErrModelTestModelUnavailable},
|
||||
{name: "missing structured code", upstream: &openai.APIError{HTTPStatusCode: 400, Code: "model_not_found"}, want: ErrModelTestModelUnavailable},
|
||||
{name: "limited", upstream: fmt.Errorf("PRIVATE: %w", &openai.APIError{HTTPStatusCode: 429}), want: ErrModelTestRateLimited},
|
||||
{name: "unavailable", upstream: &summaryHTTPError{status: 503, err: errors.New("PRIVATE_BODY")}, want: ErrModelTestUnavailable},
|
||||
{name: "HTTP timeout", upstream: &summaryHTTPError{status: 504, err: errors.New("PRIVATE_BODY")}, want: ErrModelTestTimeout},
|
||||
{name: "deadline", upstream: context.DeadlineExceeded, want: ErrModelTestTimeout},
|
||||
{name: "untrusted text", upstream: errors.New("401 429 model_not_found PRIVATE_SECRET https://private.invalid"), want: ErrModelTestUnavailable},
|
||||
{name: "error wins over output", response: "PRIVATE_OUTPUT", upstream: errors.New("PRIVATE_ERROR"), want: ErrModelTestUnavailable},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var logs bytes.Buffer
|
||||
old := log.Writer()
|
||||
log.SetOutput(&logs)
|
||||
defer log.SetOutput(old)
|
||||
provider := &model43Provider{generate: func(ctx context.Context, prompt string, opts GenOptions) (string, error) {
|
||||
deadline, ok := ctx.Deadline()
|
||||
remaining := time.Until(deadline)
|
||||
if !ok || remaining > 30*time.Second || remaining < 29*time.Second || prompt != modelTestPrompt || len(prompt) > 64 || opts.MaxOutputTokens != modelTestMaxOutputTokens || opts.Think || opts.JSONMode {
|
||||
t.Error("fixed generation options or 30s deadline missing")
|
||||
}
|
||||
return tc.response, tc.upstream
|
||||
}}
|
||||
builds, decrypts := 0, 0
|
||||
service := NewModelTester(model43Repo(func(_ context.Context, id string) (models.ResolvedSummaryModel, error) {
|
||||
if id != "saved-id" {
|
||||
t.Error("wrong catalogue entry")
|
||||
}
|
||||
return models.ResolvedSummaryModel{ID: id, ProviderID: "saved-provider", Provider: "ollama", Model: "exact-disabled-model", Endpoint: "https://PRIVATE_ENDPOINT", APIKeyEncrypted: "PRIVATE_CIPHER"}, nil
|
||||
}), model43Decrypt(func(cipher string) (string, error) {
|
||||
decrypts++
|
||||
if cipher != "PRIVATE_CIPHER" {
|
||||
t.Error("wrong encrypted key")
|
||||
}
|
||||
return "PRIVATE_KEY", nil
|
||||
}), func(name, key, model, endpoint string) (Provider, error) {
|
||||
builds++
|
||||
if name != "ollama" || key != "PRIVATE_KEY" || model != "exact-disabled-model" || endpoint != "https://PRIVATE_ENDPOINT" {
|
||||
t.Error("factory did not receive exact saved configuration")
|
||||
}
|
||||
return provider, nil
|
||||
})
|
||||
err := service.Test(context.Background(), "saved-id")
|
||||
if !errors.Is(err, tc.want) || builds != 1 || decrypts != 1 || provider.calls != 1 || provider.discoveries != 0 || logs.Len() != 0 {
|
||||
t.Fatalf("model test contract failed: calls=%d builds=%d decrypts=%d discovery=%d", provider.calls, builds, decrypts, provider.discoveries)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestTicket43ModelTestLocalFailuresAreSanitizedWithoutGeneration(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
model models.ResolvedSummaryModel
|
||||
repoErr error
|
||||
want error
|
||||
}{
|
||||
{name: "unknown", repoErr: sql.ErrNoRows, want: ErrModelTestNotFound},
|
||||
{name: "database", repoErr: errors.New("PRIVATE_DATABASE_ENDPOINT"), want: ErrModelTestLocal},
|
||||
{name: "blank model", model: models.ResolvedSummaryModel{ID: "m", ProviderID: "p", Provider: "ollama", Model: " "}, want: ErrModelTestLocal},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
builds := 0
|
||||
service := NewModelTester(model43Repo(func(context.Context, string) (models.ResolvedSummaryModel, error) { return tc.model, tc.repoErr }), nil, func(string, string, string, string) (Provider, error) { builds++; return nil, errors.New("PRIVATE") })
|
||||
if err := service.Test(context.Background(), "m"); !errors.Is(err, tc.want) || builds != 0 {
|
||||
t.Fatal("local failure escaped or reached generation")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@ -64,6 +64,9 @@ func (p *OllamaProvider) Summarize(ctx context.Context, prompt string, opts GenO
|
||||
"num_ctx": numCtx,
|
||||
},
|
||||
}
|
||||
if opts.MaxOutputTokens > 0 {
|
||||
body["options"].(map[string]interface{})["num_predict"] = opts.MaxOutputTokens
|
||||
}
|
||||
if opts.JSONMode {
|
||||
body["format"] = "json"
|
||||
}
|
||||
@ -80,9 +83,9 @@ func (p *OllamaProvider) Summarize(ctx context.Context, prompt string, opts GenO
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
raw, _ := io.ReadAll(resp.Body)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", &summaryHTTPError{status: resp.StatusCode, err: fmt.Errorf("ollama API error %d: %s", resp.StatusCode, raw)}
|
||||
raw, err := readGenerationResponse(resp)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
var result struct {
|
||||
|
||||
@ -48,6 +48,7 @@ func LogSummaryDiagnostic(d SummaryDiagnostic) error {
|
||||
// Preserve the original provider error and its chain, while exposing only status
|
||||
// to diagnostics. Do not extract categories by parsing error messages/bodies.
|
||||
type summaryHTTPError struct {
|
||||
code string
|
||||
status int
|
||||
err error
|
||||
}
|
||||
|
||||
@ -16,6 +16,9 @@ import (
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
modelTester interface {
|
||||
Test(context.Context, string) error
|
||||
}
|
||||
connectionTester interface {
|
||||
Test(context.Context, string) error
|
||||
}
|
||||
@ -45,8 +48,13 @@ func New(
|
||||
if embedded, err := companycatalog.Default(); err == nil {
|
||||
catalog = embedded
|
||||
}
|
||||
var decryptor ai.ConnectionDecryptor
|
||||
if enc != nil {
|
||||
decryptor = enc
|
||||
}
|
||||
return &Handler{
|
||||
companyCatalog: catalog,
|
||||
modelTester: ai.NewModelTester(repo, decryptor, ai.NewProvider),
|
||||
connectionTester: ai.NewConnectionTester(repo, enc, func(name, key, endpoint string) (ai.Provider, error) {
|
||||
return ai.NewProvider(name, key, "", endpoint)
|
||||
}),
|
||||
@ -72,3 +80,10 @@ func (h *Handler) SetGenerationJobs(jobs interface {
|
||||
}
|
||||
|
||||
func (h *Handler) AdminOnly() gin.HandlerFunc { return auth.AdminOnly(h.repo) }
|
||||
|
||||
// SetModelTester supplies an isolated test port; production uses NewModelTester.
|
||||
func (h *Handler) SetModelTester(tester interface {
|
||||
Test(context.Context, string) error
|
||||
}) {
|
||||
h.modelTester = tester
|
||||
}
|
||||
|
||||
53
backend/internal/api/handlers/model_probe.go
Normal file
53
backend/internal/api/handlers/model_probe.go
Normal file
@ -0,0 +1,53 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/tradarr/backend/internal/ai"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func (h *Handler) TestSummaryModel(c *gin.Context) {
|
||||
// Defence against accidental panic logging by the outer recovery middleware.
|
||||
defer func() {
|
||||
if recover() != nil {
|
||||
c.AbortWithStatusJSON(500, gin.H{"status": "unavailable"})
|
||||
}
|
||||
}()
|
||||
// A no-body action: reject parameters without reading an unbounded/slow body.
|
||||
if !assetUUID.MatchString(c.Param("id")) || c.Request.ContentLength != 0 || len(c.Request.TransferEncoding) > 0 || c.Request.URL.RawQuery != "" || c.Request.URL.ForceQuery {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"status": "unavailable"})
|
||||
return
|
||||
}
|
||||
if h.modelTester == nil {
|
||||
c.JSON(500, gin.H{"status": "unavailable"})
|
||||
return
|
||||
}
|
||||
err := h.modelTester.Test(c.Request.Context(), c.Param("id"))
|
||||
code, status := http.StatusOK, "success"
|
||||
switch {
|
||||
case err == nil:
|
||||
case errors.Is(err, ai.ErrModelTestEmpty):
|
||||
status = "empty_response"
|
||||
case errors.Is(err, ai.ErrModelTestAuth):
|
||||
status = "auth_rejected"
|
||||
case errors.Is(err, ai.ErrModelTestModelUnavailable):
|
||||
status = "model_unavailable"
|
||||
case errors.Is(err, ai.ErrModelTestRateLimited):
|
||||
status = "rate_limited"
|
||||
case errors.Is(err, ai.ErrModelTestTimeout):
|
||||
status = "timeout"
|
||||
case errors.Is(err, ai.ErrModelTestUnavailable):
|
||||
status = "unavailable"
|
||||
case errors.Is(err, ai.ErrModelTestNotFound):
|
||||
code = 404
|
||||
status = "model_unavailable"
|
||||
case errors.Is(err, ai.ErrModelTestBusy):
|
||||
code = 409
|
||||
status = "unavailable"
|
||||
default:
|
||||
code = 500
|
||||
status = "unavailable"
|
||||
}
|
||||
c.JSON(code, gin.H{"status": status})
|
||||
}
|
||||
53
backend/internal/api/handlers/model_probe_ticket43_test.go
Normal file
53
backend/internal/api/handlers/model_probe_ticket43_test.go
Normal file
@ -0,0 +1,53 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/tradarr/backend/internal/ai"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type model43Tester struct {
|
||||
err error
|
||||
calls int
|
||||
id string
|
||||
}
|
||||
|
||||
func (f *model43Tester) Test(_ context.Context, id string) error { f.calls++; f.id = id; return f.err }
|
||||
func TestTicket43ModelProbeHandlerOnlyReturnsBoundedStatus(t *testing.T) {
|
||||
const id = "00000000-0000-0000-0000-000000004301"
|
||||
for _, tc := range []struct {
|
||||
err error
|
||||
code int
|
||||
status string
|
||||
}{
|
||||
{nil, 200, "success"}, {ai.ErrModelTestEmpty, 200, "empty_response"}, {ai.ErrModelTestAuth, 200, "auth_rejected"}, {ai.ErrModelTestModelUnavailable, 200, "model_unavailable"}, {ai.ErrModelTestRateLimited, 200, "rate_limited"}, {ai.ErrModelTestTimeout, 200, "timeout"}, {ai.ErrModelTestUnavailable, 200, "unavailable"}, {ai.ErrModelTestNotFound, 404, "model_unavailable"}, {ai.ErrModelTestBusy, 409, "unavailable"}, {errors.New("PRIVATE_BODY https://private.invalid"), 500, "unavailable"},
|
||||
} {
|
||||
fake := &model43Tester{err: tc.err}
|
||||
h := &Handler{modelTester: fake}
|
||||
router := gin.New()
|
||||
router.POST("/api/admin/ai-models/:id/test", h.TestSummaryModel)
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, httptest.NewRequest("POST", "/api/admin/ai-models/"+id+"/test", nil))
|
||||
if w.Code != tc.code || w.Body.String() != `{"status":"`+tc.status+`"}` || fake.calls != 1 || fake.id != id {
|
||||
t.Fatal("model test handler violated bounded response contract")
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestTicket43ModelProbeRejectsAnyClientParametersBeforeService(t *testing.T) {
|
||||
const path = "/api/admin/ai-models/00000000-0000-0000-0000-000000004301/test"
|
||||
for _, tc := range []struct{ path, body string }{{path, `{"model":"PRIVATE","prompt":"PRIVATE","endpoint":"https://private.invalid","api_key":"PRIVATE"}`}, {path, `{}`}, {path + "?model=PRIVATE", ""}, {"/api/admin/ai-models/PRIVATE/test", ""}} {
|
||||
fake := &model43Tester{}
|
||||
h := &Handler{modelTester: fake}
|
||||
router := gin.New()
|
||||
router.POST("/api/admin/ai-models/:id/test", h.TestSummaryModel)
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, httptest.NewRequest("POST", tc.path, strings.NewReader(tc.body)))
|
||||
if w.Code != 400 || w.Body.String() != `{"status":"unavailable"}` || fake.calls != 0 {
|
||||
t.Fatal("client parameters reached model service")
|
||||
}
|
||||
}
|
||||
}
|
||||
28
backend/internal/api/model_generation_test_ticket43_test.go
Normal file
28
backend/internal/api/model_generation_test_ticket43_test.go
Normal 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"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTicket43ModelGenerationTestRouteRequiresAuthentication(t *testing.T) {
|
||||
router := api.SetupRouter(handlers.New(nil, &config.Config{}, nil, nil, nil, nil), "fixture43")
|
||||
found := false
|
||||
for _, route := range router.Routes() {
|
||||
if route.Method == http.MethodPost && route.Path == "/api/admin/ai-models/:id/test" {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("model generation test route missing")
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/api/admin/ai-models/00000000-0000-0000-0000-000000004301/test", nil))
|
||||
if w.Code != 401 {
|
||||
t.Fatal("model generation test is not authenticated")
|
||||
}
|
||||
}
|
||||
212
backend/internal/api/model_probe_ticket43_postgres_test.go
Normal file
212
backend/internal/api/model_probe_ticket43_postgres_test.go
Normal file
@ -0,0 +1,212 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/lib/pq"
|
||||
"github.com/tradarr/backend/internal/ai"
|
||||
"github.com/tradarr/backend/internal/api"
|
||||
"github.com/tradarr/backend/internal/api/handlers"
|
||||
"github.com/tradarr/backend/internal/auth"
|
||||
"github.com/tradarr/backend/internal/config"
|
||||
"github.com/tradarr/backend/internal/crypto"
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
)
|
||||
|
||||
type generationProbe43 struct {
|
||||
generate func(context.Context, string, ai.GenOptions) (string, error)
|
||||
}
|
||||
|
||||
func (*generationProbe43) Name() string { return "fixture" }
|
||||
func (p *generationProbe43) Summarize(ctx context.Context, prompt string, opts ai.GenOptions) (string, error) {
|
||||
return p.generate(ctx, prompt, opts)
|
||||
}
|
||||
func (*generationProbe43) ListModels(context.Context) ([]string, error) {
|
||||
return nil, errors.New("discovery is not generation")
|
||||
}
|
||||
func TestTicket43SavedDisabledModelAdminGenerationAndNoMutationPostgres(t *testing.T) {
|
||||
db, err := sql.Open("postgres", postgresTestURL(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
db.SetMaxOpenConns(1)
|
||||
schema := fmt.Sprintf("probe43_%d", time.Now().UnixNano())
|
||||
if _, err = db.Exec(`CREATE SCHEMA ` + pq.QuoteIdentifier(schema)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Exec(`DROP SCHEMA ` + pq.QuoteIdentifier(schema) + ` CASCADE`)
|
||||
if _, err = db.Exec(`SET search_path TO ` + pq.QuoteIdentifier(schema)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
const mid = "00000000-0000-0000-0000-000000004301"
|
||||
const sibling = "00000000-0000-0000-0000-000000004302"
|
||||
const pid = "00000000-0000-0000-0000-000000004311"
|
||||
for _, q := range []string{
|
||||
`CREATE TABLE users(id TEXT PRIMARY KEY,email TEXT,password_hash TEXT,role TEXT,summary_model_id UUID,created_at TIMESTAMPTZ DEFAULT NOW(),updated_at TIMESTAMPTZ DEFAULT NOW())`,
|
||||
`INSERT INTO users(id,email,password_hash,role,summary_model_id) VALUES('admin','admin@example.test','hash','admin','` + sibling + `'),('user','user@example.test','hash','user',NULL)`,
|
||||
`CREATE TABLE ai_providers(id UUID PRIMARY KEY,name TEXT,model TEXT,endpoint TEXT,api_key_encrypted TEXT,is_active BOOLEAN)`,
|
||||
`CREATE TABLE ai_provider_models(id UUID PRIMARY KEY,provider_id UUID REFERENCES ai_providers(id),model TEXT,enabled BOOLEAN)`,
|
||||
} {
|
||||
if _, err = db.Exec(q); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
enc := crypto.New([]byte("0123456789abcdef0123456789abcdef"))
|
||||
cipher, err := enc.Encrypt("PRIVATE_SAVED_KEY")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = db.Exec(`INSERT INTO ai_providers VALUES($1,'ollama','wrong-provider-default','https://PRIVATE_ENDPOINT.invalid',$2,false)`, pid, cipher); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = db.Exec(`INSERT INTO ai_provider_models VALUES($1,$2,'exact-saved-model',false),($3,$2,'other-enabled-model',true)`, mid, pid, sibling); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var logs bytes.Buffer
|
||||
oldWriter, oldErr := gin.DefaultWriter, gin.DefaultErrorWriter
|
||||
gin.DefaultWriter = &logs
|
||||
gin.DefaultErrorWriter = &logs
|
||||
defer func() { gin.DefaultWriter = oldWriter; gin.DefaultErrorWriter = oldErr }()
|
||||
repo := models.NewRepository(db)
|
||||
var mu sync.Mutex
|
||||
calls, builds := 0, 0
|
||||
response := " PRIVATE_GENERATED_BODY "
|
||||
var upstream error
|
||||
promptSeen := ""
|
||||
var block chan struct{}
|
||||
var started chan struct{}
|
||||
service := ai.NewModelTester(repo, enc, func(name, key, model, endpoint string) (ai.Provider, error) {
|
||||
mu.Lock()
|
||||
builds++
|
||||
mu.Unlock()
|
||||
if name != "ollama" || key != "PRIVATE_SAVED_KEY" || model != "exact-saved-model" || endpoint != "https://PRIVATE_ENDPOINT.invalid" {
|
||||
t.Error("factory did not use exact saved row/model/secret/endpoint")
|
||||
}
|
||||
return &generationProbe43{generate: func(ctx context.Context, prompt string, opts ai.GenOptions) (string, error) {
|
||||
mu.Lock()
|
||||
calls++
|
||||
promptSeen = prompt
|
||||
b, s := block, started
|
||||
body, err := response, upstream
|
||||
mu.Unlock()
|
||||
if opts.MaxOutputTokens <= 0 || opts.MaxOutputTokens > 32 || len(prompt) > 64 {
|
||||
t.Error("probe generation was not minimal")
|
||||
}
|
||||
if deadline, ok := ctx.Deadline(); !ok || time.Until(deadline) > 30*time.Second {
|
||||
t.Error("30s probe deadline missing")
|
||||
}
|
||||
if s != nil {
|
||||
close(s)
|
||||
}
|
||||
if b != nil {
|
||||
<-b
|
||||
}
|
||||
return body, err
|
||||
}}, nil
|
||||
})
|
||||
const secret = "ticket43-fixture"
|
||||
h := handlers.New(repo, &config.Config{JWTSecret: secret}, enc, nil, nil, nil)
|
||||
h.SetModelTester(service)
|
||||
router := api.SetupRouter(h, secret)
|
||||
admin, _ := auth.GenerateToken("admin", "admin@example.test", "admin", secret)
|
||||
user, _ := auth.GenerateToken("user", "user@example.test", "user", secret)
|
||||
path := "/api/admin/ai-models/" + mid + "/test"
|
||||
request := func(path, body, token string) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body))
|
||||
if token != "" {
|
||||
r.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
token string
|
||||
code int
|
||||
}{{"", 401}, {user, 403}} {
|
||||
if w := request(path, "", tc.token); w.Code != tc.code {
|
||||
t.Fatal("probe authorization failed")
|
||||
}
|
||||
}
|
||||
for _, tc := range []struct{ path, body string }{{path, `{"prompt":"PRIVATE_CLIENT_PROMPT","model":"PRIVATE_OVERRIDE"}`}, {path + "?endpoint=https://PRIVATE_QUERY.invalid", ""}} {
|
||||
w := request(tc.path, tc.body, admin)
|
||||
if w.Code != 400 || w.Body.String() != `{"status":"unavailable"}` {
|
||||
t.Fatal("client parameters were not rejected")
|
||||
}
|
||||
}
|
||||
unknown := "/api/admin/ai-models/00000000-0000-0000-0000-000000004399/test"
|
||||
if w := request(unknown, "", admin); w.Code != 404 || w.Body.String() != `{"status":"model_unavailable"}` {
|
||||
t.Fatal("missing catalogue row was not sanitized")
|
||||
}
|
||||
if w := request(path, "", admin); w.Code != 200 || w.Body.String() != `{"status":"success"}` {
|
||||
t.Fatal("disabled catalogue model/provider cannot be tested")
|
||||
}
|
||||
mu.Lock()
|
||||
if calls != 1 || builds != 1 {
|
||||
t.Error("probe ran discovery, retried, or accepted substitutions")
|
||||
}
|
||||
response = " \n\t"
|
||||
mu.Unlock()
|
||||
if w := request(path, "", admin); w.Code != 200 || w.Body.String() != `{"status":"empty_response"}` {
|
||||
t.Fatal("empty response was treated as success")
|
||||
}
|
||||
mu.Lock()
|
||||
upstream = errors.New("PRIVATE_UPSTREAM_ERROR https://PRIVATE_REMOTE.invalid")
|
||||
mu.Unlock()
|
||||
if w := request(path, "", admin); w.Code != 200 || w.Body.String() != `{"status":"unavailable"}` {
|
||||
t.Fatal("raw upstream failure escaped")
|
||||
}
|
||||
mu.Lock()
|
||||
upstream = nil
|
||||
response = "OK"
|
||||
block = make(chan struct{})
|
||||
started = make(chan struct{})
|
||||
start, finish := started, block
|
||||
mu.Unlock()
|
||||
done := make(chan *httptest.ResponseRecorder, 1)
|
||||
go func() { done <- request(path, "", admin) }()
|
||||
select {
|
||||
case <-start:
|
||||
case <-time.After(time.Second):
|
||||
close(finish)
|
||||
t.Fatal("blocking probe did not start")
|
||||
}
|
||||
if w := request(path, "", admin); w.Code != 409 || w.Body.String() != `{"status":"unavailable"}` {
|
||||
t.Error("same-provider HTTP probe was not rejected")
|
||||
}
|
||||
close(finish)
|
||||
if w := <-done; w.Code != 200 {
|
||||
t.Fatal("first concurrent probe failed")
|
||||
}
|
||||
var modelEnabled, providerActive bool
|
||||
var selected string
|
||||
if err = db.QueryRow(`SELECT enabled FROM ai_provider_models WHERE id=$1`, mid).Scan(&modelEnabled); err != nil || modelEnabled {
|
||||
t.Fatal("probe enabled saved model")
|
||||
}
|
||||
if err = db.QueryRow(`SELECT is_active FROM ai_providers WHERE id=$1`, pid).Scan(&providerActive); err != nil || providerActive {
|
||||
t.Fatal("probe activated saved provider")
|
||||
}
|
||||
if err = db.QueryRow(`SELECT summary_model_id FROM users WHERE id='admin'`).Scan(&selected); err != nil || selected != sibling {
|
||||
t.Fatal("probe changed user preference")
|
||||
}
|
||||
mu.Lock()
|
||||
seen := promptSeen
|
||||
mu.Unlock()
|
||||
for _, private := range []string{"PRIVATE_", seen, "https://PRIVATE_ENDPOINT.invalid"} {
|
||||
if private != "" && strings.Contains(logs.String(), private) {
|
||||
t.Error("probe leaked prompt/response/configuration/error into logs")
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -11,6 +11,9 @@ func SetupRouter(h *handlers.Handler, jwtSecret string) *gin.Engine {
|
||||
r.Use(gin.Recovery())
|
||||
r.Use(gin.LoggerWithConfig(gin.LoggerConfig{
|
||||
SkipPaths: []string{"/api/summaries/status"},
|
||||
// Never log rejected test query parameters or arbitrary model IDs. Test
|
||||
// outcomes are bounded responses; no generation data belongs in access logs.
|
||||
Skip: func(c *gin.Context) bool { return c.FullPath() == "/api/admin/ai-models/:id/test" },
|
||||
}))
|
||||
|
||||
r.Use(func(c *gin.Context) {
|
||||
@ -65,6 +68,7 @@ func SetupRouter(h *handlers.Handler, jwtSecret string) *gin.Engine {
|
||||
|
||||
admin.GET("/ai-models", h.ListSummaryModels)
|
||||
admin.POST("/ai-models", h.CreateSummaryModel)
|
||||
admin.POST("/ai-models/:id/test", h.TestSummaryModel)
|
||||
admin.PUT("/ai-models/:id", h.UpdateSummaryModel)
|
||||
admin.DELETE("/ai-models/:id", h.DeleteSummaryModel)
|
||||
admin.GET("/ai-providers", h.ListAIProviders)
|
||||
|
||||
@ -100,3 +100,12 @@ func (r *Repository) ResolveSummaryModel(ctx context.Context, userID string, id
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// GetSummaryModelForTest resolves the exact saved entry without requiring enabled,
|
||||
// an active provider, a user preference, or a known synthesis capacity profile.
|
||||
// It is read-only and belongs solely to the authenticated admin test use case.
|
||||
func (r *Repository) GetSummaryModelForTest(ctx context.Context, id string) (ResolvedSummaryModel, error) {
|
||||
var m ResolvedSummaryModel
|
||||
err := r.db.QueryRowContext(ctx, `SELECT m.id,p.id,p.name,m.model,p.endpoint,p.api_key_encrypted FROM ai_provider_models m JOIN ai_providers p ON p.id=m.provider_id WHERE m.id=$1`, id).Scan(&m.ID, &m.ProviderID, &m.Provider, &m.Model, &m.Endpoint, &m.APIKeyEncrypted)
|
||||
return m, err
|
||||
}
|
||||
|
||||
@ -3,6 +3,7 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/tradarr/backend/internal/ai"
|
||||
"github.com/tradarr/backend/internal/api"
|
||||
@ -19,6 +20,9 @@ import (
|
||||
)
|
||||
|
||||
type Dependencies struct {
|
||||
ModelTester interface {
|
||||
Test(context.Context, string) error
|
||||
}
|
||||
SummaryDiagnostics ai.SummaryDiagnosticCollector
|
||||
CompanyCatalog companycatalog.CompanyCatalog
|
||||
LayaRanker generation.LayaRanker
|
||||
@ -52,6 +56,9 @@ func New(repo *models.Repository, cfg *config.Config, deps Dependencies) *App {
|
||||
}
|
||||
}
|
||||
h := handlers.New(repo, cfg, enc, registry, pipeline, sched)
|
||||
if deps.ModelTester != nil {
|
||||
h.SetModelTester(deps.ModelTester)
|
||||
}
|
||||
h.SetGenerationUseCase(uc)
|
||||
h.SetIndexSearcher(deps.IndexSearcher)
|
||||
if deps.CompanyCatalog != nil {
|
||||
|
||||
@ -154,3 +154,79 @@ réintroduit aucun enregistrement dans la composition de production. La fixture
|
||||
E2E utilise désormais Bloomberg comme source injectée et activée, avec transport
|
||||
local factice et sans visite des articles. Les tests dédiés couvrent le refus API,
|
||||
la préservation PostgreSQL, le dispatch manuel/planifié et la composition RSS seule.
|
||||
|
||||
## Test de génération d'un modèle sauvegardé — ticket #43
|
||||
|
||||
`POST /api/admin/ai-models/:id/test` est une action admin sans corps ni query.
|
||||
L'identifiant doit être celui d'une entrée du catalogue. Le serveur résout cette
|
||||
ligne et son fournisseur en stockage, déchiffre la clé enregistrée et appelle
|
||||
`Provider.Summarize` via la même fabrique `NewProvider` que la synthèse. Aucun
|
||||
provider, modèle, endpoint, secret, prompt ou réglage de génération fourni par le
|
||||
client n'est accepté. Le test fournisseur existant reste une découverte
|
||||
`ListModels` distincte : il ne prouve pas qu'une génération est disponible.
|
||||
|
||||
Le test utilise un prompt fixe de 14 octets, une demande de sortie maximale de
|
||||
16 tokens, sans thinking ni JSON imposé au modèle ; Ollama utilise un contexte de
|
||||
2048 tokens et reçoit explicitement `num_predict`. La réponse doit être non vide
|
||||
après `strings.TrimSpace`, sans être renvoyée ni journalisée. Un succès ne valide
|
||||
ni la qualité de la synthèse ni la capacité du modèle pour un prompt complet.
|
||||
Aucune vérification du catalogue activé, du fournisseur actif, de la préférence
|
||||
utilisateur ou du profil de capacité n'empêche ce diagnostic. Aucun de ces états
|
||||
n'est modifié et aucune génération utilisateur ou synthèse n'est créée.
|
||||
|
||||
Le délai total du cas d'usage est de 30 secondes, ou moins si le contexte appelant
|
||||
expire avant. Un seul test de génération par ID fournisseur est admis par le
|
||||
service partagé du serveur, même entre deux modèles de ce fournisseur. Les
|
||||
fournisseurs distincts restent indépendants. Il n'y a aucune relance applicative.
|
||||
Une réponse timeout n'autorise pas à doubler un appel qui ignore l'annulation :
|
||||
son verrou reste détenu jusqu'à la sortie réelle de l'adapter. Les erreurs et
|
||||
panics libèrent le verrou sans exposer leur texte. Ces verrous sont locaux au
|
||||
processus serveur, sans écriture en base.
|
||||
|
||||
Le body contient uniquement `{status: ...}` :
|
||||
|
||||
| HTTP | Statut | Sens |
|
||||
| --- | --- | --- |
|
||||
| 200 | `success` | Réponse de génération non vide après trim |
|
||||
| 200 | `empty_response` | Appel réussi, texte généré vide |
|
||||
| 200 | `auth_rejected` | Refus d'authentification upstream identifié |
|
||||
| 200 | `model_unavailable` | Modèle refusé/introuvable upstream identifié |
|
||||
| 200 | `rate_limited` | Limitation/quota upstream identifié |
|
||||
| 200 | `timeout` | Délai/context/erreur timeout structuré |
|
||||
| 200 | `unavailable` | Autre échec upstream, sans erreur brute |
|
||||
| 404 | `model_unavailable` | Entrée absente du catalogue local |
|
||||
| 409 | `unavailable` | Un test de génération occupe déjà ce fournisseur |
|
||||
| 400 | `unavailable` | ID ou paramètres de requête invalides |
|
||||
| 500 | `unavailable` | Échec local de lecture, déchiffrement ou construction |
|
||||
|
||||
L'authentification du requérant reste celle du middleware (401/403). Les refus
|
||||
upstream utilisent HTTP 200 afin de ne pas déclencher l'expiration de session du
|
||||
client global. Le frontend peut distinguer le conflit fournisseur par HTTP 409
|
||||
sans ajouter un huitième statut au protocole.
|
||||
|
||||
La classification lit les codes HTTP/SDK et les identifiants structurés reconnus,
|
||||
jamais le message d'erreur ou une recherche textuelle. Les adapters HTTP maison
|
||||
bornent le JSON de génération à 2 Mio et le JSON de rejet à 64 Kio ; seuls le
|
||||
statut et des codes allowlistés sont conservés dans l'erreur. Le chemin du nouveau
|
||||
test est exclu du logger d'accès Gin pour ne pas journaliser une query rejetée.
|
||||
Aucun prompt, corps, clé, endpoint ni erreur brute n'est ajouté aux logs.
|
||||
|
||||
Pour Claude Code, le contexte interne de test sélectionne `--output-format json`
|
||||
et exige une enveloppe `type=result`, `subtype=success`, `is_error=false` avant de
|
||||
contrôler `result`. Une erreur CLI non structurée reste générique : stderr n'est
|
||||
jamais analysé pour deviner un refus d'auth ou une limite de débit. Stdout est
|
||||
capturé et borné, stderr jeté ; un dépassement ne devient pas une réponse tronquée
|
||||
réussie. Le sous-processus reçoit `CLAUDE_CODE_MAX_OUTPUT_TOKENS=16`,
|
||||
`CLAUDE_CODE_MAX_RETRIES=0`, le watchdog de retry désactivé et
|
||||
`MAX_THINKING_TOKENS=0`, sans changer l'environnement global. Ces réglages sont
|
||||
référencés dans la [documentation officielle Claude Code](https://code.claude.com/docs/en/env-vars).
|
||||
Le contexte de test ne provient jamais d'un paramètre HTTP. Les tests exécutent un
|
||||
binaire local factice, pas un modèle ou CLI authentifié réel.
|
||||
|
||||
Les ports dépôt/déchiffrement/fabrique et les transports fakes couvrent les
|
||||
configurations sauvegardées, les refus structurés, les erreurs locales, les
|
||||
verrous, le timeout et la confidentialité. Le serveur E2E injecte également un
|
||||
fournisseur loopback factice pour cette action, empêchant tout test navigateur
|
||||
de contacter un modèle réel. Aucune migration n'est nécessaire pour #43.
|
||||
|
||||
Le test ponctuel Claude Code passe aussi `--no-session-persistence` afin de ne pas conserver de session locale ([référence CLI](https://code.claude.com/docs/en/cli-reference)).
|
||||
|
||||
@ -410,3 +410,25 @@ Les flux RSS et leurs réglages ne sont pas modifiés. La section « Sources
|
||||
retirées » est en lecture seule ; aucune récupération ou nouvelle synthèse n'est
|
||||
lancée depuis cette section. Les outils historiques ne sont pas enregistrés dans
|
||||
la composition applicative.
|
||||
|
||||
### Tester réellement un modèle du catalogue (#43)
|
||||
|
||||
Dans Admin > Fournisseurs IA, le test d'une ligne du catalogue utilise le modèle
|
||||
et les credentials sauvegardés et effectue une courte génération. Il peut
|
||||
consommer des tokens facturés ou charger un modèle Ollama. La réponse produite
|
||||
n'est jamais affichée. Le test est disponible pour une ligne désactivée et ne
|
||||
l'active pas. Le test « fournisseur » existant ne fait que la découverte des
|
||||
modèles et reste distinct.
|
||||
|
||||
L'action API est `POST /api/admin/ai-models/:id/test`, sans corps ni query, admin
|
||||
uniquement. Les outcomes upstream sont des statuts bornés en HTTP 200 ; le verrou
|
||||
par fournisseur donne HTTP 409 et une entrée inexistante HTTP 404. Le détail du
|
||||
contrat est documenté dans `docs/architecture.md`. Un seul test de génération par
|
||||
fournisseur est admis, sans retry, pendant 30 secondes maximum côté requête.
|
||||
Les états du catalogue, fournisseurs et préférences utilisateur restent intacts.
|
||||
|
||||
Aucun modèle réel n'a été appelé pour vérifier ce lot : les tests utilisent des
|
||||
providers/transports mockés, PostgreSQL jetable et un CLI local factice. Les
|
||||
variables de limites/retry Claude Code sont passées uniquement à son
|
||||
sous-processus de test ; aucun fichier utilisateur d'auth/configuration n'est lu,
|
||||
modifié ou créé par ces tests.
|
||||
|
||||
@ -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