package ai import ( "context" "encoding/json" "errors" "io" "net/http" "strings" "testing" "github.com/tradarr/backend/internal/summaryqa" ) const web60Message = `{"type":"message","status":"completed","role":"assistant","content":[{"type":"output_text","text":"Answer with https://text-only.invalid/ ignored as metadata.","annotations":[{"type":"url_citation","url":"https://EXAMPLE.COM:443/report#part","title":" Source title "},{"type":"url_citation","url":"https://example.com/report","title":"duplicate"},{"type":"url_citation","url":"http://unsafe.invalid","title":"unsafe"},{"type":"file_citation","url":"https://file.invalid","title":"file"}]}]}` const web60Call = `{"type":"web_search_call","status":"completed","action":{"type":"search","query":"PRIVATE_QUERY"}}` func web60Response(body string, status int) *http.Response { return &http.Response{StatusCode: status, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(body))} } func TestTicket63ResponsesWebSearchIsFullContextStatelessBoundedAndStructured(t *testing.T) { calls := 0 p := newOpenAIWebQA("fixture-key", "gpt-6.1-terra") p.client = &http.Client{Transport: ticket31Transport(func(r *http.Request) (*http.Response, error) { calls++ if r.Method != "POST" || r.URL.String() != "https://api.openai.com/v1/responses" || r.Header.Get("Authorization") != "Bearer fixture-key" { t.Fatal("wrong endpoint or credentials") } var body map[string]json.RawMessage if err := json.NewDecoder(r.Body).Decode(&body); err != nil { t.Fatal(err) } for key, want := range map[string]string{"model": `"gpt-6.1-terra"`, "store": "false", "tool_choice": `"auto"`, "max_tool_calls": "2", "max_output_tokens": "4096"} { if string(body[key]) != want { t.Fatalf("%s=%s want %s", key, body[key], want) } } for _, key := range []string{"conversation", "previous_response_id", "include", "metadata", "prompt_cache_key"} { if _, ok := body[key]; ok { t.Fatal("unexpected state or expanded search context", key) } } var tools []struct { Type string Size string `json:"search_context_size"` } if json.Unmarshal(body["tools"], &tools) != nil || len(tools) != 1 || tools[0].Type != "web_search" || tools[0].Size != "low" { t.Fatal("unbounded tools", string(body["tools"])) } text := string(body["input"]) for _, expected := range []string{"FULL_SYNTHESIS", "OLD_HISTORY", "CURRENT_PASSAGE", "CURRENT_QUESTION", "fr"} { if !strings.Contains(text, expected) { t.Fatal("missing full context", expected) } } for _, private := range []string{"PRIVATE_ARTICLE", "previous_response_id", "citations", "request_id"} { if strings.Contains(text, private) { t.Fatal("private context leaked", private) } } return web60Response(`{"status":"completed","output":[`+web60Call+`,`+web60Message+`]}`, 200), nil })} req := summaryqa.StatelessRequest{UseWebSearch: true, Summary: "FULL_SYNTHESIS", History: []summaryqa.Exchange{{Answer: "OLD_HISTORY"}}, Passage: "CURRENT_PASSAGE", Question: "CURRENT_QUESTION", Language: "fr"} result, err := p.Answer(context.Background(), req) if err != nil || calls != 1 || !result.WebSearchPerformed || len(result.Citations) != 1 || result.Citations[0] != (summaryqa.Citation{Title: "Source title", URL: "https://example.com/report"}) { t.Fatalf("result=%+v err=%v calls=%d", result, err, calls) } } func TestTicket60ResponsesAutoCanAnswerWithoutSearch(t *testing.T) { p := newOpenAIWebQA("fixture", "gpt-6.2-sol") p.client = &http.Client{Transport: ticket31Transport(func(*http.Request) (*http.Response, error) { return web60Response(`{"status":"completed","output":[`+web60Message+`]}`, 200), nil })} got, err := p.Answer(context.Background(), summaryqa.StatelessRequest{UseWebSearch: true, Passage: "p", Question: "q", Language: "en"}) if err != nil || got.WebSearchPerformed || len(got.Citations) != 0 || got.Citations == nil || got.Answer == "" { t.Fatalf("auto search fabricated: %+v %v", got, err) } } func TestTicket60ResponsesFailuresAreBoundedSanitizedAndNeverRetried(t *testing.T) { for name, body := range map[string]string{ "incomplete": `{"status":"incomplete","output":[` + web60Message + `]}`, "error": `{"status":"completed","error":{"message":"PRIVATE_ERROR"},"output":[` + web60Message + `]}`, "no-answer": `{"status":"completed","output":[` + web60Call + `]}`, "tool-failed": `{"status":"completed","output":[{"type":"web_search_call","status":"failed"},` + web60Message + `]}`, "tool-overflow": `{"status":"completed","output":[` + web60Call + `,` + web60Call + `,` + web60Call + `,` + web60Message + `]}`, "refusal": `{"status":"completed","output":[{"type":"message","role":"assistant","status":"completed","content":[{"type":"refusal","refusal":"PRIVATE_REFUSAL"}]}]}`, "invalid": "PRIVATE_INVALID_JSON", "trailing": `{"status":"completed","output":[` + web60Message + `]} {}`, "oversized": strings.Repeat("x", maxWebResponseBytes+1), "answer-overflow": `{"status":"completed","output":[{"type":"message","status":"completed","role":"assistant","content":[{"type":"output_text","text":"` + strings.Repeat("x", summaryqa.MaxAnswerRunes+1) + `"}]}]}`, } { t.Run(name, func(t *testing.T) { p := newOpenAIWebQA("fixture", "gpt-6-luna") calls := 0 p.client = &http.Client{Transport: ticket31Transport(func(*http.Request) (*http.Response, error) { calls++; return web60Response(body, 200), nil })} _, err := p.Answer(context.Background(), summaryqa.StatelessRequest{UseWebSearch: true, Passage: "p", Question: "q", Language: "fr"}) if !errors.Is(err, summaryqa.ErrProvider) || strings.Contains(err.Error(), "PRIVATE") || calls != 1 { t.Fatalf("unsafe error/retry: %v calls=%d", err, calls) } }) } for _, status := range []int{401, 429, 500} { p := newOpenAIWebQA("fixture", "gpt-6.2-astra") calls := 0 p.client = &http.Client{Transport: ticket31Transport(func(*http.Request) (*http.Response, error) { calls++ return web60Response("PRIVATE_HTTP_ERROR", status), nil })} if _, err := p.Answer(context.Background(), summaryqa.StatelessRequest{UseWebSearch: true, Passage: "p", Question: "q"}); !errors.Is(err, summaryqa.ErrProvider) || calls != 1 { t.Fatal("unsafe HTTP failure", err, calls) } } } func TestTicket60WebAdapterRejectsUnsupportedAndOversizedBeforeHTTP(t *testing.T) { for _, tc := range []struct { model, passage string requested bool want error }{ {"gpt-4o-mini", "p", true, summaryqa.ErrWebSearchUnsupported}, {"gpt-6.1-terra", "p", false, summaryqa.ErrWebSearchUnsupported}, {"gpt-6.1-terra", strings.Repeat("p", summaryqa.MaxPassageRunes+1), true, summaryqa.ErrLimit}, } { p := newOpenAIWebQA("fixture", tc.model) p.client = &http.Client{Transport: ticket31Transport(func(*http.Request) (*http.Response, error) { t.Fatal("invalid request reached HTTP"); return nil, nil })} _, err := p.Answer(context.Background(), summaryqa.StatelessRequest{UseWebSearch: tc.requested, Passage: tc.passage, Question: "q"}) if !errors.Is(err, tc.want) { t.Fatalf("got %v want %v", err, tc.want) } } }