Files
magpie/internal/gateway/codex_subagent.go
T
Haogao Gu 20350dafaf gateway, agent, gui: Claude Desktop's subagents can be held to one model, set in its row on the Agents page
Claude Code in a terminal holds every subagent to one model through
CLAUDE_CODE_SUBAGENT_MODEL (its "subagents" field), and Codex through
magpie's own setting (settings.CodexSubagentModel). Claude Desktop runs
its Code tab's Claude Code with CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST=1,
and Claude Code 2.1.295 then ignores CLAUDE_CODE_SUBAGENT_MODEL,
CLAUDE_CODE_SUBAGENT_MODEL_FORCE and the tier variables in its settings
files ("Ignoring … this session's provider routing is managed by the
host"). The env Desktop 2.31226 builds for the Code tab has no key for it
either. So Desktop's subagents ran on the lead's model or on a tier's, and
only the tiers could be picked.

Claude Desktop's row now has a "subagent model" square, the same square
and strings as Codex's. It is magpie's setting
(settings.DesktopSubagentModel), which the gateway applies
(desktopSubagentPick):

- Only a claude-desktop request with x-claude-code-agent-id and tools is
  moved: a subagent's turn. The lead's turns, the tool-less helper calls
  Claude Code makes inside a subagent (on the haiku tier's model),
  terminal Claude Code and every other agent stay as asked.
- It is applied after desktopTurn, the tiers and the groups. A turn
  already on the model set isn't marked as moved. Route.Subagent,
  Route.Model and the ledger's Requested keep the model asked for; Kind
  stays empty.
- The model set must be served by its exact id (Resolve takes any model
  name under a provider that is on), enabled, and allowed to a gateway key
  held to some models (groupAllowed for a group). Otherwise the subagent
  stays on the model asked for and the trace says why, in the reasons
  Codex's subagent model already has.
- count_tokens counts on the same model.
- It is read on each request, so Desktop needn't restart. The field is
  Live (a new Field flag): /api/set and `magpie <agent> <field> <value>`
  leave Desktop's restart notice out after it, unless the pick connected
  Desktop. Codex's subagent model is unchanged.
- The getter follows a provider renamed since it was set (RenamedRef).
  The setter takes any provider/model or group/<id>, also one not served
  now (a restored profile), refuses a bare name, and keeps a Desktop
  alias by its catalog id. Options are shown while Desktop is on magpie.
- POST /api/settings keeps it; a stopped WSL distro's field copy keeps
  Live.
- The Routing page says why a Desktop subagent was moved or kept
  (subagentWhy, for a route with a subagent pick and no kind). "it is
  disabled in magpie" gets its zh, zh-TW, ja and de, which Codex's kept
  reason lacked as well.
- Unset, the pick costs one held settings read (no body decode, no
  catalog build).

Not changed: a Desktop on another computer that reaches magpie with a
named gateway key is read as Claude Code (agentOf), so none of Desktop's
routing applies to it, this included. There is no fallback when the model
set has a smaller window than the lead's.

Verified at this head, on 20769439, under a temporary HOME with Go's
caches pinned:
- Each new test fails with the guarantee it names broken by hand (a real
  FAIL, not a compile error), then passes restored. 48 Go breaks were
  first run on 8f34bbcd: settings trim and bare-name refusal; setter
  validation and clear; RenamedRef in the getter and in Unserved; the
  exact served check and served groups; the serve pick, each guard
  (agent id, tools, claude-desktop only, unset, same and resolved model);
  the named id kept in Route.Model, Kind and the ledger's Requested; each
  kept reason (unserved, disabled, held model, held group); groupAllowed;
  the next request reading a change; the session pick kept; count_tokens;
  the unset pick allocating; Live on the field, not on the tiers or on
  Codex's, copied by WSL; options while unwired and wired; alias
  conversion; the settings keep line; the GUI and CLI notice rules.
  Re-run at this head:
  - no tools guard: TestDesktopSubagentLeavesOtherRequests/helper,
    `sent "m2", want m1`
  - no agent-id guard: TestDesktopSubagentLeavesOtherRequests/lead,
    `sent "m2", want m1`
  - no count_tokens pick: TestDesktopSubagentCountTokens,
    `count sent "m1" to "/v1/messages/count_tokens", want m2`
  - Resolve instead of the exact served check: TestDesktopSubagentUnserved,
    `fake/missing: "", want "magpie doesn't serve it now"`
  - no Live rule in /api/set: TestDesktopSubagentModelNotice (gui),
    `wired Live pick notice "Claude Desktop reads this at start-up …"`
  - no keep line in POST /api/settings: TestSettingsSaveKeepsWhatItDoesNotSend,
    `DesktopSubagentModel:  after a save of the Settings page, was fake/m2`
  GUI breaks (0 pass / 2 fail in each engine): renderSteps' new aside
  removed (Desktop's moved story missing); the four "it is disabled in
  magpie" translations removed (the kept story keeps the English reason);
  the Default note's translation removed.
- go test -tags nogui ./...: 52 packages ok, no failure.
- go test -race -count=20 -run '^TestDesktopSubagent' ./internal/gateway: ok.
- gofmt -l on the changed files: nothing. go vet ./...,
  GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...,
  go build, GOOS=linux go build -tags nogui, GOOS=windows go build: exit 0.
- Playwright 1.62.1: desktop-subagent-model.test.cjs (en, zh, zh-TW, ja,
  de; 1100 and 560 wide) with codex-subagent-model, codex-subagents-lead,
  codex-start-model-field, desktop-tiers, desktop-model-menu,
  subagent-effort and every routing-*.test.cjs: 472/472 in Chromium and
  in WebKit. The whole suite: Chromium 4580/4580; WebKit 4570/4572. The
  two are red on 20769439 untouched as well: group-fold.test.cjs 3 of 3
  alone (195a1009b, fixed upstream since by a125d5c9), usage-fold.test.cjs
  4 of 9 alone there and 4 of 9 here ("as many accounts on the first
  screen as before the curves: 12 of 29").
- The built binary in a temporary HOME, `magpie serve` on a free port, a
  fake Anthropic upstream, requests shaped like Desktop's Claude Code:
  `magpie claude-desktop subagent_model fake/m2` printed no restart
  advice; a subagent's turn and its count went to m2; the lead's turn,
  a subagent's tool-less call, terminal Claude Code's and a subagent turn
  after `… subagent_model default` went to m1; claude-desktop.model stayed
  fake/m1; the ledger kept requested fake/m1.
- Not tried: a real Claude Desktop or Cowork (that needs the live
  gateway), Linux and Windows machines (GOOS vet and build only),
  WebKitGTK.

Maintainer's review on origin/main c4c3cafa2 (#2081), under a scratchpad
HOME with Go's caches pinned, machine load 120-330:
- Claude Code 2.1.299's bundled source has the "Ignoring … this
  session's provider routing is managed by the host" path, with
  CLAUDE_CODE_SUBAGENT_MODEL_FORCE in the set it ignores.
- Breaks re-run: no tools guard -> TestDesktopSubagentLeavesOtherRequests/
  helper `sent "m2", want m1` and TestDesktopSubagentCountTokens helper
  count; no count_tokens pick -> TestDesktopSubagentCountTokens `count
  sent "m1" … want m2`; the Routing page's subagentWhy aside removed ->
  desktop-subagent-model 0 pass / 2 fail (webkit, zh).
- go test -tags nogui ./internal/{gateway,agent,settings,gui,cli,provider}:
  ok on 2fbbd1694 (agent with -timeout 40m: 1857s under the load; the
  default 10m timed out mid TestClaudeNewSessionEffortLastsModelSwitch, a
  test this change doesn't touch). After rebasing onto c4c3cafa2, the
  Desktop/Subagent/SettingsSave/Live/Notice tests of those six packages: ok.
- gofmt -l: nothing. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./..., go build, GOOS=linux go build -tags nogui,
  GOOS=windows go build: ok.
- desktop-subagent-model.test.cjs now runs at 1100 and 420 (was 560):
  20/20, chromium and webkit, en zh zh-TW ja de. codex-subagent-model,
  desktop-tiers, routing-purpose-state, routing-request-model,
  routing-sealed-task: all pass in both engines.
- usage-fold's "29 accounts" case passed 4 of 4 alone in WebKit here.
- Not repeated: the author's built-binary run; a real Claude Desktop or
  Cowork; Linux and Windows machines.

Decisions on the author's questions: Live is kept as named, and Codex's
subagent model is left as it is; a subagent's tool-less helper calls stay
on the model they asked for, being Claude Code's own housekeeping rather
than the subagent's work.

Reported-by: Koohoko (#2081)
2026-10-14 15:48:19 +08:00

98 lines
3.5 KiB
Go

package gateway
import (
"context"
"net/http"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/usage"
)
// SubagentPick is a subagent's request put on the model the user set for
// its agent's subagents, in place of the one its lead asked for: Codex's
// (provider.CodexSubagentModel, willz on Discord) or Claude Desktop's
// (provider.DesktopSubagentModel). Kept says why it went on the model
// asked for instead, "" when it was put on To.
type SubagentPick struct {
Asked string `json:"asked"`
To string `json:"to"`
Kept string `json:"kept,omitempty"`
}
// Moved says the request went on To.
func (p *SubagentPick) Moved() bool { return p != nil && p.Kept == "" }
type subagentPickKey struct{}
func withSubagentPick(r *http.Request, p *SubagentPick) *http.Request {
if p == nil {
return r
}
return r.WithContext(context.WithValue(r.Context(), subagentPickKey{}, p))
}
func subagentPickOf(r *http.Request) *SubagentPick {
p, _ := r.Context().Value(subagentPickKey{}).(*SubagentPick)
return p
}
// codexSubagentPick is what is done with the model of a request: nil when
// it isn't a Codex subagent's or no model is set for them, so the request
// goes on as asked. The model set must still be served, be able to open
// the subagent's task, and be one the gateway key may use; when it isn't,
// the request goes on the model asked for and the pick says why. Any
// model opens a task handed as text (a lead on a chat provider, #1633, or
// Codex's multi-agent V1). One the ChatGPT backend sealed, its lead having
// run there, is put only on a ChatGPT account's model, as it was before
// any other could be set; on any other the subagent stays where its lead
// put it, which serve's sealed gate (sealedReader) handles as it did with
// no model set, so setting one is never worse than leaving it unset. A
// relay that sealed the lead's task (#1109) is reached that way too: the
// lead names it.
func codexSubagentPick(r *http.Request, agent, kind, asked string, body []byte) *SubagentPick {
// Codex by its token or by its User-Agent (fromCodex: its CLI, exec,
// the IDE extension, the desktop app)
if agent != "codex" && !fromCodex(r.Header) || usage.PurposeOf(kind) != "kind:collab_spawn" {
return nil
}
to := provider.CodexSubagentModel()
if to == "" || to == asked {
return nil
}
pick := &SubagentPick{Asked: asked, To: to}
if _, off := idOff(to); off {
// the user disabled it (#1867): the subagent stays on its lead's
// model, itself refused when it is disabled too
pick.Kept = "it is disabled in magpie"
return pick
}
if why := provider.CodexSubagentUnserved(to); why != "" {
pick.Kept = why
return pick
}
if !provider.CodexAccountModel(to) && sealedTaskIn(body) {
pick.Kept = sealedKept
return pick
}
if who, held := keyHolds(r); held {
if p, model, ok := provider.Resolve(to); !ok || !modelAllowed(who, p, model) {
pick.Kept = "the gateway key may not use it"
}
}
return pick
}
// sealedKept is why a Codex subagent stayed on the model its lead asked
// for when the one set for its subagents can't open its task.
const sealedKept = "its task was sealed by the ChatGPT backend that answered its lead, and only a ChatGPT account can open it"
// sealedTaskIn says a request carries a sealed agent task, not only sealed
// messages: serve leaves those out with a note (withoutSealedMessages).
func sealedTaskIn(body []byte) bool {
if !hasSealedAgentMessage(body) {
return false
}
b, _ := withoutSealedMessages(body)
return hasSealedAgentMessage(b)
}