From f37742e14d112aee9cd04a03fcac741bc08d4eac Mon Sep 17 00:00:00 2001 From: yetone Date: Tue, 3 Nov 2026 15:11:26 +0800 Subject: [PATCH] agent: a used-up ChatGPT account magpie can't serve past leaves the Codex app on its sign-in (xiaoq6285) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit xiaoq6285 on Discord (magpie 0.1.2798, the Windows Codex app, one ChatGPT Plus account, Codex on its own model joined beside the sign-in): at the five-hour limit the app showed an error and had to be restarted, then its account menu showed only "magpie" with no quota; at the reset it restarted by itself and the account came back. Cause. When the active account was held (used up, no credits), Sync's own-model takeover made magpie Codex's provider on codex/ whenever magpie's catalog listed that model on any Codex account -- the same used-up one included. With one account and no fallback every turn it took over is refused on that account anyway, while the takeover: - has account/read answer no account, so the menu drops the user, Plus and the usage meter until the reset; - changes the route twice (into it, back at the reset), and KeepCodexAppOnItsProvider ends the app's app-server each time, which ChatGPT desktop 26.1027.x shows as "ChatGPT 遇到了问题" and relaunches (#4550, still open, the app's own reaction to an ended app-server). Separately, magpie's [model_providers.magpie] requires_openai_auth follows the account out and back (openaiAuth), and codexAppRoute counted it even when that table was not Codex's model_provider, so staying beside the sign-in would still have ended the app-server at the limit and at the reset. Change. - provider.CodexServesWhileOut(model): the Codex subscription has fallbacks for codex/ (FallbackModels), or another ChatGPT account is not known held and not lapsed. - Sync's own-model takeover runs only when that holds. Otherwise Codex stays on its sign-in: the app keeps the account, its quota and reset, and shows its own limit message. With a fallback set it moves as before (affa979d5 serves the fallback through the gateway too). - codexAppRoute counts magpie.requires_openai_auth only while model_provider is magpie; the table is still written as before. - docs/subsystems/agent-wiring.md says both. Tests. - TestCodexOwnModelOneSpentAccountStaysOnItsSignIn (new): one account, no fallback, held: config stays on the sign-in, codexAppRoute and AppOut unchanged across two Syncs and the reset. - TestCodexServesWhileOut (new): one account none; another not known out yes; every account out none; a codex fallback yes. - TestCodexOwnModelGoesThroughMagpieWhileUsedUp and TestCodexOwnModelOutThenKeptOnChatGPT now set a codex fallback, the case where the takeover still serves something. Broken by hand: the CodexServesWhileOut gate taken out -> the new agent test red (Codex moved to model_provider = "magpie", codex/gpt-a); codexAppRoute counting requires_openai_auth always -> red (route changed with model_provider empty). Each put back, green. Run on mote at this head (rebased on e41ef6288), -tags nogui -timeout 45m: - internal/agent ok (381s), internal/provider ok (254s); - internal/cli FAIL in TestEveryRouteHasACommandOrIsNamed alone: GET /api/context/reply has no command, from 0872bc2a0, filed as #5026, nothing of this change; - gofmt -l clean; go vet of both packages, GOOS=linux go vet -tags nogui ./... and GOOS=windows go vet ./... ok. - internal/gateway ok (1152s) at the earlier base 3088872e6, not run again after the rebase (it imports provider; this change adds a function there and changes nothing it calls). Not tried: the real Windows Codex app signed in to a used-up Plus account (the Windows box's app is not signed in; #4550's crash was not reproduced there); a real codex app-server against a fake 429 upstream. Users with a fallback or a second account still get the takeover and its two app-server restarts, which #4550 tracks. --- docs/subsystems/agent-wiring.md | 2 +- internal/agent/agents.go | 21 +++++++-- internal/agent/codex.go | 9 +++- internal/agent/codex_usedup_test.go | 63 +++++++++++++++++++++++++ internal/provider/codex_app_out.go | 22 +++++++++ internal/provider/codex_app_out_test.go | 58 +++++++++++++++++++++++ 6 files changed, 168 insertions(+), 7 deletions(-) diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index a5891d511..5e524a78f 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -99,7 +99,7 @@ something else shows up as drift. - 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`). - 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*`. -- Codex signed in to ChatGPT stays beside its sign-in (`openai_base_url`) unless the user picks magpie API. magpie becomes its provider only while the Codex app holds the active account, which it sends nothing for: `/wham/usage` says it isn't allowed, and it has no credits and isn't a workspace still within its overage (`codexHeld`, read by `provider.CodexUsedUp`). With Codex switched off or removed in magpie (`leftAlone`), whose allowance magpie otherwise reads nothing of, the active account is still read for this alone while Codex takes magpie's models beside its sign-in or magpie is its provider for the held account (`Agent.HoldMatters`, through the `provider.CodexHoldMatters` hook; `codexHoldReading`): once a minute at most, with the token as Codex keeps it, never renewed or written (`codexTokenAsKept`), and nothing shown on the Usage page. Before, turning Codex off in magpie after its allowance ran out left the Codex app greying Send for magpie's models through restarts, and one already moved was put back on the held account (sherlock_23333 on X; `TestCodexHoldReadLeftAlone`, `TestCodexHoldMatters`). Where the app goes by what usage can't show (an experiment's gate, a reserve, a Team plan's overage under the reserve experiment), it counts as held: a wrong move costs ChatGPT extras, a missed one every turn. A saved reading kept through a failed read stops saying held once its used-up window has started again; a hold with no window used up stays till a fresh read. The app then loses its ChatGPT state (durable threads, remote control), so a window at 100% alone, which credits get past, doesn't move it (`codex.out` marks the move, and Sync undoes it once the account has room). The same holds on one of Codex's own models joined beside the sign-in (MasterYi on Discord: the Codex app greyed Send for every model on a used-up account): Sync makes magpie the provider on that model as magpie serves it (`codexOwnViaMagpie`, `codex/`), keeps the model picked in `codex.out_own`, and once the account has room puts Codex back joined on it; a model the user picked meanwhile stays theirs. With no ChatGPT account in magpie to serve it, Codex is left as it is (`TestCodexOwnModelGoesThroughMagpieWhileUsedUp`, `TestCodexOwnModelKeptOnChatGPT`). The account is read again at once when a reply says it may be out (a `usage_limit_reached` rest, or an `x-codex-*` window heard at 100%; `provider.CodexMayBeUsedUp`, at most every 20s, the active account only), not only on the five-minute look. A turn relayed to Codex's own sign-in, the one account on (`codexUpstreamOn` with no account, the gateway's `codexRelayedAccount`), is heard the same way: its `x-codex-*` windows and `codex.rate_limits` event kept as the sign-in's usage (`heardCodexLimits`), and a `usage_limit_reached` refusal reading it again. Before, only turns served through magpie's accounts were, so with one account magpie learned the account was out only at the next look, minutes on, and the Codex app kept Send greyed until it was restarted (unsplashz on Discord; `TestCodexUsedUpRelayedAsksAtOnce`, `TestCodexRelayedWindowsHeard`). A Codex started before magpie became its provider keeps sending its own model's turns to its built-in provider; while the sign-in is known out (`provider.CodexUsedUpKnown`) and the request signs as it, those go through routing as `codex/` (`codexAccounts`), as a restarted Codex's do (`TestCodexHeldSignInServedWithoutRestart`). The Codex app greys Send for every model, magpie's too, while its `authMethod` is `chatgpt` and its rate limit says not allowed (its composer's gate in ChatGPT.app 26.1013), and reads `authMethod` from its app-server's `account/read` only as the app-server starts; with magpie the provider (`requires_openai_auth` false) that answers no account, so the gate lifts. So the gateway process restarts the app's own app-server each time magpie becomes Codex's provider for the used-up account (`Agent.AppOut`) and again when Codex is put back on the account after its reset, and likewise whenever what the app-server reads as it starts and magpie writes changes, which is where its requests go (`model_provider`, `openai_base_url` and the magpie table's `base_url`; `codexAppRoute`, through the `provider.CodexAppRoute` hook): a Disconnect, a Connect, failover written or taken out. The model list is not part of it: neither `model_catalog_json` nor what the catalog holds. The catalog follows magpie's names and the effort new sessions start at, which the Codex app saves on each pick, and the ChatGPT app takes an ended app-server as a crash and relaunches, so a route that hashed the catalog (from lucis0116 on X until #4550) ended the app every few minutes (indekkusu141209 on X). A new list is read at the app's next launch or on the Agents row's Restart (`StaleCopies`) A list that drops a model and has it back at the next fetch, the same list in another order, and a catalog read half-written leave the route as it was (`TestCodexEffortPickKeepsTheAppRunning`, `TestCodexAppRouteIgnoresARename`, `TestCodexAppRouteKeepsThroughListFlaps`). Before this an app-server started while Codex was connected kept sending to the gateway after Disconnect until the app was restarted (JiangLiuer222 on X). At the watcher's first look only a used-up account's app-servers are ended, since what the others read before magpie started isn't known. It runs on every system (`KeepCodexAppOnItsProvider`, every 3s; Ethereal499 and Isdavexxx on X, MasterYi on Discord, #540: the earlier once-only reopen ran on macOS from the GUI process only, so Windows, Linux, a GUI-less magpie and the switch back stayed greyed). It ends only app-servers on magpie's Codex home (`codexAppHomeIs`: the process's `CODEX_HOME`, else `HOME/.codex`, read by `proc.EnvOf`; Windows can't tell and counts every one), only once no Codex request is in flight through the gateway nor ended in the last 10s (`Server.CodexBusy`) and no session under the Codex home has a turn started and not ended (`codexTurnOpen`), and with a clean exit (`proc.End`: SIGTERM, `TerminateProcess` with code 0), since the app shows any other exit as a crash. Each end is logged with what made the app-server stale: the account switched, the route changed, or the used-up takeover (`codex: ended the Codex app's app-server [pid] for the app to start another: `), so a crash a user reports can be put down to one of them (#4550, `TestCodexAppEndSaysWhy`). The app starts another app-server at once and keeps its window, threads and drafts (tried in the real app in a sandbox `CODEX_HOME`, both ways). An app-server that outlives three ends, or may not be ended, leaves the row saying to quit and reopen the app (`CodexAppStuck`). An ended app-server's pid gone doesn't mean the app has another: the Windows app (MSIX `OpenAI.Codex`, stdio) starts one only once the old one's stdout closes, and a child it left (an MCP server, a tool command) holds that pipe open, so the app answered "Codex app-server process is not available" until it was restarted (蛋仔 on Discord). The watcher waits `codexAppBackWait` (30s) for another app-server; when none came and the app is still open (`CodexAppOpen`), it quits and opens the app as the Agents row's Restart does (`CodexAppReopen`, Windows only), else the row says to (`CodexAppStuck`). `RestartCodexApp`, uninstall's `RestartCodexAppWhenIdle` and the switch notice's Restart (`RestartSwitchedCodexApp`) wait for it the same way and reopen or say so alike, and `recheckLeft` keeps the record while the app is open with no app-server. A turn left open in Codex's sessions holds the restart for up to `codexTurnWindow` (30m), except where the app-server is on a used-up account: after a switch off one (`SwitchWhenSpent` → `codexAppSpentSwitch`, or a switch by hand off an account last read held, `codexHeldKnown` in `noteCodexSwitch`) and when magpie becomes Codex's provider for one (`codexAppStep`'s `into`; xiaoq6285 on Discord: quota out, then another account or provider picked, and Send stayed grey; `TestCodexAppServerRestartedPastATurnStuckWhenMagpieTakesOver`, `TestCodexHandSwitchOffAHeldAccountIsSpent`). There a turn that has written no session file and sent nothing through magpie for `codexTurnStuckAfter` (2m) counts stuck and the app-server is restarted past it, since its next request would be refused on that account (蛋仔 on Discord: quota ran out mid-task and the app hung till restarted; `TestCodexAppServerRestartedPastATurnStuckOnTheSpentAccount`). An account switch restarts nothing, and neither the app nor the background daemon is said to be left on the old account (`CodexAppStale`, `CodexDaemonStale`, the CLI's switch line), while the provider Codex's config.toml names takes no ChatGPT account (`provider.CodexNoAccount`, `codexNoAccount` in [`agents.go`](../../internal/agent/agents.go)): a top-level `model_provider` other than `openai` whose `[model_providers]` table doesn't say `requires_openai_auth = true`, such as magpie's with the user's own `false` (danzi002 on Discord). Codex then sends the table's key and its app-server reads no account (codex-rs `account_state`, `resolve_provider_auth`); tried with codex-cli 0.165.0 in a sandbox `CODEX_HOME`: `account/read` and `getAuthStatus` said no account before and after auth.json was switched, and `codex exec` sent `Bearer` the table's key on both accounts. A route change still restarts it, and so does a switch under a profile, the built-in provider, a provider with no table or a config that can't be read (`TestCodexNoAccountSwitchRestartsNothing`, `TestCodexNoAccountOfEachConfig`, `TestCodexNoAccountFollowsRequiresOpenAIAuth`). Until the reset the app's ChatGPT side is off (cloud tasks, its usage meter, Log out); the Agents row says so with the reset's time (`appOut` in `/api/state`, `CodexOutUntil`), and it all comes back at the reset. While the active account is held or a window is at 90% or more, its usage is read every minute rather than every five (`codexLookEvery`). `TestCodexAppServerRestartedEachWay`, `TestCodexAppServerRestartedOnDisconnect`, `TestCodexAppRouteFollowsConnectAndDisconnect`, `TestCodexEffortPickKeepsTheAppRunning`, `TestCodexAppRouteIgnoresARename`, `TestCodexAppServerUnknown`, `TestCodexAppServerStuck`, `TestCodexAppServersOnHome`, `TestCodexTurnOpen`, `TestCodexBusy`, `codex-app-out.test.cjs`. +- Codex signed in to ChatGPT stays beside its sign-in (`openai_base_url`) unless the user picks magpie API. magpie becomes its provider only while the Codex app holds the active account, which it sends nothing for: `/wham/usage` says it isn't allowed, and it has no credits and isn't a workspace still within its overage (`codexHeld`, read by `provider.CodexUsedUp`). With Codex switched off or removed in magpie (`leftAlone`), whose allowance magpie otherwise reads nothing of, the active account is still read for this alone while Codex takes magpie's models beside its sign-in or magpie is its provider for the held account (`Agent.HoldMatters`, through the `provider.CodexHoldMatters` hook; `codexHoldReading`): once a minute at most, with the token as Codex keeps it, never renewed or written (`codexTokenAsKept`), and nothing shown on the Usage page. Before, turning Codex off in magpie after its allowance ran out left the Codex app greying Send for magpie's models through restarts, and one already moved was put back on the held account (sherlock_23333 on X; `TestCodexHoldReadLeftAlone`, `TestCodexHoldMatters`). Where the app goes by what usage can't show (an experiment's gate, a reserve, a Team plan's overage under the reserve experiment), it counts as held: a wrong move costs ChatGPT extras, a missed one every turn. A saved reading kept through a failed read stops saying held once its used-up window has started again; a hold with no window used up stays till a fresh read. The app then loses its ChatGPT state (durable threads, remote control), so a window at 100% alone, which credits get past, doesn't move it (`codex.out` marks the move, and Sync undoes it once the account has room). The same holds on one of Codex's own models joined beside the sign-in (MasterYi on Discord: the Codex app greyed Send for every model on a used-up account): Sync makes magpie the provider on that model as magpie serves it (`codexOwnViaMagpie`, `codex/`), keeps the model picked in `codex.out_own`, and once the account has room puts Codex back joined on it; a model the user picked meanwhile stays theirs. With no ChatGPT account in magpie to serve it, Codex is left as it is (`TestCodexOwnModelGoesThroughMagpieWhileUsedUp`, `TestCodexOwnModelKeptOnChatGPT`). Nor does it move when magpie would serve that model on the same used-up account alone: no fallback on the Codex subscription and no other ChatGPT account not known out (`provider.CodexServesWhileOut`). Every turn would be refused there too, and the move only hid the account, its usage and its reset from the app's menu (down to "magpie") and ended the app's app-server at the limit and again at the reset, which the ChatGPT app shows as an error and relaunches (#4550; xiaoq6285 on Discord, one Plus account in the Windows app; `TestCodexOwnModelOneSpentAccountStaysOnItsSignIn`, `TestCodexServesWhileOut`). The account is read again at once when a reply says it may be out (a `usage_limit_reached` rest, or an `x-codex-*` window heard at 100%; `provider.CodexMayBeUsedUp`, at most every 20s, the active account only), not only on the five-minute look. A turn relayed to Codex's own sign-in, the one account on (`codexUpstreamOn` with no account, the gateway's `codexRelayedAccount`), is heard the same way: its `x-codex-*` windows and `codex.rate_limits` event kept as the sign-in's usage (`heardCodexLimits`), and a `usage_limit_reached` refusal reading it again. Before, only turns served through magpie's accounts were, so with one account magpie learned the account was out only at the next look, minutes on, and the Codex app kept Send greyed until it was restarted (unsplashz on Discord; `TestCodexUsedUpRelayedAsksAtOnce`, `TestCodexRelayedWindowsHeard`). A Codex started before magpie became its provider keeps sending its own model's turns to its built-in provider; while the sign-in is known out (`provider.CodexUsedUpKnown`) and the request signs as it, those go through routing as `codex/` (`codexAccounts`), as a restarted Codex's do (`TestCodexHeldSignInServedWithoutRestart`). The Codex app greys Send for every model, magpie's too, while its `authMethod` is `chatgpt` and its rate limit says not allowed (its composer's gate in ChatGPT.app 26.1013), and reads `authMethod` from its app-server's `account/read` only as the app-server starts; with magpie the provider (`requires_openai_auth` false) that answers no account, so the gate lifts. So the gateway process restarts the app's own app-server each time magpie becomes Codex's provider for the used-up account (`Agent.AppOut`) and again when Codex is put back on the account after its reset, and likewise whenever what the app-server reads as it starts and magpie writes changes, which is where its requests go (`model_provider`, `openai_base_url` and the magpie table's `base_url`, and its `requires_openai_auth` while that table is Codex's `model_provider`: beside the sign-in the app-server reads the built-in provider's account, so the key following the account out and back is nothing it reads; `codexAppRoute`, through the `provider.CodexAppRoute` hook): a Disconnect, a Connect, failover written or taken out. The model list is not part of it: neither `model_catalog_json` nor what the catalog holds. The catalog follows magpie's names and the effort new sessions start at, which the Codex app saves on each pick, and the ChatGPT app takes an ended app-server as a crash and relaunches, so a route that hashed the catalog (from lucis0116 on X until #4550) ended the app every few minutes (indekkusu141209 on X). A new list is read at the app's next launch or on the Agents row's Restart (`StaleCopies`) A list that drops a model and has it back at the next fetch, the same list in another order, and a catalog read half-written leave the route as it was (`TestCodexEffortPickKeepsTheAppRunning`, `TestCodexAppRouteIgnoresARename`, `TestCodexAppRouteKeepsThroughListFlaps`). Before this an app-server started while Codex was connected kept sending to the gateway after Disconnect until the app was restarted (JiangLiuer222 on X). At the watcher's first look only a used-up account's app-servers are ended, since what the others read before magpie started isn't known. It runs on every system (`KeepCodexAppOnItsProvider`, every 3s; Ethereal499 and Isdavexxx on X, MasterYi on Discord, #540: the earlier once-only reopen ran on macOS from the GUI process only, so Windows, Linux, a GUI-less magpie and the switch back stayed greyed). It ends only app-servers on magpie's Codex home (`codexAppHomeIs`: the process's `CODEX_HOME`, else `HOME/.codex`, read by `proc.EnvOf`; Windows can't tell and counts every one), only once no Codex request is in flight through the gateway nor ended in the last 10s (`Server.CodexBusy`) and no session under the Codex home has a turn started and not ended (`codexTurnOpen`), and with a clean exit (`proc.End`: SIGTERM, `TerminateProcess` with code 0), since the app shows any other exit as a crash. Each end is logged with what made the app-server stale: the account switched, the route changed, or the used-up takeover (`codex: ended the Codex app's app-server [pid] for the app to start another: `), so a crash a user reports can be put down to one of them (#4550, `TestCodexAppEndSaysWhy`). The app starts another app-server at once and keeps its window, threads and drafts (tried in the real app in a sandbox `CODEX_HOME`, both ways). An app-server that outlives three ends, or may not be ended, leaves the row saying to quit and reopen the app (`CodexAppStuck`). An ended app-server's pid gone doesn't mean the app has another: the Windows app (MSIX `OpenAI.Codex`, stdio) starts one only once the old one's stdout closes, and a child it left (an MCP server, a tool command) holds that pipe open, so the app answered "Codex app-server process is not available" until it was restarted (蛋仔 on Discord). The watcher waits `codexAppBackWait` (30s) for another app-server; when none came and the app is still open (`CodexAppOpen`), it quits and opens the app as the Agents row's Restart does (`CodexAppReopen`, Windows only), else the row says to (`CodexAppStuck`). `RestartCodexApp`, uninstall's `RestartCodexAppWhenIdle` and the switch notice's Restart (`RestartSwitchedCodexApp`) wait for it the same way and reopen or say so alike, and `recheckLeft` keeps the record while the app is open with no app-server. A turn left open in Codex's sessions holds the restart for up to `codexTurnWindow` (30m), except where the app-server is on a used-up account: after a switch off one (`SwitchWhenSpent` → `codexAppSpentSwitch`, or a switch by hand off an account last read held, `codexHeldKnown` in `noteCodexSwitch`) and when magpie becomes Codex's provider for one (`codexAppStep`'s `into`; xiaoq6285 on Discord: quota out, then another account or provider picked, and Send stayed grey; `TestCodexAppServerRestartedPastATurnStuckWhenMagpieTakesOver`, `TestCodexHandSwitchOffAHeldAccountIsSpent`). There a turn that has written no session file and sent nothing through magpie for `codexTurnStuckAfter` (2m) counts stuck and the app-server is restarted past it, since its next request would be refused on that account (蛋仔 on Discord: quota ran out mid-task and the app hung till restarted; `TestCodexAppServerRestartedPastATurnStuckOnTheSpentAccount`). An account switch restarts nothing, and neither the app nor the background daemon is said to be left on the old account (`CodexAppStale`, `CodexDaemonStale`, the CLI's switch line), while the provider Codex's config.toml names takes no ChatGPT account (`provider.CodexNoAccount`, `codexNoAccount` in [`agents.go`](../../internal/agent/agents.go)): a top-level `model_provider` other than `openai` whose `[model_providers]` table doesn't say `requires_openai_auth = true`, such as magpie's with the user's own `false` (danzi002 on Discord). Codex then sends the table's key and its app-server reads no account (codex-rs `account_state`, `resolve_provider_auth`); tried with codex-cli 0.165.0 in a sandbox `CODEX_HOME`: `account/read` and `getAuthStatus` said no account before and after auth.json was switched, and `codex exec` sent `Bearer` the table's key on both accounts. A route change still restarts it, and so does a switch under a profile, the built-in provider, a provider with no table or a config that can't be read (`TestCodexNoAccountSwitchRestartsNothing`, `TestCodexNoAccountOfEachConfig`, `TestCodexNoAccountFollowsRequiresOpenAIAuth`). Until the reset the app's ChatGPT side is off (cloud tasks, its usage meter, Log out); the Agents row says so with the reset's time (`appOut` in `/api/state`, `CodexOutUntil`), and it all comes back at the reset. While the active account is held or a window is at 90% or more, its usage is read every minute rather than every five (`codexLookEvery`). `TestCodexAppServerRestartedEachWay`, `TestCodexAppServerRestartedOnDisconnect`, `TestCodexAppRouteFollowsConnectAndDisconnect`, `TestCodexEffortPickKeepsTheAppRunning`, `TestCodexAppRouteIgnoresARename`, `TestCodexAppServerUnknown`, `TestCodexAppServerStuck`, `TestCodexAppServersOnHome`, `TestCodexTurnOpen`, `TestCodexBusy`, `codex-app-out.test.cjs`. - Moving a field from one of magpie's models to another (the agent's own picker) is not drift. Moving it off magpie is. - Claude Desktop applying a configLibrary profile other than magpie's is not drift when that profile is a gateway profile for this magpie's gateway (`desktopAppliedGateway` in [`claudedesktop.go`](../../internal/agent/claudedesktop.go)): Desktop's "Import configuration" adds a file exported on another computer, magpie's profile there with the user's connectors (`managedMcpServers`), as a new entry under a random id (aa86222 on Discord). magpie keeps it applied on Reconnect and through Sync, and writes in it only `inferenceGatewayApiKey` (with a missing auth scheme) when the gateway would refuse its key (`desktopKeyApplied`; magpie's own keys count as taken, `desktopKeyTaken`). A profile for another gateway, CC Switch's among them, is still drift, and Reconnect applies magpie's. The first switch-on still starts magpie's profile from an applied one (#2035). `TestClaudeDesktopImportedProfileIsOnMagpie`. - Claude Desktop 4.4212 (10-29) seals the secrets of its configLibrary profiles at rest: at every start it writes `inferenceGatewayApiKey` (and every other string secret its schema drops on export) back as `__sealed__:v1:` + base64 of `{"configLibrary":{"key":…,"value":…}}` behind `anthropic.claude.crossProfileSecret.v1:`, protected with the user's DPAPI on Windows (entropy `anthropic.claude.crossProfileSecret.v1`, claude-native's `userDpapiProtect`) and Electron's safeStorage (the Keychain) on macOS, and it sends the gateway the key as it was. `desktopOpen` ([`desktopseal.go`](../../internal/agent/desktopseal.go)) reads the key as Desktop does: on Windows it opens the seal (`desktopUnprotect`, `CryptUnprotectData`, never prompting) and judges what is in it; a seal it can't open (macOS, another user's) is unknown, so Check doesn't call it changed and `desktopKeyApplied` doesn't write over it. Before this the key read as changed after every Desktop start and Reconnect only wrote it in the clear for Desktop to seal again (a Windows user on Discord). A key in the clear that isn't one the gateway takes, a missing key and another address are still drift (`TestClaudeDesktopSealedKeyIsNotChanged`, `TestClaudeDesktopImportedSealedKeyStays`, `TestClaudeDesktopSealedKeyOpened` on Windows). diff --git a/internal/agent/agents.go b/internal/agent/agents.go index 25e5d1e50..2ea834d14 100644 --- a/internal/agent/agents.go +++ b/internal/agent/agents.go @@ -97,16 +97,29 @@ func codexAppRoute() (route string, out, known bool) { } out = a.AppOut != nil && a.AppOut() var b strings.Builder + var mp string for _, k := range []string{"model_provider", "openai_base_url"} { v, _ := edit.GetTOMLTop(a.Path, k) + if k == "model_provider" { + mp = v + } b.WriteString(k + "=" + v + "\n") } t, _ := edit.GetTOMLTable(a.Path, "model_providers."+magpieID) b.WriteString("magpie.base_url=" + t["base_url"] + "\n") - // and whether it requires OpenAI auth, which decides whether the app - // has its ChatGPT account at all (openaiAuth in codex.go): read as the - // app-server starts, like the rest - b.WriteString("magpie.requires_openai_auth=" + t["requires_openai_auth"] + "\n") + // and, while magpie's table is Codex's provider, whether it requires + // OpenAI auth, which decides whether the app has its ChatGPT account + // at all (openaiAuth in codex.go): read as the app-server starts, like + // the rest. The app-server reads the account of the provider Codex is + // on (codex-rs account_state), so beside the sign-in, on Codex's + // built-in provider, the key follows the account running out and + // coming back (openaiAuth) with nothing for the app to read again: + // counted there, it ended the app's app-server at the limit and again + // at the reset, and the ChatGPT app showed an error and relaunched + // each time (xiaoq6285 on Discord, #4550) + if mp == magpieID { + b.WriteString("magpie.requires_openai_auth=" + t["requires_openai_auth"] + "\n") + } if out { b.WriteString("out\n") } diff --git a/internal/agent/codex.go b/internal/agent/codex.go index 86d60c992..1e846c8db 100644 --- a/internal/agent/codex.go +++ b/internal/agent/codex.go @@ -1670,8 +1670,13 @@ func codexIn(at place) *Agent { // below: magpie becomes Codex's provider on that model as // magpie serves it, the one picked kept (codex.out_own) to go // back to once the account has room. One magpie serves on no - // account of its own is left as it is. - if m := get("model"); !isMagpie(m) && !api() && chatGPT() && joined() && out() { + // account of its own is left as it is, and so is one magpie + // could serve on that same account alone, with no fallback + // and no other account (provider.CodexServesWhileOut): every + // turn would be refused there too, and the takeover only hid + // the account and its reset and restarted the app twice + // (xiaoq6285 on Discord, one Plus account) + if m := get("model"); !isMagpie(m) && !api() && chatGPT() && joined() && out() && provider.CodexServesWhileOut(m) { if id := codexOwnViaMagpie(m); id != "" { stash(map[string]string{at.key("codex.out_own"): m}) return set(id) diff --git a/internal/agent/codex_usedup_test.go b/internal/agent/codex_usedup_test.go index c192a36ad..caa53d72c 100644 --- a/internal/agent/codex_usedup_test.go +++ b/internal/agent/codex_usedup_test.go @@ -5,6 +5,8 @@ import ( "path/filepath" "strings" "testing" + + "github.com/yetone/magpie/internal/provider" ) // A ChatGPT account that runs out of its allowance after a magpie model was @@ -119,6 +121,11 @@ func TestCodexKeptOnChatGPT(t *testing.T) { // its sign-in. func TestCodexOwnModelGoesThroughMagpieWhileUsedUp(t *testing.T) { home, read := codexHome(t, `{"tokens":{"access_token":"x","id_token":"x.e30.x"}}`, "model = \"gpt-a\"\n") + // the Codex subscription falls back to another provider while the + // account is out: magpie has something to serve the turn on + if err := provider.Save(provider.Provider{ID: "codex", Fallback: []string{"fake/m1"}}); err != nil { + t.Fatal(err) + } os.WriteFile(filepath.Join(home, ".codex", "models_cache.json"), []byte(`{"models":[{"slug":"gpt-a","display_name":"A","priority":1}]}`), 0o644) cx := codex(home) @@ -176,6 +183,58 @@ func TestCodexOwnModelGoesThroughMagpieWhileUsedUp(t *testing.T) { } } +// One ChatGPT account, out, on one of Codex's own models joined beside the +// sign-in, and nothing else in magpie to serve that model on: no fallback +// on the Codex subscription and no other account (xiaoq6285 on Discord: +// a Plus account in the Windows Codex app, the menu down to "magpie" with +// no quota after the five-hour limit, the app erroring and restarting at +// the limit and again at the reset). magpie leaves Codex on its sign-in: +// every turn it took over would be refused on that same account, so the +// app keeps the account, its usage and its reset, and nothing restarts. +func TestCodexOwnModelOneSpentAccountStaysOnItsSignIn(t *testing.T) { + home, read := codexHome(t, `{"tokens":{"access_token":"x","id_token":"x.e30.x"}}`, "model = \"gpt-a\"\n") + os.WriteFile(filepath.Join(home, ".codex", "models_cache.json"), + []byte(`{"models":[{"slug":"gpt-a","display_name":"A","priority":1}]}`), 0o644) + cx := codex(home) + if ok, err := cx.Join(); err != nil || !ok { + t.Fatalf("join: %v %v", ok, err) + } + if codexOwnViaMagpie("gpt-a") == "" { + t.Fatal("magpie lists no codex/gpt-a: the test proves nothing") + } + route, _, known := codexAppRoute() + if !known { + t.Fatal("route not known") + } + // the route is what the app's app-server is ended over + // (KeepCodexAppOnItsProvider): unchanged, the app keeps running + same := func(when string) { + t.Helper() + cfg := read() + if !strings.Contains(cfg, `model = "gpt-a"`) || strings.Contains(cfg, "model_provider =") || !strings.Contains(cfg, "openai_base_url") { + t.Fatalf("%s: Codex moved off its sign-in:\n%s", when, cfg) + } + if r, out, _ := codexAppRoute(); r != route || out || cx.AppOut() { + t.Fatalf("%s: the app's app-server would be ended (out %v):\n%s\nwas:\n%s", when, out, r, route) + } + } + codexUsedUp = func() bool { return true } + for _, when := range []string{"used up", "used up, synced again"} { + if err := cx.Sync(); err != nil { + t.Fatal(err) + } + same(when) + } + codexUsedUp = func() bool { return false } + if err := cx.Sync(); err != nil { + t.Fatal(err) + } + same("reset") + if !cx.Joined() { + t.Fatal("reset: not joined") + } +} + // Kept on ChatGPT, a used-up account on one of Codex's own models leaves // Codex as it is: the user chose the sign-in. func TestCodexOwnModelKeptOnChatGPT(t *testing.T) { @@ -214,6 +273,10 @@ func TestCodexOwnModelOutThenKeptOnChatGPT(t *testing.T) { if ok, err := cx.Join(); err != nil || !ok { t.Fatalf("join: %v %v", ok, err) } + // a fallback for magpie to serve the turn on (TestCodexOwnModelOneSpentAccountStaysOnItsSignIn) + if err := provider.Save(provider.Provider{ID: "codex", Fallback: []string{"fake/m1"}}); err != nil { + t.Fatal(err) + } codexUsedUp = func() bool { return true } t.Cleanup(func() { codexUsedUp = func() bool { return false } }) if err := cx.Sync(); err != nil { diff --git a/internal/provider/codex_app_out.go b/internal/provider/codex_app_out.go index 67cd68436..5b0f0dd4e 100644 --- a/internal/provider/codex_app_out.go +++ b/internal/provider/codex_app_out.go @@ -75,3 +75,25 @@ func CodexMayBeUsedUp(user string) { c.Unlock() go codexReadNow(active) } + +// CodexServesWhileOut says magpie has something to serve Codex's own +// model on while the ChatGPT account Codex is signed in to is out: the +// Codex subscription's fallbacks, set in magpie, or another of its +// ChatGPT accounts not known out or lapsed. With neither, every turn +// magpie took over would be refused on that same account, so taking over +// would only hide the account and its reset from the app and restart the +// app's app-server twice (xiaoq6285 on Discord, one Plus account). +func CodexServesWhileOut(model string) bool { + if model == "" { + return false + } + if p, _, ok := Resolve("codex/" + model); ok && p.Account != nil && p.Account.Agent == "codex" && len(FallbackModels(p)) > 0 { + return true + } + for _, l := range Logins("codex") { + if !l.Active && l.Lapsed == "" && !codexHeldKnown(l.User) { + return true + } + } + return false +} diff --git a/internal/provider/codex_app_out_test.go b/internal/provider/codex_app_out_test.go index 5da81a23d..94226552d 100644 --- a/internal/provider/codex_app_out_test.go +++ b/internal/provider/codex_app_out_test.go @@ -98,3 +98,61 @@ func TestCodexReadNowSwitchesAtOnce(t *testing.T) { } } } + +// Whether magpie has anything to serve Codex's own model on while the +// account Codex is signed in to is out (xiaoq6285 on Discord, one Plus +// account): with that account alone and no fallback, nothing; another +// ChatGPT account not known out, or a fallback on the Codex +// subscription, is something. Another account known out is not. +func TestCodexServesWhileOut(t *testing.T) { + home := signIn(t) // me@example.com + rememberLogins(true) + if CodexServesWhileOut("gpt-5.5") { + t.Fatal("one account, no fallback: serves") + } + if CodexServesWhileOut("") { + t.Fatal("no model: serves") + } + codexSignIn(t, home, "spare@example.com", "r-spare") + rememberLogins(true) + var active, other string + for _, l := range Logins("codex") { + if l.Active { + active = l.User + } else { + other = l.User + } + } + if other == "" { + t.Fatalf("no second account: %+v", Logins("codex")) + } + loginUsageCache.Lock() + oldCache := loginUsageCache.m + loginUsageCache.m = map[string]loginUsageEntry{ + "codex/" + active: {at: time.Now(), q: SubscriptionQuota{Provider: "codex", User: active, Held: true}}, + } + loginUsageCache.Unlock() + t.Cleanup(func() { + loginUsageCache.Lock() + loginUsageCache.m = oldCache + loginUsageCache.Unlock() + }) + if !CodexServesWhileOut("gpt-5.5") { + t.Fatalf("another account (%s), not known out: doesn't serve", other) + } + loginUsageCache.Lock() + loginUsageCache.m["codex/"+other] = loginUsageEntry{at: time.Now(), q: SubscriptionQuota{Provider: "codex", User: other, Held: true}} + loginUsageCache.Unlock() + if CodexServesWhileOut("gpt-5.5") { + t.Fatal("every account out, no fallback: serves") + } + if err := Save(Provider{ID: "fb", Name: "FB", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"m"}}); err != nil { + t.Fatal(err) + } + if err := Save(Provider{ID: "codex", Fallback: []string{"fb/m"}}); err != nil { + t.Fatal(err) + } + if !CodexServesWhileOut("gpt-5.5") { + t.Fatal("a fallback on the Codex subscription: doesn't serve") + } +}