Files
magpie/internal/gateway/codex_memory.go
T
yetoneandmdwsk88 8de63c8b5a gateway, usage, gui, otlp: a request its agent canceled is no failure (#2398)
An agent that cancels its request before it is answered is logged 499
"the agent canceled the request": a person stops the reply, or sends the
next message while it is coming and Claude Desktop cancels it and asks
again, or Codex takes a subagent's report (#2398). The gateway already
says nobody failed (no rest, no reroute: TestCanceledRequestRestsNobody),
but Record.Failed is a status >= 400 or an error, so every page counted
it as a failure: the Requests card's "N failed" and success share, its
Failed filter, the CSV's error column, the Routing page's "errors your
agent saw", the Context page's error rate, the failed colour in the
Requests list, Routing and Recent calls, and the OTLP export's error
status. A Claude Desktop session on 2026-10-27 had four, each a message
sent mid-reply; #2398 had 91 of a day's 92 failures.

usage.CanceledBy tells the agent's cancel (499 with AgentCanceled) from
magpie's own limit on a request it asked of itself, logged 499 too and
still a failure (#2318). The cancel is logged with an error type of its
own, agent_canceled (usage.CanceledErrType, set in failedWith), so the
record says what it was and nothing guesses it from a 499, as #2398
asked. Record.Canceled reads the type, and a record logged before it by
its status and message, so the old log reads the same with nothing
migrated. A middleware's usage rows carry the type, so a module can tell
the cancel from magpie's own limit, which its rows (no error text)
couldn't.

Record.Failed leaves the cancel out; Totals counts it apart (Canceled, in
count and plus); RetriedRequest and the first-token and speed sums ask
Answered, so a canceled request is timed nowhere, as before; Codex's
memory of the last model still skips it. Routes and Recent calls say
canceled (set as a route is done and as a day's history is read, so old
days read the same); the Routing totals and the Context page's errors
leave it out. Ledger rows say canceled, and the pages show it muted, in neither the
failed nor the answered colour: the Requests list and its detail ("499 ·
canceled"), the Requests card ("N canceled", the success share of the requests not
canceled), the overview tile, the Routing page (a "gone" outcome, no
speed) and Recent calls (muted). New strings are in zh, zh-TW, ja and de.

The OTLP export: the records the gateway gives its observers for a
request and its try carry the type too (canceledAs), and a root span's
error.type follows Record.Failed, so a canceled request's span and its
try's go with status code 499, no error and no error.type.
TestOTelWaterfallFailureAndCancellation's canceled case held two failed
spans (the try the vendor refused as the agent left is recorded canceled,
as the request is); it now holds neither failed, both 499 and no
error.type. That change to the test is the point of this one.

mdwsk88's patch (aea0027fd) ran its tests at e056779a, a3768cdd,
c86fa2a3 and fcc0daa2, broke each check by hand (each red), and sent
real Claude Desktop cancels through a nogui build with a stand-in
upstream and OTLP collector. Its full record is on aea0027fd. Since
58541e5b (#4866) Codex's own-sign-in relay logs Codex gone mid-reply as
499 through canceled() too, so it counts as canceled
(TestCodexGoneMidReplyIsNoFailure). drawing_route.go still reads a
canceled request as not served when it decides whether a picture's
next request may stay on its provider: that is routing, not a count.

Ported to origin/main 400b66ec3 on 2026-11-07, reviewed line by line.
Two siblings it left on the old rule, and a colour, now covered:
- usage.Row.Floor (the Claude Code speed floor) asked !Failed, so a
  canceled row, whose Failed is now false, told a floor: "3000 tokens
  in 4000 ms" for a reply no one waited for. It asks Answered now, as
  the speed and first-token sums do. TestAgentCanceledTellsNoFloor.
- The route-events feed (activityOf, #3387) told a canceled try and
  done route as failed. It leaves usage.CanceledBy out, and still
  counts magpie's own 499 limit. TestRouteEventsCanceledIsNoFailure.
- routing.css: a canceled Routing row ("rt-req gone") had the
  answered green dot. Its dot is muted now.
  routing-canceled-row.test.cjs checks the row, its dot and the errors
  stat in Chromium and WebKit, in en, zh, zh-TW, ja and de.

Run at this tree (mote-run, macOS):
- go test -count=1 internal/usage, usageapi, otlp, settings,
  settingsapi and cli: ok. internal/gateway: ok with -timeout 45m
  (847s; the default 10m ran out under load). internal/gui: ok but
  TestMainWindowCorners/macOS_26_SDK (#3949, mote is on macOS 27).
- Broken by hand: Floor on Failed again makes
  TestAgentCanceledTellsNoFloor fail ("a canceled row tells a speed
  floor: 3000 tokens in 4000 ms"). activityOf without CanceledBy makes
  TestRouteEventsCanceledIsNoFailure fail ("a done route its agent
  canceled is told failed"). Restored, both pass.
- GUI: node --test --test-concurrency=4 over routing-*, usage-*,
  ledger-*, panel-*, call-*, search-*, searcher-*, settings-*, i18n-*
  and gui-* (Chromium and WebKit; the files cover en, zh, zh-TW, ja
  and de), with #2398 and #5545 in one tree: 4961 of 5016 ok. The 55
  reds are in 12 files. i18n-keys' "a plugin's words are its own"
  names other files' strings (#5327, #5426, #5482). The other 11 files
  were run alone at dc49feca9 (this tree without either change) and at
  this tree: 52 and 51 reds, the same tests. The one apart is
  usage-focus-steady, which flakes (#3501). Each is filed: #5392,
  #3414, #5048, #3799, #3415, #3954, #4627, #4628, #5223, #1529.
  routing-canceled-row.test.cjs: 10 of 10. With the .rt-req.gone rule
  taken out, its dot is the answered green rgb(24, 154, 88) and it
  fails. Restored, it passes.
- Not tried: a real Claude Desktop cancel through this tree; Windows
  and Linux runs.

Co-authored-by: mdwsk88 <11055210+mdwsk88@users.noreply.github.com>
Reported-by: mdwsk88 (dawei on Discord)
2026-11-07 04:03:01 +08:00

146 lines
6.0 KiB
Go

package gateway
import (
"net/http"
"strings"
"time"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/usage"
)
// isMemoryKind: a call Codex makes to write or consolidate its memories,
// however it names one (usage.PurposeOf's memory_consolidation).
func isMemoryKind(kind string) bool {
return usage.PurposeOf(kind) == "kind:memory_consolidation"
}
// codexTurnKey is whose turns codexTurns holds: the agent recorded and the
// gateway key it came with, so a Codex on another computer (its own key,
// #742's Codex-BWG and Codex-R4S) is told apart from this one's.
func codexTurnKey(r *http.Request, who string) string {
return who + "\x00" + access.Caller(r.Context()).KeyID
}
// rememberCodexTurn keeps the model a turn of Codex's own conversation
// was asked on, one magpie serves, for its memory calls.
func (s *Server) rememberCodexTurn(r *http.Request, who, agent, kind, asked string) {
if agent != "codex" || kind != "" {
return
}
s.codexTurns.Store(codexTurnKey(r, who), asked)
// and by its conversation, for a memory call that raced it
// (codexMemoryStandIn)
s.codexLeads.saw(r, kind, asked)
}
// isReviewCall: Codex's auto-review of an approval (the guardian), which
// it asks for on codex-auto-review, the reviewer model of OpenAI's, when
// its list has that or names it as a model's auto_review_model_override.
func isReviewCall(kind, asked string) bool {
return kind == "guardian" || asked == "codex-auto-review"
}
// freeOnChatGPT says whether a call on model by a ChatGPT account on plan
// is free (provider.ChatGPTReviewFree, which the Usage page's prices
// follow too).
func freeOnChatGPT(model, plan string) bool { return provider.ChatGPTReviewFree(model, plan) }
// codexMemoryStandIn is the model a Codex memory call goes to when magpie
// knows none by the name it came with (#742): Codex writes and
// consolidates its memories on models of its own (memories.extract_model
// and consolidation_model; by default gpt-6-luna and gpt-6.1-terra from
// Codex 0.167.0, gpt-5.6-luna and gpt-5.6-terra before) by
// their bare names, whatever it is set to, so with magpie as its provider
// every one was turned away as an unknown model before it was routed. It
// goes to the model that Codex's own turns go to — the last one it had
// answered here, else the last in the ledger (a week back) from the same
// agent with the same key — so it is routed, and in the views, as the
// memory call it is. Its auto-review (isReviewCall) goes there too when
// Codex's config names no model magpie serves (StandIn): Codex reviews on
// the conversation's model when it has no reviewer, and a Codex whose
// config magpie doesn't read as its own — on magpie through another
// provider table or a profile, under a CODEX_HOME of its own, or on
// another computer — was answered 404 "magpie knows no model
// \"codex-auto-review\"" (Adam on Discord). "" for any other call, a model
// magpie serves, or a Codex that has had no turn answered here.
//
// Codex starts its memories with each turn of a conversation, so a memory
// call can come before the turn it was started with, the first after the
// model was switched: it is read after that turn, as the app's titles are
// (codexLeads.sideOf, beside), not on the model switched away from
// (cybercaius on Discord).
//
// why is the move's reason for the trace: movedCodexFollow for a bare
// default magpie serves that went on the conversation's model instead,
// movedCodexTurn for a model magpie doesn't serve.
func (s *Server) codexMemoryStandIn(r *http.Request, who, agent, kind, asked string, body []byte) (to, why string) {
if agent != "codex" || !isMemoryKind(kind) && !isReviewCall(kind, asked) {
return "", ""
}
if _, _, ok := provider.Resolve(asked); ok {
// A memory call on one of Codex's own bare defaults that a
// provider of magpie's happens to serve under the same name:
// the name is Codex's own, not a pick of that provider's model,
// and the account it resolves to may refuse the model outright
// (400, three tries, the memory lost, #4765). With Codex's
// config naming no model for its memories, the call follows the
// conversation's, as it does on the ChatGPT backend's path
// (codexFollowTo). "" keeps it where the name resolves: any
// other call, the config's own pick, a call whose config magpie
// can't read, or no conversation of magpie's to follow.
//
// A "provider/model" id is never one of Codex's defaults, which
// are bare: it is the user's pick in memories.extract_model or
// consolidation_model, and goes as it came, whatever the config
// here says — a Remote magpie can't read the Codex config on the
// computer the call came from, and a Codex on a profile or a
// CODEX_HOME of its own has its config elsewhere too (#5413).
if !isMemoryKind(kind) || strings.Contains(asked, "/") || CodexSideSet == nil || CodexSideSet("memories") {
return "", ""
}
to := s.codexMemorySession(r, body)
if to == "" || to == asked {
return "", ""
}
return to, movedCodexFollow
}
if isMemoryKind(kind) {
if m := s.codexLeads.sideOf(r, body, true); m != "" && m != asked {
if _, _, ok := provider.Resolve(m); ok {
return m, movedCodexTurn
}
}
}
key := codexTurnKey(r, who)
if m, ok := s.codexTurns.Load(key); ok {
if m, _ := m.(string); m != "" && m != asked {
if _, _, ok := provider.Resolve(m); ok {
return m, movedCodexTurn
}
}
}
keyID := access.Caller(r.Context()).KeyID
var last usage.Record
usage.Visit(time.Now().Add(-7*24*time.Hour), func(rec usage.Record) {
if rec.Agent != who || rec.CallerKeyID != keyID || rec.Kind != "" || rec.Rejected || rec.IsReported() || !rec.Answered() || rec.Requested == "" {
return
}
if rec.Time.After(last.Time) {
last = rec
}
})
m := last.Requested
if id, ok := provider.GroupFor(m); ok {
m = id
}
if m == "" || m == asked {
return "", ""
}
if _, _, ok := provider.Resolve(m); !ok {
return "", ""
}
return m, movedCodexTurn
}