package api_test import ( "bytes" "context" "encoding/json" "errors" "github.com/gin-gonic/gin" "github.com/tradarr/backend/internal/ai" "github.com/tradarr/backend/internal/api" "github.com/tradarr/backend/internal/api/handlers" "github.com/tradarr/backend/internal/config" "github.com/tradarr/backend/internal/models" "github.com/tradarr/backend/internal/summaryqa" "os" "reflect" "strings" "testing" ) func TestTicket60UnsupportedWebSearchIsExplicitAndReplayablePostgres(t *testing.T) { f := qa53Setup(t) path := "/api/summaries/" + qa53Summary + "/conversation/messages" body := `{"request_id":"` + qa53Request + `","passage":"passage","question":"question","use_web_search":true}` for i := 0; i < 2; i++ { w := f.call(t, "POST", ticket14UserA, path, body, 422) if !strings.Contains(w.Body.String(), "web_search_unsupported") { t.Fatal("missing explicit capability error", w.Body) } } if len(f.provider.prompts) != 0 { t.Fatal("unsupported request fell back to regular provider") } } func TestTicket60OmittedWebSearchKeepsNormalAdapterAndEmptyCitationsPostgres(t *testing.T) { f := qa53Setup(t) path := "/api/summaries/" + qa53Summary + "/conversation/messages" body := `{"request_id":"` + qa53Request + `","passage":"passage","question":"question"}` for i := 0; i < 2; i++ { w := f.call(t, "POST", ticket14UserA, path, body, 200) for _, field := range []string{`"use_web_search":false`, `"web_search_performed":false`, `"citations":[]`} { if !strings.Contains(w.Body.String(), field) { t.Fatalf("missing backward-compatible search state %s", field) } } } if len(f.provider.prompts) != 1 { t.Fatal("retry called provider again") } // Reusing the same id with a changed intent is a conflicting payload. f.call(t, "POST", ticket14UserA, path, strings.TrimSuffix(body, "}")+`,"use_web_search":true}`, 409) } type web60Provider struct { requests []summaryqa.StatelessRequest result summaryqa.AnswerResult err error } func (*web60Provider) Capabilities() summaryqa.Capabilities { return summaryqa.Capabilities{WebSearch: true} } func (p *web60Provider) Answer(_ context.Context, r summaryqa.StatelessRequest) (summaryqa.AnswerResult, error) { p.requests = append(p.requests, r) return p.result, p.err } func web60Bind(t *testing.T, f *qa53Fixture, p *web60Provider) { t.Helper() if _, err := f.db.Exec(`UPDATE ai_provider_models SET model='gpt-6.1-terra'`); err != nil { t.Fatal(err) } f.service.Resolver = ai.QAResolver{Repo: f.repo, Factory: func(models.ResolvedSummaryModel) (ai.Provider, error) { return f.provider, nil }, WebSearchFactory: func(m models.ResolvedSummaryModel) (summaryqa.Provider, error) { if m.Model != "gpt-6.1-terra" || m.Provider != "openai" { t.Fatal("wrong model selected") } return p, nil }} } func web60Turn(t *testing.T, raw []byte) summaryqa.Turn { t.Helper() var envelope struct { Data summaryqa.Turn `json:"data"` } if err := json.Unmarshal(raw, &envelope); err != nil { t.Fatal(err) } return envelope.Data } func TestTicket60WebSearchPersistenceReplayPrivacyAndOwnershipPostgres(t *testing.T) { f := qa53Setup(t) p := &web60Provider{result: summaryqa.AnswerResult{Answer: "web answer", WebSearchPerformed: true, Citations: []summaryqa.Citation{{Title: " useful title ", URL: "https://EXAMPLE.COM:443/report#section"}, {Title: "duplicate", URL: "https://example.com/report"}, {Title: "bad", URL: "javascript:alert(1)"}}}} web60Bind(t, f, p) path := qa53Path() // A previous normal exchange exists, but must never be passed to web search. f.call(t, "POST", ticket14UserA, path+"/messages", qa53Body("00000000-0000-0000-0000-000000006001", "OLD_HISTORY"), 200) p.result.Answer = "web answer" body := `{"request_id":"` + qa53Request + `","passage":"CURRENT_PASSAGE","question":"CURRENT_QUESTION","use_web_search":true}` // Access logging must not contain queries, passages, answers or cited URLs. var logs bytes.Buffer old := gin.DefaultWriter gin.DefaultWriter = &logs defer func() { gin.DefaultWriter = old }() h := handlers.New(f.repo, &config.Config{JWTSecret: "qa53"}, nil, nil, nil, nil) h.SetQAUseCase(f.service) f.router = api.SetupRouter(h, "qa53") w := f.call(t, "POST", ticket14UserA, path+"/messages?secret=PRIVATE_QUERY", body, 200) first := web60Turn(t, w.Body.Bytes()) if !first.UseWebSearch || !first.WebSearchPerformed || first.Replayed || len(first.Citations) != 1 || first.Citations[0] != (summaryqa.Citation{Title: "useful title", URL: "https://example.com/report"}) { t.Fatalf("wrong structured answer: %+v", first) } if len(p.requests) != 1 || p.requests[0].Summary != "" || len(p.requests[0].History) != 0 || !p.requests[0].UseWebSearch || p.requests[0].Passage != "CURRENT_PASSAGE" || p.requests[0].Language != "fr" { t.Fatal("non-minimal web request", p.requests) } // Replay must remain available even after the selected model is disabled. if _, err := f.db.Exec(`UPDATE ai_provider_models SET enabled=false`); err != nil { t.Fatal(err) } replay := web60Turn(t, f.call(t, "POST", ticket14UserA, path+"/messages", body, 200).Body.Bytes()) if !replay.Replayed || replay.ID != first.ID || !reflect.DeepEqual(first.Citations, replay.Citations) || len(p.requests) != 1 || len(f.provider.prompts) != 1 { t.Fatal("retry regenerated result", replay) } get := f.call(t, "GET", ticket14UserA, path, "", 200) var envelope struct { Data summaryqa.Conversation `json:"data"` } if json.Unmarshal(get.Body.Bytes(), &envelope) != nil || len(envelope.Data.Messages) != 2 || !reflect.DeepEqual(envelope.Data.Messages[1].Citations, first.Citations) { t.Fatal("citations lost on reload") } f.call(t, "POST", ticket14UserA, path+"/messages", strings.Replace(body, `"use_web_search":true`, `"use_web_search":false`, 1), 409) f.call(t, "GET", ticket14UserB, path, "", 404) f.call(t, "POST", ticket14UserB, path+"/messages", body, 404) for _, secret := range []string{"PRIVATE_QUERY", "CURRENT_PASSAGE", "CURRENT_QUESTION", "example.com", "web answer", "PRIVATE_SOURCE"} { if strings.Contains(logs.String(), secret) { t.Fatal("sensitive access log", secret) } } var calls int if err := f.db.QueryRow(`SELECT count(*) FROM summary_qa_provider_calls`).Scan(&calls); err != nil || calls != 2 { t.Fatal("replay counted as provider admission", calls, err) } } func TestTicket60AutoSearchIntentAndFailedReplayPostgres(t *testing.T) { for _, failed := range []bool{false, true} { t.Run(map[bool]string{false: "not-needed", true: "provider-failed"}[failed], func(t *testing.T) { f := qa53Setup(t) p := &web60Provider{result: summaryqa.AnswerResult{Answer: "local answer", Citations: []summaryqa.Citation{{Title: "not used", URL: "https://unused.invalid/"}}}} if failed { p.err = errors.New("PRIVATE_PROVIDER_ERROR") } web60Bind(t, f, p) status := 200 if failed { status = 502 } body := `{"request_id":"` + qa53Request + `","passage":"p","question":"q","use_web_search":true}` for i := 0; i < 2; i++ { f.call(t, "POST", ticket14UserA, qa53Path()+"/messages", body, status) } if len(p.requests) != 1 || len(f.provider.prompts) != 0 { t.Fatal("provider retried or silent fallback") } var intent, performed bool var citations string if err := f.db.QueryRow(`SELECT use_web_search,web_search_performed,citations::text FROM summary_qa_turns`).Scan(&intent, &performed, &citations); err != nil || !intent || performed || citations != "[]" { t.Fatal("incorrect persisted search state", intent, performed, citations, err) } }) } } func TestTicket60ConversationAdvertisesExactModelCapabilityPostgres(t *testing.T) { f := qa53Setup(t) for _, tc := range []struct { provider, model string want bool }{ {"openai", "gpt-6.1-terra", true}, {"openai", "gpt-6.2-sol", true}, {"openai", "gpt-6.2-astra", true}, {"openai", "gpt-6-luna", true}, {"openai", "gpt-4o-mini", false}, {"openai", "gpt-6.1-terra-latest", false}, {"ollama", "gpt-6.1-terra", false}, } { if _, err := f.db.Exec(`UPDATE ai_providers SET name=$1`, tc.provider); err != nil { t.Fatal(err) } if _, err := f.db.Exec(`UPDATE ai_provider_models SET model=$1`, tc.model); err != nil { t.Fatal(err) } w := f.call(t, "GET", ticket14UserA, qa53Path(), "", 200) var envelope struct { Data summaryqa.Conversation `json:"data"` } if json.Unmarshal(w.Body.Bytes(), &envelope) != nil || envelope.Data.WebSearchSupported != tc.want || envelope.Data.ProviderSessionSupported { t.Fatalf("wrong capability for %+v: %s", tc, w.Body) } } if len(f.provider.prompts) != 0 { t.Fatal("capability discovery called provider") } } func TestTicket60MigrationBackfillsHistoricalTurnsWithoutChangingContentPostgres(t *testing.T) { f := qa53Setup(t) f.call(t, "POST", ticket14UserA, qa53Path()+"/messages", qa53Body(qa53Request, "legacy question"), 200) for _, direction := range []string{"down", "up"} { raw, err := os.ReadFile("../database/migrations/000026_qa_web_search." + direction + ".sql") if err != nil { t.Fatal(err) } if _, err = f.db.Exec(string(raw)); err != nil { t.Fatal(err) } } var intent, performed bool var citations, answer string if err := f.db.QueryRow(`SELECT use_web_search,web_search_performed,citations::text,answer FROM summary_qa_turns`).Scan(&intent, &performed, &citations, &answer); err != nil || intent || performed || citations != "[]" || answer != "A safe answer" { t.Fatal("historical content changed", intent, performed, citations, answer, err) } for _, bad := range []string{`UPDATE summary_qa_turns SET citations='{}'`, `UPDATE summary_qa_turns SET citations='null'`, `UPDATE summary_qa_turns SET web_search_performed=true`, `UPDATE summary_qa_turns SET citations='[{"title":"unperformed","url":"https://example.com/"}]'`} { if _, err := f.db.Exec(bad); err == nil { t.Fatal("invalid storage state accepted") } } }