Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
agent: Codex switched on again is joined, and its own models say where a pick goes
yetonefae438b4a5d4
diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.mdindex 908bae68a..1e8324904 100644--- a/docs/subsystems/agent-wiring.md+++ b/docs/subsystems/agent-wiring.md@@ -31,7 +31,7 @@ something else shows up as drift.## Runtime path-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). Otherwise it picks a model by the order `ConnectHow` documents and sets it through `Apply`.+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`). 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.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; 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.@@ -81,6 +81,7 @@ something else shows up as drift.- Grok App (RongleCat/grok-app, a desktop front end that starts Grok Build over ACP) keeps its provider channels in `agent-home/config.toml` under its data folder: `$GROK_APP_HOME`, else where its `directories` crate puts it, or its `~/.grok-app` fallback when that is the one there (`grokApp` in [`grokapp.go`](../../internal/agent/grokapp.go)). Its composer lists only Grok Build's official catalog, never the `[model."magpie/…"]` tables of Grok Build's row, so magpie adds itself as a channel, `[model.magpie]`, with the keys the App's Providers page writes: the gateway's `/v1`, a key naming Grok App, `api_backend = "chat_completions"`, `app_provider_mode = "generic"`, and `app_models`, a JSON list of magpie's models with `contextWindow`, `supportsVision` and their effort levels (no `none`; a default the user marks in the App stays, else medium). The picked model's `context_window` (a bare integer) and `supports_reasoning_effort` (a bare bool, Grok Build's gate for `--reasoning-effort`) are on the channel, as the App puts them there when a model is picked in its composer. `[models] default` is the route, and magpie does not set it: setting it to `"magpie"` makes the App drop its own sign-in (`ensure_independent_for_custom_route`). The route stays whatever the App had. Pressing Use on magpie under Accounts is what switches it. A magpie that already set the route puts the old one back once, on the next sync or connect (`grokAppReleased`); a Use after that stays. Disconnect drops only the channel, and puts the route back only when it is still `"magpie"`: the one stashed at connect, else the one `connect.was` holds. One of the App's own routes picked in magpie's model field is written as the route and takes magpie's channel out, as picking another provider does elsewhere. A sync with no channel and a route other than `"magpie"` writes nothing, magpie's stash included, and Check says so when the route is `"magpie"` with the channel gone. A model picked in the App's composer since is the user's and stays through a sync, and a sync with nothing to change doesn't write. Shared mode keeps `GROK_HOME` at `~/.grok` (Grok Build's library row). Independent mode, which Use turns on, reads agent-home: the Library writes `AGENTS.md`, `[mcp_servers]` in the same `config.toml`, and `skills/` there, and Grok App also reads `~/.agents/skills`. RTK has no Grok hook, so the Library lists Grok App with the switch off. The notice, while the App runs, says magpie is a custom provider in Settings › Account, a chat can pick its models in the model picker, and the App stays on its current route until Use.- JSON/JSONC config edits and their previews reject malformed input rather than editing a partially parsed document. Object edits and VS Code's model-group array edits leave the original file untouched on a parse error; valid comments and trailing commas remain supported (`internal/edit`).- A config that starts with a UTF-8 byte order mark (a Windows `settings.json` or `config.toml` saved by PowerShell, Notepad or a channel switcher, #1534) is read without it (`edit.Read`), and a write keeps it (`keepBOM` in `WriteAtomic`): the user's file keeps the encoding it was saved in. That covers every format `internal/edit` writes (JSON/JSONC and its arrays, TOML, YAML, env); Codex reads a TOML file through a BOM too, so magpie no longer refuses one. A file read some other way trims it with `edit.TrimBOM` (the Claude Code and CC Switch imports). A line an edit takes out of a CRLF file goes with its `\r\n`.+- Codex's model picker tags each of its own models by where a pick on the Agents page sends it: via magpie while routed, joined, or failing over, and direct while it is only beside its sign-in on one of magpie's models (`beside`, not joined, failover off), where such a pick takes magpie out (#940) and the GUI asks first (`TestCodexBesideOwnModelsSayDirect`).- Codex signed in to ChatGPT stays beside its sign-in (`openai_base_url`) unless the user picks magpie API. magpie becomes its provider only while the Codex app holds the active account, which it sends nothing for: `/wham/usage` says it isn't allowed, and it has no credits and isn't a workspace still within its overage (`codexHeld`, read by `provider.CodexUsedUp`). Where the app goes by what usage can't show (an experiment's gate, a reserve, a Team plan's overage under the reserve experiment), it counts as held: a wrong move costs ChatGPT extras, a missed one every turn. A saved reading kept through a failed read stops saying held once its used-up window has started again; a hold with no window used up stays till a fresh read. The app then loses its ChatGPT state (durable threads, remote control), so a window at 100% alone, which credits get past, doesn't move it (`codex.out` marks the move, and Sync undoes it once the account has room). The same holds on one of Codex's own models joined beside the sign-in (MasterYi on Discord: the Codex app greyed Send for every model on a used-up account): Sync makes magpie the provider on that model as magpie serves it (`codexOwnViaMagpie`, `codex/<model>`), keeps the model picked in `codex.out_own`, and once the account has room puts Codex back joined on it; a model the user picked meanwhile stays theirs. With no ChatGPT account in magpie to serve it, Codex is left as it is (`TestCodexOwnModelGoesThroughMagpieWhileUsedUp`, `TestCodexOwnModelKeptOnChatGPT`). The account is read again at once when a reply says it may be out (a `usage_limit_reached` rest, or an `x-codex-*` window heard at 100%; `provider.CodexMayBeUsedUp`, at most every 20s, the active account only), not only on the five-minute look. The Codex app greys Send for every model, magpie's too, while its `authMethod` is `chatgpt` and its rate limit says not allowed (its composer's gate in ChatGPT.app 26.1013), and reads `authMethod` from its app-server's `account/read` only as the app-server starts; with magpie the provider (`requires_openai_auth` false) that answers no account, so the gate lifts. So the gateway process restarts the app's own app-server each time magpie becomes Codex's provider for the used-up account (`Agent.AppOut`) and again when Codex is put back on the account after its reset, and likewise whenever what the app-server reads as it starts and magpie writes changes (`model_provider`, `openai_base_url`, `model_catalog_json`, the magpie table's `base_url`, and a hash of what the catalog file holds, `codexCatalogTag` in [`codex_app_route.go`](../../internal/agent/codex_app_route.go), read again only when its size or time changes; `codexAppRoute`, through the `provider.CodexAppRoute` hook): a Disconnect, a Connect, failover written or taken out, a provider or group renamed or a model added. Without the catalog in it the app kept the names and models it started with until it was restarted (lucis0116 on X). Before this an app-server started while Codex was connected kept sending to the gateway after Disconnect until the app was restarted (JiangLiuer222 on X). At the watcher's first look only a used-up account's app-servers are ended, since what the others read before magpie started isn't known. It runs on every system (`KeepCodexAppOnItsProvider`, every 3s; Ethereal499 and Isdavexxx on X, MasterYi on Discord, #540: the earlier once-only reopen ran on macOS from the GUI process only, so Windows, Linux, a GUI-less magpie and the switch back stayed greyed). It ends only app-servers on magpie's Codex home (`codexAppHomeIs`: the process's `CODEX_HOME`, else `HOME/.codex`, read by `proc.EnvOf`; Windows can't tell and counts every one), only once no Codex request is in flight through the gateway nor ended in the last 10s (`Server.CodexBusy`) and no session under the Codex home has a turn started and not ended (`codexTurnOpen`), and with a clean exit (`proc.End`: SIGTERM, `TerminateProcess` with code 0), since the app shows any other exit as a crash. The app starts another app-server at once and keeps its window, threads and drafts (tried in the real app in a sandbox `CODEX_HOME`, both ways). An app-server that outlives three ends, or may not be ended, leaves the row saying to quit and reopen the app (`CodexAppStuck`). Until the reset the app's ChatGPT side is off (cloud tasks, its usage meter, Log out); the Agents row says so with the reset's time (`appOut` in `/api/state`, `CodexOutUntil`), and it all comes back at the reset. While the active account is held or a window is at 90% or more, its usage is read every minute rather than every five (`codexLookEvery`). `TestCodexAppServerRestartedEachWay`, `TestCodexAppServerRestartedOnDisconnect`, `TestCodexAppRouteFollowsConnectAndDisconnect`, `TestCodexAppRouteFollowsTheCatalog`, `TestCodexAppServerUnknown`, `TestCodexAppServerStuck`, `TestCodexAppServersOnHome`, `TestCodexTurnOpen`, `TestCodexBusy`, `codex-app-out.test.cjs`.- Moving a field from one of magpie's models to another (the agent's own picker) is not drift. Moving it off magpie is.- Claude Desktop applying a configLibrary profile other than magpie's is not drift when that profile is a gateway profile for this magpie's gateway (`desktopAppliedGateway` in [`claudedesktop.go`](../../internal/agent/claudedesktop.go)): Desktop's "Import configuration" adds a file exported on another computer, magpie's profile there with the user's connectors (`managedMcpServers`), as a new entry under a random id (aa86222 on Discord). magpie keeps it applied on Reconnect and through Sync, and writes in it only `inferenceGatewayApiKey` (with a missing auth scheme) when the gateway would refuse its key (`desktopKeyApplied`; magpie's own keys count as taken, `desktopKeyTaken`). A profile for another gateway, CC Switch's among them, is still drift, and Reconnect applies magpie's. The first switch-on still starts magpie's profile from an applied one (#2035). `TestClaudeDesktopImportedProfileIsOnMagpie`.diff --git a/internal/agent/applied.go b/internal/agent/applied.goindex 065c3f2af..c668b9c0d 100644--- a/internal/agent/applied.go+++ b/internal/agent/applied.go@@ -842,6 +842,18 @@ func (a *Agent) reconnect(now map[string]string) (bool, error) {return false, nil}}+ // joined first, where the agent can be (Codex signed in with ChatGPT),+ // as the switch connects it the first time: its own models stay+ // through magpie beside the one put back. Put back on a routing group+ // alone, Codex was beside its sign-in and not joined, so picking one+ // of its own on the Agents page took it off magpie, every OpenAI model+ // then said direct, and after a group again they said via magpie+ // though a pick still went straight to OpenAI (NancyTom18 on X)+ if a.Join != nil {+ if _, err := a.Join(); err != nil {+ return true, err+ }+ }// the models on magpie first, as Connect sets them (setting Gemini// CLI's model signs it in through magpie, which its sign-in field// can't), then the rest that aren't so by thendiff --git a/internal/agent/codex.go b/internal/agent/codex.goindex e0c32b86e..f2f0ea5f8 100644--- a/internal/agent/codex.go+++ b/internal/agent/codex.go@@ -1175,9 +1175,18 @@ func codexIn(at place) *Agent {t, _ := edit.GetTOMLTable(path, "model_providers."+p)to, through = p, t["base_url"] == at.codexURL() || t["base_url"] == at.v1()}+ // beside its sign-in on one of magpie's models, not joined, one of+ // its own picked here takes magpie out (set, #940) unless failover+ // puts the base URL back: it said via magpie, and the pick went+ // straight to OpenAI with nothing asked (NancyTom18 on X)+ ownThrough := through+ if through && (p == "" || p == "openai") && beside() && !asProvider() && !api() &&+ !(joined() && chatGPT()) && !(codexFailover() && !disconnected()) {+ ownThrough = false+ }say := func(own []Option) []Option {for i := range own {- if through {+ if ownThrough {own[i].Via = true} else {own[i].Direct = todiff --git a/internal/agent/codex_reconnect_joined_test.go b/internal/agent/codex_reconnect_joined_test.gonew file mode 100644index 000000000..02e4dbdbc--- /dev/null+++ b/internal/agent/codex_reconnect_joined_test.go@@ -0,0 +1,124 @@+package agent++import (+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/yetone/magpie/internal/provider"+)++// nancyCodex is NancyTom18's Codex (on X): signed in with ChatGPT, its own+// models listed, and a routing group named for one of them.+func nancyCodex(t *testing.T) (*Agent, func() string) {+ t.Helper()+ home, read := codexHome(t, chatGPTAuth, "model = \"gpt-5.5\"\n")+ os.WriteFile(filepath.Join(home, ".codex", "models_cache.json"),+ []byte(`{"models":[{"slug":"gpt-5.5","visibility":"list","priority":1},{"slug":"gpt-5.6-luna","visibility":"list","priority":2}]}`), 0o644)+ if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"gpt-5.6-luna"}}); err != nil {+ t.Fatal(err)+ }+ if err := provider.SaveGroup(provider.Group{ID: "luna", Name: "gpt-5.6-luna", Members: []string{"relay/gpt-5.6-luna"}}); err != nil {+ t.Fatal(err)+ }+ return codex(home), read+}++// ownPath is how the model picker tags each of Codex's own models: "via"+// (through magpie) or "direct".+func ownPath(t *testing.T, cx *Agent) map[string]string {+ t.Helper()+ out := map[string]string{}+ for _, o := range cx.Fields[0].Options(cx.Values()) {+ if o.Group != "OpenAI" || o.Ref != "" {+ continue+ }+ switch {+ case o.Via && o.Direct == "":+ out[o.Value] = "via"+ case !o.Via && o.Direct != "":+ out[o.Value] = "direct"+ default:+ out[o.Value] = "both or neither"+ }+ }+ if len(out) == 0 {+ t.Fatal("no own models in the picker")+ }+ return out+}++// Connected by the switch, on a routing group, disconnected and restored,+// then switched on again: Codex comes back as the switch first connected+// it, joined, so one of its own models picked on the Agents page stays+// through magpie, as the picker says. Put back on the group alone, it was+// beside its sign-in and not joined: the OpenAI model picked took Codex+// off magpie and every row said direct (NancyTom18's first screenshot).+func TestCodexReconnectStaysJoined(t *testing.T) {+ cx, read := nancyCodex(t)+ if c, err := cx.ConnectHow(); err != nil || c.How != "joined" {+ t.Fatalf("connect: %+v %v", c, err)+ }+ if err := cx.Apply("model", "group/luna"); err != nil {+ t.Fatal(err)+ }+ if err := cx.Disconnect(); err != nil {+ t.Fatal(err)+ }+ if cfg := read(); strings.Contains(cfg, "openai_base_url") {+ t.Fatalf("disconnected:\n%s", cfg)+ }+ if c, err := cx.ConnectHow(); err != nil || c.How != "again" {+ t.Fatalf("connect again: %+v %v", c, err)+ }+ if cfg := read(); !strings.Contains(cfg, `model = "group/luna"`) || !strings.Contains(cfg, "openai_base_url") {+ t.Fatalf("connected again, not on the group:\n%s", cfg)+ }+ if !cx.Joined() {+ t.Fatal("connected again, not joined")+ }+ for m, p := range ownPath(t, cx) {+ if p != "via" {+ t.Errorf("connected again: %s says %s", m, p)+ }+ }+ if err := cx.Apply("model", "gpt-5.6-luna"); err != nil {+ t.Fatal(err)+ }+ if cfg := read(); !strings.Contains(cfg, "openai_base_url") || !strings.Contains(cfg, `model = "gpt-5.6-luna"`) || !cx.Wired() {+ t.Fatalf("an own model picked took Codex off magpie, wired %v:\n%s", cx.Wired(), cfg)+ }+ for m, p := range ownPath(t, cx) {+ if p != "via" {+ t.Errorf("on its own model: %s says %s", m, p)+ }+ }+}++// Beside its sign-in on a routing group and not joined (a magpie model+// picked while Codex wasn't connected, or a Codex connected again by an+// older magpie), one of its own picked here takes magpie out: each says+// direct, so the picker asks before it does. It said via magpie, and the+// pick went straight to OpenAI (NancyTom18's second screenshot).+func TestCodexBesideOwnModelsSayDirect(t *testing.T) {+ cx, read := nancyCodex(t)+ if err := cx.Apply("model", "group/luna"); err != nil {+ t.Fatal(err)+ }+ if !cx.Beside() || cx.Joined() || !cx.Wired() {+ t.Fatalf("not beside alone: beside %v joined %v wired %v\n%s", cx.Beside(), cx.Joined(), cx.Wired(), read())+ }+ for m, p := range ownPath(t, cx) {+ if p != "direct" {+ t.Errorf("beside: %s says %s", m, p)+ }+ }+ // and it is so+ if err := cx.Apply("model", "gpt-5.6-luna"); err != nil {+ t.Fatal(err)+ }+ if cfg := read(); strings.Contains(cfg, "openai_base_url") || cx.Wired() {+ t.Fatalf("picked one of its own, still on magpie:\n%s", cfg)+ }+}