diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index 1c34416c9..d27da74ef 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -109,7 +109,9 @@ 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 (with no credits it does when the backend says `allowed` false, and only then: `codexAtLimit`. The app's composer gate greys Send on that alone, in ChatGPT.app 26.1029 as in 26.1021, and keeps a window of an allowed account at 1% or more, so allowed not said or allowed with a window at 100% is an account it still sends for. A used-up 5h window with the week open is held through it: the backend says allowed false there, as the real Team reply in testdata does with its 5h at 100% and its week at 63%; xiaoq6285 on Discord) (`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`). Where 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` false), every turn on it would be refused too, but the Codex app greys Send for every model while the account is out, so keeping the account's menu costs a grey Send (shamen, chenhan and xiaoq6285 on Discord). Sync then makes magpie the provider on a stand-in model of magpie's that is on no ChatGPT account (`codexOtherModel`, kept in `codex.out_stand` beside `codex.out_own`), once per held/unheld transition: on the stand-in the model is magpie's, so the branch isn't met again and a steady held state writes nothing and ends no app-server. At the reset Codex is put back joined on its own model; another model picked meanwhile stays theirs (the stand-in itself picked can't be told from staying on it, and gives way to the own model). This reverses f37742e14, which left Codex on its sign-in to keep the account's menu and usage (the app-server restarts it cost, #4550, are the two the takeover makes). With nothing else in magpie to offer (no stand-in) Codex stays on its sign-in, as no takeover could send (`TestCodexOwnModelOneSpentAccountStaysOnItsSignIn`, `TestCodexOwnModelOneSpentAccountTakenOverForOtherModels`, `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. What magpie changes by itself that the app works without waits for the user, though, unless they ticked Restart the Codex app when magpie switches its account back (`Provider.RestartApp`, `provider/restartapp`, off by default, this computer's own like KeepLogin): its switch back once the account it moved off has room (`SwitchWhenSpent` → `switchLoginBy(…, true)`, `codexApp.auto`) and giving Codex its account back at the reset. Those leave the app-server running, log why, and the switch notice's Restart is the way to follow; a switch the user makes, a Connect, a Disconnect and failover written or taken out still restart it, and so does the takeover turned off by the user rather than ended by the reset: its sign-in set to Always ChatGPT (the takeover note's Keep on ChatGPT) or Codex disconnected while magpie stood in (`Agent.AppOutOff` through `provider.CodexTakeoverOff`, asked only as `out` goes false). The app-server the takeover started answers `account/read` with no account, so the app kept its ChatGPT projects and chats hidden after the user turned the takeover off to have them back, and the Windows app has no Restart of its own (Herzz____ on X, `TestCodexAppRestartedWhenTheTakeoverIsTurnedOff`). So does whatever leaves the app-server on a used-up account, tick or not: the takeover in, the first look on one, and magpie's switch off one (`needed` in `codexAppStep`), since the app greys Send there and reads the account only as its app-server starts, so with the tick off a takeover at the limit left Send grey and the fallback unreachable (v0.1.2826 to its fix). An app-server left running on the account magpie switched Codex back off is restarted too once that account is read held (`restartCodexAppLeftOnSpent`, on each full look of `KeepOnAnAccountWithRoom`, once per app-server left): it keeps the account it started on (`CodexAppStale`), so when that ran out the app greyed Send for every model while the account Codex is signed in to had room and nothing else read the old one (nb5p on Discord: B first in magpie, the app still on A; `TestCodexAppLeftOnASpentAccountIsRestarted`). atom0964 on Discord had both sign-in ticks off and the ChatGPT app relaunched at every switch between two Plus accounts (`TestCodexAppLeftRunningForMagpiesOwnChanges`, `TestCodexAppFirstLookOnAUsedUpAccountRestarts`, `restart-app.test.cjs`). 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 signed-in ChatGPT app (26.1021) can still fail on the app-server it starts next ("Hosted AppServerManager identity is not ready") and show "ChatGPT hit a snag" until it is quit and opened again (ysm119 on Discord, #4550), a fault in the app the clean end can't avoid. So for `codexAppCrashWait` (60s) after each of these ends ([`codex_app_crash.go`](../../internal/provider/codex_app_crash.go)) the app's own logs are read (`CodexAppCrashed`, [`agent/codex_app_crash.go`](../../internal/agent/codex_app_crash.go): `~/Library/Logs/com.openai.codex`, `%LOCALAPPDATA%\Codex\Logs` and the Store package's, `$XDG_STATE_HOME/codex/logs`) for a whole `fatal_error_broadcasted` line stamped after the end. When the page shows and no request has gone through magpie or been in flight since, and no Codex turn has opened since, the app is quit and opened once (`CodexAppRelaunch`: ⌘Q's quit and `open` on macOS, never forced, ChatGPT.app by its bundle id only; `CodexAppReopen` on Windows); where that can't be done (Linux, an app that didn't quit) the Agents row says to quit and reopen it (`CodexAppSnagged`, `appSnag`) until the app-servers seen then are gone or the app is closed. Logs that can't be read reopen nothing (`TestCodexAppReopenedWhenItShowsItsErrorPage`, `TestCodexAppInUseAfterItsErrorPageIsLeft`, `TestCodexAppCrashedReadsItsOwnLogs`, `TestCodexAppRelaunchOnlyTheCodexApp`, `codex-app-snag.test.cjs`). 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 (with no credits it does when the backend says `allowed` false, and only then: `codexAtLimit`. The app's composer gate greys Send on that alone, in ChatGPT.app 26.1029 as in 26.1021, and keeps a window of an allowed account at 1% or more, so allowed not said or allowed with a window at 100% is an account it still sends for. A used-up 5h window with the week open is held through it: the backend says allowed false there, as the real Team reply in testdata does with its 5h at 100% and its week at 63%; xiaoq6285 on Discord) (`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`). Where 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` false), every turn on it would be refused too, but the Codex app greys Send for every model while the account is out, so keeping the account's menu costs a grey Send (shamen, chenhan and xiaoq6285 on Discord). Sync then makes magpie the provider on a stand-in model of magpie's that is on no ChatGPT account (`codexOtherModel`, kept in `codex.out_stand` beside `codex.out_own`), once per held/unheld transition: on the stand-in the model is magpie's, so the branch isn't met again and a steady held state writes nothing and ends no app-server. At the reset Codex is put back joined on its own model; another model picked meanwhile stays theirs (the stand-in itself picked can't be told from staying on it, and gives way to the own model). This reverses f37742e14, which left Codex on its sign-in to keep the account's menu and usage (the app-server restarts it cost, #4550, are the two the takeover makes). With nothing else in magpie to offer (no stand-in) Codex stays on its sign-in, as no takeover could send (`TestCodexOwnModelOneSpentAccountStaysOnItsSignIn`, `TestCodexOwnModelOneSpentAccountTakenOverForOtherModels`, `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. What magpie changes by itself that the app works without waits for the user, though, unless they ticked Restart the Codex app when magpie switches its account back (`Provider.RestartApp`, `provider/restartapp`, off by default, this computer's own like KeepLogin): its switch back once the account it moved off has room (`SwitchWhenSpent` → `switchLoginBy(…, true)`, `codexApp.auto`) and giving Codex its account back at the reset. Those leave the app-server running, log why, and the switch notice's Restart is the way to follow; a switch the user makes, a Connect, a Disconnect and failover written or taken out still restart it, and so does the takeover turned off by the user rather than ended by the reset: its sign-in set to Always ChatGPT (the takeover note's Keep on ChatGPT) or Codex disconnected while magpie stood in (`Agent.AppOutOff` through `provider.CodexTakeoverOff`, asked only as `out` goes false). The app-server the takeover started answers `account/read` with no account, so the app kept its ChatGPT projects and chats hidden after the user turned the takeover off to have them back, and the Windows app has no Restart of its own (Herzz____ on X, `TestCodexAppRestartedWhenTheTakeoverIsTurnedOff`). So does whatever leaves the app-server on a used-up account, tick or not: the takeover in, the first look on one, and magpie's switch off one (`needed` in `codexAppStep`), since the app greys Send there and reads the account only as its app-server starts, so with the tick off a takeover at the limit left Send grey and the fallback unreachable (v0.1.2826 to its fix). An app-server left running on the account magpie switched Codex back off is restarted too once that account is read held (`restartCodexAppLeftOnSpent`, on each full look of `KeepOnAnAccountWithRoom`, once per app-server left): it keeps the account it started on (`CodexAppStale`), so when that ran out the app greyed Send for every model while the account Codex is signed in to had room and nothing else read the old one (nb5p on Discord: B first in magpie, the app still on A; `TestCodexAppLeftOnASpentAccountIsRestarted`). atom0964 on Discord had both sign-in ticks off and the ChatGPT app relaunched at every switch between two Plus accounts (`TestCodexAppLeftRunningForMagpiesOwnChanges`, `TestCodexAppFirstLookOnAUsedUpAccountRestarts`, `restart-app.test.cjs`). 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 signed-in ChatGPT app (26.1021) can still fail on the app-server it starts next ("Hosted AppServerManager identity is not ready") and show "ChatGPT hit a snag" until it is quit and opened again (ysm119 on Discord, #4550), a fault in the app the clean end can't avoid. So for `codexAppCrashWait` (60s) after each of these ends ([`codex_app_crash.go`](../../internal/provider/codex_app_crash.go)) the app's own logs are read (`CodexAppCrashed`, [`agent/codex_app_crash.go`](../../internal/agent/codex_app_crash.go): `~/Library/Logs/com.openai.codex`, `%LOCALAPPDATA%\Codex\Logs` and the Store package's, `$XDG_STATE_HOME/codex/logs`) for a whole `fatal_error_broadcasted` line stamped after the end. When the page shows and no request has gone through magpie or been in flight since, and no Codex turn has opened since, the app is quit and opened once (`CodexAppRelaunch`: ⌘Q's quit and `open` on macOS, never forced, ChatGPT.app by its bundle id only; `CodexAppReopen` on Windows), but only with Restart the Codex app ticked (`codexRestartsApp`): unasked, the quit read as magpie force-restarting the user's app whenever quota ran out (Michael25651150 on X, `TestCodexAppNotQuitUnasked`), and the same tick gates the Windows reopen when no app-server came back (`codexAppGotNone`). The app-server's own restart at the takeover isn't gated: the app reads its account only as its app-server starts, so without it Send stays grey on the used-up account. Where the tick is off or that can't be done (Linux, an app that didn't quit) the Agents row says to quit and reopen it (`CodexAppSnagged`, `appSnag`) until the app-servers seen then are gone or the app is closed. Logs that can't be read reopen nothing (`TestCodexAppReopenedWhenItShowsItsErrorPage`, `TestCodexAppInUseAfterItsErrorPageIsLeft`, `TestCodexAppCrashedReadsItsOwnLogs`, `TestCodexAppRelaunchOnlyTheCodexApp`, `codex-app-snag.test.cjs`). 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`. + +- The Codex app (ChatGPT.app 26.1103 and on) keeps its sidebar's projects per ChatGPT identity in `$CODEX_HOME/.codex-global-state.json`, under `electron-account-renderer-state-v1` (`{owner, inactive: {: {atoms, globals}}}`, the hash the sha256 hex of `JSON.stringify([chatgpt_user_id, chatgpt_account_id])`): on an account change it parks the old identity's account-scoped globals and loads the new one's, so a switch to an account that never had the app open showed no projects (Michael25651150 on X; #5497, #5602, #5702, #5874). The app reads the file only as it starts and writes its memory over it, so magpie writes it only while the app is closed ([`codex_projects.go`](../../internal/provider/codex_projects.go)): `codexProjectsStep` in `codexAppStep`, once the file, auth.json or logins.json changed (at most every 30s while the app may be open, since `CodexAppOpen` lists processes), and `CodexAppClosed` between the quit and the open of every reopen (`appQuitDone` in [`apprestart.go`](../../internal/agent/apprestart.go)). Each identity of auth.json and magpie's saved Codex logins whose snapshot has no `local-projects` key gets the project keys (`codexProjectKeys`) of the identity with the most; a list of its own, an emptied one too, is left. A ChatGPT project's mirror (`g-p-` ids, and every tie to one) isn't carried, and a backing naming another account is dropped, since the app refuses to act on a project "belongs to a different ChatGPT account". A file without the key (an older app) or that doesn't parse is left as it is; before its first write the file as it was is kept beside it (`.magpie-before-projects`). Projects added while the app runs reach the other accounts once it is closed. With no account (the takeover, `requires_openai_auth` false) the app shows no projects by its own rule, and they come back with the account (`TestCodexProjectsFollowASwitch`, `TestCodexProjectsOwnListKept`, `TestCodexProjectsUnknownFileLeft`, `TestCodexProjectsStepWaitsForTheAppToClose`). - 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/apprestart.go b/internal/agent/apprestart.go index 3ce8952d6..1c35bf149 100644 --- a/internal/agent/apprestart.go +++ b/internal/agent/apprestart.go @@ -451,6 +451,7 @@ func (a *Agent) restartWin(ctx context.Context, r restartable, c appRunning) err return restartErr(noticeRestartStillThere, a) } } + appQuitDone(a.ID) if err := winLaunch(c.main); err != nil { return restartErr(noticeRestartNoOpen, a) } @@ -544,8 +545,19 @@ func reopenBundle(ctx context.Context, a *Agent, bundle, exe string) error { case <-time.After(appPoll): } } + appQuitDone(a.ID) if err := appOpen(ctx, bundle); err != nil { return restartErr(noticeRestartNoOpen, a) } return nil } + +// appQuitDone runs once agent id's app has quit and before it opens +// again: the Codex app's projects are carried to its other accounts then, +// while it can't write over them (provider.CodexAppClosed). A var so +// tests don't touch the state file. +var appQuitDone = func(id string) { + if id == "codex" { + provider.CodexAppClosed() + } +} diff --git a/internal/provider/codex_app_crash.go b/internal/provider/codex_app_crash.go index 96219d934..b4a3a8519 100644 --- a/internal/provider/codex_app_crash.go +++ b/internal/provider/codex_app_crash.go @@ -24,8 +24,11 @@ import ( // and no Codex turn has started since nor a request gone through magpie // (the page has no composer: one that ran means it came back), magpie // quits the app and opens it again, once (CodexAppRelaunch: ⌘Q's quit on -// macOS, never forced; the Agents row's Restart on Windows). Where that -// can't be done, or the app didn't quit, the Agents row says to (snag, +// macOS, never forced; the Agents row's Restart on Windows), but only +// with the user's "Restart the Codex app" on (RestartApp): unasked, a +// quit of the user's app read as magpie force-restarting it whenever +// quota ran out (Michael25651150 on X). Where that is off or can't be +// done, or the app didn't quit, the Agents row says to (snag, // CodexAppSnagged) until the app-servers seen then are gone. // CodexAppCrashed and CodexAppRelaunch are set by the agent package. @@ -130,7 +133,14 @@ func codexAppCrashStep(ctx context.Context, now time.Time, busy func() (int, tim pids, _ := codexAppServersOn(lctx, home) cancel() err := errNoRelaunch - if CodexAppRelaunch != nil { + switch { + case !codexRestartsApp(): + // quitting the user's app and opening it again, unasked, takes + // their window with it (Michael25651150 on X: "额度用尽时会强制重启 + // codex 客户端"); the Agents row says to, and its Try again or + // Restart is theirs + err = errRelaunchOff + case CodexAppRelaunch != nil: err = CodexAppRelaunch(ctx) } if err == nil { @@ -150,4 +160,7 @@ func codexAppUnsnag() { c.Unlock() } -var errNoRelaunch = errors.New("magpie doesn't reopen the Codex app here") +var ( + errNoRelaunch = errors.New("magpie doesn't reopen the Codex app here") + errRelaunchOff = errors.New("left to the user: Restart the Codex app when magpie switches its account is off") +) diff --git a/internal/provider/codex_app_crash_test.go b/internal/provider/codex_app_crash_test.go index fbab88cd9..ecf82a2e6 100644 --- a/internal/provider/codex_app_crash_test.go +++ b/internal/provider/codex_app_crash_test.go @@ -277,3 +277,35 @@ func TestCodexAppRowRestartWatchesForTheErrorPage(t *testing.T) { t.Fatalf("the Agents row's Restart: relaunched %d", c.relaunch) } } + +// Michael25651150 on X: "额度用尽时会强制重启 codex 客户端". With the +// user's "Restart the Codex app" off (as it ships), quota running out +// still restarts the app's app-server, which the takeover needs, but the +// app showing its error page after it is never quit and opened again +// unasked: the Agents row says to, and the app's Try again or the row's +// Restart is the user's. Nor is a Windows app that started no app-server. +func TestCodexAppNotQuitUnasked(t *testing.T) { + signIn(t) + s := stubCodexApp(t) + c := stubCodexCrash(t) + codexRestartsApp = func() bool { return false } + now := time.Now() + idle := func() (int, time.Time) { return 0, now.Add(-time.Minute) } + s.running = []int{60} + codexAppStep(context.Background(), now, idle) + s.on = true // the account used up: magpie serves it + if got := codexAppStep(context.Background(), now, idle); !slices.Equal(got, []int{60}) { + t.Fatalf("ended %v, want [60]: the takeover needs the app-server's restart", got) + } + c.page, c.at = true, now.Add(2*time.Second) + now = now.Add(3 * time.Second) + codexAppStep(context.Background(), now, idle) + if c.relaunch != 0 || !CodexAppSnagged() { + t.Fatalf("relaunched %d, snag %v: want left to the user, said on the row", c.relaunch, CodexAppSnagged()) + } + reopened := 0 + CodexAppReopen = func(context.Context) error { reopened++; return nil } + if stuck := codexAppGotNone(context.Background()); !stuck || reopened != 0 { + t.Fatalf("no app-server: reopened %d, stuck %v", reopened, stuck) + } +} diff --git a/internal/provider/codex_app_server.go b/internal/provider/codex_app_server.go index 90958c4f4..2ec7a4b05 100644 --- a/internal/provider/codex_app_server.go +++ b/internal/provider/codex_app_server.go @@ -128,6 +128,12 @@ func codexAppGotNone(ctx context.Context) (stuck bool) { if CodexAppReopen == nil { return true } + if !codexRestartsApp() { + // the user's app is never quit unasked (Michael25651150 on X): + // the Agents row says to, and its Restart does it + log.Printf("codex: the Codex app started no app-server in place of the one magpie ended; left for the user to reopen (Restart the Codex app is off)") + return true + } if err := CodexAppReopen(ctx); err != nil { log.Printf("codex: the Codex app started no app-server in place of the one magpie ended; reopening it: %v", err) return true @@ -429,6 +435,7 @@ func KeepCodexAppOnItsProvider(ctx context.Context, busy func() (int, time.Time) // ended. func codexAppStep(ctx context.Context, now time.Time, busy func() (int, time.Time)) []int { codexAppCrashStep(ctx, now, busy) + codexProjectsStep(ctx) if CodexAppRoute == nil { return nil } diff --git a/internal/provider/codex_projects.go b/internal/provider/codex_projects.go new file mode 100644 index 000000000..d0dbbbae8 --- /dev/null +++ b/internal/provider/codex_projects.go @@ -0,0 +1,475 @@ +package provider + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "log" + "maps" + "os" + "path/filepath" + "slices" + "strings" + "sync" + "time" + + "github.com/yetone/magpie/internal/edit" + "github.com/yetone/magpie/internal/steady" +) + +// The Codex desktop app (26.1103 and on) keeps its sidebar's projects per +// signed-in ChatGPT identity, in $CODEX_HOME/.codex-global-state.json under +// electron-account-renderer-state-v1: {owner, inactive: {: {atoms, +// globals}}}. The owner's projects sit at the file's top level; each other +// identity's are parked under inactive, keyed by the sha256 hex of +// JSON.stringify([chatgpt_user_id, chatgpt_account_id]). When the app's +// account changes (magpie's switch: auth.json, then the app-server's +// restart) it parks the old identity's projects and loads the new one's, +// and an identity that never had the app open has none: the user's +// projects "disappear" on every switch to another account +// (Michael25651150 on X; #5497, #5602, #5702, #5874). +// +// The app reads the file only as it starts and holds it in memory, so a +// write while it runs is lost (it writes its own over it). So while the +// app is closed magpie gives each identity of its saved Codex logins that +// has no projects of its own the projects of the one that has the most +// (carryCodexProjects); the app then loads them on its next switch to +// that account. An identity that has projects, an emptied list included, +// is left alone. With no account at all (magpie's takeover, when Codex's +// provider takes no ChatGPT account) the app shows no projects, by its +// own rule; they come back with the account. + +// codexRendererKey is the file's key for the per-identity state. +const codexRendererKey = "electron-account-renderer-state-v1" + +// codexProjectKeys are the account-scoped globals that make up the +// projects the sidebar shows and what hangs off them, copied to an +// identity that has none. Accounts' own things (remote hosts, pins of +// ChatGPT projects, follow-ups) are not. +var codexProjectKeys = []string{ + "local-projects", + "project-order", + "selected-project", + "project-appearances", + "project-writable-roots", + "project-files", + "pinned-project-ids", + "pinned-thread-ids", + "sidebar-project-thread-orders", + "sidebar-thread-metadata", + "thread-project-assignments", + "thread-project-membership-host-ids", + "thread-writable-roots", + "thread-workspace-root-hints", + "thread-projectless-output-directories", + "projectless-thread-ids", + "active-workspace-roots", + "electron-saved-workspace-roots", + "electron-workspace-root-labels", + "app-server-project-id-by-legacy-project-id-by-host", + "app-server-projects-migration-by-host", + "app-server-pending-project-deletions-by-host", + "app-server-migrated-pinned-thread-ids-by-host", +} + +// codexChatGPTProject is the id prefix of a project the app mirrors from +// a ChatGPT account's own projects: that account's, never carried. +const codexChatGPTProject = "g-p-" + +// codexRendererOwner is the app's key for the identity an auth.json is +// signed in to, "" when it has no ChatGPT identity. +func codexRendererOwner(auth []byte) string { + var a codexAuth + if json.Unmarshal(auth, &a) != nil || a.AuthMode == "apikey" { + return "" + } + claims := jwtClaims(a.Tokens.IDToken) + user := claimString(claims, "https://api.openai.com/auth", "chatgpt_user_id") + account := claimString(claims, "https://api.openai.com/auth", "chatgpt_account_id") + if account == "" { + account = a.Tokens.AccountID + } + if user == "" || account == "" { + return "" + } + var b bytes.Buffer + enc := json.NewEncoder(&b) + enc.SetEscapeHTML(false) // JSON.stringify's bytes + if enc.Encode([]string{user, account}) != nil { + return "" + } + sum := sha256.Sum256(bytes.TrimSuffix(b.Bytes(), []byte("\n"))) + return hex.EncodeToString(sum[:]) +} + +// codexIdentity is what a backing in a project names. +type codexIdentity struct{ user, account string } + +func codexIdentityOf(auth []byte) codexIdentity { + var a codexAuth + if json.Unmarshal(auth, &a) != nil { + return codexIdentity{} + } + claims := jwtClaims(a.Tokens.IDToken) + acc := claimString(claims, "https://api.openai.com/auth", "chatgpt_account_id") + if acc == "" { + acc = a.Tokens.AccountID + } + return codexIdentity{claimString(claims, "https://api.openai.com/auth", "chatgpt_user_id"), acc} +} + +// codexGlobalStatePath is the Codex app's state file in home. +func codexGlobalStatePath(home string) string { + return filepath.Join(home, ".codex-global-state.json") +} + +// errCodexStateUnknown is a state file that isn't the shape this reads: +// nothing is written to it. +var errCodexStateUnknown = errors.New("the Codex app's state file isn't the shape magpie knows") + +// carryCodexProjects gives every identity in auths (auth.json bytes) that +// has no projects in the Codex app's state file at home the projects of +// the identity that has the most, and says how many it gave them to. The +// app must be closed: it writes its own over the file. A file that can't +// be read or parsed, or has no per-identity state, is left as it is. +func carryCodexProjects(home string, auths [][]byte) (int, error) { + path := codexGlobalStatePath(home) + raw, err := os.ReadFile(path) + if err != nil { + if errors.Is(err, os.ErrNotExist) { + return 0, nil + } + return 0, err + } + var top map[string]json.RawMessage + if json.Unmarshal(raw, &top) != nil || top == nil { + return 0, errCodexStateUnknown + } + rs, ok := top[codexRendererKey] + if !ok { + return 0, nil // an app before per-identity projects + } + var r struct { + Owner *string `json:"owner"` + Inactive map[string]json.RawMessage `json:"inactive"` + } + if json.Unmarshal(rs, &r) != nil { + return 0, errCodexStateUnknown + } + var keep map[string]json.RawMessage // the whole renderer object, unknown fields kept + if json.Unmarshal(rs, &keep) != nil { + return 0, errCodexStateUnknown + } + owner := "" + if r.Owner != nil { + owner = *r.Owner + } + snaps := map[string]map[string]json.RawMessage{} // hash → globals + parked := map[string]map[string]json.RawMessage{} + for h, v := range r.Inactive { + var s map[string]json.RawMessage + if json.Unmarshal(v, &s) != nil { + return 0, errCodexStateUnknown + } + var g map[string]json.RawMessage + if gs, ok := s["globals"]; ok && json.Unmarshal(gs, &g) != nil { + return 0, errCodexStateUnknown + } + parked[h], snaps[h] = s, g + } + if owner != "" { + snaps[owner] = top // the owner's globals are the file's own + } + // the source: the identity with the most projects, the owner first + src, most := "", 0 + count := func(g map[string]json.RawMessage) int { + var lp map[string]json.RawMessage + if json.Unmarshal(g["local-projects"], &lp) != nil { + return 0 + } + n := 0 + for id := range lp { + if !strings.HasPrefix(id, codexChatGPTProject) { + n++ + } + } + return n + } + if owner != "" { + src, most = owner, count(top) + } + hashes := slices.Sorted(maps.Keys(parked)) + for _, h := range hashes { + if n := count(snaps[h]); n > most { + src, most = h, n + } + } + if most == 0 { + return 0, nil + } + given := 0 + seen := map[string]bool{} + for _, auth := range auths { + h := codexRendererOwner(auth) + if h == "" || seen[h] || h == src { + continue + } + seen[h] = true + g := snaps[h] + if _, has := g["local-projects"]; has { + continue // its own list, an emptied one too + } + carried := carriedProjects(snaps[src], codexIdentityOf(auth)) + if len(carried) == 0 { + continue + } + if h == owner { + for k, v := range carried { + top[k] = v + } + } else { + s := parked[h] + if s == nil { + s = map[string]json.RawMessage{"atoms": json.RawMessage("{}")} + } + if g == nil { + g = map[string]json.RawMessage{} + } + for k, v := range carried { + g[k] = v + } + gb, err := json.Marshal(g) + if err != nil { + return 0, err + } + s["globals"] = gb + sb, err := json.Marshal(s) + if err != nil { + return 0, err + } + if r.Inactive == nil { + r.Inactive = map[string]json.RawMessage{} + } + r.Inactive[h] = sb + } + given++ + } + if given == 0 { + return 0, nil + } + ib, err := json.Marshal(r.Inactive) + if err != nil { + return 0, err + } + keep["inactive"] = ib + kb, err := json.Marshal(keep) + if err != nil { + return 0, err + } + top[codexRendererKey] = kb + out, err := json.Marshal(top) + if err != nil { + return 0, err + } + target, err := edit.Target(path) // a symlink stays, its target written + if err != nil { + return 0, err + } + mode := os.FileMode(0o644) + if fi, err := os.Stat(target); err == nil { + mode = fi.Mode().Perm() + } + // the file as it was, once, beside it: magpie's write can be undone + backup := target + ".magpie-before-projects" + if _, err := os.Lstat(backup); errors.Is(err, os.ErrNotExist) { + if err := steady.WriteFile(backup, raw, mode); err != nil { + return 0, err + } + } + // the app opened meanwhile: its own state wins + if now, err := os.ReadFile(target); err != nil || !bytes.Equal(now, raw) { + return 0, nil + } + if err := steady.WriteFile(target, out, mode); err != nil { + return 0, err + } + return given, nil +} + +// carriedProjects is the project keys of globals g as an identity id gets +// them: a ChatGPT project's mirror and every tie to one left out, and a +// project's ties to another ChatGPT account's own project dropped. +func carriedProjects(g map[string]json.RawMessage, id codexIdentity) map[string]json.RawMessage { + out := map[string]json.RawMessage{} + for _, k := range codexProjectKeys { + v, ok := g[k] + if !ok { + continue + } + if k == "local-projects" { + v = ownLocalProjects(v, id) + } else { + v = withoutChatGPTProjects(v) + } + if v != nil { + out[k] = v + } + } + if _, ok := out["local-projects"]; !ok { + return nil + } + return out +} + +// codexBackings are a local project's ties to a ChatGPT account's project. +var codexBackings = []string{"chatGptBacking", "retiredChatGptBacking", "chatGptBackingCreation"} + +func ownLocalProjects(v json.RawMessage, id codexIdentity) json.RawMessage { + var lp map[string]map[string]json.RawMessage + if json.Unmarshal(v, &lp) != nil { + return nil + } + for pid, p := range lp { + if strings.HasPrefix(pid, codexChatGPTProject) { + delete(lp, pid) + continue + } + dropped := false + for _, b := range codexBackings { + var who struct { + AccountID string `json:"accountId"` + UserID string `json:"userId"` + } + if bv, ok := p[b]; ok && (json.Unmarshal(bv, &who) != nil || who.AccountID != id.account || who.UserID != id.user) { + delete(p, b) + dropped = true + } + } + if dropped { + delete(p, "chatGptBackingRecoveryPending") + } + } + if len(lp) == 0 { + return nil + } + b, err := json.Marshal(lp) + if err != nil { + return nil + } + return b +} + +// withoutChatGPTProjects drops a ChatGPT project's id from a list, and an +// entry keyed by one or naming one from a record, one level down. +func withoutChatGPTProjects(v json.RawMessage) json.RawMessage { + isGP := func(r json.RawMessage) bool { + var s string + return json.Unmarshal(r, &s) == nil && strings.HasPrefix(s, codexChatGPTProject) + } + var list []json.RawMessage + if json.Unmarshal(v, &list) == nil { + out := list[:0] + for _, e := range list { + if !isGP(e) { + out = append(out, e) + } + } + b, _ := json.Marshal(out) + return b + } + var rec map[string]json.RawMessage + if json.Unmarshal(v, &rec) == nil && rec != nil { + for k, e := range rec { + if strings.HasPrefix(k, codexChatGPTProject) || isGP(e) { + delete(rec, k) + } + } + b, _ := json.Marshal(rec) + return b + } + if isGP(v) { + return nil + } + return v +} + +// codexProjectAuths is the auth.json of every Codex identity magpie knows +// on this computer: the one signed in now and each saved login's. +func codexProjectAuths() [][]byte { + var out [][]byte + if b, err := readAccountFile(codexAuthPath()); err == nil { + out = append(out, b) + } + for _, l := range sharedLogins() { + if l.Agent == "codex" && len(l.Auth) > 0 { + out = append(out, l.Auth) + } + } + return out +} + +// CodexAppClosed carries the user's projects to each of Codex's accounts +// that has none in the Codex app (carryCodexProjects); the caller knows +// the app is closed: the agent package between its quit and its open. +func CodexAppClosed() { + n, err := carryCodexProjects(codexHome(), codexProjectAuths()) + switch { + case err != nil: + log.Printf("codex: carrying the Codex app's projects to its other accounts: %v", err) + case n > 0: + log.Printf("codex: gave %d of Codex's accounts the Codex app's projects", n) + } + codexProjects.Lock() + codexProjects.last = codexProjectsMark() + codexProjects.Unlock() +} + +// codexProjects is what codexProjectsStep last carried at: the state +// file's and the logins' change times and sizes, so an unchanged pair +// isn't read again nor the app's processes listed every look. +var codexProjects struct { + sync.Mutex + last string + tried time.Time +} + +// codexProjectsEvery is how often a change is looked at while the app may +// be open: whether it is lists processes. +var codexProjectsEvery = 30 * time.Second + +// codexProjectsMark names the state file and the logins as they are now. +func codexProjectsMark() string { + var b strings.Builder + for _, p := range []string{codexGlobalStatePath(codexHome()), codexAuthPath(), loginsPath()} { + if fi, err := os.Stat(p); err == nil { + b.WriteString(fi.ModTime().Format(time.RFC3339Nano)) + b.WriteByte('/') + b.WriteString(fi.Name()) + b.WriteByte(' ') + } + b.WriteByte(';') + } + return b.String() +} + +// codexProjectsStep is codexAppStep's carry: once the state file or the +// logins changed, and only while the Codex app is closed. +func codexProjectsStep(ctx context.Context) { + codexProjects.Lock() + mark := codexProjectsMark() + skip := mark == codexProjects.last || time.Since(codexProjects.tried) < codexProjectsEvery + if !skip { + codexProjects.tried = time.Now() + } + codexProjects.Unlock() + if skip { + return + } + if open, known := codexAppOpenNow(ctx); !known || open { + return // carried once it is closed: what it has open it writes over + } + CodexAppClosed() +} diff --git a/internal/provider/codex_projects_test.go b/internal/provider/codex_projects_test.go new file mode 100644 index 000000000..6ac6ea622 --- /dev/null +++ b/internal/provider/codex_projects_test.go @@ -0,0 +1,327 @@ +package provider + +import ( + "context" + "encoding/json" + "os" + "slices" + "testing" + "time" +) + +// codexTestAuth is an auth.json signed in to ChatGPT user u in account a. +func codexTestAuth(u, a string) []byte { + b, _ := json.Marshal(map[string]any{ + "auth_mode": "chatgpt", + "tokens": map[string]any{ + "id_token": fakeJWT(map[string]any{ + "email": u + "@example.com", + "https://api.openai.com/auth": map[string]any{"chatgpt_user_id": u, "chatgpt_account_id": a}, + }), + "account_id": a, + }, + }) + return b +} + +// codexAppSim is the Codex app's renderer state as its GlobalState keeps +// it (ChatGPT.app 26.1103, early-bootstrap-133's selectRendererOwner): the +// file read at launch, an owner switched in memory, the file written. +type codexAppSim struct{ state map[string]any } + +// codexAccountScoped is the app's own list (nh0) of account-scoped +// globals that a switch parks and loads; the sidebar's are among them. +var codexAccountScoped = append(slices.Clone(codexProjectKeys), "remote-projects", "selected-remote-host-id", "queued-follow-ups") + +func codexAppLaunch(t *testing.T, path string) *codexAppSim { + t.Helper() + b, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + s := &codexAppSim{} + if err := json.Unmarshal(b, &s.state); err != nil { + t.Fatal(err) + } + s.selectOwner(nil) // its constructor, before the account is known + return s +} + +func (s *codexAppSim) selectOwner(r *string) { + rs, _ := s.state[codexRendererKey].(map[string]any) + if rs == nil { + return + } + cur, _ := rs["owner"].(string) + if r != nil && rs["owner"] != nil && cur == *r { + return + } + inactive := map[string]any{} + for k, v := range rs["inactive"].(map[string]any) { + inactive[k] = v + } + globals := map[string]any{} + for _, k := range codexAccountScoped { + if v, ok := s.state[k]; ok { + globals[k] = v + } + } + if rs["owner"] != nil { + inactive[cur] = map[string]any{"atoms": map[string]any{}, "globals": globals} + } + var o map[string]any + if r != nil { + o, _ = inactive[*r].(map[string]any) + delete(inactive, *r) + } + for _, k := range codexAccountScoped { + g, _ := o["globals"].(map[string]any) + if v, ok := g[k]; o != nil && ok { + s.state[k] = v + } else { + delete(s.state, k) + } + } + var owner any + if r != nil { + owner = *r + } + s.state[codexRendererKey] = map[string]any{"owner": owner, "inactive": inactive} +} + +func (s *codexAppSim) signIn(auth []byte) { + h := codexRendererOwner(auth) + if h == "" { + s.selectOwner(nil) + return + } + s.selectOwner(&h) +} + +func (s *codexAppSim) projects() []string { + lp, _ := s.state["local-projects"].(map[string]any) + return slices.Sorted(func(yield func(string) bool) { + for k := range lp { + if !yield(k) { + return + } + } + }) +} + +func (s *codexAppSim) save(t *testing.T, path string) { + t.Helper() + b, _ := json.Marshal(s.state) + if err := os.WriteFile(path, b, 0o644); err != nil { + t.Fatal(err) + } +} + +// codexStateFixture is a state file as the app leaves it signed in to a, +// with a's projects at its top level: a folder of the user's own, and a +// mirror of a's ChatGPT project, and b parked with no projects (its +// snapshot from an earlier switch, as in #5702). +func codexStateFixture(t *testing.T, home string, a []byte, b []byte) string { + t.Helper() + ida := codexIdentityOf(a) + backing := map[string]any{"accountId": ida.account, "userId": ida.user, "projectId": "g-p-1"} + state := map[string]any{ + "electron-main-window-bounds": map[string]any{"x": 10, "y": 20}, + "local-projects": map[string]any{ + "p-site": map[string]any{"id": "p-site", "name": "site", "rootPaths": []string{"/Users/me/site"}, + "retiredChatGptBacking": backing, "createdAt": 1, "updatedAt": 2}, + "g-p-1": map[string]any{"id": "g-p-1", "name": "a's ChatGPT project", "rootPaths": []string{}, + "chatGptBacking": backing, "createdAt": 1, "updatedAt": 2}, + }, + "project-order": []string{"p-site", "g-p-1"}, + "thread-project-assignments": map[string]any{"t1": "p-site", "t2": "g-p-1"}, + "remote-projects": []any{map[string]any{"id": "r1"}}, + codexRendererKey: map[string]any{ + "owner": codexRendererOwner(a), + "inactive": map[string]any{ + codexRendererOwner(b): map[string]any{"atoms": map[string]any{"x": 1}, "globals": map[string]any{"pinned-thread-ids": []string{"t9"}}}, + }, + }, + } + path := codexGlobalStatePath(home) + bs, _ := json.Marshal(state) + if err := os.WriteFile(path, bs, 0o644); err != nil { + t.Fatal(err) + } + return path +} + +// Michael25651150 on X: "切换账号 codex 添加的项目丢了 发生过好几次了". The +// Codex app keeps projects per ChatGPT identity, so magpie's switch to +// another account showed that account's empty list. With the app closed, +// magpie gives the accounts with none the projects: the app, launched and +// switched as magpie switches it, shows them on every account. +func TestCodexProjectsFollowASwitch(t *testing.T) { + home := t.TempDir() + a, b, c := codexTestAuth("user-a", "acct-a"), codexTestAuth("user-b", "acct-b"), codexTestAuth("user-c", "acct-c") + path := codexStateFixture(t, home, a, b) + + n, err := carryCodexProjects(home, [][]byte{a, b, c}) + if err != nil || n != 2 { + t.Fatalf("carried to %d (%v), want b and c", n, err) + } + for _, to := range [][]byte{b, c} { + app := codexAppLaunch(t, path) + app.signIn(a) + if got := app.projects(); !slices.Equal(got, []string{"g-p-1", "p-site"}) { + t.Fatalf("a's own projects: %v", got) + } + app.signIn(to) // magpie's switch: auth.json, the app-server's restart + if got := app.projects(); !slices.Equal(got, []string{"p-site"}) { + t.Fatalf("after the switch the app shows %v, want the user's p-site", got) + } + if got := app.state["project-order"]; !slices.Equal(anyStrings(got), []string{"p-site"}) { + t.Fatalf("project-order %v: a's ChatGPT project went along", got) + } + if got := app.state["thread-project-assignments"].(map[string]any); len(got) != 1 || got["t1"] != "p-site" { + t.Fatalf("thread-project-assignments %v", got) + } + p := app.state["local-projects"].(map[string]any)["p-site"].(map[string]any) + if _, ok := p["retiredChatGptBacking"]; ok { + t.Fatal("a's backing went to another account: the app refuses it (\"belongs to a different ChatGPT account\")") + } + if _, ok := app.state["remote-projects"]; ok { + t.Fatal("a's remote projects went along") + } + } + // b's own things stay + app := codexAppLaunch(t, path) + app.signIn(b) + if got := anyStrings(app.state["pinned-thread-ids"]); !slices.Equal(got, []string{"t9"}) { + t.Fatalf("b's pins %v", got) + } + // what magpie doesn't know is kept, and the file as it was beside it + var top map[string]any + raw, _ := os.ReadFile(path) + _ = json.Unmarshal(raw, &top) + if top["electron-main-window-bounds"] == nil { + t.Fatal("an unrelated key was lost") + } + if _, err := os.Stat(path + ".magpie-before-projects"); err != nil { + t.Fatalf("no backup: %v", err) + } + // once more: nothing to do + if n, err := carryCodexProjects(home, [][]byte{a, b, c}); n != 0 || err != nil { + t.Fatalf("carried again to %d (%v)", n, err) + } +} + +// A project the user added or removed on an account is that account's: +// an identity with a list of its own, an emptied one too, is left alone, +// and the source can be a parked identity when the owner has none. +func TestCodexProjectsOwnListKept(t *testing.T) { + home := t.TempDir() + a, b := codexTestAuth("user-a", "acct-a"), codexTestAuth("user-b", "acct-b") + path := codexStateFixture(t, home, a, b) + app := codexAppLaunch(t, path) + app.signIn(a) + app.signIn(b) + app.state["local-projects"] = map[string]any{} // b removed them all + app.save(t, path) + before, _ := os.ReadFile(path) + if n, err := carryCodexProjects(home, [][]byte{a, b}); n != 0 || err != nil { + t.Fatalf("carried to %d (%v)", n, err) + } + if after, _ := os.ReadFile(path); string(after) != string(before) { + t.Fatal("the file was written with nothing to carry") + } + // c, new, gets a's parked projects + c := codexTestAuth("user-c", "acct-c") + if n, err := carryCodexProjects(home, [][]byte{a, b, c}); n != 1 || err != nil { + t.Fatalf("carried to %d (%v), want c", n, err) + } + app = codexAppLaunch(t, path) + app.signIn(c) + if got := app.projects(); !slices.Equal(got, []string{"p-site"}) { + t.Fatalf("c shows %v", got) + } +} + +// A file magpie can't read as the app's, or one from an app before +// per-identity projects, is never written. +func TestCodexProjectsUnknownFileLeft(t *testing.T) { + a, b := codexTestAuth("user-a", "acct-a"), codexTestAuth("user-b", "acct-b") + for name, body := range map[string]string{ + "old app": `{"local-projects":{"p":{"id":"p","name":"p","rootPaths":[],"createdAt":1,"updatedAt":1}}}`, + "broken": `{"local-projects":`, + "odd shape": `{"electron-account-renderer-state-v1":{"owner":1,"inactive":[]}}`, + } { + home := t.TempDir() + path := codexGlobalStatePath(home) + if err := os.WriteFile(path, []byte(body), 0o644); err != nil { + t.Fatal(err) + } + n, _ := carryCodexProjects(home, [][]byte{a, b}) + if got, _ := os.ReadFile(path); n != 0 || string(got) != body { + t.Fatalf("%s: carried to %d, file %s", name, n, got) + } + if _, err := os.Stat(path + ".magpie-before-projects"); err == nil { + t.Fatalf("%s: a backup written", name) + } + } + if n, err := carryCodexProjects(t.TempDir(), [][]byte{a}); n != 0 || err != nil { + t.Fatalf("no file: %d %v", n, err) + } +} + +// The owner's hash is the app's: sha256 of JSON.stringify([userId, +// accountId]) (early-bootstrap-815's eaD). +func TestCodexRendererOwner(t *testing.T) { + // node -e 'console.log(require("crypto").createHash("sha256").update(JSON.stringify(["user-a","acct-a"])).digest("hex"))' + const want = "3a83b2a14d3700e107eeba3a6b5fb3a80f6b16c3c8de079ee80f8cf8b4bd15ea" + if got := codexRendererOwner(codexTestAuth("user-a", "acct-a")); got != want { + t.Fatalf("owner %q, want %q", got, want) + } + if codexRendererOwner([]byte(`{"auth_mode":"apikey"}`)) != "" { + t.Fatal("an API key has an identity") + } +} + +// The look every few seconds carries only while the app is closed: what +// the open app holds it writes over the file. +func TestCodexProjectsStepWaitsForTheAppToClose(t *testing.T) { + signIn(t) + a := codexTestAuth("user-a", "acct-a") + b := codexTestAuth("user-b", "acct-b") + if err := os.WriteFile(codexAuthPath(), b, 0o600); err != nil { + t.Fatal(err) + } + path := codexStateFixture(t, codexHome(), a, b) + oldOpen, oldEvery := CodexAppOpen, codexProjectsEvery + t.Cleanup(func() { + CodexAppOpen, codexProjectsEvery = oldOpen, oldEvery + codexProjects.Lock() + codexProjects.last, codexProjects.tried = "", time.Time{} + codexProjects.Unlock() + }) + codexProjectsEvery = 0 + open := true + CodexAppOpen = func(context.Context) (bool, bool) { return open, true } + before, _ := os.ReadFile(path) + codexProjectsStep(context.Background()) + if after, _ := os.ReadFile(path); string(after) != string(before) { + t.Fatal("written while the app is open") + } + open = false + codexProjectsStep(context.Background()) + app := codexAppLaunch(t, path) + app.signIn(b) + if got := app.projects(); !slices.Equal(got, []string{"p-site"}) { + t.Fatalf("b, signed in now, shows %v once the app closed", got) + } +} + +func anyStrings(v any) []string { + var out []string + l, _ := v.([]any) + for _, e := range l { + s, _ := e.(string) + out = append(out, s) + } + return out +}