diff --git a/docs/reference.md b/docs/reference.md index b0385a259..ba5f9cec2 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -2425,13 +2425,13 @@ to (an account added by setup-token doesn't count), magpie keeps it and says so. Add another account first, or sign out in Claude Code itself, then remove it. -With more than one Codex account on, magpie also sets `openai_base_url` -in Codex's config.toml, so a request the signed-in account has no -allowance for goes on to the others through the gateway. *Only switch -Codex's sign-in* under Providers › Codex (or `magpie accounts switch-only -codex on`) leaves that out: magpie only moves Codex's own sign-in -(`auth.json`) as above, and Codex's requests go straight to OpenAI, never -through magpie (#1907). An `openai_base_url` you wrote yourself stays. The +A Codex that isn't connected to magpie goes straight to OpenAI on its own +sign-in, however many of its accounts are on: magpie only moves Codex's +sign-in (`auth.json`) as above. Connected, a request the signed-in account +has no allowance for goes on to the others through the gateway. *Only +switch Codex's sign-in* under Providers › Codex (or `magpie accounts +switch-only codex on`) keeps Codex's requests off magpie even then +(#1907). An `openai_base_url` you wrote yourself stays. The Codex app and a running `codex app-server` read the sign-in when they start, so one already open stays on its account until it is opened again; a new `codex` session takes the new one. Connected to magpie, Codex's diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index 98772485f..0bc87266a 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -53,8 +53,8 @@ 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`). 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 ` 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; 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). An address on loopback whose path ends in the gateway's own URL (billion-context's lane, `http://127.0.0.1:18787/bili/`, which the Library's billion-context tab gives Claude Code) is magpie without asking (`chainsToGateway`): the lane runs only beside its agent, so `GET /` there found nothing, and the Agents page offered Reconnect over the user's billion-context (33sczf on X). A sync keeps such a prefix in front of the gateway (`chainPrefix` in `keptaway.go`). `TestBiliChainIsStillMagpie`, `TestClaudeBehindBiliLaneKept`. 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`, `-` 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 (`.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`. +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; 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`): 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). An address on loopback whose path ends in the gateway's own URL (billion-context's lane, `http://127.0.0.1:18787/bili/`, which the Library's billion-context tab gives Claude Code) is magpie without asking (`chainsToGateway`): the lane runs only beside its agent, so `GET /` there found nothing, and the Agents page offered Reconnect over the user's billion-context (33sczf on X). A sync keeps such a prefix in front of the gateway (`chainPrefix` in `keptaway.go`). `TestBiliChainIsStillMagpie`, `TestClaudeBehindBiliLaneKept`. 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`, `-` 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 (`.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 #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 @@ -128,7 +128,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`). An edit's result is checked as the apps read JSONC (`edit.ValidJSONC`: jsonc-parser with `allowTrailingComma`, as OpenCode, VS Code and Zed parse; a trailing comma after a value is fine, one with nothing before it, `{,}` or `},,`, is not), and an edit that would turn a file the app reads into one it can't is refused, nothing written (`checkJSONC`). A delete takes the last member's own trailing comma with it, an insert into an object of comments only adds no comma, and a lone comma an older magpie left (`"mcp": {,}` after the router was toggled for OpenCode, chenxiang0010 on Discord) is dropped by the next edit of that file (`dropLoneCommas`). - 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's model picker tags each of its own models by where a pick on the Agents page sends it: via magpie while routed or joined, and direct while it is only beside its sign-in on one of magpie's models (`beside`, not joined), where such a pick takes magpie out (#940) and the GUI asks first (`TestCodexBesideOwnModelsSayDirect`). - Show Codex's own models (`provider.OwnModelsHidden("codex")`, the switch in the Agents page's model list, #1642) also governs Codex's own picker, not only magpie's Agents page: `codexMerged` leaves the sign-in's visible models out of the list the gateway hands Codex and the Codex app's list file (`provider.CodexOwnLeftOut`; `~ownoff` is in the list's tag so Codex asks again). The model Codex is set to (`agent.CodexModelNow`), a model magpie serves on a ChatGPT account and hidden jobs (codex-auto-review) stay. It left Codex's picker as it was before, with the Codex provider off too (iiiiiimone on X). It doesn't take a pick of Codex's own model off the gateway: Codex has one `openai_base_url` for every model, so one it is still set to goes to `/backend-api/codex` and on to OpenAI on Codex's own sign-in (`codexUpstreamOn`), never through magpie's accounts while the Codex provider is off. `TestCodexListWithOwnModelsOff`. - Every other agent's own models (`ownProvider` in [`agents.go`](../../internal/agent/agents.go), the provider list read from its own auth file or config: Pi, OpenCode, Goose, Crush, Cline, Hermes, the WSL twins and the rest; omp's `ompOwnOptions`) say `Direct` with the provider's name: each is asked of that vendor on the agent's own sign-in or key, so a pick takes the agent off magpie. The picker tags them direct, lists them after magpie's, and asks before such a pick turns 「接入」 off (maxleebeta on Discord: Pi's own OpenCode Go model switched it off with nothing said; `TestOwnModelsSayTheyGoDirect`, `agent-own-direct.test.cjs`). - A line magpie writes into an agent's TOML, YAML or dotenv config gets a comment line of its own just above it, `# magpie: ; ` (`edit.Mark`, set to `agent.lineNote` by the CLI's `run` in [`mark.go`](../../internal/agent/mark.go); the edit side in [`internal/edit/mark.go`](../../internal/edit/mark.go)). Jevik_AI on X deleted magpie's folders by hand, and Codex's `config.toml` kept `openai_base_url` on the gateway with nothing in it naming magpie: every turn was a 502. Only a one-line scalar that points at the gateway or names magpie's model list gets one, and only when the write adds or changes that line, or it had a note already; a line of the user's own that magpie leaves as it is gets none. The note is never on the value's line: Grok App's `providers.rs` reads the rest of a line as the value. Every write takes the notes out first and puts them back over the lines that still need one, so a note goes with its line and a Disconnect leaves none. A YAML note that would change what the file reads as isn't added (`sameYAMLValue`). JSON has no comments and gets none. Tests set no `Mark`, so their exact bytes stay; `TestMarkedLinesEveryAgent` connects every agent with notes on and checks each gateway line has one, a second sync writes nothing, and Disconnect leaves none; `TestCodexMarkedLines`, `internal/edit`'s `TestMark*`. @@ -212,11 +212,11 @@ something else shows up as drift. - The other way round, a value that names one of magpie's models the agent isn't shown (kept from it by `magpie visible` or a model not ticked for it), a model of one of magpie's providers that isn't on its list (a remote magpie's group added there since the list was fetched), or a `group/…` magpie has no group for, is refused by `Spell` (`notOffered`), and nothing changes. It used to be written as the agent's own: Pi read `remote/group/smart` as its own provider `remote` and model `group/smart`, and was taken out of magpie (#2376). A model shown the agent that a field offers fewer of (Claude Desktop's tiers) is still taken, and so is a value whose provider part one of the agent's own models goes by (`openai/…` in Pi) ([`agent.go`](../../internal/agent/agent.go), `TestSpellRefusesMagpieModelNotOffered`). - `Reapply` on `unwired` sets again every field on one of magpie's models and every field set to magpie itself (`magpieID`, as `Wired` takes it): Claude Desktop's drift shows on a tier, and its `provider` field is what writes the gateway back (dumplings on Discord). Claude Desktop's `Check` judges only the set of folders whose Claude-3p it ran in last (`desktopRead`, by `desktopdir.LastRun`), every set when it ran in none: magpie writes both of an MSIX install's sets, and 2.31226 reads the real `%LOCALAPPDATA%\Claude-3p`, so the package's copy being emptied is not Desktop off magpie. - `unreachable` never sets anything: the config is right, and the page's pill only says what has to listen. The exception is an address a WSL distro reached Windows at before (`distro.Was`, kept in `wsl.json`) while it reaches Windows at another now: the pill offers that one, and `Reapply` moves the config there (`Agent.move`, Codex's `codexMoveGateway`). An address no distro was seen at is the user's own and is never moved. An unknown answer (no probe yet) and a gateway down on loopback too are not drift. Tests stub `reachProbe` in `TestMain`. A WSL twin's address on a WSL network is asked from inside the running distro (`reachFrom`, `wslReach`: curl, wget or bash's /dev/tcp), never from Windows, where the gateway's own listener answers whatever the firewall keeps out. A distro that can't connect is told the firewall rule that lets it in (`wslFirewallCommand`). A stopped distro is never run to be asked, and one with nothing to ask with is not drift. -- `proxied` (Muma102kMichael on X: every project and every new chat 502 after magpie took Codex over) is this machine's Codex sending its requests for the gateway through a proxy that doesn't pass them on, while the gateway answers here ([`codex_proxy.go`](../../internal/agent/codex_proxy.go)). Codex's reqwest takes `HTTP_PROXY`, else the system's proxy for `http://` (macOS' HTTP entry alone, never its HTTPS or SOCKS one; Windows' `ProxyServer` only when it is one address for every protocol), else `ALL_PROXY`, and lets only an exact IP or a CIDR in `NO_PROXY` (on Windows, with no `NO_PROXY`, the bypass list with `*.` taken out) keep 127.0.0.1 off it: `127.*` and `localhost` don't, and macOS' exceptions aren't read. With `[features] respect_system_proxy` it asks the system alone, matching its list itself, wildcards and `` included, and goes direct when no proxy is set there; a macOS SOCKS entry alone it can't use, and takes `HTTP_PROXY`/`ALL_PROXY` then (codex-rs `outbound_proxy`; tried with codex-cli 0.162.1). Its reqwest has no SOCKS, so a `socks5://` proxy is spoken to as an HTTP one, and the probe does the same. The environment is Codex's: the login shell's `*_PROXY` (`proc.LoginEnv`, which a terminal's Codex and the ChatGPT app's both have; only exported ones, as the probe asks a child `/bin/sh` for them, so fish's unexported universal `http_proxy` doesn't count, #2627) over magpie's own, which a magpie opened from the Dock lacks (liu_dyj on X: a `NO_PROXY=127.0.0.1` in the profile, or a macOS proxy with no HTTP entry, warned while Codex went direct). `codexProxyFor` works out that proxy the same way, and a `GET /` through it must come back as magpie's (`proxyProbe`), tried as `reachable` is. Its pill says how to fix it, as `unreachable`'s does, naming the proxy and the variable it was read from, `http_proxy` or `HTTP_PROXY` as it is (`Addr`, `Detail`), through `netproxy.Redact`, without its user and password (#1886), while the probe goes through it whole, and the dialog has Disconnect from magpie. Account failover, which magpie writes uninvited, waits for that probe (`codexProxyOK`) and isn't written while the proxy doesn't pass Codex on, and one it wrote goes again. Tests stub the env, the system proxy and `proxyProbe` in `TestMain`. +- `proxied` (Muma102kMichael on X: every project and every new chat 502 after magpie took Codex over) is this machine's Codex sending its requests for the gateway through a proxy that doesn't pass them on, while the gateway answers here ([`codex_proxy.go`](../../internal/agent/codex_proxy.go)). Codex's reqwest takes `HTTP_PROXY`, else the system's proxy for `http://` (macOS' HTTP entry alone, never its HTTPS or SOCKS one; Windows' `ProxyServer` only when it is one address for every protocol), else `ALL_PROXY`, and lets only an exact IP or a CIDR in `NO_PROXY` (on Windows, with no `NO_PROXY`, the bypass list with `*.` taken out) keep 127.0.0.1 off it: `127.*` and `localhost` don't, and macOS' exceptions aren't read. With `[features] respect_system_proxy` it asks the system alone, matching its list itself, wildcards and `` included, and goes direct when no proxy is set there; a macOS SOCKS entry alone it can't use, and takes `HTTP_PROXY`/`ALL_PROXY` then (codex-rs `outbound_proxy`; tried with codex-cli 0.162.1). Its reqwest has no SOCKS, so a `socks5://` proxy is spoken to as an HTTP one, and the probe does the same. The environment is Codex's: the login shell's `*_PROXY` (`proc.LoginEnv`, which a terminal's Codex and the ChatGPT app's both have; only exported ones, as the probe asks a child `/bin/sh` for them, so fish's unexported universal `http_proxy` doesn't count, #2627) over magpie's own, which a magpie opened from the Dock lacks (liu_dyj on X: a `NO_PROXY=127.0.0.1` in the profile, or a macOS proxy with no HTTP entry, warned while Codex went direct). `codexProxyFor` works out that proxy the same way, and a `GET /` through it must come back as magpie's (`proxyProbe`), tried as `reachable` is. Its pill says how to fix it, as `unreachable`'s does, naming the proxy and the variable it was read from, `http_proxy` or `HTTP_PROXY` as it is (`Addr`, `Detail`), through `netproxy.Redact`, without its user and password (#1886), while the probe goes through it whole, and the dialog has Disconnect from magpie. Tests stub the env, the system proxy and `proxyProbe` in `TestMain`. - Listing never starts a stopped WSL distro. A stopped distro's agent shows what was last seen there (`asleep`, `wsl.json`); setting one of its fields writes its files, which starts the distro. The Library keeps what it last saw of each agent's places there in the same memory (`WSLKeep`, `WSLKept`; see [library](library.md)), and lists a stopped distro's agents from it. - Codex's sign-in (`login`) is ChatGPT (`""`, the default), Always ChatGPT (`chatgpt`) or magpie API (`api`). With ChatGPT, magpie's models join Codex's own beside the sign-in (`openai_base_url`), and while the Codex app holds the ChatGPT account Codex is signed in to (`codexUsedUp`, `provider.CodexUsedUp`: OpenAI no longer allows the account and it has no credits left, a workspace still within its overage excepted), magpie is made Codex's provider (`codex.out`): the Codex app sends nothing at all on an account it holds, a magpie model's turn included (#540), and as a provider of its own magpie is past that. A window at 100% with credits left doesn't count, and Codex stays signed in. Sync puts it back beside the sign-in once the account has room. Always ChatGPT never does that: Codex stays in its ChatGPT state, and the Codex app may send nothing till the account has room, while Codex CLI's turns still reach magpie by the base URL, and its routing and other accounts serve them. Codex's app-server answers `account/read` and `getAuthStatus` with no account and no token for a provider without `requires_openai_auth`, and the Codex app then switches to an identity of no account: its ChatGPT mode's chats and projects ("Work") are gone, with its Chrome control (#1824) and cloud tasks, while magpie's models still answer (Qyburn3 on X). So `[model_providers.magpie]` says `requires_openai_auth = true` while Codex has a ChatGPT sign-in with room (`openaiAuth`: `codexChatGPTKnown` and not `codexUsedUp`), magpie API included; Codex still sends magpie's key (`experimental_bearer_token`) and no ChatGPT-Account-ID, with the same tools (tried with ChatGPT.app 26.1021 and its codex 0.164.0-alpha.11 against a capturing server). Not for an API key alone (Codex drops its image tool for a provider requiring OpenAI auth, `uses_openai_actor_authorization`), no sign-in (the app would ask for one), or a sign-in the Codex app holds: the app would read its rate limit again and grey Send for magpie's models too, which `codex.out` exists to get past. Sync writes the key in or takes it out as the sign-in or the allowance changes, an older magpie's table included (`authStale`), and the key is part of the app-server's route (`codexAppRoute`), so the Codex app is restarted onto its account (`TestCodexMagpieProviderKeepsChatGPTAccount`, `TestCodexAppRouteFollowsOpenAIAuth`). While magpie is Codex's provider for `codex.out` the app has no account till the reset, so the Agents row opened over that takeover names browser use among what is off and offers Keep on ChatGPT right there (`keepChatGPT`, posting `login` = `chatgpt`); picked on one of Codex's own models taken over (`codex/`), `set` puts Codex back on its sign-in at once, `model_provider` and `model_catalog_json` gone, where it had left magpie the provider (eddie.zhan on Discord, `TestCodexOwnModelOutThenKeptOnChatGPT`). While magpie is Codex's provider (magpie API, or `codex.out`), `Joined` reports false although the `codex.joined` mark stays for Sync's way back: the Agents row said Codex's own models stay in `/model` beside magpie's, the ChatGPT state the Codex app blocks sending in, and the app only leaves that state once it is restarted (#2267, `TestCodexProviderIsNotJoined`). A Codex that reaches the gateway from another machine (a WSL distro under NAT, or `MAGPIE_ADDR` pinned beyond loopback, `onAnotherMachine(at.gw())`) is wired as one with no ChatGPT sign-in (`chatGPT()` is false there): never joined or beside, since beside its sign-in it would send its ChatGPT token to `/backend-api/codex`, and from there the gateway takes a named key alone, so every request was a 401 (#2145, `TestCodexBeyondLoopbackNotJoined`). magpie is its provider and it sends `gwKey()`, the LAN sharing key; one of its own models picked goes straight to OpenAI on its sign-in. - Whether Codex is signed in to ChatGPT is read from its auth.json or keychain item (`codexChatGPTKnown`, `provider.CodexSignInKnown`). Codex rewrites auth.json in place when it refreshes its tokens (codex-rs `FileAuthStorage::save` opens it with truncate), so a read in that moment finds it empty or cut off, and a keychain read can fail for a moment. Such a read is unknown, and Codex is taken to be as magpie last wired it (joined, beside, or `codex.out`); only a sign-in that isn't there (no auth.json, no item) or holds no ChatGPT token is "not signed in". Taking an unknown read for "not signed in" made Sync or a pick move Codex from beside its sign-in to magpie as its provider, with no `codex.out` to bring it back, and the Codex app showed "magpie" for its account and magpie's catalog for its models, on and off (lucy on Discord, v0.1.1394; `TestCodexHalfWrittenAuthKeepsSignIn`, `TestCodexHalfWrittenAuthKeepsOut`, `TestCodexSignInKnown`). A top-level `forced_login_method = "api"` in Codex's config.toml (another tool or guide writes it; magpie never does) counts as no ChatGPT sign-in: Codex logs such a sign-in out as the TUI starts and its app-server reads no account (codex-rs `enforce_login_restrictions`, `load_auth`), so wired beside it the Codex app asked for a sign-in and offered an API key alone (Tiger on Discord). magpie is then the provider without `requires_openai_auth`, and Codex needs no sign-in. The line is the user's and stays; taking it out brings the ChatGPT account back to the Codex app (`requires_openai_auth`) (`TestCodexForcedAPILoginIsNoChatGPT`). So does a sign-in OpenAI refused to refresh for good (jjt on Discord, #4308): Codex keeps its auth.json as it was and the refusal in memory alone, and wired beside it every turn, magpie's models too, failed at Codex's workspace routing discovery (`/wham/accounts/check`, 401). magpie refreshes Codex's sign-in itself (`codexTokenRenewing`, on its usage read), and a refusal Codex takes as permanent (codex-rs `request_chatgpt_token_refresh`: `refresh_token_expired`, `_reused` or `_invalidated`, a 400 `invalid_grant`, or a 401 carrying an error code; `codexRefreshGone`) is kept for that Codex home as the refused refresh token's hash (`codex-signin-gone.json`, only while the store still holds that token). `codexChatGPTKnown` reads that sign-in as none (`provider.CodexSignInGone`), and magpie is the provider without `requires_openai_auth`; the user's auth.json stays. A 5xx, a network error, a 401 with no code, or a token Codex replaced meanwhile marks nothing, and a record that can't be read is unknown. Signed in again, the refresh token is another one and counts at once; `KeepOnAnAccountWithRoom`'s loop (`noteCodexGoneNow`) has Sync write `requires_openai_auth` back within minutes (`TestCodexGoneSignInIsNoChatGPT`, `TestCodexSignInGoneWhenRefusedForGood`). In left-alone mode magpie doesn't refresh Codex's sign-in, so nothing is recorded there. -- Codex signed in to ChatGPT and not connected still gets `openai_base_url` while more of its ChatGPT accounts are on in magpie (`failover`, stash `codex.failover`; with a CC Switch mirror as its provider, the mirror's `base_url` and `codex.mirror_failover`), so a turn its own account has no allowance for goes on to the next — never for a Codex that reaches the gateway from another machine, where that path takes a named key alone and the failed-over turn came back a 401 (#2145, `TestCodexFailoverBeyondLoopbackNotWritten`); Sync takes one it wrote before off again. That Codex is `FailingOver`: not `Wired`, yet its requests go through magpie. The Agents row says so and what turns it off (`FailoverSaid` in the CLI and TUI, `failover` in `/api/state`, a button to Providers › Codex in the GUI), and the gateway hands it only its own models from `/backend-api/codex/models` (`CodexOwnOnly`, set on `gateway.CodexOwnOnly` by main; its ETag carries `provider.CodexOwnListTag`, and Sync ages a `models_cache.json` without it). A connected WSL Codex shares the gateway path, so while one is connected every Codex gets magpie's models (#1385). A base URL the user wrote by hand (#856) isn't failover's and stays a plain not-connected row. A Codex the user disconnected gets no failover till they connect it again. The app serving the gateway takes failover out as it quits (`EndFailover`, `EndCodexFailover` in `OnShutdown`), so a Codex left on its own goes straight to OpenAI rather than retrying a gateway that's gone (Leon920717 on X); the next start's Sync writes it again. Codex's app-server read the old base URL as it started and keeps it, and `KeepCodexDaemonCurrent` ends with magpie, so `EndCodexFailover` restarts it there when no codex session is on it (`codexDaemonCheck`); with one on it, it stays on the gone gateway until the user restarts it (thisisvainxx on X: "several restarts"). So does every thread already open, in the Codex app above all: each turn went to the closed port, and a system proxy in between answered `503 Service Unavailable: Unknown error, url: http://127.0.0.1:3425/backend-api/codex/responses` until magpie was opened again (idkatbro on X; without a proxy Codex says "Connection refused" and reconnects). Masking plays no part: it runs only in the gateway, and its own 503 says why. When `EndCodexFailover` took failover out, the gateway's address is this computer's and Codex runs (`provider.CodexPIDs`: the app's app-server, the daemon, the CLI's sessions, an editor's codex), `OnShutdown` starts `magpie codex-relay` apart from itself (`agent.RelayOpenCodex`, `codexrelay.Start`; Setsid, or a detached process on Windows). It waits up to 60 s for the gateway to let go of the port, then serves only `/backend-api/codex/*` from Codex on this computer (a loopback Host, no Origin) and passes each request to the ChatGPT backend as the gateway passes a turn of Codex's own: the same item-id, compaction and Claude-seal rewrites, zstd and proxy, signed by the caller's own Authorization (`gateway.CodexRelay`). A magpie model, a turn on one of magpie's accounts, and a turn masking would have masked are refused with a readable 400 instead (Codex retries a 5xx five times over and shows a 4xx at once); anything else says magpie isn't running, never as magpie (`ServedBy`). It ends once every Codex process it was left for has and nothing is in flight, and the next magpie to serve the gateway asks it to leave (`codexrelay.Leave` in `ListenAndServe` and `serveGatewayLocked`; a POST with the token from `codex-relay.json`, 0600 in magpie's folder): it closes its listener at once and finishes the turns it streams, up to 30 minutes. `TestCodexRelay*`, `TestLeaveFreesPortAndFinishesStream`, `TestEndsWhenCodexGone`, `TestLeaveNeedsToken`. Not covered: a connected Codex (magpie's models, left pointed at magpie by design), a Codex in a WSL distro, and a magpie that ends without quitting. Every restart magpie makes runs `codex app-server daemon restart` as its own responsible process on macOS (`proc.CombinedOutputOwn`, a disclaimed `posix_spawn`): the daemon works in the folder of each codex attached to it, and as magpie's child the first codex in ~/Desktop had macOS ask for the Desktop folder in magpie's name (reformed9448 on Discord; `TestRestartedCodexDaemonIsNotMagpies`). A magpie built without cgo (the CLI) still restarts it as its own child. A connected Codex keeps magpie as it quits: its model is one of magpie's, and Disconnect is what puts its own config back. A magpie that ends without quitting (killed, a crash, `magpie serve`) leaves failover in place. +- A Codex that isn't connected is never pointed at the gateway, however many of its ChatGPT accounts are on in magpie. magpie once wrote `openai_base_url` for it by itself while another account was on, for account failover (#1385; stash `codex.failover`, and with a CC Switch mirror as its provider, the mirror's `base_url` and `codex.mirror_failover`), so an unconnected Codex's every request went through magpie, its row saying not connected, until a Disconnect (TylerBai_loveai on X). Failover between Codex's accounts now comes with connecting it. Sync takes out what failover wrote before, the marked base URL or mirror `base_url` (`failover` in codex.go), and the route change restarts the app-server; a base URL the user wrote by hand (#856) has no mark and stays. `TestCodexNotConnectedStaysOffMagpie`, `TestCodexFailoverFromBeforeTakenOut`, `TestCodexSwitchOnlyKeepsCodexOffTheGateway`, `TestCodexHandWrittenBaseURLStays`. Until that Sync, such a Codex is `FailingOver`: not `Wired`, yet its requests go through magpie. The Agents row says so (`FailoverSaid` in the CLI and TUI, `failover` in `/api/state`), and the gateway hands it only its own models from `/backend-api/codex/models` (`CodexOwnOnly`). The app serving the gateway takes failover out as it quits (`EndFailover`, `EndCodexFailover` in `OnShutdown`), so a Codex left on its own goes straight to OpenAI rather than retrying a gateway that's gone (Leon920717 on X). Codex's app-server read the old base URL as it started and keeps it, and `KeepCodexDaemonCurrent` ends with magpie, so `EndCodexFailover` restarts it there when no codex session is on it (`codexDaemonCheck`); with one on it, it stays on the gone gateway until the user restarts it (thisisvainxx on X: "several restarts"). So does every thread already open, in the Codex app above all: each turn went to the closed port, and a system proxy in between answered `503 Service Unavailable: Unknown error, url: http://127.0.0.1:3425/backend-api/codex/responses` until magpie was opened again (idkatbro on X; without a proxy Codex says "Connection refused" and reconnects). Masking plays no part: it runs only in the gateway, and its own 503 says why. When `EndCodexFailover` took failover out, the gateway's address is this computer's and Codex runs (`provider.CodexPIDs`: the app's app-server, the daemon, the CLI's sessions, an editor's codex), `OnShutdown` starts `magpie codex-relay` apart from itself (`agent.RelayOpenCodex`, `codexrelay.Start`; Setsid, or a detached process on Windows). It waits up to 60 s for the gateway to let go of the port, then serves only `/backend-api/codex/*` from Codex on this computer (a loopback Host, no Origin) and passes each request to the ChatGPT backend as the gateway passes a turn of Codex's own: the same item-id, compaction and Claude-seal rewrites, zstd and proxy, signed by the caller's own Authorization (`gateway.CodexRelay`). A magpie model, a turn on one of magpie's accounts, and a turn masking would have masked are refused with a readable 400 instead (Codex retries a 5xx five times over and shows a 4xx at once); anything else says magpie isn't running, never as magpie (`ServedBy`). It ends once every Codex process it was left for has and nothing is in flight, and the next magpie to serve the gateway asks it to leave (`codexrelay.Leave` in `ListenAndServe` and `serveGatewayLocked`; a POST with the token from `codex-relay.json`, 0600 in magpie's folder): it closes its listener at once and finishes the turns it streams, up to 30 minutes. `TestCodexRelay*`, `TestLeaveFreesPortAndFinishesStream`, `TestEndsWhenCodexGone`, `TestLeaveNeedsToken`. Not covered: a connected Codex (magpie's models, left pointed at magpie by design), a Codex in a WSL distro, and a magpie that ends without quitting. Every restart magpie makes runs `codex app-server daemon restart` as its own responsible process on macOS (`proc.CombinedOutputOwn`, a disclaimed `posix_spawn`): the daemon works in the folder of each codex attached to it, and as magpie's child the first codex in ~/Desktop had macOS ask for the Desktop folder in magpie's name (reformed9448 on Discord; `TestRestartedCodexDaemonIsNotMagpies`). A magpie built without cgo (the CLI) still restarts it as its own child. A connected Codex keeps magpie as it quits: its model is one of magpie's, and Disconnect is what puts its own config back. A magpie that ends without quitting (killed, a crash, `magpie serve`) leaves failover in place. - Codex's "applies to" field (`scope`, stash `codex.scope`; hpnjstar on X) chooses `codex -p magpie` alone: Codex reads `--profile ` from `.config.toml` beside `config.toml` (tried with codex-cli 0.165.0; it refuses `-p` while `config.toml` holds the legacy `[profiles.magpie]` or `profile = "magpie"`), so magpie writes `magpie.config.toml` with `model_provider`, `model`, `model_catalog_json`, the effort and its own `[model_providers.magpie]`, and never touches `config.toml` or the top-level `model_provider`, `model` and `openai_base_url` ([`codex_profile.go`](../../internal/agent/codex_profile.go)). Only magpie's models are offered; none of Codex's own, no joining, failover, CC Switch tables or subagent fields. Disconnect deletes that file and magpie's catalog. The choice changes only while Codex is disconnected, so the two wirings never share a config. An older Codex without profile files isn't served (`TestCodexProfileOnlyLeavesConfigTomlAlone`). - Codex on a magpie model the user has since unchecked in its provider's model list (`provider.Unpicked`: the provider has picks, its served models lack it, and it is not a decision model) moves to that provider's first model magpie lists for Codex (`pickedInstead`, [`model_unpicked.go`](../../internal/agent/model_unpicked.go)), in each wiring: Codex's Sync puts it through `set`, as picking it does, and the profile's Sync through `put` (JNDliuliuM on X: Codex CLI, restarted, still started on the old model; `Resolve` still serves it). A provider with no picks, whose list is the vendor's, keeps a model it lacks (#2642), and one with none of its models listed leaves Codex where it is. Other agents' model fields, and Codex's subagent and compaction models, are not moved yet (#6504). - A Codex thread keeps the provider it was started on. While a magpie model is on, CC Switch's provider tables go through magpie too (`takeTables`), and get their own base URL back when Codex steps off magpie (`giveTables`, stash `codex.tables`). CC Switch's OpenAI mirror (a table of another id, `name = "OpenAI"`, `requires_openai_auth`, no `base_url`) isn't reached by `openai_base_url`, which takes only the built-in provider to magpie: a thread started on it and reopened went straight to ChatGPT, which refused the magpie model picked in it, and magpie never saw the request (#1796). While Codex goes to magpie by the base URL, `takeMirrors` gives each such mirror magpie's ChatGPT backend as its `base_url` (stash `codex.mirrors`), and `giveMirrors` takes it off again; a mirror a profile names, or one whose `base_url` was changed since, stays as it is. Moving the threads onto another provider is the Sessions page's Move (#887). Codex 0.166 refuses to resume a thread whose provider isn't the one configured ("This chat uses openai, but your current provider is magpie", openai/codex#58865; 毅 on Discord), and for a legacy thread the rollout's `session_meta` wins over the state DB row. So when magpie becomes the provider, bringOver relabels plain rollouts in place and also moves legacy threads Codex packed to `.jsonl.zst` that were updated in the last 30 days, up to 128 MB a sync, newest first, each with a copy kept in the trash (`sessions.MovePackedCodexThreads`, `TestCodexThreadsFollowMagpieIn`, `TestMovePackedCodexThreads`); bringBack moves them back. A paginated thread (`history_mode = 'paginated'` in the row, every thread Codex 0.166 starts) is listed and resumed on the provider its row names, never its files' (codex-rs thread-store `read_thread`: "Paginated history may contain only a suffix, so its display metadata lives in SQLite"), so the 30 days and the budget left an API-key user's older OpenAI threads refused in the Codex app (Parry_Moody and Cyrus on Discord). Every one now moves by its row alone, of any age, packed or not, an id of any length, its files neither written nor copied (`sessions.RetagPagedCodexThreads`, after the in-place relabel), in bringOver, bringBack, bringOfficial, bringBeside and giveBeside (`RetagPagedCodexThreadIDs`); one a Codex has open (its writer lock, which would write its provider back) or wrote to in the last minute waits for the next sync. The Sessions page lists a paginated thread on its row's provider (`codexPagedProviders`, read again when the database or its WAL changes). Tried with the real codex 0.166.0 (`codex exec resume`): refused on magpie with the row on openai, resumed after the retag, and back on OpenAI after the reverse (`TestCodexPagedThreadsFollowByRow`, `TestRetagPagedCodexThreads`). Codex rebuilds a row from the rollout when a search listing or a missing row reconciles it, which would put a retagged thread back on its file's provider until the next sync. A thread a move leaves where it was because it was written to in the last minute or a Codex holds it open gets one more Sync once it is quiet and let go (`sessions.CodexThreadsBusyOn`: a recent rollout, or its writer lock held, tried under Codex's coordination lock; `codexThreadsLater` looks every 15s for up to 12h, one wait per home and provider): no other Sync may come for hours. bringBack's (the thread a turn ran in during the takeover, as the account came back) otherwise stayed on magpie, and the Codex app couldn't resume it on OpenAI, so Retry failed each time and its model read unavailable (nb5p on Discord, `TestCodexTakeoverThreadComesBackOnceQuiet`). bringOver's and lendOwn's are the chats the Codex app had loaded as magpie became Codex's provider: the app holds every loaded thread's lock however long ago it was written (tried with codex 0.165's app-server), checks a loaded thread's provider against config.toml at each turn, and refuses it ("This chat uses OpenAI, but your current provider is magpie", crypto0xfish on Discord) until it lets the thread go; resumed after that, it was refused again on its row's `openai` until something else synced (`TestCodexOpenThreadFollowsMagpieOnceLetGo`). The chat open at the switch is moved by its row (a legacy one in place, at equal id length) just before the Codex app's app-server is ended for the route change (`provider.CodexBeforeAppEnd`, `codexRetagOpenThreads`, `sessions.RetagLoadedCodexThreads`): the app holds its lock, but the end is a clean SIGTERM that writes nothing back, and the next app-server resumes it on the new provider, in both directions (tried with the real codex 0.167.1 app-server: refused with `modelProviderMismatch` openai to magpie and `modelProviderNotConfigured` magpie to openai without the retag, resumed with it; hubo31377762 on X; `TestCodexOpenThreadsMoveBeforeAppServerEnds`, `TestCodexRouteChangeMovesOpenChatsFirst`). The resumed thread's sandbox falls back to config.toml's default whatever the provider (#6028, a separate bug). That is done for the provider Codex was on before magpie (stash `codex.provider`, `openai` when none), a provider of the user's own too: a relay's table or CC Switch's `custom`, whose threads the Codex app listed and refused to open on magpie ("This chat uses custom, but your current provider is magpie", hxy920830 on X). An id of magpie's length (`custom`) is relabelled in place; any other (`myrelay`) is rewritten with a copy kept, the threads of the last 30 days, 128 MB a sync, newest first (`sessions.MoveRecentCodexThreads`), and none moves of a provider a profile names. OpenAI's threads come to magpie too, since the Codex app lists them and refuses each one there as it did on that provider ("此聊天使用的是 OpenAI,但你当前的提供商是 magpie", Lice9735 on X, Codex on its own `openai-http` table before). They are recorded in stash `codex.lent` with the user's provider as `to`, as `lendOwn` records its own below: the Disconnect gives every thread on magpie to that provider, where Codex resumes them, and `giveLent` gives these back to OpenAI once Codex is on it again. None moves while a profile names `openai` (`TestCodexOpenAIThreadsFollowMagpieFromOwnProvider`). Before, they stayed on OpenAI there. The Disconnect puts the user's `model_provider` back and bringBack returns the threads to it; so does CC Switch switching back to that provider (`TestCodexThreadsFollowMagpieIn`, `TestMoveRecentCodexThreads`). A thread started on `cc-switch-official`, the id CC Switch 3.17 to 3.20 gave the official account, is moved to `openai` (or `magpie`, whichever Codex is on) while magpie wires Codex, as CC Switch 4 does itself (#7948 there), unless the user's own top-level `model_provider` or a profile names that id (`bringOfficial`, AcMilan on Discord, `TestCodexMovesCCSwitchOfficialThreads`). CC Switch's OpenAI mirror is the ChatGPT account's as much, and the Codex app names a provider by its table's `name`, so a thread on the mirror with Codex on `openai`, or the other way round, was refused as "This chat uses OpenAI, but your current provider is OpenAI" (Chris on Discord; codex 0.167 `exec resume` refuses both by id, 0.168 drops the check). Its threads move the same way: `bringOfficial` takes every mirror table's that isn't at the top, named by a profile, or the provider magpie took down (stash `codex.provider`, whose threads `bringBeside` and `bringOver` move with a record and give back at the Disconnect), and a mirror at the top takes OpenAI's through `lendOwn` (`TestCodexMirrorThreadsFollowOpenAI`, `TestCodexMirrorAtTopJoinsWithItsThreads`, `TestCodexMirrorAtTopTakesOpenAIThreads`). Before #4347 (v0.1.2652) the beside wiring took a provider of the user's (CC Switch's `custom`) down and kept it in stash `codex.provider`, leaving Codex on OpenAI by the base URL with every thread of that provider refused ("This chat uses custom, but your current provider is openai", yikelizi9438 on Discord). While Codex stays so (routed by `openai_base_url`, no top-level `model_provider`), `bringBeside` moves that provider's threads to `openai` the same way (in place at OpenAI's length, the last 30 days rewritten otherwise) and records them in stash `codex.brought`; the Disconnect puts the provider back and `giveBeside` returns exactly those threads to it (`sessions.MoveCodexThreadIDs`), and if magpie becomes Codex's provider instead they go on to `magpie` (`followBeside`), where bringBack returns them at the Disconnect (`TestCodexBesideBringsTakenProvidersThreads`). The other way round, Codex on a provider of the user's at the top (CC Switch's `custom`, kept since #4347, CC Switch's OpenAI mirror too; not magpie, `openai` or `cc-switch-official`) could not continue a thread started on OpenAI before ("This chat uses openai, but your current provider is custom. Switch to openai to continue", harris on Discord, after CC Switch). Each Sync moves OpenAI's threads to that provider the same way (`lendOwn`: in place at OpenAI's length, by the row for a paginated one, the last 30 days rewritten otherwise) and records them in stash `codex.lent`; once Codex is on OpenAI again `giveLent` returns exactly those (`sessions.MoveCodexThreadIDs`, `RetagPagedCodexThreadIDs`), the record kept while Codex is on that provider or on magpie and dropped on any other. None moves while a profile names `openai`, after the user disconnected Codex, or from a distro's Codex (`TestCodexOwnProviderTakesOpenAIThreads`, `TestCodexOwnProviderLeavesOpenAIThreads`). Each rewrite (`codexOnto`, shared by bringOver, bringBeside and lendOwn) goes `packedBudget` bytes a sync, newest first; when the budget stops it with threads left (`MovePackedCodexThreads` and `MoveRecentCodexThreads` say `more`), it asks for the next sync at once (`codexThreadsAgain`) instead of leaving them refused until something else syncs, which may be hours away (`TestCodexThreadsLeftByTheBudgetAskAgain`). Threads on any other provider, and ones older than 30 days that can't be relabelled in place, stay put: the Sessions page's Move or Resume takes them over. @@ -280,7 +280,7 @@ go test -tags nogui ./internal/agent -run '^TestGrokApp' go test -tags nogui ./internal/agent -run 'ClaudeScience' go test -tags nogui ./internal/gateway -run 'TestClaudeScience' go test -tags nogui ./internal/agent -run '^TestPlugged' -go test -tags nogui ./internal/agent -run 'TestCodexFailoverOnlyKeepsOwnModels|TestCodexOwnModelThroughMagpieWhileAccountsOn|TestCodexHandWrittenBaseURLStays|TestCodexProxyFor|TestRealProxyProbe|TestCodexEnvTakesLoginShell|TestCodexFailoverHeldWhileProxyDoesNotPassOn|TestCodexProxiedDrift|TestCodexFailoverEndsWithMagpie|TestCodexMirrorFailoverHeldAndEndsWithMagpie' +go test -tags nogui ./internal/agent -run 'TestCodexFailoverOnlyKeepsOwnModels|TestCodexNotConnectedStaysOffMagpie|TestCodexFailoverFromBeforeTakenOut|TestCodexHandWrittenBaseURLStays|TestCodexProxyFor|TestRealProxyProbe|TestCodexEnvTakesLoginShell|TestCodexProxiedDrift|TestCodexFailoverEndsWithMagpie|TestCodexMirrorFailoverEndsWithMagpie' go test -tags nogui ./internal/agent -run 'TestDisconnectStaysThroughSync|TestCodexDisconnectStaysWithAccountsOn|TestCodexAPIDisconnectStays' go test -tags nogui ./internal/tune ./internal/agent -run 'TestCompact|TestCacheTTL|TestTune' go test -tags nogui ./internal/sessions -run 'CompactTook' diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index ae2221d2e..1426f2bf7 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -61,7 +61,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | Export to files | `ExportLogins` (ChatGPT, Claude) writes the saved accounts in the two formats `ImportLogins` reads (heyiwei5 and Rk1ngggg on X): Sub2API's `sub2api-data` (one file, `sub2apiAccount`: `platform` openai or anthropic, as Sub2API's `account_data.go` has it) or CLIProxyAPI's auth files (one an account, `cliproxyAuth`, named `-[-].json`), so a round trip into magpie, Sub2API or CLIProxyAPI works (`TestExportClaudeRoundTrip`, `TestExportCodexRoundTrip`). A CLIProxyAPI Claude file also carries `account_uuid` and `org_uuid`, which its own readers ignore and `loginEntry` keeps, so two seats of one email stay two accounts. The file holds live sign-ins: it is written 0600 and never over a file (`WriteExport`), no surface prints a token, and each says first (`ExportRisk`) that whoever has the file is signed in as the account, and that a ChatGPT refresh token renews in one place only, so the first tool to renew it signs the other out. An account with no refresh token (access-only, a setup-token) is skipped and named with why. The window's *Export accounts to a file…* row on a ChatGPT or Claude account list (`acctexport.js`, `POST /api/signin/export`) saves into Downloads (a folder of its own for CLIProxyAPI's) and shows the path; `magpie accounts export [...] [--format sub2api\|cliproxyapi] [--to ] [--yes]` asks first without `--yes`. | [`login_export.go`](../../internal/provider/login_export.go), [`accounts_cli.go`](../../internal/cli/accounts_cli.go), [`gui/providers.go`](../../internal/gui/providers.go), [`acctexport.js`](../../internal/gui/assets/acctexport.js) | | Claude setup-token | A Claude account can be added from the long-lived token `claude setup-token` prints (sfss5362 on X), which Claude Code takes in `CLAUDE_CODE_OAUTH_TOKEN` (the window's *Use a setup-token instead…* and *Add an account by setup-token…*, `POST /api/signin/claude-token`). `AddClaudeSetupToken` keeps it in `logins.json` as `{"setupToken":…}`, named `Claude setup-token <6 hex of its hash>` (it tells no email), on beside the others; the same token again is the same account. Such a token has the inference scope only: Claude Code's `auth status` says `oauth_token` with no email or plan, and its `/usage` prints the API cost view, so `/usage` is never run for it and its allowance is unknown (`errClaudeSetupToken`, kept by `passing` as saying nothing about the account) until a reply's rate-limit event tells it. Its config directory (`claudeTokenDir`) holds no `.credentials.json`, which Claude Code could fall back to on a refused token. Claude Code itself is never signed in to it: `addLogin`, `switchLogin`, `putClaudeLogin`, `SetKeepLoginAs`, `NextLogin` and `signInToFirst` pass it over, and the window shows Remove and *magpie only* in place of Use and Make first. Not tried with a real token. | [`claude_setup_token.go`](../../internal/provider/claude_setup_token.go), [`claude_subscription.go`](../../internal/gateway/claude_subscription.go) (`inClaudeDir`), [`providers.go`](../../internal/gui/providers.go) | | ChatGPT access token only | A saved ChatGPT account can be kept with only the access token it has (EastonXvii on X: `savedLogin.AccessOnly`, `codex_access_only.go`), from the import (`ImportCodexAccessOnly`; the window's *Access token only* tick, `magpie accounts import codex --access-only`) or on a saved account (`SetLoginAccessOnly`; `POST /api/login/access-only` and `/renewed`, the row's ⋯, `magpie accounts access-only codex on|off`). magpie never refreshes it, which would rotate its refresh token and sign out where it came from: the import sends nothing to ChatGPT's token endpoint and needs an unexpired access token and an id_token (a refresh token is optional, and the import is told apart by its access token); `renewSaved` hands out the token while its own exp is ahead (`accessOnlyToken`), refuses a forced renewal without lapsing, and lapses the account once the token has run out or the backend turned it away (`accessOnlyLapse`, a `refreshRefused`); the keep-alive passes it over. Codex itself is never signed in to it (`switchable`, `switchSavedLogin`, `NextLogin`'s return, keep-as), and the account Codex renews itself, here or in another `CODEX_HOME`, can't be kept so (`errAccessOnlyHeld`). Its row says *magpie only*, and once lapsed *Access expired* with *Import again*. Signing in to it again in magpie, or importing it without the tick, replaces the entry with one magpie renews. | -| Switch accounts only | magpie as a Claude Code (or Codex) account switcher alone, with nothing connected (the owner on X; growaiskills, Rennix7t). In the window, the Agents row of a Claude Code or Codex not connected says the account it is signed in to (`switchEntry` in app.js, from the providers list `prefetchProviders` reads at start, so `/api/state` reads no keychain for it), also when magpie has no models to connect (`switchable`, before the `empty` line). Its menu, headed *Switch accounts only*, lists the agent's saved accounts: a pick goes through `POST /api/login/switch` (`SwitchLogin`), or `provider/keeplogin` with `keepLoginAs` when the agent is kept signed in to an account of the user's choosing, as the account rows do; the button says *Switched* for five seconds and the status line says new sessions use the account, one already open keeps its own until started again. *Only switch {agent}'s sign-in* (`SwitchOnly` above, `provider/switchonly`) is a ticked item there (Codex: with more than one usable account, as under Providers), and the row then says *Not connected · switching accounts only*. *Manage accounts…*, and a pick whose sign-in lapsed, open Providers › the agent. A Codex failing over (#1385) has it in place of the old *ChatGPT accounts* button. In the tray panel (whose Quick panel shortcut opens it from any app, shuizhuyu on X) it is the *account* line of the agent's opened row (`.ag-who`), drawn from the list kept from the last read (`panelAccounts`, `GET /api/providers?last=1`, no keychain read; a fresh read only when none is kept), so opening the panel reads no sign-in. The menu waits for one fresh `/api/providers` read and opens on what it says; *Manage accounts…* and a lapsed pick open the window's Providers (`window/main?view=providers`). The provider and login actions keep their answer as the last list (`keepProviders`), so a switch made anywhere is in the panel's next line at once (`TestKeptProvidersFollowActions`, `panel-switch-accounts.test.cjs`). Not on a WSL twin's row, not on a connected agent's. | [`app.js`](../../internal/gui/assets/app.js), [`logins.go`](../../internal/provider/logins.go) | +| Switch accounts only | magpie as a Claude Code (or Codex) account switcher alone, with nothing connected (the owner on X; growaiskills, Rennix7t). In the window, the Agents row of a Claude Code or Codex not connected says the account it is signed in to (`switchEntry` in app.js, from the providers list `prefetchProviders` reads at start, so `/api/state` reads no keychain for it), also when magpie has no models to connect (`switchable`, before the `empty` line). Its menu, headed *Switch accounts only*, lists the agent's saved accounts: a pick goes through `POST /api/login/switch` (`SwitchLogin`), or `provider/keeplogin` with `keepLoginAs` when the agent is kept signed in to an account of the user's choosing, as the account rows do; the button says *Switched* for five seconds and the status line says new sessions use the account, one already open keeps its own until started again. *Only switch {agent}'s sign-in* (`SwitchOnly` above, `provider/switchonly`) is a ticked item there (Codex: with more than one usable account, as under Providers), and the row then says *Not connected · switching accounts only*. *Manage accounts…*, and a pick whose sign-in lapsed, open Providers › the agent. A Codex still failing over from a magpie before (#1385, until the next Sync takes it out) has it in place of the old *ChatGPT accounts* button. In the tray panel (whose Quick panel shortcut opens it from any app, shuizhuyu on X) it is the *account* line of the agent's opened row (`.ag-who`), drawn from the list kept from the last read (`panelAccounts`, `GET /api/providers?last=1`, no keychain read; a fresh read only when none is kept), so opening the panel reads no sign-in. The menu waits for one fresh `/api/providers` read and opens on what it says; *Manage accounts…* and a lapsed pick open the window's Providers (`window/main?view=providers`). The provider and login actions keep their answer as the last list (`keepProviders`), so a switch made anywhere is in the panel's next line at once (`TestKeptProvidersFollowActions`, `panel-switch-accounts.test.cjs`). Not on a WSL twin's row, not on a connected agent's. | [`app.js`](../../internal/gui/assets/app.js), [`logins.go`](../../internal/provider/logins.go) | | Used-up switch | When the account Codex or Claude Code is signed in to has used its allowance, the agent is signed in to the next account that is on and has room (#208). Claude Code whose requests go to magpie's gateway (`ClaudeThroughMagpie`: its settings' `ANTHROPIC_BASE_URL` is the gateway, either sign-in) is not moved: the gateway already sends its requests to an account with room, and moving the sign-in only took away what the user signed it in for, such as claude.ai connectors (oreoft on Discord set it back more than ten times; `TestClaudeRoutedThroughMagpieKeepsItsSignIn`). Not routed, or with *Only switch Claude Code's sign-in*, it still moves. Codex's sign-in goes back to the account it moved off once that has room again, as the gateway's Smart and In order give it requests again; routed Until used up it doesn't, as the gateway keeps the requests on the next (`routes.Drain`), so it stays with them till that one is used up too, as Claude Code's and a switch-only Codex's do unless routed In order (`returnsToFirst`; WalterAIBuilder on X: Codex signed back in to the first showed that one in use while the second's week was spent, `TestCodexDrainSignInStaysOnTheNext`). When every one is past its line too, it goes to the one with the most room left (`roomLeft`: the fullest stopping window's distance below the switch share, or the account's own cap when lower), when that has more than the account it is on by `roomMargin` (1 point), so two all but even accounts don't trade it each look; else it stays (StringKe in #4532, after cswap's `best`; `TestNextLoginTakesTheMostRoomWhenAllArePast`). A Claude account on overages (/usage's "You are currently using your overages…" line) is read with its windows and a spent *Extra usage* row of text (`claudeOveragesWindow`: Used 100, ending when the last used-up window renews, else at the next reading), so it is moved off as a used-up one; before, the line made the reading an error, and the switch, which stays on an account it can't read, left Claude Code billing overages (StringKe, #4532; `TestClaudeSwitchOffOverages`). The GUI says the row *In use* in the reader's language. Under the accounts of a Claude Code or Codex with more than one, the switch is a switch of its own, *Switch {agent}'s account automatically* (the `auto-switch` box in app.js; off is `KeepLogin`, posted to `provider/keeplogin`; before 11-11 a *Keep {agent} signed in to* tick that turned it off, which a user read as the switch gone). On, a line under it says what the switch does with that agent's sign-in (`SignInMovesOf`, `signInMoves` on its `/api/providers` row, `signInMovesLine`): left where the user put it while Claude Code's requests go through the gateway (`gateway`), else the share it moves at and whether it comes back to the first (`moves`), each decided as `NextLogin` decides it (`TestSignInMovesSaysWhatSwitchDoes`). Off, it names the account the agent stays on, with a pick of another (`keepLoginAs`). Switch-only always moves the sign-in, so the switch is held on there (sign-in-moves.test.cjs). Beside the switch, an ⓘ mark whose hover card (settingshints.js, the box a `.hint-row` with its `.hint` lines out of sight) says how the switch works and why it is the agent's own use of the account: the sign-in written where the agent keeps its own, as `/login` or `codex login` does; usage read by Claude Code's own `/usage` or where Codex's `/status` reads it; for Claude Code, every request still sent by Claude Code itself straight to Anthropic; and that sharing an account is against the vendor's terms. It promises nothing about bans (autoswitchtip.js, loaded when the switch is drawn). Only where the sign-in moves: `moves`, or `kept` without `routed`, which `SignInMovesOf` sets when Claude Code goes through the gateway, so turning the switch on would move its requests, not its sign-in. Routing (`Allowances`) skips Text rows, so the gateway's own choice of account doesn't count it. A model's own week (`Current week (Sonnet only)`, `(Fable)`) counts for that model in routing, not for the switch, which moves the sign-in only on windows that count every model (`usedPast`); "Sonnet only" is read as the Sonnet week, `7 days · Sonnet` counting `sonnet`, the window the `seven_day_sonnet` header keeps (#4532, `TestClaudeUsageSonnetOnly`). `magpie accounts switch next` (`NextInOrder`) takes the other accounts the agent can be signed in to (`switchable`, not lapsed), on or off in magpie as the accounts list's *Use* does, so one the agent signed itself in to, which starts off, is in the rotation (StringKe, #4532; `TestNextTakesAccountsThatAreOff`), from the one after the account the agent is on, wrapping round: the first with room, else the one with the most room left, said to be past its line; with no reading of any, it refuses rather than guess (`TestNextInOrder`). For Codex, *Only switch Codex's sign-in* (`SwitchOnly`, `SetSwitchOnly`) keeps magpie's `openai_base_url` failover out of Codex's config, so the switch is all magpie does (#1907); an unreadable providers.json reads as switch-only, so the failover is not written on a guess. For Claude, the same setting keeps the accounts to Claude Code (`Provider.KeptToAgent`): `On()` is false, so the gateway, catalog and groups serve nothing on them, while switching and usage, gated by `leftAlone` on the raw `Off`, go on. No request of a saved Claude account passes magpie then, so one Claude Code wasn't signed in to since has no reading: once the account Claude Code is on is spent, `NextLogin` reads such a spare (`readSpare`, `spareRead` in `claudeWindows`) by Claude Code's own `/usage` in the account's directory, in order and only till one has room; a spare read once is not read again, and one whose read failed waits `claudeUsageWait` (cn_Vincentzyx on X, `TestClaudeSwitchOnlyReadsUnreadSpares`). Codex's spares are read through their saved tokens and had no such gap. Claude Code on its own login is out long before a five-minute look notices (#4443: 4% left to refused in two minutes): while Claude has an account to move to, `KeepOnAnAccountWithRoom` looks at its sign-in every `claudeLookEvery` (a minute) between its full looks when `claudeLookDue`, that is when the account Claude Code is on is near out (`claudeNearOut`, `codexNearShare`; its `/usage` is then due after `claudeNearOutWait` rather than `claudeUsageWait`), or when Claude Code wrote a `rate_limit` refusal ("You've hit your … limit") into one of its sessions since that account's last `/usage` (`scanClaudeLimits`, which reads only what was appended to each `projects/*/*.jsonl` since the last scan). The refusal names no account, so it only makes the `/usage` read due (and the reading stale, `StaleAllowance`); the read decides (`TestClaudeNearOutIsReadEveryMinute`, `TestClaudeRefusalInSessionReadsAtOnce`, `TestKeepOnAnAccountWithRoomLooksAtClaudeNearOut`). | [`codex_switch.go`](../../internal/provider/codex_switch.go) | | Removing the signed-in account | `ForgetLogin` signs Codex or Claude Code in to another of its accounts first (`nextOnForget`: the first other that is on, else one whose sign-in holds, else any, never a setup-token account or one Codex keeps in another folder: `switchable`), then forgets this one; a switch that fails removes nothing (StringKe, #4532: Claude's was refused while Codex's switched). Codex's only account is signed out as `codex logout` does. Claude Code is never signed out: its last account it can be signed in to is refused with `SignedInError{Only}` (GUI code `signed_in_only`, and that account has no *Remove*). Claude Code's own credential is never deleted; the forgotten account's folder (`forgetClaudeDir`) is its own. `TestForgetLiveClaudeSwitchesFirst`, `TestForgetOnlyClaudeIsKept`, `codex-signout.test.cjs`. | | Claude Code's proxy | Claude Code on its own subscription asks Anthropic itself, through the proxy its env names. While any Claude account has a proxy of its own (`AccountProxies`), the `env` of Claude Code's `settings.json` names the proxy of the account it is signed in to (#1807): `HTTPS_PROXY` and `HTTP_PROXY` set to that account's own, else the subscription's `Proxy` (`ProxyOfLogin`), and `NO_PROXY` to loopback; none for `direct` or a SOCKS proxy, which Claude Code can't use. It is written on every switch (`switchLogin`, the user's or `SwitchWhenSpent`), when the Claude subscription is saved, and at the gateway's look every `loginSwitchEvery` (a sign-in made in Claude Code itself). Claude Code reads its env at start, so only sessions started after the switch take it. A proxy key the user set (in either case) is theirs: magpie then writes none and takes out none of theirs. What magpie wrote is kept in `claude-proxy-env.json`, and a key is magpie's only while it holds that value. A `settings.json` that doesn't parse is left as it is. Its log lines name the proxy through `netproxy.Redact`, without its user and password (#1886); the env gets it whole. | [`claude_proxy_env.go`](../../internal/provider/claude_proxy_env.go) | diff --git a/internal/agent/agent.go b/internal/agent/agent.go index c574c59d5..566f30274 100644 --- a/internal/agent/agent.go +++ b/internal/agent/agent.go @@ -235,15 +235,15 @@ type Agent struct { // is that group's (#750). Routed func() bool // FailingOver reports an agent that isn't connected whose requests - // still go through magpie's gateway, for account failover alone (Codex - // signed in to ChatGPT with more of its accounts on in magpie, #1385): - // the Agents page says so and what turns it off, and the gateway lists - // it only its own models. + // still go through magpie's gateway, for account failover alone: what + // a magpie from before wrote in Codex's config by itself (#1385), till + // Sync takes it out (TylerBai_loveai on X). The Agents page says so, + // and the gateway lists it only its own models. FailingOver func() bool // EndFailover takes out what account failover wrote, for magpie // quitting: left there, the agent would be pointed at a gateway that // no longer answers, and retry till magpie is open again (Leon920717 - // on X). The next start's Sync writes it again. + // on X). EndFailover func() error // TakeLeftovers takes out what magpie wrote that no Disconnect could // name: an address at magpie's gateway whose marks are gone (magpie's diff --git a/internal/agent/codex.go b/internal/agent/codex.go index 3ebb6d627..fb9e3190e 100644 --- a/internal/agent/codex.go +++ b/internal/agent/codex.go @@ -1560,69 +1560,28 @@ func codexIn(at place) *Agent { } forget(at.key("codex.lent")) } - // Codex on one of its own models goes through magpie too while more of - // its ChatGPT accounts are on there, so one out of its allowance hands - // the turn to the next; with none, or once the user disconnected Codex, - // it goes straight to OpenAI again + // A Codex that isn't connected goes straight to OpenAI on its own + // sign-in, however many of its ChatGPT accounts are on in magpie. + // magpie once pointed it at the gateway by itself for account failover + // (#1385) while another of its accounts was on, so an unconnected + // Codex's every request went through magpie, the row saying not + // connected, until a Disconnect the user had no reason to look for + // (TylerBai_loveai on X). Failover between the accounts comes with + // connecting Codex. What failover wrote goes as Sync next runs: the + // base URL it marked (codex.failover), or CC Switch's OpenAI mirror it + // pointed at magpie (codex.mirror_failover). A base URL the user wrote + // by hand, unmarked, is theirs and stays (#856). failover := func() error { if wired() || asProvider() { return nil } - p := get("model_provider") - mirror := isCCSwitchMirror(p) - if !mirror { - _ = dropMirrorFailover() + if err := dropMirrorFailover(); err != nil { + return err } - if p != "" && p != "openai" && !mirror { + if stashShared()[at.key("codex.failover")] != "1" { return nil } - // a Codex that reaches the gateway from another machine is never - // pointed at the Codex path: the gateway takes a named key there, - // so the turn failover handed it came back a 401 (#2145) - on := !disconnected() && codexFailover() && !onAnotherMachine(at.gw()) - // failover is magpie's own idea, not the user's: never handed - // Codex's requests while a proxy they'd go through doesn't pass - // them on to magpie, which would have every turn fail with 502 - // (codex_proxy.go); one written before goes again - if on && at.spell == nil && !codexProxyOK(path, at.gw()) { - on = false - } - if mirror { - t, _ := edit.GetTOMLTable(path, "model_providers."+p) - hasGateway := t["base_url"] == at.codexURL() - switch { - case on && !hasGateway: - if err := edit.SetTOMLKey(path, "model_providers."+p, "base_url", at.codexURL()); err != nil { - return err - } - stash(map[string]string{at.key("codex.mirror_failover"): p}) - case !on && hasGateway: - if err := edit.DelTOMLKey(path, "model_providers."+p, "base_url"); err != nil { - return err - } - forget(at.key("codex.mirror_failover")) - } - return nil - } - // the base URL failover wrote is marked (codex.failover), and only - // that one goes again: one the user wrote in config.toml by hand, - // to have Codex's own models go through magpie, stays (#856: it was - // gone again each time magpie started). One already there while - // failover is on is taken as failover's, as a magpie from before - // the mark wrote it. - owned := stashShared()[at.key("codex.failover")] == "1" - switch { - case on && !viaBase(): - if err := edit.SetTOMLTop(path, edit.KV{Path: "openai_base_url", Value: at.codexURL()}); err != nil { - return err - } - stash(map[string]string{at.key("codex.failover"): "1"}) - case on && !owned: - stash(map[string]string{at.key("codex.failover"): "1"}) - case !on && viaBase() && owned: - return dropBase() - } - return nil + return dropBase() } // failingOver: Codex reaches magpie for account failover alone, by the // base URL failover wrote (codex.failover) or by CC Switch's OpenAI @@ -1655,12 +1614,12 @@ func codexIn(at place) *Agent { 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) + // its own picked here takes magpie out (set, #940): 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()) { + !(joined() && chatGPT()) { ownThrough = false } say := func(own []Option) []Option { diff --git a/internal/agent/codex_ccswitch_test.go b/internal/agent/codex_ccswitch_test.go index 7a7612c4e..e5a20833f 100644 --- a/internal/agent/codex_ccswitch_test.go +++ b/internal/agent/codex_ccswitch_test.go @@ -112,7 +112,8 @@ func TestCodexKeepsHandPointedCCSwitchTable(t *testing.T) { // CC Switch's official OpenAI provider mirror writes model_provider = "custom" // and a [model_providers.custom] table with name = "OpenAI", requires_openai_auth = true // and no base_url (#504): it is the official provider, so its models are grouped -// under OpenAI and failover moves Codex onto magpie while another account is on. +// under OpenAI, and neither it nor a relay's table is pointed at magpie for a +// Codex not connected while another account is on (TylerBai_loveai on X). func TestCodexCCSwitchOfficialOpenAIMirror(t *testing.T) { const ccSwitchOfficialMirror = "model_provider = \"custom\"\nmodel = \"gpt-5.4\"\n\n" + "[model_providers.custom]\nname = \"OpenAI\"\nrequires_openai_auth = true\nsupports_websockets = true\nwire_api = \"responses\"\n" @@ -182,29 +183,15 @@ func TestCodexCCSwitchOfficialOpenAIMirror(t *testing.T) { os.WriteFile(filepath.Join(filepath.Dir(provider.Path()), "logins.json"), b, 0o600) } logins(true) - if err := cxFailover.Sync(); err != nil { - t.Fatal(err) - } - tb, err := edit.GetTOMLTable(pathFailover, "model_providers.custom") - if err != nil { - t.Fatal(err) - } - codexURL := here(homeFailover).codexURL() - if tb["base_url"] != codexURL { - t.Fatalf("mirror table base_url = %q, want %q", tb["base_url"], codexURL) - } - if strings.Contains(readFailover(), "openai_base_url") { - t.Fatalf("mirror failover wrote openai_base_url:\n%s", readFailover()) - } - - // When failover turns off, base_url is removed and the file is byte-identical to original - logins(false) - if err := cxFailover.Sync(); err != nil { - t.Fatal(err) - } - if got := readFailover(); got != ccSwitchOfficialMirror { - t.Fatalf("failover off left config not byte-identical:\ngot:\n%s\nwant:\n%s", got, ccSwitchOfficialMirror) + for i := 0; i < 2; i++ { + if err := cxFailover.Sync(); err != nil { + t.Fatal(err) + } + if got := readFailover(); got != ccSwitchOfficialMirror { + t.Fatalf("sync %d with another account on changed CC Switch's mirror:\ngot:\n%s\nwant:\n%s", i, got, ccSwitchOfficialMirror) + } } + _ = pathFailover // Real relays with a base_url never get pointed at magpie gateway for failover homeRelayFailover, readRelayFailover := codexHome(t, string(me), ccSwitchCodex) @@ -222,20 +209,17 @@ func TestCodexCCSwitchOfficialOpenAIMirror(t *testing.T) { t.Fatalf("real relay got openai_base_url:\n%s", readRelayFailover()) } - // Switching to a relay while failover was active on the mirror clears the marker + // Switching to a relay while failover from before was on the mirror clears the marker // without deleting the relay's own base_url on Sync or Set. homeSwitch, readSwitch := codexHome(t, string(me), ccSwitchOfficialMirror) cxSwitch := codex(homeSwitch) pathSwitch := filepath.Join(homeSwitch, ".codex", "config.toml") logins(true) - if err := cxSwitch.Sync(); err != nil { + // mirror failover as a magpie from before left it, marker and all + if err := edit.SetTOMLKey(pathSwitch, "model_providers.custom", "base_url", here(homeSwitch).codexURL()); err != nil { t.Fatal(err) } - // Verify mirror failover was activated and marker was set - tbSwitch, _ := edit.GetTOMLTable(pathSwitch, "model_providers.custom") - if tbSwitch["base_url"] != here(homeSwitch).codexURL() { - t.Fatalf("mirror base_url = %q, want codexURL", tbSwitch["base_url"]) - } + stash(map[string]string{"codex.mirror_failover": "custom"}) // User switches CC Switch to a relay, reusing the custom table if err := os.WriteFile(pathSwitch, []byte(ccSwitchCodex), 0o644); err != nil { t.Fatal(err) diff --git a/internal/agent/codex_failover_beyond_test.go b/internal/agent/codex_failover_beyond_test.go index 4272a2645..ec95de648 100644 --- a/internal/agent/codex_failover_beyond_test.go +++ b/internal/agent/codex_failover_beyond_test.go @@ -17,7 +17,8 @@ import ( // the same to it) is never pointed at the gateway's Codex path for account // failover either: from there the gateway takes a named key alone, so the // turn failover handed magpie came back a 401 — the shape #2145 took out -// of the joined case, still written by failover for a Codex not connected. +// of the joined case. No Codex not connected is pointed there now +// (TestCodexNotConnectedStaysOffMagpie); one written before goes. func TestCodexFailoverBeyondLoopbackNotWritten(t *testing.T) { claims := func(m map[string]any) string { b, _ := json.Marshal(m) diff --git a/internal/agent/codex_failover_test.go b/internal/agent/codex_failover_test.go index 6e8f7b7f1..fffc2c44e 100644 --- a/internal/agent/codex_failover_test.go +++ b/internal/agent/codex_failover_test.go @@ -12,68 +12,121 @@ import ( "testing" "time" + "github.com/yetone/magpie/internal/edit" "github.com/yetone/magpie/internal/gateway" "github.com/yetone/magpie/internal/provider" ) -// Codex on one of its own models, signed in to ChatGPT, goes through -// magpie while another of its accounts is on there — so a turn the first -// has no allowance left for goes to the next — and straight to OpenAI -// once none is. -func TestCodexOwnModelThroughMagpieWhileAccountsOn(t *testing.T) { - claims := func(m map[string]any) string { - b, _ := json.Marshal(m) - return "h." + base64.RawURLEncoding.EncodeToString(b) + ".s" +// TylerBai_loveai on X: Codex (the app) signed in to ChatGPT and not +// connected, two more of the user's ChatGPT accounts added and on in +// magpie. magpie pointed Codex at its gateway by itself for account +// failover (#1385), so every Codex request went through magpie while the +// Agents row said not connected, until a Disconnect and cleanup. A Codex +// that isn't connected goes straight to OpenAI: no start, sync or pick of +// one of its own models writes magpie into its config, however many of its +// accounts are on. +func TestCodexNotConnectedStaysOffMagpie(t *testing.T) { + me, _ := json.Marshal(codexChatGPTAuth("me@example.com", "acct-1")) + const own = "model = \"gpt-5.5\"\n" + home, read := codexHome(t, string(me), own) + var saved []map[string]any + for i, u := range []string{"spare1@example.com", "spare2@example.com"} { + saved = append(saved, map[string]any{"agent": "codex", "user": u, "on": true, + "seen": time.Now(), "auth": codexChatGPTAuth(u, "acct-"+string(rune('2'+i)))}) } - auth := func(email, acct string) map[string]any { - return map[string]any{"auth_mode": "chatgpt", "tokens": map[string]any{ - "id_token": claims(map[string]any{"email": email}), - "access_token": claims(map[string]any{"exp": time.Now().Add(time.Hour).Unix()}), - "refresh_token": "r-" + acct, "account_id": acct}} - } - me, _ := json.Marshal(auth("me@example.com", "acct-1")) - home, read := codexHome(t, string(me), "model = \"gpt-5.5\"\n") + b, _ := json.Marshal(saved) + os.MkdirAll(filepath.Dir(provider.Path()), 0o755) + os.WriteFile(filepath.Join(filepath.Dir(provider.Path()), "logins.json"), b, 0o600) cx := codex(home) - logins := func(on bool) { - b, _ := json.Marshal([]map[string]any{{"agent": "codex", "user": "spare@example.com", "on": on, - "seen": time.Now(), "auth": auth("spare@example.com", "acct-2")}}) + check := func(when string) { + t.Helper() + cfg := read() + if strings.Contains(cfg, "openai_base_url") || strings.Contains(cfg, "model_provider") || strings.Contains(cfg, "127.0.0.1") { + t.Fatalf("%s: an unconnected Codex pointed at magpie:\n%s", when, cfg) + } + if cx.Wired() || cx.FailingOver() || cx.FailoverSaid() != "" || CodexOwnOnly() { + t.Fatalf("%s: wired %v, failing over %v", when, cx.Wired(), cx.FailingOver()) + } + if s := stashLoad(); s["codex.failover"] != "" { + t.Fatalf("%s: failover marked: %v", when, s) + } + } + SyncCatalog() + check("magpie's start") + for i := 0; i < 2; i++ { + if err := cx.Sync(); err != nil { + t.Fatal(err) + } + check("sync") + } + if err := cx.Pick("model", "gpt-5.4"); err != nil { + t.Fatal(err) + } + if cfg := read(); !strings.Contains(cfg, `model = "gpt-5.4"`) { + t.Fatalf("pick not written:\n%s", cfg) + } + check("own model picked") +} + +// A Codex a magpie from before pointed at the gateway for failover, the +// reporter's config as they upgrade: the base URL it marked goes as Sync +// next runs, the Codex app's app-server restarted for it like any change of +// route, and it stays gone. So does CC Switch's OpenAI mirror that failover +// pointed at magpie (xuxing0727 on X), back to CC Switch's own bytes. +func TestCodexFailoverFromBeforeTakenOut(t *testing.T) { + me, _ := json.Marshal(codexChatGPTAuth("me@example.com", "acct-1")) + accountsOn := func() { + b, _ := json.Marshal([]map[string]any{{"agent": "codex", "user": "spare@example.com", "on": true, + "seen": time.Now(), "auth": codexChatGPTAuth("spare@example.com", "acct-2")}}) os.MkdirAll(filepath.Dir(provider.Path()), 0o755) os.WriteFile(filepath.Join(filepath.Dir(provider.Path()), "logins.json"), b, 0o600) } - logins(false) - if err := cx.Fields[0].Set("gpt-5.4"); err != nil { + home, read := codexHome(t, string(me), "model = \"gpt-5.5\"\n") + accountsOn() + if err := edit.SetTOMLTop(filepath.Join(home, ".codex", "config.toml"), edit.KV{Path: "openai_base_url", Value: here(home).codexURL()}); err != nil { t.Fatal(err) } - if cfg := read(); strings.Contains(cfg, "openai_base_url") { - t.Fatalf("one account:\n%s", cfg) + stash(map[string]string{"codex.failover": "1"}) + cx := codex(home) + if !cx.FailingOver() { + t.Fatalf("not the reporter's state:\n%s", read()) + } + for i := 0; i < 2; i++ { + if err := cx.Sync(); err != nil { + t.Fatal(err) + } + if cfg := read(); cfg != "model = \"gpt-5.5\"\n" { + t.Fatalf("sync %d left failover's base URL:\n%s", i, cfg) + } + if cx.FailingOver() || stashLoad()["codex.failover"] != "" { + t.Fatalf("sync %d: failing over %v", i, cx.FailingOver()) + } + } + + const unified = "model_provider = \"custom\"\nmodel = \"gpt-5.5\"\n\n" + + "[model_providers.custom]\nname = \"OpenAI\"\nrequires_openai_auth = true\nsupports_websockets = true\nwire_api = \"responses\"\n" + home, read = codexHome(t, string(me), unified) + accountsOn() + if err := edit.SetTOMLKey(filepath.Join(home, ".codex", "config.toml"), "model_providers.custom", "base_url", here(home).codexURL()); err != nil { + t.Fatal(err) + } + stash(map[string]string{"codex.mirror_failover": "custom"}) + cx = codex(home) + if !cx.FailingOver() { + t.Fatalf("not the mirror's state:\n%s", read()) } - logins(true) if err := cx.Sync(); err != nil { t.Fatal(err) } - if cfg := read(); !strings.Contains(cfg, `openai_base_url = "http://127.0.0.1:`) || !strings.Contains(cfg, `model = "gpt-5.4"`) { - t.Fatalf("second account on:\n%s", cfg) - } - // picked again, it stays so - if err := cx.Fields[0].Set("gpt-5.5"); err != nil { - t.Fatal(err) - } - if cfg := read(); !strings.Contains(cfg, "openai_base_url") || !strings.Contains(cfg, `model = "gpt-5.5"`) { - t.Fatalf("picked with two accounts on:\n%s", cfg) - } - logins(false) - if err := cx.Sync(); err != nil { - t.Fatal(err) - } - if cfg := read(); strings.Contains(cfg, "openai_base_url") || !strings.Contains(cfg, `model = "gpt-5.5"`) { - t.Fatalf("second account off:\n%s", cfg) + if cfg := read(); cfg != unified || cx.FailingOver() { + t.Fatalf("CC Switch's mirror left on magpie (failing over %v):\n%s", cx.FailingOver(), cfg) } } // A base URL the user wrote in config.toml by hand, to have Codex's own -// models go through magpie, stays when magpie starts (Sync) with no other -// ChatGPT account on to fail over to: failover takes away only the one it -// wrote (#856: it was gone again after every magpie update). +// models go through magpie, stays when magpie starts (Sync): what failover +// wrote is taken away, and only that (#856: it was gone again after every +// magpie update). func TestCodexHandWrittenBaseURLStays(t *testing.T) { base := gateway.URL() + gateway.CodexPath home, read := codexHome(t, `{"tokens":{"access_token":"x","id_token":"x.e30.x"}}`, @@ -90,10 +143,11 @@ func TestCodexHandWrittenBaseURLStays(t *testing.T) { } // #1385 (shenghsi): Codex signed in to ChatGPT, not connected, with two -// more of the user's ChatGPT accounts on in magpie. failover points Codex at -// the gateway; the Agents row says it goes through magpie for that and what -// turns it off, and Codex's model list is its own, not its own and 62 of -// magpie's. Connected, it is magpie's models' again. +// more of the user's ChatGPT accounts on in magpie, pointed at the gateway +// by a magpie from before for failover. Till Sync takes that out, the +// Agents row says it goes through magpie for that, and Codex's model list +// is its own, not its own and 62 of magpie's. Connected, it is magpie's +// models' again. func TestCodexFailoverOnlyKeepsOwnModels(t *testing.T) { claims := func(m map[string]any) string { b, _ := json.Marshal(m) @@ -115,10 +169,11 @@ func TestCodexFailoverOnlyKeepsOwnModels(t *testing.T) { b, _ := json.Marshal(saved) os.MkdirAll(filepath.Dir(provider.Path()), 0o755) os.WriteFile(filepath.Join(filepath.Dir(provider.Path()), "logins.json"), b, 0o600) - // Codex fetched magpie's whole list before - cache := filepath.Join(home, ".codex", "models_cache.json") - now := time.Now().UTC().Format(time.RFC3339) - os.WriteFile(cache, []byte(`{"etag":"\"v1+magpie-`+provider.CodexListTag()+`\"","fetched_at":"`+now+`","models":[]}`), 0o644) + // what a magpie from before wrote for failover + if err := edit.SetTOMLTop(filepath.Join(home, ".codex", "config.toml"), edit.KV{Path: "openai_base_url", Value: here(home).codexURL()}); err != nil { + t.Fatal(err) + } + stash(map[string]string{"codex.failover": "1"}) up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, `{"models":[{"slug":"gpt-5.5","priority":1}]}`) @@ -146,12 +201,8 @@ func TestCodexFailoverOnlyKeepsOwnModels(t *testing.T) { } cx := codex(home) - if err := cx.Sync(); err != nil { - t.Fatal(err) - } - s := stashLoad() - if cfg := read(); !strings.Contains(cfg, "openai_base_url") || s["codex.failover"] != "1" || s["codex.joined"] != "" || s["codex.beside"] != "" { - t.Fatalf("not the reporter's state: stash %v\n%s", s, cfg) + if cfg := read(); !strings.Contains(cfg, "openai_base_url") { + t.Fatalf("not the reporter's state:\n%s", cfg) } if cx.Wired() || !cx.FailingOver() || !CodexOwnOnly() || !strings.Contains(cx.FailoverSaid(), "Providers › Codex") { t.Errorf("wired %v, failing over %v, own only %v, said %q", cx.Wired(), cx.FailingOver(), CodexOwnOnly(), cx.FailoverSaid()) @@ -159,9 +210,6 @@ func TestCodexFailoverOnlyKeepsOwnModels(t *testing.T) { if got := models(); len(got) != 1 || got[0] != "gpt-5.5" { t.Errorf("failover-only Codex lists %v, want just gpt-5.5", got) } - if c, _ := os.ReadFile(cache); !strings.Contains(string(c), "1970-01-01") { - t.Errorf("Codex's cached list of magpie's models kept:\n%s", c) - } // connected, magpie's models are in its list and the row says connected if ok, err := cx.Join(); !ok || err != nil { diff --git a/internal/agent/codex_proxy.go b/internal/agent/codex_proxy.go index e1a789bc2..1a36ce980 100644 --- a/internal/agent/codex_proxy.go +++ b/internal/agent/codex_proxy.go @@ -43,10 +43,9 @@ import ( // magpie opened from the Dock has neither, so the login shell's are asked // (proc.LoginEnv), over magpie's own. // -// So before magpie hands Codex's requests to the gateway uninvited (account -// failover), and while it has them, it asks the way Codex would go: through -// which proxy, and whether a request sent through it reaches magpie (Drift -// kind "proxied"). +// So while magpie has Codex's requests, it asks the way Codex would go: +// through which proxy, and whether a request sent through it reaches +// magpie (Drift kind "proxied"). // codexProxyEnv, codexSystemProxy and codexProxyOS are what codexProxyFor // reads, and loginEnv what codexEnv does; vars so tests can say. @@ -245,13 +244,6 @@ func codexThroughProxy(cfg, base string) (ok, known bool, proxy, from string) { return ok, known, proxy, from } -// codexProxyOK is codexThroughProxy waited for: whether Codex gets to the -// gateway at base, a proxy in its way tried now when it hasn't been. -func codexProxyOK(cfg, base string) bool { - proxy, _ := codexProxyFor(cfg, base) - return proxy == "" || probedNow("proxy "+proxy+" "+base, func() bool { return proxyProbe(base, proxy) }) -} - // codexProxiedDetail says what keeps Codex off magpie through proxy, and // how to get it there. func codexProxiedDetail(base, proxy, from string) string { diff --git a/internal/agent/codex_proxy_test.go b/internal/agent/codex_proxy_test.go index 9cc02dc3a..eaafa58d0 100644 --- a/internal/agent/codex_proxy_test.go +++ b/internal/agent/codex_proxy_test.go @@ -256,53 +256,6 @@ func socksOnly(t *testing.T) string { return ln.Addr().String() } -// Muma102kMichael on X: Codex 502 on every project and every new chat once -// magpie took it over, its requests for 127.0.0.1 sent through a proxy that -// didn't pass them on. Failover, which magpie writes uninvited, is never -// written then, and one written before goes again; once the proxy passes -// them on, it is. -func TestCodexFailoverHeldWhileProxyDoesNotPassOn(t *testing.T) { - claims := func(m map[string]any) string { - b, _ := json.Marshal(m) - return "h." + base64.RawURLEncoding.EncodeToString(b) + ".s" - } - auth := func(email, acct string) map[string]any { - return map[string]any{"auth_mode": "chatgpt", "tokens": map[string]any{ - "id_token": claims(map[string]any{"email": email}), - "access_token": claims(map[string]any{"exp": time.Now().Add(time.Hour).Unix()}), - "refresh_token": "r-" + acct, "account_id": acct}} - } - me, _ := json.Marshal(auth("me@example.com", "acct-1")) - home, read := codexHome(t, string(me), "model = \"gpt-5.5\"\n") - b, _ := json.Marshal([]map[string]any{{"agent": "codex", "user": "spare@example.com", "on": true, - "seen": time.Now(), "auth": auth("spare@example.com", "acct-2")}}) - os.MkdirAll(filepath.Dir(provider.Path()), 0o755) - os.WriteFile(filepath.Join(filepath.Dir(provider.Path()), "logins.json"), b, 0o600) - - works := false - proxyAs(t, nil, netproxy.Proxy{URL: "http://127.0.0.1:7890", HTTP: "http://127.0.0.1:7890", Bypass: []string{"localhost", "127.*"}}, "windows", &works) - cx := codex(home) - sync := func() string { - t.Helper() - reachForget() - if err := cx.Sync(); err != nil { - t.Fatal(err) - } - return read() - } - if cfg := sync(); strings.Contains(cfg, "openai_base_url") { - t.Fatalf("written while the proxy doesn't pass it on:\n%s", cfg) - } - works = true - if cfg := sync(); !strings.Contains(cfg, `openai_base_url = "`+gateway.URL()) { - t.Fatalf("not written once the proxy passes it on:\n%s", cfg) - } - works = false - if cfg := sync(); strings.Contains(cfg, "openai_base_url") || !strings.Contains(cfg, `model = "gpt-5.5"`) { - t.Fatalf("kept once the proxy stopped passing it on:\n%s", cfg) - } -} - // Connected to magpie, with the gateway up but Codex's way to it through a // proxy that answers 502: the row says so, which proxy and where it is set, // rather than connected (kind "proxied"); once the proxy passes it on, or @@ -370,9 +323,10 @@ func TestCodexProxiedDriftShowsNoCredentials(t *testing.T) { } // Leon920717 on X: with magpie quit, Codex CLI kept retrying the gateway -// till magpie was open again. The failover base URL magpie wrote goes as -// the magpie serving the gateway quits (EndCodexFailover), and the next -// start's Sync writes it again; a base URL the user wrote stays. +// till magpie was open again. The failover base URL a magpie from before +// wrote goes as the magpie serving the gateway quits (EndCodexFailover), +// and the next start's Sync doesn't write it again (TylerBai_loveai on X); +// a base URL the user wrote stays. func TestCodexFailoverEndsWithMagpie(t *testing.T) { claims := func(m map[string]any) string { b, _ := json.Marshal(m) @@ -396,12 +350,10 @@ func TestCodexFailoverEndsWithMagpie(t *testing.T) { } logins(true) cx := codex(home) - if err := cx.Sync(); err != nil { + if err := edit.SetTOMLTop(cx.Path, edit.KV{Path: "openai_base_url", Value: here(home).codexURL()}); err != nil { t.Fatal(err) } - if cfg := read(); !strings.Contains(cfg, "openai_base_url") { - t.Fatalf("failover not written:\n%s", cfg) - } + stash(map[string]string{"codex.failover": "1"}) wasKeep := keepCodexDaemon t.Cleanup(func() { keepCodexDaemon = wasKeep }) var asked []string @@ -423,8 +375,8 @@ func TestCodexFailoverEndsWithMagpie(t *testing.T) { if err := cx.Sync(); err != nil { t.Fatal(err) } - if cfg := read(); !strings.Contains(cfg, "openai_base_url") { - t.Fatalf("not written again on the next start:\n%s", cfg) + if cfg := read(); strings.Contains(cfg, "openai_base_url") { + t.Fatalf("written again on the next start:\n%s", cfg) } // the user's own base URL, with no failover on, stays @@ -448,10 +400,10 @@ func TestCodexFailoverEndsWithMagpie(t *testing.T) { } // CC Switch with "unify Codex session history" on (xuxing0727 on X) runs -// the official sign-in as its "custom" mirror, so failover goes on that -// table's base_url rather than openai_base_url: it too waits for the proxy -// to pass Codex on, and goes as the magpie serving the gateway quits. -func TestCodexMirrorFailoverHeldAndEndsWithMagpie(t *testing.T) { +// the official sign-in as its "custom" mirror, so failover went on that +// table's base_url rather than openai_base_url: one a magpie from before +// wrote goes as the magpie serving the gateway quits. +func TestCodexMirrorFailoverEndsWithMagpie(t *testing.T) { // CC Switch's own bytes (src-tauri services/provider/mod.rs) const unified = "model_provider = \"custom\"\nmodel = \"gpt-5.5\"\n\n" + "[model_providers.custom]\nname = \"OpenAI\"\nrequires_openai_auth = true\nsupports_websockets = true\nwire_api = \"responses\"\n" @@ -477,24 +429,11 @@ func TestCodexMirrorFailoverHeldAndEndsWithMagpie(t *testing.T) { t.Cleanup(func() { keepCodexDaemon = wasKeep }) keepCodexDaemon = func(context.Context, string, time.Time) provider.CodexDaemonCheck { return provider.CodexDaemonCheck{} } - works := false - proxyAs(t, map[string]string{"HTTP_PROXY": "http://127.0.0.1:7890"}, netproxy.Proxy{}, "darwin", &works) cx := codex(home) - sync := func() string { - t.Helper() - reachForget() - if err := cx.Sync(); err != nil { - t.Fatal(err) - } - return read() - } - if cfg := sync(); strings.Contains(cfg, "base_url") { - t.Fatalf("written while the proxy doesn't pass it on:\n%s", cfg) - } - works = true - if cfg := sync(); !strings.Contains(cfg, `base_url = "`+gateway.URL()) { - t.Fatalf("not written once the proxy passes it on:\n%s", cfg) + if err := edit.SetTOMLKey(cx.Path, "model_providers.custom", "base_url", here(home).codexURL()); err != nil { + t.Fatal(err) } + stash(map[string]string{"codex.mirror_failover": "custom"}) if _, err := EndCodexFailover(); err != nil { t.Fatal(err) } diff --git a/internal/agent/codex_switch_only_test.go b/internal/agent/codex_switch_only_test.go index 3e55a1349..a4743887e 100644 --- a/internal/agent/codex_switch_only_test.go +++ b/internal/agent/codex_switch_only_test.go @@ -13,12 +13,10 @@ import ( ) // #1907 (foobra): two ChatGPT accounts, both on in magpie, for Codex -// Desktop and the CLI alone, not for the gateway. With more accounts on, -// magpie points Codex at the gateway to fail over between them (#1385); -// switch-only takes that base URL out, so Codex goes straight to OpenAI and -// magpie only switches its sign-in, and nothing puts it back while it is -// on. Off again, failover writes it back. A base URL the user wrote by hand -// is theirs, and stays either way (#856). +// Desktop and the CLI alone, not for the gateway. Codex isn't connected, so +// it goes straight to OpenAI whether switch-only is on or off, and magpie +// only switches its sign-in; a base URL the user wrote by hand is theirs, +// and stays either way (#856). func TestCodexSwitchOnlyKeepsCodexOffTheGateway(t *testing.T) { claims := func(m map[string]any) string { b, _ := json.Marshal(m) @@ -38,53 +36,34 @@ func TestCodexSwitchOnlyKeepsCodexOffTheGateway(t *testing.T) { os.WriteFile(filepath.Join(filepath.Dir(provider.Path()), "logins.json"), b, 0o600) cx := codex(home) - if err := cx.Sync(); err != nil { - t.Fatal(err) - } - if cfg := read(); !strings.Contains(cfg, "openai_base_url") || !cx.FailingOver() { - t.Fatalf("not the reporter's state, failing over %v:\n%s", cx.FailingOver(), cfg) - } - - if err := provider.SetSwitchOnly("codex", true); err != nil { - t.Fatal(err) - } - for i := 0; i < 2; i++ { + for _, only := range []bool{false, true, false} { + if err := provider.SetSwitchOnly("codex", only); err != nil { + t.Fatal(err) + } if err := cx.Sync(); err != nil { t.Fatal(err) } if cfg := read(); strings.Contains(cfg, "openai_base_url") || !strings.Contains(cfg, `model = "gpt-5.5"`) { - t.Fatalf("switch-only, sync %d:\n%s", i, cfg) + t.Fatalf("switch-only %v:\n%s", only, cfg) } if cx.FailingOver() || cx.FailoverSaid() != "" || CodexOwnOnly() { - t.Fatalf("switch-only, sync %d: failing over %v, said %q, own only %v", i, cx.FailingOver(), cx.FailoverSaid(), CodexOwnOnly()) + t.Fatalf("switch-only %v: failing over %v, said %q, own only %v", only, cx.FailingOver(), cx.FailoverSaid(), CodexOwnOnly()) } } - if err := provider.SetSwitchOnly("codex", false); err != nil { - t.Fatal(err) - } - if err := cx.Sync(); err != nil { - t.Fatal(err) - } - if cfg := read(); !strings.Contains(cfg, "openai_base_url") || !cx.FailingOver() { - t.Fatalf("switch-only off, failing over %v:\n%s", cx.FailingOver(), cfg) - } - - // the user's own base URL, switch-only on: theirs, kept - if err := cx.EndFailover(); err != nil { - t.Fatal(err) - } - forget("codex.failover") + // the user's own base URL: theirs, kept, switch-only on or off base := codexGatewayURL() cfg := filepath.Join(home, ".codex", "config.toml") os.WriteFile(cfg, []byte("model = \"gpt-5.5\"\nopenai_base_url = \""+base+"\"\n"), 0o644) - if err := provider.SetSwitchOnly("codex", true); err != nil { - t.Fatal(err) - } - if err := cx.Sync(); err != nil { - t.Fatal(err) - } - if got := read(); !strings.Contains(got, `openai_base_url = "`+base+`"`) { - t.Fatalf("the user's base URL taken away:\n%s", got) + for _, only := range []bool{true, false} { + if err := provider.SetSwitchOnly("codex", only); err != nil { + t.Fatal(err) + } + if err := cx.Sync(); err != nil { + t.Fatal(err) + } + if got := read(); !strings.Contains(got, `openai_base_url = "`+base+`"`) { + t.Fatalf("switch-only %v: the user's base URL taken away:\n%s", only, got) + } } } diff --git a/internal/agent/disconnect_stays_test.go b/internal/agent/disconnect_stays_test.go index fe2b5846e..ddb131149 100644 --- a/internal/agent/disconnect_stays_test.go +++ b/internal/agent/disconnect_stays_test.go @@ -104,7 +104,7 @@ func codexChatGPTAuth(email, acct string) map[string]any { // paynezhuang on Discord: Codex signed in to ChatGPT, with another of the // user's ChatGPT accounts on in magpie. magpie's first start pointed Codex -// at the gateway for failover; the user switched Codex on, then chose +// at the gateway for failover then; the user switched Codex on, then chose // "Disconnect from magpie", and after each update and restart Codex had // magpie's base URL in config.toml again. A disconnect is the user's say: // no start brings it back, with ChatGPT sign-in or magpie API, until the @@ -120,9 +120,11 @@ func TestCodexDisconnectStaysWithAccountsOn(t *testing.T) { os.MkdirAll(filepath.Dir(provider.Path()), 0o755) os.WriteFile(filepath.Join(filepath.Dir(provider.Path()), "logins.json"), b, 0o600) cx := codex(home) - // magpie's first start: failover points Codex at the gateway + // magpie's first start: a magpie from before pointed Codex at + // the gateway for failover then; Codex not connected stays off + // it now (TylerBai_loveai on X) SyncCatalog() - if cfg := read(); !strings.Contains(cfg, "openai_base_url") { + if cfg := read(); strings.Contains(cfg, "openai_base_url") { t.Fatalf("first start, two accounts on:\n%s", cfg) } if login != "" { diff --git a/internal/agent/reach.go b/internal/agent/reach.go index bb7618425..b507358bf 100644 --- a/internal/agent/reach.go +++ b/internal/agent/reach.go @@ -187,7 +187,7 @@ func chainsToGateway(v, want string) bool { } // magpieAsked is magpieAt waited for, for a write: base, not asked yet, is -// asked now (probedNow, as codexProxyOK asks a proxy), so what the write +// asked now (probedNow), so what the write // reads after is magpie's answer there. Unasked, surelyMagpie is no, and // the first write in a magpie just started, the CLI's, took a proxy to // magpie for the user's own endpoint (#1985). One answered before, at any diff --git a/internal/cli/accounts_cli.go b/internal/cli/accounts_cli.go index dca135ce5..6b9bb2788 100644 --- a/internal/cli/accounts_cli.go +++ b/internal/cli/accounts_cli.go @@ -1099,7 +1099,7 @@ func switchOnlyCmd(args []string) error { case id == "codex" && on: fmt.Println("on · magpie only switches Codex's sign-in; its requests go straight to OpenAI") case id == "codex": - fmt.Println("off · with more of its accounts on, Codex's requests go through magpie to fail over between them") + fmt.Println("off · while Codex is connected, its requests go through magpie to fail over between its accounts") case on: fmt.Println("on · magpie only switches Claude Code's sign-in; it serves no requests on the Claude accounts") default: @@ -1124,7 +1124,7 @@ func switchOnlyCmd(args []string) error { case id == "codex" && on: fmt.Println(green.Render("✓"), "magpie only switches Codex's sign-in to an account with room; its requests go straight to OpenAI. A Codex app or session already open stays on its account until it is opened again.") case id == "codex": - fmt.Println(green.Render("✓"), "with more of its accounts on, Codex's requests go through magpie to fail over between them again") + fmt.Println(green.Render("✓"), "while Codex is connected, its requests go through magpie to fail over between its accounts again") case on: fmt.Println(green.Render("✓"), "magpie only switches Claude Code's sign-in to an account with room; it serves no requests on the Claude accounts. A Claude Code session already open stays on its account until it is started again.") default: diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index cd8529aad..520cc0ade 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -1655,7 +1655,7 @@ function switchEntry(a) { openProtoMenu(b, opts, "u:" + cur, (v) => { const l = ls.find((x) => "u:" + x.user === v); if (v === "only") accountAction("provider/switchonly", { id: p.id, switchOnly: !p.switchOnly }, !p.switchOnly ? on - : cx ? t("{agent}'s requests go through magpie to fail over to your other accounts again", ag) : t("magpie serves requests on these accounts again")); + : cx ? t("A connected {agent} fails over to your other accounts through magpie again", ag) : t("magpie serves requests on these accounts again")); else if (v === "manage" || l?.lapsed) pn ? api("window/main?view=providers", {}).catch(statusErr) : openProvider(a.id); else if (l && l.user !== cur) switchAccountTo(a, p, l.user); }, "Switch accounts only", "sess-menu", "right"); @@ -13712,7 +13712,7 @@ function renderAccounts(a, p) { const cx = a.agent === "codex", ag = { agent: a.agentName }; if (p && (cx && several || a.agent === "claude")) { const [only, cb] = tick(t("Only switch {agent}'s sign-in", ag), p.switchOnly); - const [tip, on, off] = cx ? [t("When an account is used up, magpie signs {agent} in to the next one, and requests go straight to OpenAI. Open {agent} sessions keep their account until reopened.", ag), t("magpie only switches {agent}'s sign-in; its requests go straight to OpenAI", ag), t("{agent}'s requests go through magpie to fail over to your other accounts again", ag)] + const [tip, on, off] = cx ? [t("When an account is used up, magpie signs {agent} in to the next one, and requests go straight to OpenAI. Open {agent} sessions keep their account until reopened.", ag), t("magpie only switches {agent}'s sign-in; its requests go straight to OpenAI", ag), t("A connected {agent} fails over to your other accounts through magpie again", ag)] : [t("When an account is used up, magpie signs {agent} in to the next one. Requests on these accounts don't go through magpie.", ag), t("magpie serves no requests on these accounts"), t("magpie serves requests on these accounts again")]; only.title = tip; cb.onchange = () => accountAction("provider/switchonly", { id: p.id, switchOnly: cb.checked }, cb.checked ? on : off); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 2e937291f..0ae95cbb1 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -2185,7 +2185,7 @@ const I18N = { "When an account is used up, magpie signs {agent} in to the next one. Requests on these accounts don't go through magpie.": "账号额度用完时,magpie 把 {agent} 切到下一个账号。这些账号的请求都不经过 magpie。", "magpie serves no requests on these accounts": "magpie 不在这些账号上处理任何请求", "magpie serves requests on these accounts again": "magpie 重新在这些账号上处理请求", - "{agent}'s requests go through magpie to fail over to your other accounts again": "{agent} 的请求重新经过 magpie,以便转到你的其他账号", + "A connected {agent} fails over to your other accounts through magpie again": "接入后,{agent} 重新经过 magpie 转到你的其他账号", "the first account": "首选账号", "Account to stay signed in to": "始终登录的账号", "The account {agent} stays signed in to": "{agent} 始终登录的账号", @@ -7445,7 +7445,7 @@ const I18N = { "When an account is used up, magpie signs {agent} in to the next one. Requests on these accounts don't go through magpie.": "帳號額度用完時,magpie 把 {agent} 切到下一個帳號。這些帳號的請求都不經過 magpie。", "magpie serves no requests on these accounts": "magpie 不在這些帳號上處理任何請求", "magpie serves requests on these accounts again": "magpie 重新在這些帳號上處理請求", - "{agent}'s requests go through magpie to fail over to your other accounts again": "{agent} 的請求重新經過 magpie,以便轉到你的其他帳號", + "A connected {agent} fails over to your other accounts through magpie again": "接入後,{agent} 重新經過 magpie 轉到你的其他帳號", "the first account": "首選帳號", "Account to stay signed in to": "始終登入的帳號", "The account {agent} stays signed in to": "{agent} 始終登入的帳號", @@ -12680,7 +12680,7 @@ const I18N = { "When an account is used up, magpie signs {agent} in to the next one. Requests on these accounts don't go through magpie.": "アカウントを使い切ると、magpie が {agent} を次のアカウントに切り替えます。これらのアカウントのリクエストは magpie を通りません。", "magpie serves no requests on these accounts": "magpie はこれらのアカウントでリクエストを処理しません", "magpie serves requests on these accounts again": "magpie はこれらのアカウントで再びリクエストを処理します", - "{agent}'s requests go through magpie to fail over to your other accounts again": "{agent} のリクエストは再び magpie を経由し、他のアカウントへ切り替えられます", + "A connected {agent} fails over to your other accounts through magpie again": "接続した {agent} は再び magpie を経由して他のアカウントへ切り替わります", "the first account": "最初のアカウント", "Account to stay signed in to": "サインインしたままにするアカウント", "The account {agent} stays signed in to": "{agent} がサインインしたままにするアカウント", @@ -17946,7 +17946,7 @@ const I18N = { "When an account is used up, magpie signs {agent} in to the next one. Requests on these accounts don't go through magpie.": "Ist ein Konto aufgebraucht, meldet magpie {agent} beim nächsten an. Anfragen dieser Konten laufen nicht über magpie.", "magpie serves no requests on these accounts": "magpie bearbeitet keine Anfragen über diese Konten", "magpie serves requests on these accounts again": "magpie bearbeitet wieder Anfragen über diese Konten", - "{agent}'s requests go through magpie to fail over to your other accounts again": "Die Anfragen von {agent} laufen wieder über magpie, um auf deine anderen Konten auszuweichen", + "A connected {agent} fails over to your other accounts through magpie again": "Ein verbundenes {agent} weicht wieder über magpie auf deine anderen Konten aus", "the first account": "dem ersten Konto", "Account to stay signed in to": "Konto für die dauerhafte Anmeldung", "The account {agent} stays signed in to": "Das Konto, bei dem {agent} angemeldet bleibt", diff --git a/internal/gui/tests/switch-only.test.cjs b/internal/gui/tests/switch-only.test.cjs index 82ec95f45..9a8bf0776 100644 --- a/internal/gui/tests/switch-only.test.cjs +++ b/internal/gui/tests/switch-only.test.cjs @@ -61,7 +61,7 @@ const strings = [ "Only switch {agent}'s sign-in", "When an account is used up, magpie signs {agent} in to the next one, and requests go straight to OpenAI. Open {agent} sessions keep their account until reopened.", "magpie only switches {agent}'s sign-in; its requests go straight to OpenAI", - "{agent}'s requests go through magpie to fail over to your other accounts again", + "A connected {agent} fails over to your other accounts through magpie again", ]; for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {