routing: a request magpie put on another model says why (Neo)

Neo (Discord #feedback, Claude Desktop through the gateway) saw a
Requests row asking chatflowsai/claude-opus-5-5 served by AgentRouter's
gpt-6.1-sol, and read it as Claude asking for another provider's model
on its own. Claude Desktop names its own short requests (a title, its
connection check) on the first Claude-looking id in the list, here
chatflowsai's opus, and magpie keeps them on the chat's model by design
(desktopTurn, 51f66fe8b/13b4a29ab). The routing is right; the row never
said why the model changed.

Changed:
- Route gets Moved {to, why}, set wherever serve puts a request on
  another model before the trace starts: Desktop's tier, title, check,
  gone-model and side-turn moves (desktopMove returns the reason), the
  classifier and Claude tier stand-ins, the stand-in, Codex's turn and
  Privacy's mask route. A subagent's own move clears it (it has its own
  tag).
- Routing's list rows, replay, panel and story tag such a row "Title"
  or "Stand-in" and say why in the tooltip and story. Desktop's
  connection_check kind (da3c5e0c0) already explains itself, so it
  gets no second sentence (movedSays).
- zh, zh-TW, ja, de for the new strings; gateway-routing.md says it.
Not changed: codexFollowTo/codexMaskRoute still show the moved model as
asked.

Run:
- Full Go suite `go test -timeout 45m ./...` on mote at e30092847
  (before the rebase onto cae01311c): 79 ok; the one FAIL is
  internal/gui TestMainWindowCorners/macOS_26_SDK, #3949, same message.
- At 557c4f950 (on cae01311c), on mote: gofmt clean, go vet ./...,
  GOOS=windows go vet ./..., GOOS=linux go vet ./internal/gateway/...
  ./internal/usage/... (a whole-tree Linux vet needs cgo for Wails):
  ok. go test internal/gateway/... and internal/usage/... ok;
  internal/gui's reds are the AppKit windows killed at their deadline
  (#2645, #4125), TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and
  TestColdTurnsTaken (#4510), none of them Routing's.
- Rebased onto b1a1b950f (b52c39b65 changed routing/client.js): this
  head, on mote: gofmt clean, go vet ./internal/..., GOOS=windows go vet
  of gateway and gui, go test ./internal/gateway/... ok. Rebased again
  onto a511b11d8: go vet of gateway and gui, and go test -run
  'Desktop|Moved|Classif|StandIn|Subagent' ./internal/gateway/: ok.
- The full GUI suite at e30092847 was swamped by other sessions' suites
  (4771 browserType.launch 180s timeouts, #4125), so it tests nothing.
  mote's browsers were broken again (#4125), so the 208 GUI files that
  reach Routing or i18n ran on Linux (WSL magpie-desktop) at 557c4f950:
  2921 tests, 2823 pass, 98 fail in 37 files. Those 37 files at
  origin/main b1a1b950f: 76 of 428 red; at this head: 80 of 428, the
  differing ones the same tests in other languages or engines (rule
  drag/remove, rest-try-now, routing-flood, group-morph), filed as
  #4121, #4120, #4471, #2215, #3789, #3094, #2564. i18n-keys' one red
  is #4524 ("Unmarked", on main). At this head routing-moved-why,
  routing-session-title, claude-subagent-tag and i18n-keys: 83 of 84,
  the one is #4524.
- routing-moved-why.test.cjs runs en/zh/zh-TW/ja/de, both engines, at
  1100 and 420 wide.

Broken by hand: with `Moved: moved,` taken out of serve's Route literal,
TestClaudeDesktopMoveSaysWhy is red ("title's route moved <nil>, want
agentrouter/gpt-6.1-sol by desktop-title"); with origin/main's
client.js, routing-moved-why is red (0/2).

Not tried: a real Claude Desktop. Neo's earlier effort high-as-medium
report was not looked at here.
This commit is contained in:
yetone
2026-10-31 18:05:17 +08:00
parent a511b11d8b
commit 6b8261029b
8 changed files with 497 additions and 23 deletions
+1
View File
@@ -158,6 +158,7 @@ recorded as a prediction failure (`noPrediction`).
- A model set for Claude Desktop's subagents (`settings.DesktopSubagentModel`, the Agents page's Claude Desktop "subagent model") is put on a subagent's turn in Desktop's Code tab or Cowork after `desktopTurn`, the tiers and the groups, whatever model its lead or its tier asked for (`desktopSubagentPick` in [`desktop_subagent.go`](../../internal/gateway/desktop_subagent.go)). Desktop runs its Claude Code with `CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST=1`, under which Claude Code ignores the `CLAUDE_CODE_SUBAGENT_MODEL` magpie writes into its settings (see [agent wiring](agent-wiring.md)). A subagent's request is one with `x-claude-code-agent-id` (`subagentOf`) from `claude-desktop`, and only one that offers tools is its turn: Claude Code's tool-less helper calls inside a subagent, on the haiku tier's model, stay where they are, and so do the lead's turns, terminal Claude Code's and every other agent's. The model set must be served by its exact id (`provider.DesktopSubagentUnserved`: `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 goes on the model asked for and the route trace says why (`Route.Subagent`, said on the Routing page by `subagentWhy`, its `Kind` staying empty). `Route.Model` and the ledger's `Requested` keep the model the subagent asked for. `count_tokens` counts on the model set the same way (`countTokens`). The setting is read on each request, so a change needs no restart of Desktop, and a provider renamed since it was set is read by its new id (`RenamedRef`). 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, this included, applies to it. A subagent's turn, moved or not, is never kept as the session's model in `claude-desktop.model` (`desktopTurn`'s `bySubagent`): a subagent on the opus tier's model took the session's place until the lead's next turn, and Desktop's titles asked for meanwhile went to it.
- Desktop's subagent effort (`settings.DesktopSubagentEffort`, `desktopSubagentEffort` in [`desktop_subagent.go`](../../internal/gateway/desktop_subagent.go)) applies to the same subagent tool turns, independently of model replacement. Empty leaves requests unchanged. Set, it takes the place of a request model's effort suffix before the existing attempt-level effort fitting: a member fixed at an effort wins, then this pick fitted within group/model levels, then the turn's or request's effort. `withFixedEffort` can enable reasoning when it was disabled, or disable it with `none` on a model that supports that level; a reasonless model is still sent no reasoning fields. `countTokens` applies the pick after restoring any unmasked body. `Route.Effort` keeps the incoming effort, `Route.SubagentEffort` the configured pick, and each try and usage record the level actually sent; the Routing story explains the configured pick even when no model was replaced. A nonempty model pick already classifies the turn, so the effort check reuses it; empty effort costs only a held-settings read. The next request takes a changed or cleared effort without a Desktop restart.
- Every Claude Code subagent's turn, Desktop's or a terminal's, moved or not, keeps its `x-claude-code-agent-id` in `Route.SubagentID` (`subagentTurnOf` in [`desktop_subagent.go`](../../internal/gateway/desktop_subagent.go)): a request with the id that offers tools and names no kind, the turn the two settings above take. Claude Code 2.1.295 sends the id from any agent context but the main one; its `x-claude-code-request-class` and `x-claude-code-agent-type` hints go only to a first-party base URL or with `CLAUDE_CODE_GATEWAY_HINT_HEADERS`, so magpie doesn't get them. A Desktop pick or effort that found the turn is trusted, so the body isn't decoded again, and a request without the id isn't decoded at all. The Routing page tags it as Codex's subagents are (`tagKind` in [`routing.js`](../../internal/gui/assets/routing.js)): in the request list, the story, the replay and the tray panel, with the reason `kindWhy` gives Codex's. `Kind` stays empty, so its purpose stays unmarked in the Purpose filter, as in the ledger and on the Usage page. The ledger's `Subagent` keeps the same id, and also marks a subagent's tool-less helper calls, which aren't tagged. A route recorded before this has no id and no tag.
- A request a stand-in of magpie's put on another model than the agent named keeps that model and the rule in `Route.Moved` (`ModelMove{To, Why}` in [`trace.go`](../../internal/gateway/trace.go), set by `move` in `serve`): Claude Desktop's moves (`desktopMove` in [`desktop.go`](../../internal/gateway/desktop.go): `desktop-title`, `desktop-check`, `desktop-gone`, each with a `-first` form when it went to the first model listed for want of a chat turn or a menu pick, `desktop-tier`, `desktop-beside`, `desktop-aside`), `classifier`, `claude-tier`, `stand-in` (the agent's config), `codex-turn` (`codexMemoryStandIn`) and `privacy` (`maskRouteFor`). A subagent's move says its own (`Route.Subagent`), and a group or `Resolve` names no move. The Routing page tags such a row Title or Stand-in (`movedTag`, `movedWhy` in the routing plugin's client.js), in the list, the replay and the tray panel, and says why in the row's title and once in the story; a kind's tag wins, and its story still says the move, but for Desktop's connection check (`connection_check`), whose own story says where it went (`movedSays`). Neo on Discord read Desktop's title on `chatflowsai/claude-opus-5-5` (the only Claude-looking id Desktop is shown, so its own pick) served on the chat's `agentrouter/gpt-6.1-sol` as the model swapped unasked (`TestClaudeDesktopMoveSaysWhy`, `routing-moved-why.test.cjs`). Codex backend rewrites done before `serve` (`codexFollowTo`, `codexMaskRoute`) show the moved model as asked and have no `Moved`.
- A Chat or Responses client's effort spelled `off` (`reasoning_effort`, or `reasoning.effort`, any case) is read at the top of `serve` as magpie's own off level, `none` (`offAsNone`, plugins#334), and a model asked `<model>:off` as `<model>:none` (`askedAt`): every check and route below reads `none`, a model with an off level is sent its own spelling of it, and one without goes at its least level as `none` asked does (`fitEffort`). `off` itself is never sent on. `saysOff` looks for it without parsing the body, which only a body naming it pays for.
- A level a vendor names in words of its own (`catalog.EffortAliases`: Trae's `light` and `extra_high`, which Our Free Model's plugin lists) is the level it is (`EffortLevel`): `effortOf` reads it as `low` or `xhigh`, and `NearestEffort` places a model's own words by it, so `low` asked of a model listing `light` is sent as `light`, and its `light` as it is (nianshou5 on Discord; `TestNearestEffortTakesVendorWords`, `TestPluginThinkingOff`). dsh and Pi offer such a model's levels as theirs, sent in its words (`modelEffort` in [`agents.go`](../../internal/agent/agents.go); `TestDshOffersTraeNamedLevels`).
- Rules and image inputs are handled here too.
+48 -16
View File
@@ -523,11 +523,42 @@ func loadPicked() {
// sent with max_tokens 64000); one for a model magpie doesn't serve still
// goes there whoever sent it.
func desktopTurn(asked string, body []byte, byClaudeCode, bySubagent bool) string {
m, _ := desktopMove(asked, body, byClaudeCode, bySubagent)
return m
}
// The reasons desktopMove gives for serving a Desktop request on another
// model than it named, kept on its route (Route.Moved) so the Routing
// page says why (Neo on Discord: a row asking for chatflowsai's opus,
// answered by AgentRouter's GPT, read as magpie swapping the model).
const (
movedTier = "desktop-tier" // Claude Code's own id of a tier: the model picked for it
movedCheck = "desktop-check" // Desktop's check that the gateway answers: its menu's model
movedCheckFirst = "desktop-check-first" // …or, with none chosen, the first model it lists
movedTitle = "desktop-title" // a short call without tools Desktop names a model for: the chat's
movedTitleFirst = "desktop-title-first" // …or, before any turn, the first model it lists
movedGone = "desktop-gone" // a model magpie doesn't serve: the chat's
movedGoneFirst = "desktop-gone-first" // …or, before any turn, the first model it lists
movedBeside = "desktop-beside" // Claude Code's own id of a Claude model: that tier on the chat's provider
movedAside = "desktop-aside" // Claude Code's own call: the chat's model
)
// desktopMove is desktopTurn and why the model it gives isn't asked, ""
// when it is.
func desktopMove(asked string, body []byte, byClaudeCode, bySubagent bool) (string, string) {
to, why := desktopMoveTo(asked, body, byClaudeCode, bySubagent)
if to == asked {
return to, ""
}
return to, why
}
func desktopMoveTo(asked string, body []byte, byClaudeCode, bySubagent bool) (string, string) {
if asked == "" {
return asked
return asked, ""
}
if m := desktopTierTurn(asked); m != "" {
return m
return m, movedTier
}
if desktopProbe(body) {
// Desktop's check that the gateway answers, as it starts and from
@@ -536,15 +567,12 @@ func desktopTurn(asked string, body []byte, byClaudeCode, bySubagent bool) strin
// of whichever session last ran (desktopPicked) on its own,
// which may be days old and on another provider
if m := desktopChosen(); m != "" {
if m == asked {
return asked
}
return m
return m, movedCheck
}
if m := desktopDefault(asked); m != "" {
return m
return m, movedCheckFirst
}
return asked
return asked, ""
}
tools := hasTools(body)
desktopPicked.Lock()
@@ -556,7 +584,7 @@ func desktopTurn(asked string, body []byte, byClaudeCode, bySubagent bool) strin
// the session goes on on it: newer than a menu changed meanwhile
desktopPicked.at = time.Now()
}
return asked
return asked, ""
}
aside := small(body)
if byClaudeCode {
@@ -578,25 +606,29 @@ func desktopTurn(asked string, body []byte, byClaudeCode, bySubagent bool) strin
// a provider lists a model by that name (desktopTierTurn takes
// one no provider serves)
if m := DesktopTiers()[claudeTier(asked)]; m != "" {
return m
return m, movedTier
}
}
if (gone || elsewhere) && !title {
if m := servedBeside(asked, picked, byClaudeCode); m != "" {
return m
return m, movedBeside
}
}
if elsewhere {
return picked
return picked, movedAside
}
if gone || title {
why, first := movedTitle, movedTitleFirst
if gone {
why, first = movedGone, movedGoneFirst
}
if picked != "" {
return picked
return picked, why
}
if m := desktopDefault(asked); m != "" {
return m
return m, first
}
return asked
return asked, ""
}
if tools && !bySubagent {
desktopPicked.model, desktopPicked.at = asked, time.Now()
@@ -604,7 +636,7 @@ func desktopTurn(asked string, body []byte, byClaudeCode, bySubagent bool) strin
os.WriteFile(desktopPickedPath(), []byte(asked+"\n"), 0o600)
}
}
return asked
return asked, ""
}
// claudeOwnID: asked is a Claude model by Claude's own id
+117
View File
@@ -0,0 +1,117 @@
package gateway
import (
"encoding/json"
"net/http/httptest"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// Neo on Discord: a Routing › Requests row read "chatflowsai/claude-opus-5-5"
// asked and AgentRouter's gpt-6.1-sol served, with nothing saying why, and
// read as Claude Desktop asking for another provider's model by itself. It
// was Desktop's own short request (a chat's title), which Desktop names by
// the only Claude-looking id it is shown and magpie keeps on the chat's
// model. The trace says so: Route.Moved names the model served and the rule
// that moved it, and a request served as asked has none.
func TestClaudeDesktopMoveSaysWhy(t *testing.T) {
f := &fake{reply: sse(
`event: message_start`+"\n"+`data: {"type":"message_start","message":{"id":"m","type":"message","role":"assistant","model":"m","content":[],"usage":{"input_tokens":1,"output_tokens":0}}}`,
`event: message_stop`+"\n"+`data: {"type":"message_stop"}`)}
up := setup(t, provider.Anthropic, f)
for _, p := range []provider.Provider{
{ID: "agentrouter", Name: "AgentRouter", Key: "k", Anthropic: up.URL, Models: []string{"gpt-6.1-sol"}},
{ID: "chatflowsai", Name: "ChatFlowsAI", Key: "k", Anthropic: up.URL, Models: []string{"claude-opus-5-5"}},
} {
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
}
s := New()
h := s.Handler()
send := func(body string) *Route {
t.Helper()
f.got = nil
req := httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body))
req.Header.Set("x-api-key", Token+"-claude-desktop")
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
s.trace.mu.Lock()
defer s.trace.mu.Unlock()
return s.trace.routes[len(s.trace.routes)-1]
}
// the chat turn, on AgentRouter's GPT: served as asked, nothing moved
r := send(`{"model":"agentrouter/gpt-6.1-sol","max_tokens":32000,"stream":true,"tools":[{"name":"Bash","input_schema":{"type":"object"}}],"messages":[{"role":"user","content":"hi"}]}`)
if r.Moved != nil {
t.Fatalf("a turn served as asked says moved: %+v", r.Moved)
}
// Desktop's title, on the opus it picks by itself: served on the chat's
// model, and the row says so
r = send(`{"model":"chatflowsai/claude-opus-5-5","max_tokens":200,"stream":true,"system":"You write short session titles.","messages":[{"role":"user","content":"hi"}]}`)
if got := modelOf(f.got); got != "gpt-6.1-sol" {
t.Fatalf("title sent %q", got)
}
if r.Moved == nil || r.Moved.To != "agentrouter/gpt-6.1-sol" || r.Moved.Why != movedTitle {
t.Fatalf("title's route moved %+v, want agentrouter/gpt-6.1-sol by %s", r.Moved, movedTitle)
}
b, _ := json.Marshal(r)
if !strings.Contains(string(b), `"moved":{"to":"agentrouter/gpt-6.1-sol","why":"desktop-title"}`) {
t.Fatalf("history JSON: %s", b)
}
// Desktop's connection check on that opus: served elsewhere, and says so
r = send(`{"model":"chatflowsai/claude-opus-5-5","max_tokens":1,"messages":[{"role":"user","content":"."}]}`)
if r.Moved == nil || (r.Moved.Why != movedCheck && r.Moved.Why != movedCheckFirst) || r.Moved.To == "chatflowsai/claude-opus-5-5" {
t.Fatalf("check's route moved %+v", r.Moved)
}
// a turn on the opus itself is as asked
r = send(`{"model":"chatflowsai/claude-opus-5-5","max_tokens":32000,"stream":true,"tools":[{"name":"Bash","input_schema":{"type":"object"}}],"messages":[{"role":"user","content":"hi"}]}`)
if r.Moved != nil {
t.Fatalf("a turn on opus says moved: %+v", r.Moved)
}
}
// each way desktopMove takes a model elsewhere names its rule, and a
// request it leaves alone names none
func TestDesktopMoveReasons(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
desktopPicked.Lock()
desktopPicked.model, desktopPicked.from = "", ""
desktopPicked.Unlock()
for _, p := range []provider.Provider{
{ID: "agentrouter", Name: "AgentRouter", Key: "k", Anthropic: "http://127.0.0.1:1", Models: []string{"gpt-6.1-sol"}},
{ID: "chatflowsai", Name: "ChatFlowsAI", Key: "k", Anthropic: "http://127.0.0.1:1", Models: []string{"claude-opus-5-5"}},
} {
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
}
turn := []byte(`{"max_tokens":32000,"tools":[{"name":"Bash"}],"messages":[{"role":"user","content":"hi"}]}`)
title := []byte(`{"max_tokens":200,"system":"You write short session titles.","messages":[{"role":"user","content":"hi"}]}`)
// no turn yet: a title goes to the first model listed
if to, why := desktopMove("chatflowsai/claude-opus-5-5", title, false, false); why != movedTitleFirst && (why != "" || to != "chatflowsai/claude-opus-5-5") {
t.Errorf("first title: %q by %q", to, why)
}
if to, why := desktopMove("agentrouter/gpt-6.1-sol", turn, false, false); to != "agentrouter/gpt-6.1-sol" || why != "" {
t.Fatalf("turn: %q by %q", to, why)
}
if to, why := desktopMove("chatflowsai/claude-opus-5-5", title, false, false); to != "agentrouter/gpt-6.1-sol" || why != movedTitle {
t.Errorf("title: %q by %q", to, why)
}
if to, why := desktopMove("claude-haiku-4-5-20251001", turn, false, false); to != "agentrouter/gpt-6.1-sol" || why != movedGone {
t.Errorf("unserved: %q by %q", to, why)
}
if to, why := desktopMove("claude-haiku-5-5", title, true, false); to != "agentrouter/gpt-6.1-sol" || why == "" {
t.Errorf("Claude Code's haiku: %q by %q", to, why)
}
if to, why := desktopMove("chatflowsai/claude-opus-5-5", turn, false, false); to != "chatflowsai/claude-opus-5-5" || why != "" {
t.Errorf("opus turn: %q by %q", to, why)
}
}
+27 -2
View File
@@ -155,6 +155,16 @@ func wiresOf(ctx context.Context) map[string]string {
return settings.Shared().Wires()
}
// The reasons serve gives a model move of its own (ModelMove.Why);
// Claude Desktop's are desktopMove's.
const (
movedClassifier = "classifier" // Claude Code's auto mode classifier: the model /model moved its tier to
movedClaudeTier = "claude-tier" // Claude Code's full id of a Claude model: the model set for its tier
movedStandIn = "stand-in" // a model magpie doesn't serve: the one the agent's config names
movedCodexTurn = "codex-turn" // Codex's memory or auto-review call: its last turn's model
movedPrivacy = "privacy" // a request masking would change: Settings › Privacy's model for it
)
// standIn is StandIn's model for one magpie shows no entry for: not a
// catalog id or model, nor a ready provider's "provider/model".
func standIn(agent, asked string) string {
@@ -1922,12 +1932,22 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
// the group's, as "group/<id>" is, rather than one provider's that
// serves it: the Routing view shows the group it went to
asked = call.Model
// a stand-in below that puts the request on another model says so
// on its route, and why (Route.Moved)
var moved *ModelMove
move := func(to, why string) {
if why != "" && to != "" && to != call.Model {
moved = &ModelMove{To: to, Why: why}
}
}
desktopCheck := false // Claude Desktop's check that the gateway answers
if agent == "claude-desktop" {
sub, _ := subagentOf(r.Header)
probe := desktopProbe(body)
desktopCheck = probe
asked = desktopTurn(asked, body, fromClaudeCode(r.Header), sub != "")
var why string
asked, why = desktopMove(asked, body, fromClaudeCode(r.Header), sub != "")
move(asked, why)
if probe {
// tagged on the Routing page and in the ledger as the check it
// is: Desktop names its model itself, the first listed when no
@@ -1975,11 +1995,13 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
// Claude Code's auto mode classifier on its sonnet tier, which
// follows a main model /model has moved: the model it moved to
asked = grouped(at(m))
move(m, movedClassifier)
} else if m := claudeTierStandIn(r, agent, asked); m != "" {
// Claude Code (or a wrapper, T3 Code) naming one of Anthropic's
// models by its full id: the model it is set to use for that tier,
// whether or not magpie serves the id too
asked = grouped(at(m))
move(m, movedClaudeTier)
} else if g := grouped(asked); g != asked {
asked = g
} else if m := standIn(agent, asked); m != "" {
@@ -1988,9 +2010,11 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
// group, and its auto-review's codex-auto-review, stood in for by
// that same name, went on unresolved, a 404 (Adam on Discord)
asked = grouped(at(m))
move(m, movedStandIn)
}
if m := s.codexMemoryStandIn(r, call.Agent, agent, call.Kind, asked, body); m != "" {
asked = m
move(m, movedCodexTurn)
}
// a Codex subagent on the model set for Codex's subagents, whatever
// its lead asked for (willz on Discord), and a Claude Desktop
@@ -2092,6 +2116,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
g, ms, isGroup = provider.FindGroup(to)
g = g.Live()
sentWhole = true
move(to, movedPrivacy)
} else {
capture.ResponseWriter, body, unmask, maskedHits = rw, b, done, hits
}
@@ -2615,7 +2640,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
capture.tools = tools
}
tierAsked := bodyTier(from, body) // the service tier the client asked for (#1784)
tr := s.trace.beginFor(r, Route{turn: turn, dirOf: dirOf(from, plain), tools: tools, imageTurn: drawingTurnID(metadata.Turn), imageCaller: codexTurnKey(r, call.Agent), TitleLink: link, Pinned: pin, Time: start, Agent: call.Agent, Session: sessionOf(r.Header), Conv: convOf(r.Header, body), ParentSession: titleParentSession(r.Header, metadata, call.Kind), Kind: call.Kind, For: call.For, Model: call.Model, Effort: requestEffort(from, body), Tier: tierAsked, Provider: p.ID, Group: group, Rule: hit, Nested: nested, SealedTask: sealedTask, LeadAccount: leadAccount, Compaction: compactionWho(checkpoint), Subagent: subagent, SubagentEffort: subagentEffort, Sub: subOf(r.Header), SubagentID: subagentID, Affinity: shown, Order: pl.order, Left: append(slices.Clip(pl.left), smallW...)})
tr := s.trace.beginFor(r, Route{turn: turn, dirOf: dirOf(from, plain), tools: tools, imageTurn: drawingTurnID(metadata.Turn), imageCaller: codexTurnKey(r, call.Agent), TitleLink: link, Pinned: pin, Time: start, Agent: call.Agent, Session: sessionOf(r.Header), Conv: convOf(r.Header, body), ParentSession: titleParentSession(r.Header, metadata, call.Kind), Kind: call.Kind, For: call.For, Model: call.Model, Effort: requestEffort(from, body), Tier: tierAsked, Provider: p.ID, Group: group, Rule: hit, Nested: nested, SealedTask: sealedTask, LeadAccount: leadAccount, Compaction: compactionWho(checkpoint), Subagent: subagent, Moved: moved, SubagentEffort: subagentEffort, Sub: subOf(r.Header), SubagentID: subagentID, Affinity: shown, Order: pl.order, Left: append(slices.Clip(pl.left), smallW...)})
if watched != nil {
watched.routeID = tr.ID
}
+18
View File
@@ -31,6 +31,20 @@ import (
const traceKeep = 60
// Route is one request's way through routing.
// ModelMove is a stand-in that put a request on another model than the one
// it named: To, the model it went on (before a routing group's pick), and
// Why, a word the Routing page says it by. A Desktop's own call (desktopMove's
// reasons), Claude Code's tiers (movedClaudeTier, movedClassifier), an
// agent's configured stand-in (movedStandIn), Codex's last turn's model
// (movedCodexTurn) and Privacy's unmasked route (movedPrivacy). Without it
// a row read "asked for chatflowsai/claude-opus-5-5 → agentrouter" with
// nothing to say a title, not the user's turn, was put on the chat's model
// (Neo on Discord).
type ModelMove struct {
To string `json:"to"`
Why string `json:"why"`
}
type Route struct {
// callerKey: the gateway key the request came with, so a key held to
// a budget, models or accounts is told the routes of its own requests
@@ -71,6 +85,10 @@ type Route struct {
// Subagent is a Codex or Claude Desktop subagent's request put on
// the model set for its subagents, or kept on the one asked for and why
Subagent *SubagentPick `json:"subagent,omitempty"`
// Moved: the request was served on another model than Model names,
// by one of magpie's stand-ins, and why (ModelMove); nil when it went
// where it asked, or to a routing group by its name
Moved *ModelMove `json:"moved,omitempty"`
// Sub: the Claude Code subagent the request is of (subagentOf), whose
// session header is its conversation's; "" for the conversation's own
Sub string `json:"sub,omitempty"`
+44 -5
View File
@@ -2937,6 +2937,7 @@ function routingPage(part) {
: t("{agent} asked for {model}", { agent: agentName(r.agent), model: r.model }) + " → " + (main?.name || r.provider), ""]);
if (tagKind(r)) items.push([kindWhy(r), "aside kind"]);
else if (r.subagent) items.push([subagentWhy(r), "aside"]);
if (movedSays(r)) items.push([movedWhy(r), tagKind(r) ? "aside" : "aside stood"]);
if (r.subagentEffort) items.push([t("The subagent effort set in magpie is {effort}; the model's supported levels and a routing group's fixed member effort still apply.", { effort: t(r.subagentEffort) }), "aside"]);
if (r.sealedTask) items.push([t(r.group
? "This subagent task is encrypted. Only ChatGPT accounts can read it; other providers (such as Claude) are excluded regardless of quota."
@@ -3014,6 +3015,7 @@ function routingPage(part) {
li.dataset.k = k;
li.append(...(/^(why|ok|bad|wait|aside)$/.test(c) ? logoed(s, r, w) : [s]));
if (c === "aside kind") li.prepend(kindTag(r), " ");
if (c === "aside stood") li.prepend(movedTag(r), " ");
if (c === "swap") li.prepend(swapTag(tr), " ");
if (c === "aside time") li.replaceChildren(timeElement(tr));
if (c === "aside held") li.append(" ", ...heldActions(tr.model));
@@ -3157,6 +3159,41 @@ function routingPage(part) {
? t("{agent} requested a subagent on {model} and it stayed there: its subagents are set to {to}, but {why}.", { agent, model: r.subagent.asked, to: r.subagent.to, why: t(r.subagent.kept) })
: t("{agent} requested a subagent on {model}; magpie put it on {to}, the model set for its subagents.", { agent, model: r.subagent.asked, to: r.subagent.to });
}
// a request a stand-in of magpie's put on another model than it named
// (Route.Moved): why, on its row's tag, its title and its story. Neo on
// Discord read "chatflowsai/claude-opus-5-5 → AgentRouter · gpt-6.1-sol"
// as magpie swapping the model, where it was Claude Desktop's title, on
// a model Desktop picked itself, kept on the chat's model
// Desktop's connection check says where it went in its own story
// (kindWhy), so its move isn't said again
function movedSays(r) { return !!r.moved && r.kind !== "connection_check"; }
function movedWhy(r) {
const agent = agentName(r.agent), v = { agent, model: r.model, to: r.moved.to };
switch (r.moved.why) {
case "desktop-title": return t("{agent} picked {model} by itself for a short request without tools, such as a chat's title; magpie served it on {to}, the model of its latest chat turn, so it stays with the provider the chat is on.", v);
case "desktop-title-first": return t("{agent} picked {model} by itself for a short request without tools, such as a chat's title; magpie served it on {to}, the first model it lists, as it has had no chat turn yet.", v);
case "desktop-gone": return t("{agent} asked for {model}, which magpie doesn't serve; magpie served it on {to}, the model of its latest chat turn.", v);
case "desktop-gone-first": return t("{agent} asked for {model}, which magpie doesn't serve; magpie served it on {to}, the first model it lists.", v);
case "desktop-tier": return t("Claude Code in {agent} asked for {model}, its own id for a Claude tier; magpie served it on {to}, the model picked for that tier.", v);
case "desktop-beside": return t("Claude Code in {agent} asked for {model} for a call of its own; magpie served it on {to}, that tier's model on the provider the chat is on.", v);
case "desktop-aside": return t("Claude Code in {agent} asked for {model} for a call of its own; magpie served it on {to}, the chat's model, so it stays with the provider the chat is on.", v);
case "classifier": return t("{agent}'s auto mode classifier asked for {model}; magpie served it on {to}, the model /model moved its tier to.", v);
case "claude-tier": return t("{agent} asked for {model} by Claude's full id; magpie served it on {to}, the model set for that tier.", v);
case "stand-in": return t("{agent} asked for {model}, which magpie doesn't serve; magpie served it on {to}, the model its config names.", v);
case "codex-turn": return t("{agent} asked for {model} for a call of its own, which magpie doesn't serve; magpie served it on {to}, the model its last turn was answered on.", v);
case "privacy": return t("Masking would have changed this request, so magpie sent it as written to {to}, the model set for that in Settings › Privacy.", v);
default: return t("magpie served it on {to} in place of {model}.", v);
}
}
function movedTag(r) {
const why = r.moved.why;
const k = el("span", "kind stood", /^desktop-title/.test(why) ? kindName("title") : t("Stand-in"));
k.title = movedWhy(r);
return k;
}
// the tag a request's row has: what the call was for, else why magpie
// put it on another model
const rowTags = (r) => tagKind(r) ? [kindTag(r)] : movedSays(r) ? [movedTag(r)] : [];
function kindWhy(r) {
const agent = agentName(r.agent);
if (purposeOf(tagKind(r)) === "kind:collab_spawn" && r.subagent) return subagentWhy(r);
@@ -3247,8 +3284,9 @@ function routingPage(part) {
// the row no longer says (#337)
function reqTitle(r, how, tr) {
const head = `${agentName(r.agent)} · ${r.model} → `;
// the folder its agent works in, the last two levels of it (#1068)
const folder = r.folder ? "\n" + t("Folder") + ": " + r.folder : "";
// the folder its agent works in, the last two levels of it (#1068),
// and why it went on another model than it named
const folder = (movedSays(r) ? "\n" + movedWhy(r) : "") + (r.folder ? "\n" + t("Folder") + ": " + r.folder : "");
const w = how !== "bad" && r.tries.length > 1 && tr && tried(r, tr);
if (!w) return head + r.provider + folder;
const first = r.tries[0], f = tried(r, first);
@@ -3857,7 +3895,8 @@ function routingPage(part) {
const sw = el("i", "ag");
sw.style.setProperty("--agent", hueOf(r.agent));
asked.append(sw, icon(ag?.icon || "generic"), el("span", "m", r.model));
if (tagKind(r)) { asked.classList.add("kinded"); asked.append(kindTag(r)); }
const tags = rowTags(r);
if (tags.length) { asked.classList.add("kinded"); asked.append(...tags); }
// the reasoning the model was sent at — the turn's pick, or the
// agent's fitted to the model's levels — after the one the agent
// asked for when that was another (xhigh → max), so a level the
@@ -4503,7 +4542,7 @@ function routingPage(part) {
sw.style.setProperty("--agent", hueOf(r.agent));
const [said] = outcome(r);
row.append(el("span", "rp-n", t("request {i} of {n}", { i: g.n, n: p.plan.length })), sw,
el("b", "", agentName(r.agent)), el("code", "mdl", r.model), ...(tagKind(r) ? [kindTag(r)] : []), el("span", "rp-to", "→ " + said),
el("b", "", agentName(r.agent)), el("code", "mdl", r.model), ...rowTags(r), el("span", "rp-to", "→ " + said),
el("span", "rp-at", t("sent {time}", { time: new Date(r.time).toLocaleTimeString(intlLang(), { hour: "2-digit", minute: "2-digit", second: "2-digit", hour12: false }) })));
row.onclick = () => { cur = r; renderLog(); };
return row;
@@ -7685,7 +7724,7 @@ function routingPage(part) {
const ag = agentOf(r.agent);
const asked = el("span", "pr-a");
asked.append(icon(ag?.icon || "generic"), el("span", "pr-who", agentName(r.agent)), el("code", "m", r.model));
if (tagKind(r)) asked.append(kindTag(r));
asked.append(...rowTags(r));
const when = el("span", "at", new Date(r.time).toLocaleTimeString(intlLang(), { hour: "2-digit", minute: "2-digit", second: "2-digit", hourCycle: "h23" }));
// where it went: the provider, the account or key, and the model that
// answered — marked when the reply names another than the one sent
@@ -460,6 +460,20 @@ magpie.strings({
"{who} is left out: {name} lists {model} to its other keys, not this one.": "{who} 不参与:{name} 只为其他 key 列出了 {model},未为此 key 列出。",
"{who} is answering…": "{who} 正在回答…",
"rerouted from {from}": "改道自 {from}",
"{agent} picked {model} by itself for a short request without tools, such as a chat's title; magpie served it on {to}, the model of its latest chat turn, so it stays with the provider the chat is on.": "{agent} 自行选了 {model} 来发一个不带工具的短请求(比如对话标题);magpie 让 {to} 来处理,即它最近一轮对话所用的模型,这样它留在对话所在的服务商。",
"{agent} picked {model} by itself for a short request without tools, such as a chat's title; magpie served it on {to}, the first model it lists, as it has had no chat turn yet.": "{agent} 自行选了 {model} 来发一个不带工具的短请求(比如对话标题);magpie 让 {to} 来处理,即它列出的第一个模型,因为它还没有过对话轮次。",
"{agent} asked for {model}, which magpie doesn't serve; magpie served it on {to}, the model of its latest chat turn.": "{agent} 请求了 {model},但 magpie 不提供它;magpie 让 {to} 来处理,即它最近一轮对话所用的模型。",
"{agent} asked for {model}, which magpie doesn't serve; magpie served it on {to}, the first model it lists.": "{agent} 请求了 {model},但 magpie 不提供它;magpie 让 {to} 来处理,即它列出的第一个模型。",
"Claude Code in {agent} asked for {model}, its own id for a Claude tier; magpie served it on {to}, the model picked for that tier.": "{agent} 里的 Claude Code 用它自己的 Claude 档位 id 请求了 {model};magpie 让 {to} 来处理,即为该档位选的模型。",
"Claude Code in {agent} asked for {model} for a call of its own; magpie served it on {to}, that tier's model on the provider the chat is on.": "{agent} 里的 Claude Code 为它自己的调用请求了 {model};magpie 让 {to} 来处理,即对话所在服务商上该档位的模型。",
"Claude Code in {agent} asked for {model} for a call of its own; magpie served it on {to}, the chat's model, so it stays with the provider the chat is on.": "{agent} 里的 Claude Code 为它自己的调用请求了 {model};magpie 让 {to} 来处理,即对话所用的模型,这样它留在对话所在的服务商。",
"{agent}'s auto mode classifier asked for {model}; magpie served it on {to}, the model /model moved its tier to.": "{agent} 的自动模式分类器请求了 {model};magpie 让 {to} 来处理,即 /model 把该档位改成的模型。",
"{agent} asked for {model} by Claude's full id; magpie served it on {to}, the model set for that tier.": "{agent} 用 Claude 的完整 id 请求了 {model};magpie 让 {to} 来处理,即为该档位设定的模型。",
"{agent} asked for {model}, which magpie doesn't serve; magpie served it on {to}, the model its config names.": "{agent} 请求了 {model},但 magpie 不提供它;magpie 让 {to} 来处理,即它配置里写的模型。",
"{agent} asked for {model} for a call of its own, which magpie doesn't serve; magpie served it on {to}, the model its last turn was answered on.": "{agent} 为它自己的调用请求了 {model},但 magpie 不提供它;magpie 让 {to} 来处理,即它上一轮所用的模型。",
"Masking would have changed this request, so magpie sent it as written to {to}, the model set for that in Settings › Privacy.": "脱敏会改动这个请求,所以 magpie 把它原样发给了 {to},即在 设置 › 隐私 里为此设定的模型。",
"magpie served it on {to} in place of {model}.": "magpie 让 {to} 代替 {model} 处理了它。",
"Stand-in": "替代",
"{who} answered in {ms}{tk}. {agent} got one clean reply and never saw the {n} that failed first.": "{who} 用 {ms} 完成回答{tk}。{agent} 只收到一次正常回复,看不到之前失败的 {n} 次。",
"{who} answered in {ms}{tk}.": "{who} 用 {ms} 完成回答{tk}。",
"{who} answered {status} · {fail}. {how}; the request goes on to {next} before any of the reply reaches {agent}.": "{who} 返回 {status} · {fail}。{how};请求在回复到达 {agent} 前转给 {next}。",
@@ -1067,6 +1081,20 @@ magpie.strings({
"{who} is left out: {name} lists {model} to its other keys, not this one.": "{who} 不參與:{name} 只為其他 key 列出了 {model},未為此 key 列出。",
"{who} is answering…": "{who} 正在回答…",
"rerouted from {from}": "改道自 {from}",
"{agent} picked {model} by itself for a short request without tools, such as a chat's title; magpie served it on {to}, the model of its latest chat turn, so it stays with the provider the chat is on.": "{agent} 自行選了 {model} 來發一個不帶工具的短請求(例如對話標題);magpie 讓 {to} 來處理,即它最近一輪對話所用的模型,這樣它留在對話所在的服務商。",
"{agent} picked {model} by itself for a short request without tools, such as a chat's title; magpie served it on {to}, the first model it lists, as it has had no chat turn yet.": "{agent} 自行選了 {model} 來發一個不帶工具的短請求(例如對話標題);magpie 讓 {to} 來處理,即它列出的第一個模型,因為它還沒有過對話輪次。",
"{agent} asked for {model}, which magpie doesn't serve; magpie served it on {to}, the model of its latest chat turn.": "{agent} 請求了 {model},但 magpie 不提供它;magpie 讓 {to} 來處理,即它最近一輪對話所用的模型。",
"{agent} asked for {model}, which magpie doesn't serve; magpie served it on {to}, the first model it lists.": "{agent} 請求了 {model},但 magpie 不提供它;magpie 讓 {to} 來處理,即它列出的第一個模型。",
"Claude Code in {agent} asked for {model}, its own id for a Claude tier; magpie served it on {to}, the model picked for that tier.": "{agent} 裡的 Claude Code 用它自己的 Claude 檔位 id 請求了 {model};magpie 讓 {to} 來處理,即為該檔位選的模型。",
"Claude Code in {agent} asked for {model} for a call of its own; magpie served it on {to}, that tier's model on the provider the chat is on.": "{agent} 裡的 Claude Code 為它自己的呼叫請求了 {model};magpie 讓 {to} 來處理,即對話所在服務商上該檔位的模型。",
"Claude Code in {agent} asked for {model} for a call of its own; magpie served it on {to}, the chat's model, so it stays with the provider the chat is on.": "{agent} 裡的 Claude Code 為它自己的呼叫請求了 {model};magpie 讓 {to} 來處理,即對話所用的模型,這樣它留在對話所在的服務商。",
"{agent}'s auto mode classifier asked for {model}; magpie served it on {to}, the model /model moved its tier to.": "{agent} 的自動模式分類器請求了 {model};magpie 讓 {to} 來處理,即 /model 把該檔位改成的模型。",
"{agent} asked for {model} by Claude's full id; magpie served it on {to}, the model set for that tier.": "{agent} 用 Claude 的完整 id 請求了 {model};magpie 讓 {to} 來處理,即為該檔位設定的模型。",
"{agent} asked for {model}, which magpie doesn't serve; magpie served it on {to}, the model its config names.": "{agent} 請求了 {model},但 magpie 不提供它;magpie 讓 {to} 來處理,即它設定裡寫的模型。",
"{agent} asked for {model} for a call of its own, which magpie doesn't serve; magpie served it on {to}, the model its last turn was answered on.": "{agent} 為它自己的呼叫請求了 {model},但 magpie 不提供它;magpie 讓 {to} 來處理,即它上一輪所用的模型。",
"Masking would have changed this request, so magpie sent it as written to {to}, the model set for that in Settings › Privacy.": "去識別化會改動這個請求,所以 magpie 把它原樣送給了 {to},即在 設定 › 隱私 裡為此設定的模型。",
"magpie served it on {to} in place of {model}.": "magpie 讓 {to} 代替 {model} 處理了它。",
"Stand-in": "替代",
"{who} answered in {ms}{tk}. {agent} got one clean reply and never saw the {n} that failed first.": "{who} 用 {ms} 完成回答{tk}。{agent} 只收到一次正常回覆,看不到之前失敗的 {n} 次。",
"{who} answered in {ms}{tk}.": "{who} 用 {ms} 完成回答{tk}。",
"{who} answered {status} · {fail}. {how}; the request goes on to {next} before any of the reply reaches {agent}.": "{who} 返回 {status} · {fail}。{how};請求在回覆到達 {agent} 前轉給 {next}。",
@@ -1672,6 +1700,20 @@ magpie.strings({
"{who} is left out: {name} lists {model} to its other keys, not this one.": "{who} は除外:{name} は {model} をこのキーではなく他のキーに割り当てています。",
"{who} is answering…": "{who} が応答中…",
"rerouted from {from}": "{from} から迂回",
"{agent} picked {model} by itself for a short request without tools, such as a chat's title; magpie served it on {to}, the model of its latest chat turn, so it stays with the provider the chat is on.": "{agent} はツールなしの短いリクエスト(チャットのタイトルなど)に {model} を自分で選びました。magpie は {to}(直近のチャットのターンのモデル)で応答し、チャットと同じプロバイダーに留めました。",
"{agent} picked {model} by itself for a short request without tools, such as a chat's title; magpie served it on {to}, the first model it lists, as it has had no chat turn yet.": "{agent} はツールなしの短いリクエスト(チャットのタイトルなど)に {model} を自分で選びました。まだチャットのターンがないため、magpie は {to}(一覧の最初のモデル)で応答しました。",
"{agent} asked for {model}, which magpie doesn't serve; magpie served it on {to}, the model of its latest chat turn.": "{agent} は magpie が提供していない {model} をリクエストしました。magpie は {to}(直近のチャットのターンのモデル)で応答しました。",
"{agent} asked for {model}, which magpie doesn't serve; magpie served it on {to}, the first model it lists.": "{agent} は magpie が提供していない {model} をリクエストしました。magpie は {to}(一覧の最初のモデル)で応答しました。",
"Claude Code in {agent} asked for {model}, its own id for a Claude tier; magpie served it on {to}, the model picked for that tier.": "{agent} の Claude Code が Claude のティアの独自 id で {model} をリクエストしました。magpie は {to}(そのティアに選ばれたモデル)で応答しました。",
"Claude Code in {agent} asked for {model} for a call of its own; magpie served it on {to}, that tier's model on the provider the chat is on.": "{agent} の Claude Code が自身の呼び出しに {model} をリクエストしました。magpie は {to}(チャットのプロバイダーにあるそのティアのモデル)で応答しました。",
"Claude Code in {agent} asked for {model} for a call of its own; magpie served it on {to}, the chat's model, so it stays with the provider the chat is on.": "{agent} の Claude Code が自身の呼び出しに {model} をリクエストしました。magpie は {to}(チャットのモデル)で応答し、チャットと同じプロバイダーに留めました。",
"{agent}'s auto mode classifier asked for {model}; magpie served it on {to}, the model /model moved its tier to.": "{agent} の自動モードの分類器が {model} をリクエストしました。magpie は {to}(/model がそのティアを移したモデル)で応答しました。",
"{agent} asked for {model} by Claude's full id; magpie served it on {to}, the model set for that tier.": "{agent} が Claude の完全な id で {model} をリクエストしました。magpie は {to}(そのティアに設定されたモデル)で応答しました。",
"{agent} asked for {model}, which magpie doesn't serve; magpie served it on {to}, the model its config names.": "{agent} は magpie が提供していない {model} をリクエストしました。magpie は {to}(設定に書かれたモデル)で応答しました。",
"{agent} asked for {model} for a call of its own, which magpie doesn't serve; magpie served it on {to}, the model its last turn was answered on.": "{agent} は自身の呼び出しに magpie が提供していない {model} をリクエストしました。magpie は {to}(直前のターンに応答したモデル)で応答しました。",
"Masking would have changed this request, so magpie sent it as written to {to}, the model set for that in Settings › Privacy.": "マスキングでこのリクエストが変わるため、magpie はそのまま {to}(設定 › プライバシーで指定されたモデル)に送りました。",
"magpie served it on {to} in place of {model}.": "magpie は {model} の代わりに {to} で応答しました。",
"Stand-in": "代替",
"{who} answered in {ms}{tk}. {agent} got one clean reply and never saw the {n} that failed first.": "{who} が {ms}{tk} で応答しました。{agent} にはクリーンな応答が 1 つ届き、先に失敗した {n} 件は見えていません。",
"{who} answered in {ms}{tk}.": "{who} が {ms}{tk} で応答しました。",
"{who} answered {status} · {fail}. {how}; the request goes on to {next} before any of the reply reaches {agent}.": "{who} が {status} · {fail} を返しました。{how}。応答が {agent} に届く前に、リクエストは {next} に回ります。",
@@ -2279,6 +2321,20 @@ magpie.strings({
"{who} is left out: {name} lists {model} to its other keys, not this one.": "{who} bleibt außen vor: {name} listet {model} für seine anderen Schlüssel, nicht für diesen.",
"{who} is answering…": "{who} antwortet…",
"rerouted from {from}": "umgeleitet von {from}",
"{agent} picked {model} by itself for a short request without tools, such as a chat's title; magpie served it on {to}, the model of its latest chat turn, so it stays with the provider the chat is on.": "{agent} hat {model} selbst für eine kurze Anfrage ohne Werkzeuge gewählt, etwa den Titel eines Chats; magpie hat sie mit {to} beantwortet, dem Modell seines letzten Chat-Zugs, damit sie beim Anbieter des Chats bleibt.",
"{agent} picked {model} by itself for a short request without tools, such as a chat's title; magpie served it on {to}, the first model it lists, as it has had no chat turn yet.": "{agent} hat {model} selbst für eine kurze Anfrage ohne Werkzeuge gewählt, etwa den Titel eines Chats; magpie hat sie mit {to} beantwortet, dem ersten Modell seiner Liste, da es noch keinen Chat-Zug gab.",
"{agent} asked for {model}, which magpie doesn't serve; magpie served it on {to}, the model of its latest chat turn.": "{agent} hat {model} angefordert, das magpie nicht anbietet; magpie hat sie mit {to} beantwortet, dem Modell seines letzten Chat-Zugs.",
"{agent} asked for {model}, which magpie doesn't serve; magpie served it on {to}, the first model it lists.": "{agent} hat {model} angefordert, das magpie nicht anbietet; magpie hat sie mit {to} beantwortet, dem ersten Modell seiner Liste.",
"Claude Code in {agent} asked for {model}, its own id for a Claude tier; magpie served it on {to}, the model picked for that tier.": "Claude Code in {agent} hat {model} mit seiner eigenen ID für eine Claude-Stufe angefordert; magpie hat sie mit {to} beantwortet, dem für diese Stufe gewählten Modell.",
"Claude Code in {agent} asked for {model} for a call of its own; magpie served it on {to}, that tier's model on the provider the chat is on.": "Claude Code in {agent} hat {model} für einen eigenen Aufruf angefordert; magpie hat ihn mit {to} beantwortet, dem Modell dieser Stufe beim Anbieter des Chats.",
"Claude Code in {agent} asked for {model} for a call of its own; magpie served it on {to}, the chat's model, so it stays with the provider the chat is on.": "Claude Code in {agent} hat {model} für einen eigenen Aufruf angefordert; magpie hat ihn mit {to} beantwortet, dem Modell des Chats, damit er beim Anbieter des Chats bleibt.",
"{agent}'s auto mode classifier asked for {model}; magpie served it on {to}, the model /model moved its tier to.": "Der Klassifikator des Automodus von {agent} hat {model} angefordert; magpie hat ihn mit {to} beantwortet, dem Modell, auf das /model seine Stufe gesetzt hat.",
"{agent} asked for {model} by Claude's full id; magpie served it on {to}, the model set for that tier.": "{agent} hat {model} mit Claudes voller ID angefordert; magpie hat sie mit {to} beantwortet, dem für diese Stufe festgelegten Modell.",
"{agent} asked for {model}, which magpie doesn't serve; magpie served it on {to}, the model its config names.": "{agent} hat {model} angefordert, das magpie nicht anbietet; magpie hat sie mit {to} beantwortet, dem Modell aus seiner Konfiguration.",
"{agent} asked for {model} for a call of its own, which magpie doesn't serve; magpie served it on {to}, the model its last turn was answered on.": "{agent} hat für einen eigenen Aufruf {model} angefordert, das magpie nicht anbietet; magpie hat ihn mit {to} beantwortet, dem Modell, das seinen letzten Zug beantwortet hat.",
"Masking would have changed this request, so magpie sent it as written to {to}, the model set for that in Settings › Privacy.": "Die Maskierung hätte diese Anfrage verändert, daher hat magpie sie unverändert an {to} gesendet, das dafür unter Einstellungen › Datenschutz festgelegte Modell.",
"magpie served it on {to} in place of {model}.": "magpie hat sie mit {to} statt {model} beantwortet.",
"Stand-in": "Ersatz",
"{who} answered in {ms}{tk}. {agent} got one clean reply and never saw the {n} that failed first.": "{who} antwortete in {ms}{tk}. {agent} erhielt eine saubere Antwort und sah die {n} vorherigen Fehlschläge nie.",
"{who} answered in {ms}{tk}.": "{who} antwortete in {ms}{tk}.",
"{who} answered {status} · {fail}. {how}; the request goes on to {next} before any of the reply reaches {agent}.": "{who} antwortete mit {status} · {fail}. {how}; die Anfrage geht an {next}, bevor etwas von der Antwort {agent} erreicht.",
@@ -0,0 +1,186 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// Neo on Discord read a Requests row, "chatflowsai/claude-opus-5-5 →
// AgentRouter · gpt-6.1-sol", as Claude Desktop asking for another
// provider's model, with nothing saying why. A route magpie put on another
// model than the agent named (Route.Moved) is tagged in the list by request
// and by session, in the replay and the tray panel, and says why under the
// pointer, in the row's title and once in the story. A kind's tag wins, and
// its story says the move too, but for Desktop's connection check, whose
// own story says where it went; a route served as asked has no tag. All
// APIs are faked.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const assets = path.resolve(__dirname, "../assets");
const now = Date.now();
const at = (min) => new Date(now - min * 60e3).toISOString();
const seat = (provider, model) => ({ id: provider, provider, name: provider, who: "Test key", kind: "key", model });
const req = (id, agent, session, model, provider, sent, extra = {}) => ({ id, seq: id, time: at(9 - id), agent, session, model, provider,
order: [seat(provider, sent)], tries: [{ id: provider, model: sent, start: at(9 - id), done: true, status: 200, ms: 900 }],
done: true, status: 200, ms: 900, tokens: 1200, ...extra });
const opus = "chatflowsai/claude-opus-5-5", gpt = "agentrouter/gpt-6.1-sol";
// Newest first, as the list shows them. The oldest replays first.
const routes = [
req(5, "claude-desktop", "desk", gpt, "agentrouter", "gpt-6.1-sol"),
req(4, "claude-desktop", "", opus, "agentrouter", "gpt-6.1-sol", { kind: "connection_check", moved: { to: gpt, why: "desktop-check" } }),
req(3, "claude", "term", "fake/m1", "fake", "m2", { moved: { to: "fake/m2", why: "privacy" } }),
req(2, "codex", "cx", "fake/m1", "fake", "m2", { kind: "review", moved: { to: "fake/m2", why: "codex-turn" } }),
req(1, "claude-desktop", "", opus, "agentrouter", "gpt-6.1-sol", { moved: { to: gpt, why: "desktop-title" } }),
];
function serve(lang) {
const state = { agents: [{ id: "claude-desktop", name: "Claude Desktop", fields: [] }, { id: "claude", name: "Claude Code", fields: [] }, { id: "codex", name: "Codex", fields: [] }],
profiles: [], settings: { lang, theme: "light" } };
return async (route) => {
const url = new URL(route.request().url());
const json = (data) => route.fulfill({ json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json(state);
if (url.pathname === "/api/gateway/trace") {
if (url.searchParams.has("wait")) return new Promise(() => {});
return json({ mine: true, now: new Date().toISOString(), seq: 5, totals: { requests: 5, rerouted: 0, errors: 0 }, routes });
}
if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] });
if (url.pathname === "/api/gateway/session-titles") return json({ titles: {} });
if (url.pathname === "/api/usage" && url.searchParams.get("period") === "today") return json({ calls: 5, input: 0, output: 0, cache_read: 0, cache_write: 0, reasoning: 0, cost: 0, series: [] });
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } });
if (url.pathname === "/api/usage/quotas") return json([]);
if (url.pathname === "/api/window/fit") return route.fulfill({ status: 204 });
if (url.pathname.startsWith("/api/")) return json({});
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
return route.fulfill({ body: await fs.readFile(file), contentType });
};
}
// Expected reader-facing words, independent of the translation lookup.
const W = {
en: { title: "Title", check: "Connection check", stood: "Stand-in", review: "Review",
titleWhy: "Claude Desktop picked chatflowsai/claude-opus-5-5 by itself for a short request without tools, such as a chat's title; magpie served it on agentrouter/gpt-6.1-sol, the model of its latest chat turn, so it stays with the provider the chat is on.",
privacy: "Masking would have changed this request, so magpie sent it as written to fake/m2, the model set for that in Settings › Privacy.",
codex: "Codex asked for fake/m1 for a call of its own, which magpie doesn't serve; magpie served it on fake/m2, the model its last turn was answered on." },
zh: { title: "标题", check: "连接检查", stood: "替代", review: "审查",
titleWhy: "Claude Desktop 自行选了 chatflowsai/claude-opus-5-5 来发一个不带工具的短请求(比如对话标题);magpie 让 agentrouter/gpt-6.1-sol 来处理,即它最近一轮对话所用的模型,这样它留在对话所在的服务商。",
privacy: "脱敏会改动这个请求,所以 magpie 把它原样发给了 fake/m2,即在 设置 › 隐私 里为此设定的模型。",
codex: "Codex 为它自己的调用请求了 fake/m1,但 magpie 不提供它;magpie 让 fake/m2 来处理,即它上一轮所用的模型。" },
"zh-TW": { title: "標題", check: "連線檢查", stood: "替代", review: "審查",
titleWhy: "Claude Desktop 自行選了 chatflowsai/claude-opus-5-5 來發一個不帶工具的短請求(例如對話標題);magpie 讓 agentrouter/gpt-6.1-sol 來處理,即它最近一輪對話所用的模型,這樣它留在對話所在的服務商。",
privacy: "去識別化會改動這個請求,所以 magpie 把它原樣送給了 fake/m2,即在 設定 › 隱私 裡為此設定的模型。",
codex: "Codex 為它自己的呼叫請求了 fake/m1,但 magpie 不提供它;magpie 讓 fake/m2 來處理,即它上一輪所用的模型。" },
ja: { title: "タイトル", check: "接続チェック", stood: "代替", review: "レビュー",
titleWhy: "Claude Desktop はツールなしの短いリクエスト(チャットのタイトルなど)に chatflowsai/claude-opus-5-5 を自分で選びました。magpie は agentrouter/gpt-6.1-sol(直近のチャットのターンのモデル)で応答し、チャットと同じプロバイダーに留めました。",
privacy: "マスキングでこのリクエストが変わるため、magpie はそのまま fake/m2(設定 › プライバシーで指定されたモデル)に送りました。",
codex: "Codex は自身の呼び出しに magpie が提供していない fake/m1 をリクエストしました。magpie は fake/m2(直前のターンに応答したモデル)で応答しました。" },
de: { title: "Titel", check: "Verbindungstest", stood: "Ersatz", review: "Review",
titleWhy: "Claude Desktop hat chatflowsai/claude-opus-5-5 selbst für eine kurze Anfrage ohne Werkzeuge gewählt, etwa den Titel eines Chats; magpie hat sie mit agentrouter/gpt-6.1-sol beantwortet, dem Modell seines letzten Chat-Zugs, damit sie beim Anbieter des Chats bleibt.",
privacy: "Die Maskierung hätte diese Anfrage verändert, daher hat magpie sie unverändert an fake/m2 gesendet, das dafür unter Einstellungen › Datenschutz festgelegte Modell.",
codex: "Codex hat für einen eigenen Aufruf fake/m1 angefordert, das magpie nicht anbietet; magpie hat ihn mit fake/m2 beantwortet, dem Modell, das seinen letzten Zug beantwortet hat." },
};
const engines = process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"];
const langs = process.env.LANGS ? process.env.LANGS.split(",") : Object.keys(W);
for (const engine of engines) {
for (const lang of langs) {
for (const width of [1100, 420]) {
test(`${engine} ${lang} ${width}px: a request magpie put on another model says why`, async (t) => {
const w = W[lang];
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const errors = [], pages = [];
t.after(async () => {
if (process.env.ARTIFACT_DIR) {
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
for (const [i, p] of pages.entries()) await p.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-moved-why-${i}.png`) });
}
await browser.close();
});
const open = async (url, viewport, bySession = false) => {
const page = await browser.newPage({ viewport, reducedMotion: "reduce" });
pages.push(page);
page.setDefaultTimeout(5000);
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang));
await page.addInitScript((on) => localStorage.setItem("magpie.routingBySession", on ? "1" : "0"), bySession);
await page.goto(url);
return page;
};
const tags = (page, sel) => page.locator(sel).evaluateAll((rows) => rows.map((r) => {
const k = r.querySelectorAll(".kind");
return k.length > 1 ? "two tags" : k[0] ? [k[0].textContent, k[0].title] : ["", ""];
}));
const want = [["", ""], [w.check], [w.stood, w.privacy], [w.review], [w.title, w.titleWhy]];
const same = (got, msg) => assert.deepEqual(got.map((x, i) => want[i].length === 1 ? [x[0]] : x), want, msg);
const said = [null, null, w.privacy, w.codex, w.titleWhy];
// the list, by request: the tag beside the model, the reason under
// the pointer and in the row's title, nothing pushed out of the row
let page = await open("http://magpie.test/?view=routing", { width, height: 760 });
await page.locator(".rt-req").nth(routes.length - 1).waitFor();
same(await tags(page, ".rt-req"), "by request");
const titles = await page.locator(".rt-req").evaluateAll((rows) => rows.map((r) => r.title));
for (const [i, s] of said.entries()) {
if (s) assert(titles[i].includes("\n" + s), `row ${i} title: ${titles[i]}`);
else assert(!/magpie served|magpie sent it as written/.test(titles[i]), `row ${i} title: ${titles[i]}`);
}
const fits = await page.locator(".rt-req").evaluateAll((rows) => rows.map((r) => r.scrollWidth <= r.clientWidth + 1));
assert.deepEqual(fits, routes.map(() => true), "a row overflows");
// the story: the reason said once, with the tag when no kind has one
for (const [i, s] of said.entries()) {
if (i) {
await page.close();
page = await open("http://magpie.test/?view=routing", { width, height: 760 });
await page.locator(".rt-req").nth(routes.length - 1).waitFor();
}
await page.locator(".rt-req").nth(i).evaluate((e) => e.click());
await page.waitForFunction((i) => document.querySelectorAll(".rt-req")[i]?.getAttribute("aria-pressed") === "true", i);
const story = await page.locator(".rt-steps").textContent();
const stood = await page.locator(".rt-steps li.stood .kind").allTextContents();
if (!s) {
// served as asked, or Desktop's check, whose own story says it
assert.deepEqual(stood, [], `row ${i} has a stand-in line`);
continue;
}
assert.equal(story.split(s).length - 1, 1, `row ${i}: ${s}\nonce in\n${story}`);
assert.deepEqual(stood, i === 3 ? [] : [want[i][0]], `story tag of row ${i}`);
}
// the replay: the oldest, Desktop's title, goes first with its tag
await page.close();
page = await open("http://magpie.test/?view=routing", { width, height: 760 });
await page.locator(".rt-req").nth(routes.length - 1).waitFor();
const replay = await page.evaluate(() => t("Replay them all"));
await page.getByRole("button", { name: replay, exact: true }).evaluate((e) => e.click());
const played = await page.waitForFunction(() => {
const e = document.querySelector(".rp-what .rp-req");
return e && e.querySelector(".mdl") && { tag: e.querySelector(".kind")?.textContent || "", title: e.querySelector(".kind")?.title || "" };
}).then((h) => h.jsonValue());
assert.deepEqual(played, { tag: w.title, title: w.titleWhy });
await page.getByRole("button", { name: await page.evaluate(() => t("Stop replay")), exact: true }).evaluate((e) => e.click());
await page.waitForFunction(() => document.querySelector(".rt-replay").hidden);
// by session: the same tags and reasons
await page.close();
page = await open("http://magpie.test/?view=routing", { width, height: 760 }, true);
await page.locator(".rt-req").nth(routes.length - 1).waitFor();
const sorted = (xs) => xs.map((x) => x[0] === w.review || x[0] === w.check ? [x[0]] : x).map((x) => JSON.stringify(x)).sort();
assert.deepEqual(sorted(await tags(page, ".rt-req")), sorted(want), "by session");
// the tray panel's rows, from the live trace
const panel = await open("http://magpie.test/?mode=panel", { width: Math.min(width, 440), height: 600 });
await panel.locator('[data-ptab="routing"]').click();
await panel.locator(".pr-req").nth(routes.length - 1).waitFor();
const pr = await panel.locator(".pr-req").evaluateAll((rows) => rows.map((r) => [r.querySelector(".pr-a .kind")?.textContent || "", r.querySelector(".pr-a .kind")?.title || ""]));
same(pr, "panel");
const pt = await panel.locator(".pr-req").evaluateAll((rows) => rows.map((r) => r.title));
assert(pt[4].includes(w.titleWhy), `panel title: ${pt[4]}`);
assert.deepEqual(errors, []);
});
}
}
}