From b56bfb5a946e1e4b96f6ec7ecb469ff81e303bb7 Mon Sep 17 00:00:00 2001 From: yetone Date: Tue, 6 Oct 2026 18:26:22 +0800 Subject: [PATCH] =?UTF-8?q?gateway:=20an=20upstream=20that=20answers=20200?= =?UTF-8?q?=20with=20a=20web=20page,=20with=20nothing=20at=20all,=20or=20w?= =?UTF-8?q?ith=20JSON=20that=20isn't,=20has=20failed=20as=20a=20502=20does?= =?UTF-8?q?,=20so=20a=20group=20asks=20its=20next=20member=20(#1012,=20cth?= =?UTF-8?q?123456:=20Codex=20on=20group/medium,=20agentrouter/deepseek-v4-?= =?UTF-8?q?flash=20now=20and=20then=20answered=20200=20text/html;=20the=20?= =?UTF-8?q?log=20said=20status=3D200=20done=3Dtrue=20in=3D0=20out=3D0=20se?= =?UTF-8?q?rved=3Dnull,=20codex/gpt-6-luna=20was=20never=20asked,=20and=20?= =?UTF-8?q?Codex=20failed=20with=20"stream=20disconnected=20before=20compl?= =?UTF-8?q?etion:=20stream=20closed=20before=20response.completed")=20?= =?UTF-8?q?=E2=80=94=20the=20candidate=20loop=20judged=20a=20try=20by=20it?= =?UTF-8?q?s=20status=20alone,=20and=20holdWriter=20passes=20a=20200=20tha?= =?UTF-8?q?t=20is=20neither=20text/event-stream=20nor=20application/json?= =?UTF-8?q?=20straight=20to=20the=20agent,=20so=20the=20page=20went=20to?= =?UTF-8?q?=20Codex=20as=20the=20reply.=20notAnAPIReply=20now=20reads=20ev?= =?UTF-8?q?ery=202xx=20(but=20204)=20an=20upstream=20gives,=20in=20forward?= =?UTF-8?q?Once=20(every=20relayed=20and=20translated=20request,=20every?= =?UTF-8?q?=20API,=20plugins=20included)=20and=20in=20the=20built-in=20cli?= =?UTF-8?q?ents'=20own=20requests=20(the=20ChatGPT=20backend's=20/response?= =?UTF-8?q?s,=20Kiro,=20Zed,=20Qoder,=20Devin,=20Cursor,=20Command=20Code)?= =?UTF-8?q?:=20a=20text/html=20reply,=20a=20body=20that=20begins=20as=20a?= =?UTF-8?q?=20web=20page=20whatever=20its=20Content-Type,=20an=20empty=20b?= =?UTF-8?q?ody,=20or=20one=20sent=20as=20JSON=20that=20doesn't=20begin=20w?= =?UTF-8?q?ith=20{=20or=20[=20is=20turned=20into=20the=20502=20it=20stands?= =?UTF-8?q?=20for,=20with=20a=20JSON=20error=20saying=20what=20came=20back?= =?UTF-8?q?=20("answered=20200=20OK=20with=20a=20web=20page=20(text/html),?= =?UTF-8?q?=20not=20an=20API=20reply:=20=E2=80=9CJust=20a=20moment...?= =?UTF-8?q?=E2=80=9D",=20the=20firewall=20hint=20for=20a=20block=20page).?= =?UTF-8?q?=20It=20then=20fails=20over,=20rests=20a=20minute=20and=20is=20?= =?UTF-8?q?logged=20as=20any=20502=20before=20the=20reply=20begins=20does;?= =?UTF-8?q?=20a=20provider=20with=20nobody=20after=20it=20hands=20the=20ag?= =?UTF-8?q?ent=20that=20502=20rather=20than=20the=20page.=20Only=20the=20f?= =?UTF-8?q?irst=20bytes=20are=20peeked,=20which=20a=20stream=20waits=20for?= =?UTF-8?q?=20anyway;=20a=20read=20that=20fails=20is=20left=20to=20the=20r?= =?UTF-8?q?eader,=20a=20compressed=20body=20and=20anything=20else=20as=20i?= =?UTF-8?q?t=20came.=20TestNotAnAPIReplyFailsOver=20(Chat,=20Responses=20a?= =?UTF-8?q?nd=20Messages,=20streamed=20and=20not,=20a=20member=20answering?= =?UTF-8?q?=20a=20Cloudflare=20page=20as=20text/html,=20as=20JSON=20and=20?= =?UTF-8?q?as=20SSE,=20an=20empty=20body=20as=20JSON=20and=20as=20SSE,=20a?= =?UTF-8?q?nd=20plain=20text=20as=20JSON;=20the=20next=20member=20must=20a?= =?UTF-8?q?nswer=20and=20the=20log=20name=20why)=20fails=20without=20the?= =?UTF-8?q?=20change=20in=20all=2036=20cases=20(the=20page=20relayed=20to?= =?UTF-8?q?=20the=20agent,=20or=20b=20never=20asked,=20or=20no=20reason=20?= =?UTF-8?q?logged)=20and=20passes;=20TestNotAnAPIReplyAlone=20(a=20502=20w?= =?UTF-8?q?ith=20the=20reason,=20logged=20502)=20and=20TestCodexBackendWeb?= =?UTF-8?q?Page=20(the=20ChatGPT=20backend's=20page=20reached=20Codex=20as?= =?UTF-8?q?=20a=20200)=20fail=20without=20it=20and=20pass;=20TestAPIReplyU?= =?UTF-8?q?ntouched=20keeps=20JSON=20after=20whitespace,=20SSE=20with=20an?= =?UTF-8?q?d=20without=20a=20Content-Type,=20gzip,=20XML,=20a=20204=20and?= =?UTF-8?q?=20a=20404=20as=20they=20came.=20-race=20-count=3D10=20on=20the?= =?UTF-8?q?m;=20go=20test=20-tags=20nogui=20./internal/gateway=20./interna?= =?UTF-8?q?l/provider,=20go=20vet=20(darwin,=20windows),=20gofmt=20-l,=20l?= =?UTF-8?q?inux=20and=20windows=20(nogui)=20builds=20pass.=20Not=20tried?= =?UTF-8?q?=20with=20the=20reporter's=20relay=20(agentrouter)=20itself;=20?= =?UTF-8?q?the=20page=20is=20a=20Cloudflare=20challenge's,=20as=20the=20is?= =?UTF-8?q?sue=20has=20only=20its=20Content-Type.=20docs/subsystems/gatewa?= =?UTF-8?q?y-routing.md=20says=20it.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/subsystems/gateway-routing.md | 3 +- internal/gateway/codex_backend.go | 5 + internal/gateway/commandcode.go | 1 + internal/gateway/cursor.go | 1 + internal/gateway/devin.go | 1 + internal/gateway/gateway.go | 5 +- internal/gateway/kiro.go | 6 +- internal/gateway/notapi.go | 115 +++++++++++++++++ internal/gateway/notapi_test.go | 197 +++++++++++++++++++++++++++++ internal/gateway/qoder.go | 1 + internal/gateway/zed.go | 1 + 11 files changed, 332 insertions(+), 4 deletions(-) create mode 100644 internal/gateway/notapi.go create mode 100644 internal/gateway/notapi_test.go diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index c8115c685..d9e5804f6 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -40,6 +40,7 @@ served by a plugin are in [Provider and plugin ownership](provider-plugins.md). ## Constraints and failure behavior - A fallback happens only while none of the reply has been sent. An agent never gets half a reply from one upstream and the rest from another. +- A 2xx that can't be an API's answer is the 502 it stands for (`notAnAPIReply`, #1012): a web page (`text/html`, or a body that begins as one: a sign-in page, Cloudflare's challenge), a body with nothing in it, or one sent as JSON that doesn't begin as JSON. Every upstream request goes through it (`forwardOnce`, and the built-in clients' own: the ChatGPT backend's `/responses`, Kiro, Zed, Qoder, Devin, Cursor, Command Code), so it fails over, rests and is logged as a 502 does, its reason naming the page's title. Only the first bytes are peeked, which a stream waits for anyway, and a compressed body is left as it came. - A streamed request is never left silent while its vendor says nothing. `holdWriter.watch` runs beside each try: past `keepHeldAfter` (15s) it sends a held try's agent the stream's 200 and SSE comments (`keepAlive`), none of the try, so another candidate may still answer in the same stream; once the reply passes, it puts a comment between two of its lines after `keepaliveEvery` of quiet. It stops after `keepaliveLongest` (5 minutes) with nothing from the vendor. A proxy in front such as Cloudflare (125s) otherwise ends the request (#947). Gemini streams get no comments (#934). - A resting candidate is tried last, never dropped (`restLast`). A lone candidate is tried even while it rests, because there is no other. - Routing decides who goes first only when nobody has answered the conversation yet. Affinity keeps the answerer while its cache is worth it. Auto mode keeps it across turns while at least `cacheWorth` (1024) tokens were read from the cache and the cache isn't cold (`cacheCold`, 5 minutes). @@ -54,7 +55,7 @@ served by a plugin are in [Provider and plugin ownership](provider-plugins.md). ## Verification ```sh -go test -tags nogui ./internal/gateway -run 'TestQuiet|TestSilentHeld|TestRotateSpreadsSessions|TestRouting|TestSmartRouting|TestFallback|TestNoFallbackForOtherErrors|TestLastFallbackErrorReachesTheAgent|TestRateLimitedSinksToTheBack|TestGroupRateLimitedSinks|TestAffinity|TestSeveralKeysOnTakeOverFromEachOther|TestSubscriptionAccountsTakeOver|TestGroup|TestTrace|TestImageTool|TestCodexNoCredits|TestClaudeGoesOnMessagesWhereTheRelayHasThem|TestAutoRelaysOnTheClientsOwnAPI|TestSearchOfferedStaysOnTheClientsAPI|TestCodexSearchAnsweredOnResponses|TestAgentEffortOnCursorLocal|TestAzureCompactionWithoutMagpiesReasoning|TestCodexCompact' +go test -tags nogui ./internal/gateway -run 'TestQuiet|TestSilentHeld|TestRotateSpreadsSessions|TestRouting|TestSmartRouting|TestFallback|TestNoFallbackForOtherErrors|TestLastFallbackErrorReachesTheAgent|TestRateLimitedSinksToTheBack|TestGroupRateLimitedSinks|TestAffinity|TestSeveralKeysOnTakeOverFromEachOther|TestSubscriptionAccountsTakeOver|TestGroup|TestTrace|TestImageTool|TestCodexNoCredits|TestClaudeGoesOnMessagesWhereTheRelayHasThem|TestAutoRelaysOnTheClientsOwnAPI|TestSearchOfferedStaysOnTheClientsAPI|TestCodexSearchAnsweredOnResponses|TestAgentEffortOnCursorLocal|TestAzureCompactionWithoutMagpiesReasoning|TestCodexCompact|TestNotAnAPIReply|TestAPIReplyUntouched|TestCodexBackendWebPage' go test -tags nogui ./internal/provider -run 'TestGroup|TestCodexCreditsSwitch|TestRenewedAccountForgetsItsAllowance|TestNative' ``` diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index ceedffdda..e3fae4f7d 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -470,6 +470,11 @@ func (s *Server) codexUpstream(w http.ResponseWriter, r *http.Request, rest stri } body = b } + if rest == "/responses" { + // a web page or nothing at all, served 200, is the 502 it stands + // for (#1012) + res = notAnAPIReply(res, "OpenAI: ") + } defer res.Body.Close() if base == codexAPIBase && res.StatusCode == http.StatusUnauthorized { // Codex signed in with an API key OpenAI refuses — often one a diff --git a/internal/gateway/commandcode.go b/internal/gateway/commandcode.go index 563c2948e..02853d1dd 100644 --- a/internal/gateway/commandcode.go +++ b/internal/gateway/commandcode.go @@ -284,6 +284,7 @@ func (s *Server) askCommandCode(api, key, model string) round { if err != nil { return nil, 502, "Command Code: " + err.Error() } + res = notAnAPIReply(res, "") // a web page served 200 (#1012) if res.StatusCode/100 != 2 { b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20)) res.Body.Close() diff --git a/internal/gateway/cursor.go b/internal/gateway/cursor.go index 22ac9526f..f0c5dc059 100644 --- a/internal/gateway/cursor.go +++ b/internal/gateway/cursor.go @@ -311,6 +311,7 @@ func (s *Server) cursorRun(ctx context.Context, req *Request, model, id, tok, ba pw.Close() return nil, 502, "Cursor: " + err.Error() } + res = notAnAPIReply(res, "") // a web page served 200 (#1012) if res.StatusCode/100 != 2 { b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20)) res.Body.Close() diff --git a/internal/gateway/devin.go b/internal/gateway/devin.go index cb6b98149..e1844f533 100644 --- a/internal/gateway/devin.go +++ b/internal/gateway/devin.go @@ -86,6 +86,7 @@ func (s *Server) askDevin(home, model string) round { if err != nil { return nil, 502, "Devin: " + err.Error() } + res = notAnAPIReply(res, "") // a web page served 200 (#1012) if res.StatusCode/100 != 2 { b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20)) res.Body.Close() diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index fda391bdf..c2e3bd68b 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -2692,8 +2692,9 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provid if err != nil { return res, err } - // Cline's whole replies come in {success, data} - return clineUnwrapped(p, res), nil + // Cline's whole replies come in {success, data}; a web page or + // nothing at all, served 200, is the 502 it stands for (#1012) + return notAnAPIReply(clineUnwrapped(p, res), ""), nil } // fromClaudeCode is a request Claude Code sent, by the User-Agent it gives diff --git a/internal/gateway/kiro.go b/internal/gateway/kiro.go index e12022124..1b31c3bf9 100644 --- a/internal/gateway/kiro.go +++ b/internal/gateway/kiro.go @@ -122,7 +122,11 @@ func (s *Server) sendKiro(ctx context.Context, auth provider.KiroAuth, body []by } { req.Header.Set(k, v) } - return s.client.Do(req) + res, err := s.client.Do(req) + if err != nil { + return res, err + } + return notAnAPIReply(res, ""), nil // a web page served 200 (#1012) } // kiroFailure is the status and message for an error Kiro answered with: diff --git a/internal/gateway/notapi.go b/internal/gateway/notapi.go new file mode 100644 index 000000000..c4f4f6a99 --- /dev/null +++ b/internal/gateway/notapi.go @@ -0,0 +1,115 @@ +package gateway + +import ( + "bufio" + "bytes" + "encoding/json" + "html" + "io" + "net/http" + "regexp" + "strings" + + "github.com/yetone/magpie/internal/provider" +) + +// notAnAPIReply turns a 2xx reply that can't be a model API's answer into +// the 502 it stands for: a web page (a sign-in page, Cloudflare's +// challenge, a relay's own error page, served 200 text/html), a body that +// is empty, or one sent as JSON that doesn't begin as JSON. Each was taken +// for an answer: relayed to the agent as it came, logged as served with +// nothing in or out, the group's next member never asked — Codex was +// handed a text/html page from a relay and failed with "stream closed +// before response.completed" (#1012). Read as a 502, it is a failure like +// any other before the reply begins: the next key, account or member is +// asked, the try rests as a 502 does, and the log says why. Only the +// reply's first bytes are looked at, which a stream waits for anyway; a +// read that fails is left to the reader, as it was. name prefixes the +// reason, for a caller that doesn't put the provider's name before it. +func notAnAPIReply(res *http.Response, name string) *http.Response { + if res == nil || res.StatusCode < 200 || res.StatusCode >= 300 || res.StatusCode == http.StatusNoContent || res.Body == nil { + return res + } + ct := strings.ToLower(res.Header.Get("Content-Type")) + if strings.HasPrefix(ct, "text/html") { + return asBadGateway(res, name, webPage(res, ct)) + } + br := bufio.NewReaderSize(res.Body, 4<<10) + res.Body = readCloser{br, res.Body} + if _, err := br.Peek(1); err == io.EOF { + return asBadGateway(res, name, "answered "+res.Status+" with nothing in it, not an API reply") + } else if err != nil { + return res + } + if ce := res.Header.Get("Content-Encoding"); ce != "" && ce != "identity" { + return res // compressed: its first bytes say nothing of what it is + } + head, _ := br.Peek(br.Buffered()) + head = bytes.TrimLeft(head, " \t\r\n\ufeff") + switch { + case htmlStart.Match(head) && !strings.Contains(ct, "xml"): + return asBadGateway(res, name, webPage(res, ct)) + case strings.Contains(ct, "json") && len(head) > 0 && head[0] != '{' && head[0] != '[': + b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<10)) + return asBadGateway(res, name, "answered "+res.Status+" with a reply that isn't JSON, not an API reply: "+clipRunes(string(bytes.TrimSpace(b)), 200)) + } + return res +} + +// htmlStart is how a web page begins. +var htmlStart = regexp.MustCompile(`(?i)^<(!doctype\s+html|html[\s>]|head[\s>]|body[\s>])`) + +// pageTitle is a web page's title. +var pageTitle = regexp.MustCompile(`(?is)]*>(.*?)`) + +// webPage says what a page served in place of a reply was, by its title, +// and for a firewall's block page what to do about it. +func webPage(res *http.Response, ct string) string { + b, _ := io.ReadAll(io.LimitReader(res.Body, 64<<10)) + if ct == "" { + ct = "no Content-Type" + } + why := "answered " + res.Status + " with a web page (" + strings.TrimSpace(strings.SplitN(ct, ";", 2)[0]) + "), not an API reply" + if m := pageTitle.FindSubmatch(b); m != nil { + if t := strings.Join(strings.Fields(html.UnescapeString(string(m[1]))), " "); t != "" { + why += ": “" + clipRunes(t, 120) + "”" + } + } + if provider.EdgeBlocked(b) { + why += " — " + provider.BlockedHint + } + return why +} + +// asBadGateway is res as the 502 it stands for, saying why in an error +// body every reader of one finds its message in. +func asBadGateway(res *http.Response, name, why string) *http.Response { + io.Copy(io.Discard, io.LimitReader(res.Body, 1<<20)) + res.Body.Close() + msg := name + why + b, _ := json.Marshal(map[string]any{"error": map[string]any{"message": msg, "type": "bad_gateway"}, "message": msg}) + h := res.Header.Clone() + for _, k := range []string{"Content-Type", "Content-Length", "Content-Encoding", "Transfer-Encoding"} { + h.Del(k) + } + h.Set("Content-Type", "application/json") + out := *res + out.StatusCode, out.Status = http.StatusBadGateway, "502 Bad Gateway" + out.Header, out.Body, out.ContentLength = h, io.NopCloser(bytes.NewReader(b)), int64(len(b)) + return &out +} + +// readCloser reads through a buffer in front of a body, and closes the +// body. +type readCloser struct { + io.Reader + io.Closer +} + +// clipRunes is s cut to at most n runes. +func clipRunes(s string, n int) string { + if r := []rune(s); len(r) > n { + return string(r[:n]) + "…" + } + return s +} diff --git a/internal/gateway/notapi_test.go b/internal/gateway/notapi_test.go new file mode 100644 index 000000000..eed456a59 --- /dev/null +++ b/internal/gateway/notapi_test.go @@ -0,0 +1,197 @@ +package gateway + +import ( + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// cloudflarePage is a page a relay serves 200 text/html in place of a +// reply (#1012): Cloudflare's challenge, as it begins. +const cloudflarePage = `Just a moment...
` + +// notAPIOn saves a provider speaking proto at s, its only model m. +func notAPIOn(t *testing.T, id string, proto provider.Protocol, s *scripted) *httptest.Server { + t.Helper() + up := httptest.NewServer(s) + t.Cleanup(up.Close) + p := provider.Provider{ID: id, Name: strings.ToUpper(id), Key: "k", Models: []string{"m"}} + switch proto { + case provider.Anthropic: + p.Anthropic = up.URL + case provider.Responses: + p.Responses = up.URL + "/v1" + default: + p.Chat = up.URL + "/v1" + } + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + return up +} + +// goodReply is a whole reply saying "from b", streamed or not, in proto. +func goodReply(proto provider.Protocol, stream bool) reply { + switch { + case proto == provider.Chat && !stream: + return reply{200, "application/json", `{"id":"ok","choices":[{"index":0,"message":{"role":"assistant","content":"from b"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":2}}`} + case proto == provider.Chat: + return reply{200, "text/event-stream", sse(`data: {"id":"ok","choices":[{"index":0,"delta":{"role":"assistant","content":"from b"}}]}`, + `data: {"id":"ok","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":2}}`, + `data: [DONE]`)} + case proto == provider.Responses && !stream: + return reply{200, "application/json", `{"id":"resp_b","object":"response","status":"completed","model":"m","output":[{"type":"message","id":"msg_b","role":"assistant","status":"completed","content":[{"type":"output_text","text":"from b","annotations":[]}]}],"usage":{"input_tokens":3,"output_tokens":2,"total_tokens":5}}`} + case proto == provider.Responses: + return reply{200, "text/event-stream", sse(`event: response.created`+"\n"+`data: {"type":"response.created","response":{"id":"resp_b","status":"in_progress","output":[]}}`, + `event: response.output_text.delta`+"\n"+`data: {"type":"response.output_text.delta","item_id":"msg_b","output_index":0,"content_index":0,"delta":"from b"}`, + `event: response.completed`+"\n"+`data: {"type":"response.completed","response":{"id":"resp_b","status":"completed","model":"m","output":[{"type":"message","id":"msg_b","role":"assistant","status":"completed","content":[{"type":"output_text","text":"from b","annotations":[]}]}],"usage":{"input_tokens":3,"output_tokens":2,"total_tokens":5}}}`)} + case !stream: + return reply{200, "application/json", `{"id":"msg_b","type":"message","role":"assistant","model":"m","content":[{"type":"text","text":"from b"}],"stop_reason":"end_turn","usage":{"input_tokens":3,"output_tokens":2}}`} + } + return reply{200, "text/event-stream", sse(`event: message_start`+"\n"+`data: {"type":"message_start","message":{"id":"msg_b","role":"assistant","content":[],"usage":{"input_tokens":3}}}`, + `event: content_block_start`+"\n"+`data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`, + `event: content_block_delta`+"\n"+`data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"from b"}}`, + `event: content_block_stop`+"\n"+`data: {"type":"content_block_stop","index":0}`, + `event: message_delta`+"\n"+`data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":2}}`, + `event: message_stop`+"\n"+`data: {"type":"message_stop"}`)} +} + +// askOn sends a request for model in proto, streamed or not. +func askOn(s *Server, proto provider.Protocol, model string, stream bool) *httptest.ResponseRecorder { + st := "false" + if stream { + st = "true" + } + var path, body string + switch proto { + case provider.Responses: + path, body = "/v1/responses", `{"model":"`+model+`","stream":`+st+`,"input":[{"role":"user","content":"hi"}]}` + case provider.Anthropic: + path, body = "/v1/messages", `{"model":"`+model+`","max_tokens":10,"stream":`+st+`,"messages":[{"role":"user","content":"hi"}]}` + default: + path, body = "/v1/chat/completions", `{"model":"`+model+`","stream":`+st+`,"messages":[{"role":"user","content":"hi"}]}` + } + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", path, strings.NewReader(body))) + return rec +} + +// A group member that answers 200 with a web page, with nothing at all or +// with something sent as JSON that isn't, has failed before its reply +// began: the next member answers, on every API, streamed or not, and the +// log says why the first one didn't (#1012: Codex on group/medium was +// handed a relay's text/html page, logged 200 with nothing in or out). +func TestNotAnAPIReplyFailsOver(t *testing.T) { + bad := []struct { + name string + r reply + why string + }{ + {"html", reply{200, "text/html; charset=utf-8", cloudflarePage}, `with a web page (text/html), not an API reply: “Just a moment...”`}, + {"html as json", reply{200, "application/json", cloudflarePage}, "with a web page (application/json)"}, + {"html as sse", reply{200, "text/event-stream", "\n" + cloudflarePage}, "with a web page (text/event-stream)"}, + {"empty", reply{200, "application/json", ""}, "with nothing in it"}, + {"empty sse", reply{200, "text/event-stream", ""}, "with nothing in it"}, + {"not json", reply{200, "application/json", "upstream connect error or disconnect/reset before headers"}, "with a reply that isn't JSON, not an API reply: upstream connect error"}, + } + for _, proto := range []provider.Protocol{provider.Chat, provider.Responses, provider.Anthropic} { + for _, stream := range []bool{false, true} { + for _, x := range bad { + name := string(proto) + "/" + x.name + if stream { + name += "/stream" + } + t.Run(name, func(t *testing.T) { + fresh(t) + a := &scripted{replies: []reply{x.r}} + b := &scripted{replies: []reply{goodReply(proto, stream)}} + notAPIOn(t, "a", proto, a) + notAPIOn(t, "b", proto, b) + if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"a/m", "b/m"}, Routing: provider.Ordered}); err != nil { + t.Fatal(err) + } + s := New() + rec := askOn(s, proto, "group/g", stream) + if rec.Code != 200 || !strings.Contains(rec.Body.String(), "from b") || strings.Contains(rec.Body.String(), "Just a moment") || a.n != 1 || b.n != 1 { + t.Fatalf("%d %s (a %d, b %d)", rec.Code, rec.Body.String(), a.n, b.n) + } + calls := s.Recent() + if len(calls) == 0 || calls[0].Status != 200 || !strings.Contains(calls[0].Fallback, x.why) { + t.Fatalf("log: %+v", calls) + } + }) + } + } + } +} + +// A provider with nobody after it hands the agent a 502 saying what came +// back, not the page as a reply, and the log has it as the error it was. +func TestNotAnAPIReplyAlone(t *testing.T) { + fresh(t) + a := &scripted{replies: []reply{{200, "text/html; charset=utf-8", cloudflarePage}}} + notAPIOn(t, "a", provider.Responses, a) + s := New() + rec := askOn(s, provider.Responses, "a/m", true) + body := rec.Body.String() + if strings.Contains(body, "", 200}, + {"application/json", "", "", 204}, + {"text/html", "", "", 404}, + } { + res := &http.Response{StatusCode: x.code, Status: http.StatusText(x.code), Header: http.Header{}, Body: io.NopCloser(strings.NewReader(x.body))} + if x.ct != "" { + res.Header.Set("Content-Type", x.ct) + } + if x.ce != "" { + res.Header.Set("Content-Encoding", x.ce) + } + got := notAnAPIReply(res, "") + raw, _ := io.ReadAll(got.Body) + b := string(raw) + if got.StatusCode != x.code || b != x.body { + t.Errorf("%+v: %d %q", x, got.StatusCode, b) + } + } +} + +// Codex's own sign-in, relayed to the ChatGPT backend, is told of a web +// page served 200 as the 502 it is, not handed the page as its stream. +func TestCodexBackendWebPage(t *testing.T) { + setup(t, provider.Chat, &fake{t: t}) + chatgpt(t, func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + io.WriteString(w, cloudflarePage) + }) + req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(`{"model":"gpt-5.5","stream":true,"input":[]}`)) + req.Header.Set("Authorization", "Bearer chatgpt-token") + rec := httptest.NewRecorder() + New().Handler().ServeHTTP(rec, req) + if rec.Code != http.StatusBadGateway || strings.Contains(rec.Body.String(), "