gateway: a refused or empty-failed Codex relay's call carries its route (#2481)

The Routing page's "Request and response" finds a request's call by its
route (RouteCall). Of codexUpstreamOn's three record exits only the
success one set Call.Route, so a turn whose API key OpenAI refused (401)
or that the backend failed with nothing said opened as "the request is
gone" though its call was one of the last 40. Both failure exits now
carry the route through routeOf, which is 0 for a compaction: both exits
are reached by /responses/compact too, where no route opens.

Reported with a patch by ggbdpq (gua2100 on Discord). The patch set
Route: tr.ID unguarded on the empty-failure exit; since the
outrageous_piglet change that exit also takes a compaction, where tr is
nil, so that line panics on a compaction failed with an empty body.
routeOf guards both exits. gui-shell.md says which Codex exits carry
the route.

Run (sandbox HOME, caches pinned):
- TestCodexKeyRefusedCarriesItsRoute, TestCodexEmptyFailureCarriesItsRoute
  (ggbdpq's, the asserts moved into routeHasItsCall) and the new
  TestCodexCompactEmptyFailureRecordsNoRoute: ok.
- Broken by hand: with both exits back to no Route, the first two fail
  "route N: no call in the ring, so Request and response says the
  request is gone"; with the patch's unguarded tr.ID on the empty exit,
  the compaction test panics (nil pointer dereference). Restored: ok.
- go test -tags nogui -run 'TestCodex|TestRouting|TestArchive|TestRouteCall'
  ./internal/gateway: ok (31s).
- gofmt -l clean; go vet darwin, GOOS=windows, GOOS=linux -tags nogui on
  ./internal/gateway: clean.

Not tried: a real OpenAI 401 or a real empty ChatGPT backend failure
(fake upstreams); the GUI's routing-bodies test (the GUI is unchanged);
the full ./... suite (one suite per machine, others running).

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
This commit is contained in:
yetone
2026-10-28 00:41:37 +08:00
committed by yetone
co-authored by ggbdpq
parent 5a9fb36a10
commit 7f0f71a0ef
3 changed files with 96 additions and 3 deletions
+3 -1
View File
@@ -310,7 +310,9 @@ its story's head has "Request and response", which fetches
`GET /api/gateway/call?route=…` (`Server.RouteCall`) only when pressed.
A call carries the Routing request it was (`Call.Route`, the trace's
`Route.ID`, set where `serve`, the Codex backend and a refused title
record it); a route id is not a call id. When the ring no longer has it,
record it; the Codex backend's refused key and empty failure too, but not
a compaction's, which opens no route: `TestCodexKeyRefusedCarriesItsRoute`);
a route id is not a call id. When the ring no longer has it,
the story shows the request archive's copy through `archivePanel` if the
route names one (`Route.Archive`, `call.archiveName()`, set only when the
archive was on for that request), and otherwise says how to turn the
+12 -2
View File
@@ -1228,7 +1228,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
// models was picked, which goes out with Codex's own sign-in
msg, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
writeError(w, provider.Responses, res.StatusCode, codexKeyRefused(msg))
s.record(Call{Time: start, From: provider.Responses, To: provider.Responses, Model: modelOf(body),
s.record(Call{Route: routeOf(tr), Time: start, From: provider.Responses, To: provider.Responses, Model: modelOf(body),
Provider: "openai", Agent: callerOf(r).agent, Status: res.StatusCode,
Millis: time.Since(start).Milliseconds(), Error: res.Status})
end(res.StatusCode, res.Status, 0, 0)
@@ -1251,7 +1251,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
// as its markup: said where the turn, or the compaction
// (outrageous_piglet on Discord), went
failWith(res.StatusCode, said)
s.record(Call{Time: start, From: provider.Responses, To: provider.Responses, Model: modelOf(body),
s.record(Call{Route: routeOf(tr), Time: start, From: provider.Responses, To: provider.Responses, Model: modelOf(body),
Provider: "openai", Agent: callerOf(r).agent, Kind: callKind(r.Header), Status: res.StatusCode,
Millis: time.Since(start).Milliseconds(), Error: said})
end(res.StatusCode, said, 0, 0)
@@ -1632,6 +1632,16 @@ func codexSaidNothing(rest, model, who string, res *http.Response, msg []byte) (
"or pick one of magpie's models in Codex (provider/model, or set it in magpie's Agents view)", true
}
// routeOf is the id of the route a Codex relay opened, so the call it
// records is the one the Routing page's "Request and response" opens (#2481);
// 0 for a compaction, which opens none.
func routeOf(tr *Route) int64 {
if tr == nil {
return 0
}
return tr.ID
}
// apiKey reports whether Codex signed in with an API key rather than a
// ChatGPT account.
func apiKey(h http.Header) bool {
+81
View File
@@ -183,6 +183,87 @@ func TestCodexAPIKeyRecordedAsOpenAI(t *testing.T) {
}
}
// A Codex relay OpenAI refuses (an API key it turns away) is still the
// request its Routing row is: the call it records carries the route, so
// the Routing page's "Request and response" opens it while the recent
// calls have it, instead of saying it is gone (#2481, ggbdpq).
func TestCodexKeyRefusedCarriesItsRoute(t *testing.T) {
setup(t, provider.Chat, &fake{t: t})
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
io.WriteString(w, `{"error":{"message":"Incorrect API key provided: sk-synth***","type":"invalid_request_error","code":"invalid_api_key"}}`)
}))
t.Cleanup(up.Close)
was := codexAPIBase
codexAPIBase = up.URL + "/v1"
t.Cleanup(func() { codexAPIBase = was })
s := New()
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(`{"model":"gpt-5.5","stream":true,"input":"hi"}`))
req.Header.Set("Authorization", "Bearer sk-synthetic")
s.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("%d %s", rec.Code, rec.Body.String())
}
routeHasItsCall(t, s, http.StatusUnauthorized)
}
// A Codex relay the backend fails with nothing said (Codex shows it as
// "Unknown error" alone) is the request its Routing row is too.
func TestCodexEmptyFailureCarriesItsRoute(t *testing.T) {
chatgpt(t, func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
})
s := New()
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(`{"model":"gpt-5.5","stream":true,"input":"hi"}`))
req.Header.Set("Authorization", "Bearer chatgpt-token")
s.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusInternalServerError {
t.Fatalf("%d %s", rec.Code, rec.Body.String())
}
routeHasItsCall(t, s, http.StatusInternalServerError)
}
// A compaction failed with nothing said reaches the same exit with no
// route open: Codex is still told what happened and the call is still
// recorded, with no route to carry.
func TestCodexCompactEmptyFailureRecordsNoRoute(t *testing.T) {
chatgpt(t, func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
})
s := New()
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", CodexPath+"/responses/compact", strings.NewReader(`{"model":"gpt-5.5","input":[]}`))
req.Header.Set("Authorization", "Bearer chatgpt-token")
s.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusInternalServerError || !strings.Contains(rec.Body.String(), "this compaction") {
t.Fatalf("%d %s", rec.Code, rec.Body.String())
}
calls := s.Recent()
if len(calls) != 1 || calls[0].Status != http.StatusInternalServerError || calls[0].Route != 0 {
t.Fatalf("recorded %+v", calls)
}
}
// routeHasItsCall checks that the one route the trace has finds its call,
// the one that answered status.
func routeHasItsCall(t *testing.T, s *Server, status int) {
t.Helper()
st := s.Trace(t.Context(), 0, 0)
if len(st.Routes) != 1 {
t.Fatalf("routing view has %d routes, want the turn", len(st.Routes))
}
c, ok := s.RouteCall(st.Routes[0].ID)
if !ok {
t.Fatalf("route %d: no call in the ring, so Request and response says the request is gone though its call is one of the last 40", st.Routes[0].ID)
}
if c.Status != status {
t.Errorf("route %d is the call %d (%d), not the failure (%d)", st.Routes[0].ID, c.ID, c.Status, status)
}
}
// A compaction signed by another account is that account's, not the
// sign-in the request would have relayed on. A request naming another
// ChatGPT account than the sign-in magpie reads (a Codex in WSL, or