agent: magpie's own Claude work folder isn't Claude Code bypassing magpie (ifccod7391564 on X)

The bridge runs Claude Code in os.TempDir()'s magpie-claude-work(-<uid>),
and on the user's own home those prompts go into ~/.claude/history.jsonl
too. LastUsed read them as Claude Code used with none of its requests
reaching magpie, and the Agents page warned "Claude Code 最近绕过了
magpie". The owner's own history.jsonl has 1594 such lines, project
/private/var/folders/.../T/magpie-claude-work-501. LastUsed now passes
over lines whose project is that folder (inMagpieWork: the last path
element, either slash, so a Mac's /private/var, C:/…, C:\… and a WSL
mount all match; magpie-claude-workshop does not). lastJSONLTime takes a
skip; Codex's history.jsonl has no project and passes nil.

Run (wsl-run, magpie-desktop; mote refused SSH the whole time):
- go test -count=1 -timeout 45m ./internal/provider ./internal/agent:
  provider ok; agent ok but TestGrokInstalled, the known WSL2 binfmt
  red (#3548), unrelated
- TestClaudeBridgePromptsArentBypass, TestDriftBypassed on Windows: ok
- cross-OS go vet as in the provider commit; gofmt -l clean
Broken by hand: LastUsed with skip nil: the new test is red with the
reporter's bypassed drift.
Not tried: the GUI (no GUI change), the macOS run (mote down).
This commit is contained in:
yetone
2026-11-10 18:21:32 +08:00
parent 980a4b981f
commit bc0d9e8739
5 changed files with 72 additions and 7 deletions
+1 -1
View File
@@ -43,7 +43,7 @@ something else shows up as drift.
1. **Connect.** The Agents page's switch calls `ConnectHow` (`POST /api/agents/{action}/{id}` in [`internal/gui/api.go`](../../internal/gui/api.go)). It stashes the current values (`<id>.connect.was`). It brings back the models used before a switch-off (`reconnect`), or calls `Join` where the agent keeps its own model (Codex signed in with ChatGPT). `reconnect` calls `Join` first too, so a Codex switched off on a routing group comes back joined, as the switch first connected it: put back on the group alone it was beside its sign-in only, and an own model picked on the Agents page took it off magpie (NancyTom18 on X, `TestCodexReconnectStaysJoined`). One that can't join then (a provider of the user's own, magpie API) is connected as at first unless its own model was one of magpie's: its memories' or subagents' model put back alone read as connected while its own model stayed off magpie (#3868, `TestCodexOffAndOnJoinsAgainWithItsHelpersOnMagpie`). Otherwise it picks a model by the order `ConnectHow` documents and sets it through `Apply`.
2. **Pick.** `Pick` sets a field from the model picker. Picking one of magpie's models on an agent that isn't connected connects it first. Each row of a model picker that a provider served with a timed reply this week says how fast: tokens a second, or the first token's wait when only that was timed (`speedTag` in app.js, from `GET /api/model-speeds`, `modelSpeeds` in [`internal/gui/speeds.go`](../../internal/gui/speeds.go): the usage ledger's mean TTFT and decode speed by `provider/model`, the catalog ref an option carries). Under a search, rows that match equally go fastest first by about how long a 200-token reply takes (`speedRank`), the untimed last, so a model several providers serve lists the fastest one first (axuhere on X). Without a search the rows keep catalog order, grouped by provider. A routing group that always asks the fastest provider is the Speed first strategy ([gateway routing](gateway-routing.md)).
3. **Notice.** After a change the page shows `Notice` when the agent reads its config only at start-up and needs a restart. A field that is `Live` (`Field.Live`: magpie's own setting, which the gateway reads on each request, Claude Desktop's `subagent_model` and `subagent_effort`) needs no restart, so `POST /api/set` and `magpie <agent> <field> <value>` leave the Notice out after it, unless the pick connected the agent too (`Pick` on an agent not connected). A stopped WSL distro's copy of a field keeps the flag (`asleep`).
4. **Drift.** As the Agents page is drawn, `Drift` compares the config with `applied.json`. It runs `Check` first, then each field. An agent pointed at magpie through a reverse proxy is still on magpie (#1985, davisjiahao: a company's nginx at `https://ai.corp.example/magpie`). `wiringOff`, where most agents' `Check` compares a URL, and the checks of their own (Claude Code's managed settings, Reasonix's provider) take a URL that isn't magpie's when it ends with magpie's path, the rest is an http or https address on another machine (`onAnotherMachine`) or one on this machine's loopback with a path of its own (`loopbackWithPath`: the reporter's compliance proxy at `http://127.0.0.1:8788/claude-code-anthropic/<route>`; `proxyBase`), and `GET <rest>/` there answers as the gateway's own `GET /` does (`{"name":"magpie"}`, `magpieAt` in [`reach.go`](../../internal/agent/reach.go), tried in the background like `reachProbe`). Something else there (a relay CC Switch put in) is `unwired`, as is an address on this machine's loopback without a path, which is magpie's on an older port and is never tried. Until the answer is known it isn't drift, so Reconnect isn't offered and doesn't write the proxy away; port moves (`OnGateway`, `Rewire`) re-set only `unwired` agents, so they leave it too. Codex keeps such an address by magpie's key, as for #816 (`codexKeptGateway`: http or https, any port, a path before magpie's, loopback with a path). A model picked in Claude Code keeps it too once magpie has answered there (`surelyMagpie`; `routed` and `gwAt` in `claude.go`), so a proxy every request must go through isn't bypassed; at a relay, a pick points Claude Code at this magpie. Every write to Claude Code (a field's `Set`, `Sync`, `Unwire`) asks such an address first where magpie hasn't answered yet, and waits (`claudeAsk`, `magpieAsked`, as `codexProxyOK` does): unasked, it read as a relay, and the first write in a magpie just started (the CLI's: a pick, the `Sync` a provider added runs, Disconnect) wrote the proxy away, turned the auto mode review back on, or left magpie in and forgot the endpoint the user had. `Follow` writes nothing until the answer is in, and reads never wait. Claude Code's address is asked only while what it sends is for magpie (`claudeProxied`, `claudeKeyed`: a key the gateway takes, or none where it keeps its claude.ai sign-in through magpie): with a key of the user's own it is their endpoint, never asked, and the drift a model of magpie's name there shows says that address, or an administrator's in managed settings, as it is (`whatsOff`; zhangt2333, #3480: magpie sent `GET /` about every 30 s to the `ANTHROPIC_BASE_URL` of a Claude Code it never connected). Tests stub `magpieAt` in `TestMain` as known and not magpie. When the config is right and points at an address off loopback (a WSL twin under NAT, or this machine's Codex at an address the user kept, #816), it tries that address ([`reach.go`](../../internal/agent/reach.go)): in the background, at most every 20 s, never waited for. When nothing answers there while the gateway answers on loopback, the drift is `unreachable` (#1013), with what has to listen there: Share on local network, the user's portproxy, Windows' firewall. Then it checks whether the agent's latest use (`LastUsed`, `Reached`) reached the gateway: a request Codex's log says went to the host its config keeps magpie at, or one the gateway saw from it after (`lastSeen`), reached it.
4. **Drift.** As the Agents page is drawn, `Drift` compares the config with `applied.json`. It runs `Check` first, then each field. An agent pointed at magpie through a reverse proxy is still on magpie (#1985, davisjiahao: a company's nginx at `https://ai.corp.example/magpie`). `wiringOff`, where most agents' `Check` compares a URL, and the checks of their own (Claude Code's managed settings, Reasonix's provider) take a URL that isn't magpie's when it ends with magpie's path, the rest is an http or https address on another machine (`onAnotherMachine`) or one on this machine's loopback with a path of its own (`loopbackWithPath`: the reporter's compliance proxy at `http://127.0.0.1:8788/claude-code-anthropic/<route>`; `proxyBase`), and `GET <rest>/` there answers as the gateway's own `GET /` does (`{"name":"magpie"}`, `magpieAt` in [`reach.go`](../../internal/agent/reach.go), tried in the background like `reachProbe`). Something else there (a relay CC Switch put in) is `unwired`, as is an address on this machine's loopback without a path, which is magpie's on an older port and is never tried. Until the answer is known it isn't drift, so Reconnect isn't offered and doesn't write the proxy away; port moves (`OnGateway`, `Rewire`) re-set only `unwired` agents, so they leave it too. Codex keeps such an address by magpie's key, as for #816 (`codexKeptGateway`: http or https, any port, a path before magpie's, loopback with a path). A model picked in Claude Code keeps it too once magpie has answered there (`surelyMagpie`; `routed` and `gwAt` in `claude.go`), so a proxy every request must go through isn't bypassed; at a relay, a pick points Claude Code at this magpie. Every write to Claude Code (a field's `Set`, `Sync`, `Unwire`) asks such an address first where magpie hasn't answered yet, and waits (`claudeAsk`, `magpieAsked`, as `codexProxyOK` does): unasked, it read as a relay, and the first write in a magpie just started (the CLI's: a pick, the `Sync` a provider added runs, Disconnect) wrote the proxy away, turned the auto mode review back on, or left magpie in and forgot the endpoint the user had. `Follow` writes nothing until the answer is in, and reads never wait. Claude Code's address is asked only while what it sends is for magpie (`claudeProxied`, `claudeKeyed`: a key the gateway takes, or none where it keeps its claude.ai sign-in through magpie): with a key of the user's own it is their endpoint, never asked, and the drift a model of magpie's name there shows says that address, or an administrator's in managed settings, as it is (`whatsOff`; zhangt2333, #3480: magpie sent `GET /` about every 30 s to the `ANTHROPIC_BASE_URL` of a Claude Code it never connected). Tests stub `magpieAt` in `TestMain` as known and not magpie. When the config is right and points at an address off loopback (a WSL twin under NAT, or this machine's Codex at an address the user kept, #816), it tries that address ([`reach.go`](../../internal/agent/reach.go)): in the background, at most every 20 s, never waited for. When nothing answers there while the gateway answers on loopback, the drift is `unreachable` (#1013), with what has to listen there: Share on local network, the user's portproxy, Windows' firewall. Then it checks whether the agent's latest use (`LastUsed`, `Reached`) reached the gateway: a request Codex's log says went to the host its config keeps magpie at, or one the gateway saw from it after (`lastSeen`), reached it. Claude Code's `LastUsed` passes over the prompts in its `history.jsonl` whose `project` is magpie's own work folder (`magpie-claude-work`, `-<uid>` off Windows; `inMagpieWork`): the bridge's runs write there too and went through magpie (ifccod7391564 on X: they warned Claude Code bypassed magpie; `TestClaudeBridgePromptsArentBypass`).
5. **Disconnect.** `Disconnect` puts back what the stash kept and forgets the record. It also marks the agent disconnected (`<id>.disconnected` in the stash, `Disconnected`) until the user connects it again (`connect`, or an `Apply` that leaves it wired): nothing magpie does by itself puts magpie back in meanwhile, neither a start's `Sync` nor Codex's account failover nor #701's magpie API wiring (paynezhuang on Discord: Codex had `openai_base_url` back after every update). A Codex thread keeps the provider it was started on, so one started while magpie was Codex's provider (its API, or the takeover of a used-up account) still sends to `/v1` after Disconnect or a switch back to ChatGPT. One of Codex's own models asked there that no account in magpie serves (an OpenAI model of Codex's models cache or the catalog), from Codex on this computer with no held gateway key, goes on Codex's own ChatGPT sign-in through `codexBackend`, magpie's key and `x-openai-actor-authorization` left behind (`codexOwnOffMagpie` in [`codex_own_v1.go`](../../internal/gateway/codex_own_v1.go)); it was answered 404 "magpie knows no model" (iuengei on Discord). With the sign-in out of reach (subscription accounts off, signed out, expired) the 404 says why and to start a new thread. `TestCodexOwnModelOnMagpieThreadGoesOnSignIn`, `TestCodexOwnModelOnMagpieThreadStaysHere`, `TestCodexOwnModelOnMagpieThreadSaysWhy`.
## Constraints and failure behavior
+6 -3
View File
@@ -1004,9 +1004,9 @@ func (a *Agent) reconnect(now map[string]string) (bool, error) {
// lastJSONLTime reads the newest Unix timestamp (seconds or milliseconds)
// under key in the last lines of a prompt log, passing over the lines whose
// text (under textKey) is a slash command: those an agent answers itself.
// Zero if there is none.
func lastJSONLTime(path, key, textKey string) time.Time {
// text (under textKey) is a slash command: those an agent answers itself,
// and those skip, when given, says magpie's own. Zero if there is none.
func lastJSONLTime(path, key, textKey string, skip func(map[string]json.RawMessage) bool) time.Time {
f, err := os.Open(path)
if err != nil {
return time.Time{}
@@ -1028,6 +1028,9 @@ func lastJSONLTime(path, key, textKey string) time.Time {
if json.Unmarshal(m[textKey], &text) == nil && strings.HasPrefix(strings.TrimSpace(text), "/") {
continue
}
if skip != nil && skip(m) {
continue
}
n, err := strconv.ParseInt(string(m[key]), 10, 64)
if err != nil {
continue
+46
View File
@@ -131,6 +131,52 @@ func TestDriftBypassed(t *testing.T) {
}
}
// ifccod7391564 on X: the prompts magpie's bridge gives Claude Code, in
// magpie's own work folder, go into its history.jsonl too. They reached
// magpie, so they are no use round it: only the user's own prompts there
// count as Claude Code bypassing magpie.
func TestClaudeBridgePromptsArentBypass(t *testing.T) {
home, _ := codexHome(t, "", "")
managed := claudeManaged
claudeManaged = func() string { return filepath.Join(home, "managed-settings.json") }
t.Cleanup(func() { claudeManaged = managed })
defer func(s time.Time) { started = s }(started)
started = time.Now().Add(-time.Hour)
defer func(f func(string) time.Time) { lastSeen = f }(lastSeen)
lastSeen = func(string) time.Time { return time.Time{} }
a := claude(home)
if err := a.Apply("model", "fake/m1"); err != nil {
t.Fatal(err)
}
m := appliedLoad()
r := m["claude"]
r.At = time.Now().Add(-10 * time.Minute)
m["claude"] = r
appliedSave(m)
hist := filepath.Join(home, ".claude", "history.jsonl")
at := time.Now().Add(-5 * time.Minute).UnixMilli()
var lines string
for _, project := range []string{
"/private/var/folders/xz/6c5sgg_n3sgdlpc209dpp2n80000gn/T/magpie-claude-work-501", // the reporter's Mac
"/tmp/magpie-claude-work-1000/",
`C:\\Users\\me\\AppData\\Local\\Temp\\magpie-claude-work`,
"C:/Users/me/AppData/Local/Temp/magpie-claude-work",
"/mnt/c/Users/me/AppData/Local/Temp/magpie-claude-work",
} {
lines += fmt.Sprintf(`{"display":"[Pasted text #1 +30 lines]","timestamp":%d,"project":"%s","sessionId":"s"}`+"\n", at, project)
}
os.WriteFile(hist, []byte(lines), 0o600)
if d := a.Drift(); d != nil {
t.Fatalf("magpie's own prompts counted as bypass: %+v", d)
}
// the user's own prompt, in a folder of theirs, still does: even one
// whose name only starts like magpie's
os.WriteFile(hist, []byte(lines+fmt.Sprintf(`{"display":"hi","timestamp":%d,"project":"/Users/me/magpie-claude-workshop","sessionId":"u"}`+"\n", at)), 0o600)
if d := a.Drift(); d == nil || d.Kind != "bypassed" {
t.Fatalf("the user's own prompt: %+v", d)
}
}
// A profile that sets its own provider wins over magpie's top level.
func TestCodexDriftProfile(t *testing.T) {
home, read := codexHome(t, "", "")
+18 -2
View File
@@ -2436,9 +2436,11 @@ func claudeIn(at place) *Agent {
}
return wiringOff("Claude Code", path, getEnv, "ANTHROPIC_AUTH_TOKEN", at.gwKey())
},
// every prompt typed into Claude Code goes into history.jsonl
// every prompt typed into Claude Code goes into history.jsonl, and
// so does every one magpie's bridge gives it in magpie's own work
// folder, which went through magpie (ifccod7391564 on X)
LastUsed: func() time.Time {
return lastJSONLTime(filepath.Join(filepath.Dir(path), "history.jsonl"), "timestamp", "display")
return lastJSONLTime(filepath.Join(filepath.Dir(path), "history.jsonl"), "timestamp", "display", inMagpieWork)
},
// a session takes a new CLAUDE_CODE_EFFORT_LEVEL on its next
// request, but settings.json's effort and ultracode, and the env's
@@ -3086,3 +3088,17 @@ func claudeNarrowed() bool {
_, hidden := provider.CatalogFor("claude")
return len(hidden) > 0
}
// inMagpieWork: a line of Claude Code's history.jsonl is a prompt magpie's
// bridge gave it, in magpie's own work folder (os.TempDir()'s
// magpie-claude-work, magpie-claude-work-<uid> off Windows), whatever the
// path to it (/private/var/… on a Mac, C:/… or a WSL mount on Windows).
func inMagpieWork(m map[string]json.RawMessage) bool {
var project string
if json.Unmarshal(m["project"], &project) != nil {
return false
}
base := strings.TrimRight(project, `/\`)
base = base[strings.LastIndexAny(base, `/\`)+1:]
return base == "magpie-claude-work" || strings.HasPrefix(base, "magpie-claude-work-")
}
+1 -1
View File
@@ -2227,7 +2227,7 @@ func codexIn(at place) *Agent {
return ""
},
// every prompt typed into Codex goes into history.jsonl
LastUsed: func() time.Time { return lastJSONLTime(filepath.Join(dir, "history.jsonl"), "ts", "text") },
LastUsed: func() time.Time { return lastJSONLTime(filepath.Join(dir, "history.jsonl"), "ts", "text", nil) },
// the Codex app writes no history.jsonl, but it and the TUI log each
// model request they open
Reached: func(since time.Time) (time.Time, string, bool) { return codexReached(dir, since) },