diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index 804a87c1f..33e2ba2b0 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -36,7 +36,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 (`.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`). 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 ` 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/`; `proxyBase`), and `GET /` 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; before that, or at a relay, a pick points Claude Code at this magpie. 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/`; `proxyBase`), and `GET /` 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; before that, or at a relay, a pick points Claude Code at this magpie. 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. 5. **Disconnect.** `Disconnect` puts back what the stash kept and forgets the record. It also marks the agent disconnected (`.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 @@ -154,7 +154,7 @@ go test -tags nogui ./internal/agent -run '^TestPenguin' go test -tags nogui ./internal/agent -run 'TestClaudeAutoModeReview|TestClaudeReviewedOnlyWhereMessagesReachClaude|TestT3CodeAutoModeReview|TestConnect|TestDisconnect|Drift|TestKeptAddress|TestWSLAgentAddress|TestReachProbe|TestDryRunKnowsTheAskersProviders|TestReseat|TestPort|TestWSL|TestClaudeKeepsItsClaudeAISignIn|TestClaudeSignIn|TestClaudeOwnEndpointWithAnEmptyKey|TestClaudeAtAnOlderGatewayAddress' go test -tags nogui ./internal/agent go test -tags nogui ./internal/agent -run '^TestAir' -go test -tags nogui ./internal/agent -run 'TestReverseProxy|TestClaudeManagedProxyIsStillMagpie|TestMagpieProbe|TestCodexBehindReverseProxy|TestCodexSignedInBehindReverseProxy|TestAwayPath|TestClaudeBehindLocalProxyKeepsIt' +go test -tags nogui ./internal/agent -run 'TestReverseProxy|TestClaudeManagedProxyIsStillMagpie|TestMagpieProbe|TestCodexBehindReverseProxy|TestCodexSignedInBehindReverseProxy|TestAwayPath|TestClaudeBehindLocalProxyKeepsIt|OwnEndpointNeverAsked' go test -tags nogui ./internal/agent ./internal/edit -run 'TestSyncKeepsAnAddressOnAnotherMachine|TestKeptAwayOnlyWhatIsSure|TestKeyValuesFormats|TestFilteredWrites|TestOwnWritesDuringASyncWithALinkedConfig' go test -tags nogui ./internal/edit -run 'BOM|CRLF|JSONC|TrailingComma|LoneComma' go test -tags nogui ./internal/library -run TestHubToggleKeepsOpenCodeJSONCValid diff --git a/internal/agent/applied.go b/internal/agent/applied.go index 94bb20fb5..17ddce797 100644 --- a/internal/agent/applied.go +++ b/internal/agent/applied.go @@ -1013,15 +1013,21 @@ func wiringOff(name, file string, get func(string) (string, bool), kvs ...string if keyHolds(v, want) || v != "" && reachesMagpie(v, want) { continue } - where := name + "'s " + k + " (" + filepath.Base(file) + ")" - switch { - case v == "": - return where + " is gone, so it no longer reaches magpie" - case strings.Contains(strings.ToLower(k), "url"): - return where + " is " + v + ", not magpie's gateway at " + want - default: - return where + " was changed, so magpie's gateway won't take its requests" - } + return whatsOff(name, file, k, v, want) } return "" } + +// whatsOff is what wiringOff says of k in an agent's config, v where +// magpie wrote want. +func whatsOff(name, file, k, v, want string) string { + where := name + "'s " + k + " (" + filepath.Base(file) + ")" + switch { + case v == "": + return where + " is gone, so it no longer reaches magpie" + case strings.Contains(strings.ToLower(k), "url"): + return where + " is " + v + ", not magpie's gateway at " + want + default: + return where + " was changed, so magpie's gateway won't take its requests" + } +} diff --git a/internal/agent/claude.go b/internal/agent/claude.go index 76b9552a3..b1e224ecf 100644 --- a/internal/agent/claude.go +++ b/internal/agent/claude.go @@ -611,10 +611,10 @@ func claudeIn(at place) *Agent { spell := provider.ClaudeSpelled model := jsonGet(path, "model") // routed: on magpie's gateway, or on a proxy to it where magpie has - // answered (#1985), which a pick keeps (gwAt) - routed := func() bool { u := env("ANTHROPIC_BASE_URL"); return u == at.gw() || surelyMagpie(u, at.gw()) } + // answered (#1985, claudeProxied), which a pick keeps (gwAt) + routed := func() bool { u := env("ANTHROPIC_BASE_URL"); return u == at.gw() || claudeProxied(at, path, u) } gwAt := func() string { - if u := env("ANTHROPIC_BASE_URL"); u != at.gw() && surelyMagpie(u, at.gw()) { + if u := env("ANTHROPIC_BASE_URL"); claudeProxied(at, path, u) { return u } return at.gw() @@ -2154,17 +2154,26 @@ func claudeIn(at place) *Agent { if !isMagpie(get()) { return "" } + getEnv := func(k string) (string, bool) { return edit.GetJSON(path, "env."+k) } + // an address that isn't the gateway's is asked whether it is + // magpie behind a proxy (#1985) only while what Claude Code + // sends is for magpie (claudeKeyed): with a key of the user's + // own it is their endpoint, told as it is, never asked (#3480) + keyed := claudeKeyed(at, path) // an administrator's settings win over the user's managed := claudeManaged() if at.sys != nil { managed = at.sys("/etc/claude-code/managed-settings.json") } - if u, _ := edit.GetJSON(managed, "env.ANTHROPIC_BASE_URL"); u != "" && u != at.gw() && !reachesMagpie(u, at.gw()) { + if u, _ := edit.GetJSON(managed, "env.ANTHROPIC_BASE_URL"); u != "" && u != at.gw() && !(keyed && reachesMagpie(u, at.gw())) { return "Claude Code's managed settings (" + at.native(managed) + ") set ANTHROPIC_BASE_URL to " + u + ", which wins over magpie's" } - getEnv := func(k string) (string, bool) { return edit.GetJSON(path, "env."+k) } - if off := wiringOff("Claude Code", path, getEnv, "ANTHROPIC_BASE_URL", at.gw()); off != "" { - return off + if keyed { + if off := wiringOff("Claude Code", path, getEnv, "ANTHROPIC_BASE_URL", at.gw()); off != "" { + return off + } + } else if u, _ := getEnv("ANTHROPIC_BASE_URL"); u != at.gw() { + return whatsOff("Claude Code", path, "ANTHROPIC_BASE_URL", u, at.gw()) } if why := claudeCloud(at, path); why != "" { return why @@ -2635,7 +2644,7 @@ func ClassifierStandIn(agent, model string) string { func claudeClassifierIn(at place, model string) string { path := filepath.Join(at.claudeDir(), "settings.json") env := func(k string) string { v, _ := edit.GetJSON(path, "env."+k); return provider.ClaudeRead(v) } - if u := env("ANTHROPIC_BASE_URL"); u != at.gw() && !surelyMagpie(u, at.gw()) { + if u := env("ANTHROPIC_BASE_URL"); u != at.gw() && !claudeProxied(at, path, u) { return "" } if env(claudeAutoModeEnv) != "" { @@ -2661,13 +2670,13 @@ func claudeClassifierIn(at place, model string) string { return followAt("sonnet", bare(main), effort) } -func claudeStandIn(path, model string) string { return claudeStandInAt(path, model, gateway.URL()) } +func claudeStandIn(path, model string) string { return claudeStandInAt(here(""), path, model) } -// claudeStandInAt is claudeStandIn for a Claude Code that reaches the -// gateway at gw. -func claudeStandInAt(path, model, gw string) string { +// claudeStandInAt is claudeStandIn for the Claude Code at a place, which +// reaches the gateway at its own address. +func claudeStandInAt(at place, path, model string) string { env := func(k string) string { v, _ := edit.GetJSON(path, "env."+k); return provider.ClaudeRead(v) } - if u := env("ANTHROPIC_BASE_URL"); u != gw && !surelyMagpie(u, gw) { + if u := env("ANTHROPIC_BASE_URL"); u != at.gw() && !claudeProxied(at, path, u) { return "" } // the model Claude Code is set to itself, by that id, is its own pick @@ -2694,6 +2703,34 @@ func claudeStandInAt(path, model, gw string) string { return main } +// claudeKeyed says what the Claude Code at a place (its settings at path) +// sends is for magpie: a key the gateway takes (keyHolds, as Check asks of +// it), or none where it keeps its claude.ai sign-in through magpie, which +// magpie set (claude.login) on a Claude Code it wired (wired_at, which +// Disconnect forgets) where the gateway takes any key (signInHere). +func claudeKeyed(at place, path string) bool { + if tok, _ := edit.GetJSON(path, "env.ANTHROPIC_AUTH_TOKEN"); tok != "" { + return keyHolds(tok, at.gwKey()) + } + st := stashLoad() + return at.gwKey() == gateway.Token && st[at.key("claude.login")] == "claudeai" && st[at.key("claude"+wiredAt)] != "" +} + +// claudeProxied says u, the base URL the Claude Code at a place (its +// settings at path) has in place of the gateway's, is a proxy to it where +// magpie has answered (#1985, surelyMagpie). It is asked only where it can +// be another way to magpie (proxyBase), and only while Claude Code sends +// it what is for magpie (claudeKeyed): with a key of the user's own, u is +// their endpoint. zhangt2333 (#3480) never connected Claude Code, and the +// Agents page's reads of it sent GET / about every 30s to the endpoint in +// its settings. +func claudeProxied(at place, path, u string) bool { + if _, ok := proxyBase(u, at.gw()); !ok || u == at.gw() { + return false + } + return claudeKeyed(at, path) && surelyMagpie(u, at.gw()) +} + // claudeMain is the model a Claude Code routed through magpie runs on, as // settings.json names it: its model, which /model saves, an alias there // resolved through its tier. With none, the ANTHROPIC_MODEL an older diff --git a/internal/agent/claude_dotted_test.go b/internal/agent/claude_dotted_test.go index ec3cdbcf1..d0d324e79 100644 --- a/internal/agent/claude_dotted_test.go +++ b/internal/agent/claude_dotted_test.go @@ -7,7 +7,6 @@ import ( "testing" "github.com/yetone/magpie/internal/edit" - "github.com/yetone/magpie/internal/gateway" "github.com/yetone/magpie/internal/provider" ) @@ -130,7 +129,7 @@ func TestClaudeDottedVersionsGoInDashed(t *testing.T) { if model() != "relay/claude-haiku-4-5" || env("ANTHROPIC_DEFAULT_OPUS_MODEL") != "relay/claude-haiku-4-5" { t.Fatalf("followers go with the pick:\n%s", readFile(path)) } - if got := claudeStandInAt(path, "some-unknown-model", gateway.URL()); got != "relay/claude-haiku-4.5" { + if got := claudeStandInAt(here(""), path, "some-unknown-model"); got != "relay/claude-haiku-4.5" { t.Fatalf("stand-in: %q", got) } noDots() diff --git a/internal/agent/claude_fable_test.go b/internal/agent/claude_fable_test.go index fc2b0aac7..7651a7d98 100644 --- a/internal/agent/claude_fable_test.go +++ b/internal/agent/claude_fable_test.go @@ -60,7 +60,7 @@ func TestClaudeFableTierOnClaude(t *testing.T) { t.Fatalf("fable shown as %q, want following", a.Field("fable").Get()) } // Claude Code's own fable, asked of the gateway, runs on the main model - if got := claudeStandInAt(path, "claude-fable-5-1", env("ANTHROPIC_BASE_URL")); got != "anth/claude-opus-5-5" { + if got := claudeStandInAt(here(""), path, "claude-fable-5-1"); got != "anth/claude-opus-5-5" { t.Fatalf("claude-fable-5-1 stands in as %q", got) } // another Claude model that is no Fable @@ -90,7 +90,7 @@ func TestClaudeFableTierOnClaude(t *testing.T) { if env("ANTHROPIC_DEFAULT_OPUS_MODEL") != m || env("ANTHROPIC_DEFAULT_SONNET_MODEL") != m || env("ANTHROPIC_DEFAULT_HAIKU_MODEL") != m { t.Fatalf("on %s the other tiers should follow:\n%s", m, readFile(path)) } - if got := claudeStandInAt(path, "claude-fable-5-1", env("ANTHROPIC_BASE_URL")); got != m { + if got := claudeStandInAt(here(""), path, "claude-fable-5-1"); got != m { t.Fatalf("on %s claude-fable-5-1 stands in as %q", m, got) } } diff --git a/internal/agent/claude_pick_test.go b/internal/agent/claude_pick_test.go index 7aa774a24..da6b4a1f7 100644 --- a/internal/agent/claude_pick_test.go +++ b/internal/agent/claude_pick_test.go @@ -48,7 +48,7 @@ func TestClaudeModelPickedInClaudeCode(t *testing.T) { if v := a.Values(); v["model"] != "deepseek/flash" || v["opus"] != "" || v["haiku"] != "deepseek/lite" { t.Fatalf("the pick is the main model, the tiers that followed still follow: %v", v) } - if got := claudeStandInAt(path, "claude-sonnet-5", gateway.URL()); got != "deepseek/pro" { + if got := claudeStandInAt(here(""), path, "claude-sonnet-5"); got != "deepseek/pro" { t.Fatalf("sonnet's stand-in before Follow: %q", got) } if err := a.Follow(); err != nil { @@ -58,7 +58,7 @@ func TestClaudeModelPickedInClaudeCode(t *testing.T) { env("ANTHROPIC_DEFAULT_SONNET_MODEL") != "deepseek/flash" || env("ANTHROPIC_DEFAULT_HAIKU_MODEL") != "deepseek/lite" { t.Fatalf("followers go with the pick, haiku keeps its own:\n%s", readFile(path)) } - if got := claudeStandInAt(path, "some-unknown-model", gateway.URL()); got != "deepseek/flash" { + if got := claudeStandInAt(here(""), path, "some-unknown-model"); got != "deepseek/flash" { t.Fatalf("a model of no tier stands in for the pick: %q", got) } diff --git a/internal/agent/proxy_kept_test.go b/internal/agent/proxy_kept_test.go index 975b316ca..a23564847 100644 --- a/internal/agent/proxy_kept_test.go +++ b/internal/agent/proxy_kept_test.go @@ -406,3 +406,167 @@ func TestClaudeBehindLocalProxyKeepsIt(t *testing.T) { t.Fatalf("a pick at a relay left %s", u) } } + +// zhangt2333 (#3480): Claude Code never connected to magpie, its settings +// pointing it at an endpoint of the user's own with a key of its own, got +// GET / about every 30s from magpie: each read of it while the Agents page +// was up asked that address whether it was magpie behind a proxy (#1985). +// Claude Code sending a key of its own is on the user's endpoint, never +// asked: not by a read, its drift (a model named as one of magpie's there +// is told by the address, as it is, an administrator's too), a pick, or a +// request's stand-ins. Once it +// sends magpie's key, or keeps its claude.ai sign-in through magpie, a +// proxy put in by hand is asked, is still magpie, and a pick keeps it. +// After Disconnect, its own endpoint and key back, nothing is asked again, +// though the claude.ai sign-in stays kept for the next time (its key in +// ANTHROPIC_API_KEY, so none in ANTHROPIC_AUTH_TOKEN). +func TestClaudeOwnEndpointNeverAsked(t *testing.T) { + t.Run("nginx", func(t *testing.T) { claudeOwnEndpointNeverAsked(t, corpProxy, "ANTHROPIC_AUTH_TOKEN") }) + t.Run("local", func(t *testing.T) { claudeOwnEndpointNeverAsked(t, localProxy, "ANTHROPIC_API_KEY") }) +} + +func claudeOwnEndpointNeverAsked(t *testing.T, proxy, ownKey string) { + t.Setenv("MAGPIE_ADDR", "") + const own = "https://relay.example/anthropic" + home, path := claudeSettings(t, `{"model":"opus","env":{"ANTHROPIC_BASE_URL":"`+own+`","`+ownKey+`":"sk-own"}}`) + saveDeepseek(t) + // both would answer as magpie: whether they are asked is the point + asked := fakeMagpieAt(t, map[string]bool{own: true, proxy: true}) + env := func(k string) string { v, _ := edit.GetJSON(path, "env."+k); return v } + cl := claude(home) + read := func() { + vals := cl.Values() + for _, f := range cl.Fields { + if f.Options != nil { + f.Options(vals) + } + } + cl.Wired() + cl.Drift() + claudeStandIn(path, "claude-haiku-4-5") + claudeClassifierIn(here(home), "deepseek/pro") + } + never := func(when string) { + t.Helper() + if b := asked(); len(b) > 0 { + t.Fatalf("%s: asked %v", when, b) + } + } + + read() + never("never connected") + if cl.Wired() || cl.Drift() != nil { + t.Fatalf("never connected, yet wired %v, drift %+v", cl.Wired(), cl.Drift()) + } + // a model of the endpoint's own named as one of magpie's: the address + // is told as it is, an administrator's too, and none as gone + edit.SetJSON(path, edit.KV{Path: "model", Value: "deepseek/pro"}) + read() + never("a model of magpie's name") + if d := cl.Drift(); d == nil || d.Kind != "unwired" || !strings.Contains(d.Detail, "ANTHROPIC_BASE_URL") || !strings.Contains(d.Detail, own) { + t.Fatalf("its own key, a model of magpie's name: %+v", d) + } + managed := claudeManaged + claudeManaged = func() string { return filepath.Join(home, "managed-settings.json") } + t.Cleanup(func() { claudeManaged = managed }) + os.WriteFile(claudeManaged(), []byte(`{"env":{"ANTHROPIC_BASE_URL":"`+proxy+`"}}`), 0o644) + if d := cl.Drift(); d == nil || !strings.Contains(d.Detail, "managed settings") || !strings.Contains(d.Detail, proxy) { + t.Fatalf("its own key, an administrator's proxy: %+v", d) + } + never("an administrator's proxy") + os.Remove(claudeManaged()) + edit.DelJSON(path, "env.ANTHROPIC_BASE_URL") + if d := cl.Drift(); d == nil || !strings.Contains(d.Detail, "ANTHROPIC_BASE_URL") || !strings.Contains(d.Detail, "is gone") { + t.Fatalf("its own key, no address: %+v", d) + } + edit.SetJSON(path, edit.KV{Path: "env.ANTHROPIC_BASE_URL", Value: own}, edit.KV{Path: "model", Value: "opus"}) + // a pick writes magpie's address and key, its own kept for Disconnect + if err := cl.Apply("model", "deepseek/flash"); err != nil { + t.Fatal(err) + } + never("a pick") + if env("ANTHROPIC_BASE_URL") != gateway.URL() || env("ANTHROPIC_AUTH_TOKEN") != gateway.Token { + t.Fatalf("after a pick:\n%s", readFile(path)) + } + + // the proxy put in by hand, magpie's key kept (#1985) + edit.SetJSON(path, edit.KV{Path: "env.ANTHROPIC_BASE_URL", Value: proxy}) + if d := cl.Drift(); d != nil { + t.Fatalf("magpie's key at the proxy: %+v", d) + } + // its claude.ai sign-in kept through magpie: no key at all + if err := cl.Apply("login", "claudeai"); err != nil { + t.Fatal(err) + } + if tok, has := edit.GetJSON(path, "env.ANTHROPIC_AUTH_TOKEN"); !has || tok != "" || env("ANTHROPIC_BASE_URL") != proxy { + t.Fatalf("the claude.ai sign-in at the proxy:\n%s", readFile(path)) + } + if d := cl.Drift(); d != nil || cl.Values()["login"] != "claudeai" { + t.Fatalf("the claude.ai sign-in at the proxy: drift %+v, sign-in %q", d, cl.Values()["login"]) + } + if err := cl.Apply("model", "deepseek/pro"); err != nil { + t.Fatal(err) + } + if u := env("ANTHROPIC_BASE_URL"); u != proxy { + t.Fatalf("a pick with the claude.ai sign-in wrote %s", u) + } + b := asked() + if len(b) == 0 { + t.Fatal("the proxy was never asked") + } + for _, base := range b { + if base != proxy { + t.Fatalf("asked %s, not the proxy", base) + } + } + + if err := cl.Disconnect(); err != nil { + t.Fatal(err) + } + if env("ANTHROPIC_BASE_URL") != own || env(ownKey) != "sk-own" { + t.Fatalf("after Disconnect:\n%s", readFile(path)) + } + n := len(asked()) + read() + if b := asked(); len(b) != n { + t.Fatalf("asked after Disconnect: %v", b[n:]) + } +} + +// The same for Claude Code in a WSL distro, whose stash keys are its own. +func TestWSLClaudeOwnEndpointNeverAsked(t *testing.T) { + const own = "https://relay.example/anthropic" + root, home := claudeDistroHome(t, `{"model":"opus","env":{"ANTHROPIC_BASE_URL":"`+own+`","ANTHROPIC_AUTH_TOKEN":"sk-own"}}`) + saveDeepseek(t) + d := distro{Name: "Debian", Root: root, Home: "/home/me", Has: map[string]bool{"dir:.claude": true}, + Gateway: "172.20.0.1", Running: true} + a := wslAgent(wslKindOf("claude"), d) + at := d.place(a.ID) + path := filepath.Join(home, ".claude", "settings.json") + asked := fakeMagpieAt(t, map[string]bool{own: true, corpProxy: true}) + a.Values() + a.Wired() + a.Drift() + claudeStandInAt(at, path, "claude-haiku-4-5") + claudeClassifierIn(at, "deepseek/pro") + if err := a.Apply("model", "deepseek/flash"); err != nil { + t.Fatal(err) + } + if b := asked(); len(b) > 0 { + t.Fatalf("its own endpoint asked: %v", b) + } + edit.SetJSON(path, edit.KV{Path: "env.ANTHROPIC_BASE_URL", Value: corpProxy}) + if dr := a.Drift(); dr != nil { + t.Fatalf("magpie's key at the proxy: %+v", dr) + } + if err := a.Apply("login", "claudeai"); err != nil { + t.Fatal(err) + } + if dr := a.Drift(); dr != nil || a.Values()["login"] != "claudeai" { + t.Fatalf("the claude.ai sign-in at the proxy: drift %+v, sign-in %q", dr, a.Values()["login"]) + } + if b := asked(); len(b) == 0 || b[0] != corpProxy { + t.Fatalf("asked %v", b) + } + noOwnClaude(t) +} diff --git a/internal/agent/wsl.go b/internal/agent/wsl.go index 1c7768db6..b5fa1844c 100644 --- a/internal/agent/wsl.go +++ b/internal/agent/wsl.go @@ -1346,7 +1346,7 @@ func wslReady(kind string) []distro { func wslClaudeStandIn(model string) string { for _, d := range wslReady("claude") { path := filepath.Join(d.local(d.Home), ".claude", "settings.json") - if m := claudeStandInAt(path, model, d.base()); m != "" { + if m := claudeStandInAt(d.place("claude@wsl:"+d.Name), path, model); m != "" { return m } }