diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index ac70e7230..6cd743bbd 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -105,7 +105,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 (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. 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 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. 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`. - 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 09502d291..1126b8a62 100644 --- a/internal/agent/agents.go +++ b/internal/agent/agents.go @@ -59,6 +59,8 @@ func init() { // reopened on Windows, where its stdout was held open provider.CodexAppOpen = codexAppOpen provider.CodexAppReopen = codexAppReopen + provider.CodexAppCrashed = codexAppCrashed + provider.CodexAppRelaunch = codexAppRelaunch // and what the Codex app holds is read while Codex takes magpie's // models beside its sign-in, Codex switched off in magpie or not // Claude Code's own sign-in is left where the user put it while its diff --git a/internal/agent/codex_app_crash.go b/internal/agent/codex_app_crash.go new file mode 100644 index 000000000..4a7727957 --- /dev/null +++ b/internal/agent/codex_app_crash.go @@ -0,0 +1,198 @@ +package agent + +import ( + "bytes" + "context" + "errors" + "io" + "os" + "path/filepath" + "slices" + "strings" + "time" +) + +// The Codex app's own logs, read for the page it shows when it can't go on +// after magpie restarted its app-server (provider.CodexAppCrashed, see +// provider/codex_app_crash.go). The app writes them as its file logger +// does in 26.1021 (file-based-logger: macOS ~/Library/Logs/, +// Windows %LOCALAPPDATA%\Codex\Logs, Linux $XDG_STATE_HOME/codex/logs, +// each with a YYYY/MM/DD folder for the UTC day a file was opened), one +// line per entry: ` [] `. +// The Store app on Windows writes the same folder under its package's +// LocalCache (seen on the Windows box). + +// codexLogEnv reads the environment for the log folders; a var for tests. +var codexLogEnv = os.Getenv + +// codexAppLogRoots are the folders the Codex app writes its logs in here. +func codexAppLogRoots() []string { + home := codexLogEnv("HOME") + if home == "" { + home, _ = os.UserHomeDir() + } + switch { + case restartOnMac: + return []string{filepath.Join(home, "Library", "Logs", desktopApps["codex"].id)} + case restartOnWindows: + local := codexLogEnv("LOCALAPPDATA") + if local == "" { + local = filepath.Join(home, "AppData", "Local") + } + return []string{ + filepath.Join(local, "Codex", "Logs"), + filepath.Join(local, "Packages", "OpenAI.Codex_2p2nqsd0c76g0", "LocalCache", "Local", "Codex", "Logs"), + } + case restartOnLinux: + state := codexLogEnv("XDG_STATE_HOME") + if state == "" { + state = filepath.Join(home, ".local", "state") + } + return []string{filepath.Join(state, "codex", "logs")} + } + return nil +} + +// codexLogDays is how many of a root's newest day folders are read: a file +// stays in the day it was opened in while the app writes on to it. +const codexLogDays = 7 + +// codexLogTail is how much of the end of a log file is read. +const codexLogTail = 512 << 10 + +// codexFatalLine is what the app's AppServerConnection logs as it shows the +// page (broadcastFatalError). +const codexFatalLine = " [AppServerConnection] fatal_error_broadcasted" + +// codexAppCrashed is provider.CodexAppCrashed: the first page the app +// logged at or after since (less a second for the clock's grain), read in +// the files written to since then. known is false when no root can be +// read; a root that isn't there is the app never having run on it. +func codexAppCrashed(since time.Time) (at time.Time, crashed, known bool) { + from := since.Add(-time.Second) + for _, root := range codexAppLogRoots() { + files, ok := codexLogFiles(root, from) + known = known || ok + for _, f := range files { + if t, ok := codexFatalIn(f, from); ok && (!crashed || t.Before(at)) { + at, crashed = t, true + } + } + } + return at, crashed, known +} + +// codexLogFiles are the .log files under root's newest day folders written +// to at or after from; ok is false when root can't be read. +func codexLogFiles(root string, from time.Time) (files []string, ok bool) { + if _, err := os.ReadDir(root); errors.Is(err, os.ErrNotExist) { + return nil, true + } else if err != nil { + return nil, false + } + var days []string + for _, y := range codexLogDirs(root) { + for _, m := range codexLogDirs(y) { + days = append(days, codexLogDirs(m)...) + } + } + slices.Sort(days) + if len(days) > codexLogDays { + days = days[len(days)-codexLogDays:] + } + for _, d := range days { + es, _ := os.ReadDir(d) + for _, e := range es { + if e.IsDir() || !strings.HasSuffix(e.Name(), ".log") { + continue + } + if info, err := e.Info(); err == nil && !info.ModTime().Before(from) { + files = append(files, filepath.Join(d, e.Name())) + } + } + } + return files, true +} + +// codexLogDirs are dir's folders named by digits alone (a year, month or +// day), in full. +func codexLogDirs(dir string) []string { + es, _ := os.ReadDir(dir) + var out []string + for _, e := range es { + if e.IsDir() && e.Name() != "" && strings.Trim(e.Name(), "0123456789") == "" { + out = append(out, filepath.Join(dir, e.Name())) + } + } + return out +} + +// codexFatalIn is the time of the first page logged in the file at path +// at or after from, read in its last codexLogTail bytes. A line the app +// is still writing (no newline yet) and the part line the tail cuts into +// are left out. +func codexFatalIn(path string, from time.Time) (time.Time, bool) { + f, err := os.Open(path) + if err != nil { + return time.Time{}, false + } + defer f.Close() + info, err := f.Stat() + if err != nil { + return time.Time{}, false + } + off := max(info.Size()-codexLogTail, 0) + b, err := io.ReadAll(io.NewSectionReader(f, off, info.Size()-off)) + if err != nil { + return time.Time{}, false + } + if off > 0 { + i := bytes.IndexByte(b, '\n') + if i < 0 { + return time.Time{}, false + } + b = b[i+1:] + } + if i := bytes.LastIndexByte(b, '\n'); i >= 0 { + b = b[:i+1] + } else { + return time.Time{}, false + } + for line := range bytes.Lines(b) { + if !bytes.Contains(line, []byte(codexFatalLine)) { + continue + } + stamp, _, _ := bytes.Cut(line, []byte(" ")) + t, err := time.Parse(time.RFC3339Nano, string(stamp)) + if err == nil && !t.Before(from) { + return t, true + } + } + return time.Time{}, false +} + +// codexAppRelaunch is provider.CodexAppRelaunch: it quits the Codex app +// and opens it again, as the Agents row's Restart does for an app: on +// macOS ChatGPT.app (com.openai.codex) asked to quit as ⌘Q does and opened +// once every process of its bundle has ended, never forced (an app still +// open then is left, and the row says to quit it); on Windows the Store +// app's windows closed, its tree ended when it stays in the tray, and +// opened again (codexAppReopen). Nothing is done for an app not running: +// it was quit meanwhile. Linux isn't reopened. +func codexAppRelaunch(ctx context.Context) error { + switch { + case restartOnWindows: + return codexAppReopen(ctx) + case restartOnMac: + c, ok := findRestartable(restartable{mac: desktopApps["codex"]}) + if !ok { + return nil + } + a, err := Find("codex") + if err != nil { + a = &Agent{ID: "codex", Name: "Codex"} + } + return reopenBundle(ctx, a, c.bundle, c.exe) + } + return errors.New("magpie reopens the Codex app on macOS and Windows only") +} diff --git a/internal/agent/codex_app_crash_test.go b/internal/agent/codex_app_crash_test.go new file mode 100644 index 000000000..0586fecdd --- /dev/null +++ b/internal/agent/codex_app_crash_test.go @@ -0,0 +1,225 @@ +package agent + +import ( + "context" + "os" + "path/filepath" + "regexp" + "runtime" + "slices" + "testing" + "time" +) + +// codexLog writes a log file of the Codex app's under root's day folder +// for day, as the app's file logger names it, modified at mod. +func codexLog(t *testing.T, root string, day time.Time, text string, mod time.Time) string { + t.Helper() + dir := filepath.Join(root, day.UTC().Format("2006"), day.UTC().Format("01"), day.UTC().Format("02")) + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + p := filepath.Join(dir, "codex-desktop-581d5b6a-a43b-4ec2-8343-17b4d18217bb-390-t0-i1-000015-0.log") + if err := os.WriteFile(p, []byte(text), 0o644); err != nil { + t.Fatal(err) + } + if err := os.Chtimes(p, mod, mod); err != nil { + t.Fatal(err) + } + return p +} + +// the lines as ChatGPT.app 26.1021 writes them (the owner's logs and the +// app's broadcastFatalError) +func exitedLine(at time.Time) string { + return at.UTC().Format("2006-01-02T15:04:05.000Z") + " error [AppServerConnection] Codex CLI process exited classifiedAsExpected=true code=0 connectionId=93 signal=null transport=stdio\n" +} + +func fatalLine(at time.Time) string { + return at.UTC().Format("2006-01-02T15:04:05.000Z") + " error [AppServerConnection] fatal_error_broadcasted initialized=true listenerCount=2 pendingRequestCount=0 transportKind=stdio\n" +} + +// The page the Codex app shows when it can't go on after magpie restarted +// its app-server (ysm119 on Discord) is read from the app's own logs: a +// complete fatal_error_broadcasted line at or after the end, in a file +// written to since, in the newest day folders (a file opened the day +// before is written on to past midnight UTC). The clean exit it logs +// first, a page from before, a line still being written and another +// app's folder are none of it. +func TestCodexAppCrashedReadsItsOwnLogs(t *testing.T) { + home := restartSandbox(t) + restartOnMac = true + root := filepath.Join(home, "Library", "Logs", "com.openai.codex") + since := time.Date(2026, 11, 5, 23, 59, 58, 0, time.UTC) + + if _, crashed, known := codexAppCrashed(since); crashed || !known { + t.Fatalf("no logs at all: crashed %v, known %v (the app never ran)", crashed, known) + } + // the end's clean exit and a page from an hour before + p := codexLog(t, root, since.Add(-2*time.Hour), fatalLine(since.Add(-time.Hour))+exitedLine(since.Add(time.Second)), since.Add(time.Second)) + if _, crashed, _ := codexAppCrashed(since); crashed { + t.Fatal("the clean exit or an old page read as the page") + } + // the page, half-written + half := fatalLine(since.Add(3 * time.Second)) + os.WriteFile(p, []byte(fatalLine(since.Add(-time.Hour))+exitedLine(since.Add(time.Second))+half[:len(half)-1]), 0o644) + os.Chtimes(p, since.Add(3*time.Second), since.Add(3*time.Second)) + if _, crashed, _ := codexAppCrashed(since); crashed { + t.Fatal("a line still being written read as the page") + } + // whole, in the file opened the day before + os.WriteFile(p, []byte(fatalLine(since.Add(-time.Hour))+exitedLine(since.Add(time.Second))+half), 0o644) + os.Chtimes(p, since.Add(3*time.Second), since.Add(3*time.Second)) + at, crashed, known := codexAppCrashed(since) + if !crashed || !known || !at.Equal(since.Add(3*time.Second)) { + t.Fatalf("the page: at %v, crashed %v, known %v", at, crashed, known) + } + // a file not written to since the end isn't read + os.Chtimes(p, since.Add(-time.Minute), since.Add(-time.Minute)) + if _, crashed, _ := codexAppCrashed(since); crashed { + t.Fatal("a file untouched since the end read") + } + // the next day's folder + codexLog(t, root, since.Add(time.Hour), exitedLine(since.Add(time.Second))+fatalLine(since.Add(4*time.Second)), since.Add(5*time.Second)) + if at, crashed, _ := codexAppCrashed(since); !crashed || !at.Equal(since.Add(4*time.Second)) { + t.Fatalf("the next day's folder: at %v, crashed %v", at, crashed) + } + + // another app's logs (the beta's bundle id) are not the Codex app's + home = restartSandbox(t) + restartOnMac = true + codexLog(t, filepath.Join(home, "Library", "Logs", "com.openai.codex.beta"), since, fatalLine(since.Add(time.Second)), since.Add(time.Second)) + if _, crashed, _ := codexAppCrashed(since); crashed { + t.Fatal("another app's page read as the Codex app's") + } + + // a log folder that can't be read is unknown + if runtime.GOOS != "windows" { + root := filepath.Join(home, "Library", "Logs", "com.openai.codex") + os.MkdirAll(root, 0o755) + os.Chmod(root, 0) + t.Cleanup(func() { os.Chmod(root, 0o755) }) + if _, err := os.ReadDir(root); err == nil { + t.Skip("running as a user who reads any folder") + } + if _, crashed, known := codexAppCrashed(since); crashed || known { + t.Fatalf("an unreadable folder: crashed %v, known %v", crashed, known) + } + } +} + +// Windows and Linux keep the logs where the app's file logger puts them +// there: %LOCALAPPDATA%\Codex\Logs, which the Store app writes under its +// package's LocalCache, and $XDG_STATE_HOME/codex/logs (~/.local/state +// without it). +func TestCodexAppCrashedReadsEachSystemsFolder(t *testing.T) { + since := time.Date(2026, 11, 5, 8, 0, 0, 0, time.UTC) + page := exitedLine(since.Add(time.Second)) + fatalLine(since.Add(2*time.Second)) + for _, tc := range []struct { + name string + set func(home string) + root func(home string) string + }{ + {"windows", func(home string) { + restartOnWindows = true + t.Setenv("LOCALAPPDATA", filepath.Join(home, "AppData", "Local")) + }, func(home string) string { return filepath.Join(home, "AppData", "Local", "Codex", "Logs") }}, + {"windows store", func(home string) { + restartOnWindows = true + t.Setenv("LOCALAPPDATA", filepath.Join(home, "AppData", "Local")) + }, func(home string) string { + return filepath.Join(home, "AppData", "Local", "Packages", "OpenAI.Codex_2p2nqsd0c76g0", "LocalCache", "Local", "Codex", "Logs") + }}, + {"linux", func(home string) { + restartOnLinux = true + t.Setenv("XDG_STATE_HOME", filepath.Join(home, "state")) + }, func(home string) string { return filepath.Join(home, "state", "codex", "logs") }}, + {"linux default", func(home string) { + restartOnLinux = true + t.Setenv("XDG_STATE_HOME", "") + }, func(home string) string { return filepath.Join(home, ".local", "state", "codex", "logs") }}, + } { + t.Run(tc.name, func(t *testing.T) { + home := restartSandbox(t) + tc.set(home) + if _, crashed, _ := codexAppCrashed(since); crashed { + t.Fatal("a page with no logs") + } + codexLog(t, tc.root(home), since, page, since.Add(3*time.Second)) + if at, crashed, known := codexAppCrashed(since); !crashed || !known || !at.Equal(since.Add(2*time.Second)) { + t.Fatalf("at %v, crashed %v, known %v", at, crashed, known) + } + }) + } +} + +// The app is reopened as the Agents row's Restart reopens an app on a Mac: +// ChatGPT.app, known by its bundle id, quit as ⌘Q does and opened once it +// has ended, never another bundle (a Codex.app of another id), and never +// forced (one still open is said). An app not open: nothing. Linux: not done. +func TestCodexAppRelaunchOnlyTheCodexApp(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("the bundle paths are built with filepath, so a Windows run spells them with \\ (#4115)") + } + home := restartSandbox(t) + apps := filepath.Join(home, "Applications") + chatgpt := macApp(t, apps, "ChatGPT.app", "com.openai.codex", "ChatGPT") + other := macApp(t, apps, "Codex.app", "com.openai.codex.beta", "Codex") + restartOnMac = true + appFolders = func() []string { return []string{apps} } + appQuitWait = 100 * time.Millisecond + alive := map[string]bool{chatgpt: true, other: true} + stays := false + running = func(pat string) []runningProc { + var out []runningProc + exe := map[string]string{chatgpt: "ChatGPT", other: "Codex"} + for b, on := range alive { + for _, cmd := range []string{ + b + "/Contents/MacOS/" + exe[b], + b + "/Contents/Resources/codex app-server --analytics-default-enabled", + } { + if on && regexp.MustCompile(pat).MatchString(cmd) { + out = append(out, runningProc{time.Hour, cmd}) + } + } + } + return out + } + var quit, opened []string + appQuit = func(_ context.Context, b string) error { + quit = append(quit, b) + if !stays { + alive[b] = false + } + return nil + } + appOpen = func(_ context.Context, b string) error { + opened = append(opened, b) + alive[b] = true + return nil + } + if err := codexAppRelaunch(context.Background()); err != nil { + t.Fatal(err) + } + if !slices.Equal(quit, []string{chatgpt}) || !slices.Equal(opened, []string{chatgpt}) || !alive[other] { + t.Fatalf("quit %q, opened %q, the other app running %v", quit, opened, alive[other]) + } + + // one that doesn't quit: said, not opened again + quit, opened, stays = nil, nil, true + if err := codexAppRelaunch(context.Background()); err == nil || len(opened) > 0 { + t.Fatalf("an app that stayed: %v, opened %q", err, opened) + } + + // not running: nothing + quit, alive[chatgpt] = nil, false + if err := codexAppRelaunch(context.Background()); err != nil || len(quit) > 0 { + t.Fatalf("not running: %v, quit %q", err, quit) + } + + restartOnMac, restartOnLinux = false, true + alive[chatgpt] = true + if err := codexAppRelaunch(context.Background()); err == nil || len(quit) > 0 { + t.Fatalf("linux: %v, quit %q", err, quit) + } +} diff --git a/internal/gui/api.go b/internal/gui/api.go index c0383bfcd..093648ad9 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -244,6 +244,9 @@ type agentJSON struct { // was its provider, which shows no account or usage till it restarts // (provider.CodexAppBack), for the row's Restart AppBack bool `json:"appBack,omitempty"` + // AppSnag: the Codex app showed its error page after magpie restarted + // its app-server and magpie couldn't reopen it (provider.CodexAppSnagged) + AppSnag bool `json:"appSnag,omitempty"` // Failover: not connected, yet its requests go through magpie for // account failover alone (agent.Agent.FailingOver, #1385) Failover bool `json:"failover,omitempty"` @@ -2772,6 +2775,9 @@ func state() stateJSON { aj.Source = a.Source() aj.Failover = a.FailingOver != nil && a.FailingOver() } + if a.ID == "codex" && a.WSL == "" { + aj.AppSnag = provider.CodexAppSnagged() + } aj.AppRestart = a.AppBehind() if a.Import != nil { aj.Import = a.Import() diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 2aa8caa40..dab933158 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -1389,6 +1389,7 @@ function connectLine(a, kind) { return line; } if (kind === "empty" && !switchable(a)) { say(t("Add a key or a subscription first; then there are models to connect")); return line; } + if (a.appSnag) { say(t("The {agent} app hit an error · quit it and open it again", { agent: a.name }), "wait"); return line; } if (!a.wired && a.native && a.native.provider !== "disconnected") { say(t(a.native.detail), "bad"); if (a.native.provider === "invalid") line.append(driftFix(a, "Reconnect")); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 8d78ade11..35fab260c 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -2149,6 +2149,7 @@ const I18N = { "{user}'s ChatGPT allowance is used up, so magpie serves {agent}'s turns until it resets.": "{user} 的 ChatGPT 额度已用完,重置前由 magpie 接管 {agent} 的对话。", "{agent}'s ChatGPT allowance is used up, so magpie serves its turns until it resets.": "{agent} 的 ChatGPT 额度已用完,重置前由 magpie 接管它的对话。", "Till then the {agent} app's ChatGPT side is off: its ChatGPT chats and projects, browser use (its Chrome control), cloud tasks, its account, its usage meter and Log out. They come back after the reset, once the app's app-server restarts: this row offers the restart then.": "在此之前,{agent} 应用的 ChatGPT 功能暂时关闭:ChatGPT 聊天和项目、浏览器操作(Chrome 控制)、云端任务、账号、用量显示和退出登录。额度重置后,等应用的 app-server 重启就会恢复;届时这一行会提供重启按钮。", + "The {agent} app hit an error · quit it and open it again": "{agent} 应用出错了 · 请退出后重新打开", "Back on ChatGPT · restart the {agent} app to see its account": "已回到 ChatGPT · 重启 {agent} 应用才能看到账号", "magpie gave {agent} back its ChatGPT account after the reset. The {agent} app still runs on the app-server it started while magpie served it, so it shows no account, no usage and none of its ChatGPT side until that restarts. Restart does it now; its window stays.": "额度重置后,magpie 已把 ChatGPT 账号还给 {agent}。但 {agent} 应用仍在用 magpie 接管期间启动的 app-server,所以在它重启前看不到账号、用量和其他 ChatGPT 功能。点“重启”即可立即重启;窗口保持不变。", "Only its app-server restarts, for its ChatGPT account; its window stays. A running turn stops.": "只重启它的 app-server,以读取 ChatGPT 账号;窗口保持不变。正在运行的回合会停止。", @@ -6766,6 +6767,7 @@ const I18N = { "{user}'s ChatGPT allowance is used up, so magpie serves {agent}'s turns until it resets.": "{user} 的 ChatGPT 額度已用完,重設前由 magpie 接管 {agent} 的對話。", "{agent}'s ChatGPT allowance is used up, so magpie serves its turns until it resets.": "{agent} 的 ChatGPT 額度已用完,重設前由 magpie 接管它的對話。", "Till then the {agent} app's ChatGPT side is off: its ChatGPT chats and projects, browser use (its Chrome control), cloud tasks, its account, its usage meter and Log out. They come back after the reset, once the app's app-server restarts: this row offers the restart then.": "在此之前,{agent} 應用的 ChatGPT 功能暫時關閉:ChatGPT 聊天和專案、瀏覽器操作(Chrome 控制)、雲端任務、帳號、用量顯示和登出。額度重設後,等應用的 app-server 重新啟動就會恢復;屆時這一行會提供重新啟動按鈕。", + "The {agent} app hit an error · quit it and open it again": "{agent} 應用程式出錯了 · 請結束後重新開啟", "Back on ChatGPT · restart the {agent} app to see its account": "已回到 ChatGPT · 重新啟動 {agent} 應用才能看到帳號", "magpie gave {agent} back its ChatGPT account after the reset. The {agent} app still runs on the app-server it started while magpie served it, so it shows no account, no usage and none of its ChatGPT side until that restarts. Restart does it now; its window stays.": "額度重設後,magpie 已把 ChatGPT 帳號還給 {agent}。但 {agent} 應用仍在使用 magpie 接管期間啟動的 app-server,所以在它重新啟動前看不到帳號、用量和其他 ChatGPT 功能。點「重啟」即可立即重新啟動;視窗保持不變。", "Only its app-server restarts, for its ChatGPT account; its window stays. A running turn stops.": "只重新啟動它的 app-server,以讀取 ChatGPT 帳號;視窗保持不變。正在執行的回合會停止。", @@ -11359,6 +11361,7 @@ const I18N = { "{user}'s ChatGPT allowance is used up, so magpie serves {agent}'s turns until it resets.": "{user} の ChatGPT の利用枠を使い切ったため、リセットまで magpie が {agent} のターンを処理します。", "{agent}'s ChatGPT allowance is used up, so magpie serves its turns until it resets.": "{agent} の ChatGPT の利用枠を使い切ったため、リセットまで magpie がそのターンを処理します。", "Till then the {agent} app's ChatGPT side is off: its ChatGPT chats and projects, browser use (its Chrome control), cloud tasks, its account, its usage meter and Log out. They come back after the reset, once the app's app-server restarts: this row offers the restart then.": "それまで {agent} アプリの ChatGPT 機能(ChatGPT のチャットとプロジェクト、ブラウザ操作(Chrome の操作)、クラウドタスク、アカウント、使用量の表示、ログアウト)はオフになります。リセット後、アプリの app-server が再起動すると戻ります。そのときこの行に再起動ボタンが出ます。", + "The {agent} app hit an error · quit it and open it again": "{agent} アプリでエラーが発生しました · 終了してもう一度開いてください", "Back on ChatGPT · restart the {agent} app to see its account": "ChatGPT に戻りました · アカウントを表示するには {agent} アプリを再起動", "magpie gave {agent} back its ChatGPT account after the reset. The {agent} app still runs on the app-server it started while magpie served it, so it shows no account, no usage and none of its ChatGPT side until that restarts. Restart does it now; its window stays.": "リセット後、magpie は {agent} に ChatGPT アカウントを戻しました。ただし {agent} アプリは magpie が代わりに応答していた間に起動した app-server のままなので、再起動するまでアカウント、使用量、その他の ChatGPT 機能は表示されません。「再起動」ですぐに再起動します。ウィンドウはそのままです。", "Only its app-server restarts, for its ChatGPT account; its window stays. A running turn stops.": "app-server だけを再起動して ChatGPT アカウントを読み込ませます。ウィンドウはそのままです。実行中のターンは止まります。", @@ -15983,6 +15986,7 @@ const I18N = { "{user}'s ChatGPT allowance is used up, so magpie serves {agent}'s turns until it resets.": "Das ChatGPT-Kontingent von {user} ist aufgebraucht, daher bedient magpie die Anfragen von {agent}, bis es zurückgesetzt wird.", "{agent}'s ChatGPT allowance is used up, so magpie serves its turns until it resets.": "Das ChatGPT-Kontingent von {agent} ist aufgebraucht, daher bedient magpie seine Anfragen, bis es zurückgesetzt wird.", "Till then the {agent} app's ChatGPT side is off: its ChatGPT chats and projects, browser use (its Chrome control), cloud tasks, its account, its usage meter and Log out. They come back after the reset, once the app's app-server restarts: this row offers the restart then.": "Bis dahin ist die ChatGPT-Seite der {agent}-App aus: ihre ChatGPT-Chats und -Projekte, Browser-Nutzung (ihre Chrome-Steuerung), Cloud-Aufgaben, ihr Konto, ihre Nutzungsanzeige und Abmelden. Nach dem Zurücksetzen kommt sie wieder, sobald der App-Server der App neu startet: Diese Zeile bietet dann den Neustart an.", + "The {agent} app hit an error · quit it and open it again": "Die {agent}-App hat einen Fehler · beende sie und öffne sie erneut", "Back on ChatGPT · restart the {agent} app to see its account": "Wieder bei ChatGPT · {agent}-App neu starten, um das Konto zu sehen", "magpie gave {agent} back its ChatGPT account after the reset. The {agent} app still runs on the app-server it started while magpie served it, so it shows no account, no usage and none of its ChatGPT side until that restarts. Restart does it now; its window stays.": "magpie hat {agent} nach dem Zurücksetzen sein ChatGPT-Konto zurückgegeben. Die {agent}-App läuft noch auf dem App-Server, den sie startete, während magpie sie bediente, und zeigt darum kein Konto, keine Nutzung und nichts von ihrer ChatGPT-Seite, bis dieser neu startet. „Neu starten“ erledigt das jetzt; das Fenster bleibt offen.", "Only its app-server restarts, for its ChatGPT account; its window stays. A running turn stops.": "Nur sein App-Server startet neu, um sein ChatGPT-Konto zu lesen; das Fenster bleibt offen. Ein laufender Turn wird angehalten.", diff --git a/internal/gui/tests/codex-app-snag.test.cjs b/internal/gui/tests/codex-app-snag.test.cjs new file mode 100644 index 000000000..2ceee832e --- /dev/null +++ b/internal/gui/tests/codex-app-snag.test.cjs @@ -0,0 +1,84 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// ysm119 on Discord (#4550): after magpie restarted the Codex app's +// app-server, a signed-in ChatGPT app showed "ChatGPT hit a snag" till it +// was quit and opened again. magpie reopens it itself when nothing runs; +// where it couldn't (Linux, an app that didn't quit), the Agents row says +// to (appSnag), over what it would say of its provider. Every language, +// both engines, wide and narrow. No backend, the API is faked. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const codex = (appSnag) => ({ + id: "codex", name: "Codex", path: "/fixture/config.toml", wired: true, + fields: [{ key: "model", label: "model", value: "gpt-6.1-sol", options: [{ value: "gpt-6.1-sol", label: "gpt-6.1-sol", ref: "gpt-6.1-sol" }] }], + appSnag, +}); + +const words = { + en: "The Codex app hit an error · quit it and open it again", + zh: "Codex 应用出错了 · 请退出后重新打开", + "zh-TW": "Codex 應用程式出錯了 · 請結束後重新開啟", + ja: "Codex アプリでエラーが発生しました · 終了してもう一度開いてください", + de: "Die Codex-App hat einen Fehler · beende sie und öffne sie erneut", +}; + +function serve(lang, snag) { + const state = { agents: [codex(snag)], profiles: [], settings: { lang, theme: "light" } }; + return async (route) => { + const url = new URL(route.request().url()); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:false};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return route.fulfill({ json: state }); + if (url.pathname === "/api/plugins") return route.fulfill({ json: { plugins: [] } }); + if (url.pathname === "/api/usage/quotas") return route.fulfill({ json: [] }); + if (url.pathname === "/api/groups") return route.fulfill({ json: { groups: [] } }); + if (url.pathname === "/api/agents/cli") return route.fulfill({ json: { agents: {}, pending: false } }); + if (url.pathname === "/api/providers") return route.fulfill({ json: { providers: [], presets: [], excluded: [], gateway: { running: true, window: true } } }); + if (url.pathname.startsWith("/api/")) return route.fulfill({ json: {} }); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + await route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +const row = '.row.agent[data-id="codex"]'; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of Object.keys(words)) { + for (const width of [980, 440]) { + test(`${engine} ${lang} ${width}px: the Codex row says to quit and reopen the app after its error page`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await browser.newPage({ viewport: { width, height: 800 } }); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, true)); + await page.goto("http://magpie.test/?view=agents"); + const st = page.locator(`${row} .ag-st-t`); + await st.waitFor(); + assert.equal((await st.textContent()).trim(), words[lang]); + assert.ok(await page.locator(`${row} .ag-st.wait, ${row} .wait .ag-st-t, ${row} .wait`).count() > 0, "said as a wait"); + const box = await st.boundingBox(); + assert.ok(box && box.x >= 0 && box.x + box.width <= width + 0.5, "the line is on the page: " + JSON.stringify(box)); + const side = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth); + assert.ok(side <= 1, "scrolls sideways: " + side); + assert.deepEqual(errors, []); + }); + } + } + test(`${engine}: without appSnag the row says nothing of it`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await browser.newPage({ viewport: { width: 980, height: 800 } }); + await page.route("**/*", serve("en", undefined)); + await page.goto("http://magpie.test/?view=agents"); + await page.locator(`${row} .ag-st-t`).waitFor(); + assert.doesNotMatch(await page.locator(`${row} .ag-st-t`).textContent(), /hit an error/); + }); +} diff --git a/internal/provider/codex_app_crash.go b/internal/provider/codex_app_crash.go new file mode 100644 index 000000000..96219d934 --- /dev/null +++ b/internal/provider/codex_app_crash.go @@ -0,0 +1,153 @@ +package provider + +import ( + "context" + "errors" + "log" + "slices" + "time" +) + +// A signed-in ChatGPT app (26.1021 and on) can't always take the +// app-server magpie ended: the one it starts in its place answers its +// handshake, and then the app's own Hosted AppServerManager finds the +// account it had cached cleared with the old connection ("Hosted +// AppServerManager identity is not ready"), logs fatal_error_broadcasted +// and shows "ChatGPT hit a snag / Please try again" over the whole window +// till it is quit and opened again (ysm119 on Discord, #4550: sljdxde, +// wang9262, Indekkusu545). That is in the app, out of magpie's reach; the +// app-server's own exit is clean (code 0, which it counts expected). +// +// So for codexAppCrashWait after magpie ends an app-server, its logs are +// read for that line (CodexAppCrashed, the agent package's: the app's own +// log folder, a line stamped after the end). When the app shows the page +// 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, +// CodexAppSnagged) until the app-servers seen then are gone. + +// CodexAppCrashed and CodexAppRelaunch are set by the agent package. +// CodexAppCrashed says whether the Codex app logged the page it shows +// when it can't go on (fatal_error_broadcasted) at or after since, and +// when; known false when its logs can't be read. CodexAppRelaunch quits +// the app and opens it again, erring where it can't. +var ( + CodexAppCrashed func(since time.Time) (at time.Time, crashed, known bool) + CodexAppRelaunch func(ctx context.Context) error + // codexAppCrashWait is how long after an end the logs are read: the + // app logs the page within seconds of the new app-server's start + codexAppCrashWait = 60 * time.Second +) + +// watchCodexAppCrash starts reading the app's logs for the page, from +// now, or carries a watch already running on to now's window. +func watchCodexAppCrash(now time.Time) { + c := &codexApp + c.Lock() + defer c.Unlock() + watchCodexAppCrashLocked(now) +} + +func watchCodexAppCrashLocked(now time.Time) { + c := &codexApp + if c.crashBy.IsZero() || c.crashSince.After(now) { + c.crashSince = now + } + c.crashBy = now.Add(codexAppCrashWait) +} + +// CodexAppSnagged is whether the Codex app showed the page it shows when +// it can't go on after magpie restarted its app-server, and magpie +// couldn't reopen it: the user quits it and opens it again. +func CodexAppSnagged() bool { + c := &codexApp + c.Lock() + defer c.Unlock() + return c.snag +} + +// codexAppCrashStep is codexAppStep's look at the app after an end: it +// reads the logs while a watch runs, reopens the app that shows the page, +// and forgets a snag once the app-servers running at it are gone. +func codexAppCrashStep(ctx context.Context, now time.Time, busy func() (int, time.Time)) { + c := &codexApp + c.Lock() + since, by, snag, snagPids := c.crashSince, c.crashBy, c.snag, slices.Clone(c.snagPids) + c.Unlock() + home := codexHome() + if snag { + if open, known := codexAppOpenNow(ctx); known && !open { + codexAppUnsnag() + return + } + lctx, cancel := context.WithTimeout(ctx, codexAppListWait) + pids, err := codexAppServersOn(lctx, home) + cancel() + // a listing that fails is unknown: the snag stays. With none + // running at it, one that starts is the app's new start + if err == nil && (len(snagPids) > 0 || len(pids) > 0) && + !slices.ContainsFunc(pids, func(p int) bool { return slices.Contains(snagPids, p) }) { + codexAppUnsnag() + } + if by.IsZero() { + return + } + } + if by.IsZero() || CodexAppCrashed == nil { + return + } + at, crashed, _ := CodexAppCrashed(since) + if !crashed { + // a page not seen in the window, or logs that can't be read, end + // the watch: an unread log never reopens the app + if !now.Before(by) { + c.Lock() + if c.crashBy.Equal(by) { + c.crashSince, c.crashBy = time.Time{}, time.Time{} + } + c.Unlock() + } + return + } + c.Lock() + c.crashSince, c.crashBy = time.Time{}, time.Time{} + c.Unlock() + // the page has no composer: a request or a turn since means the app + // came back (its Try again) and is in use, never cut short + if busy != nil { + if n, last := busy(); n > 0 || last.After(at) { + log.Printf("codex: the Codex app showed its error page after magpie restarted its app-server, and has sent since; left as it is") + return + } + } + if codexTurnRunning(home, now, at) { + log.Printf("codex: the Codex app showed its error page after magpie restarted its app-server, and a Codex turn runs since; left as it is") + return + } + lctx, cancel := context.WithTimeout(ctx, codexAppListWait) + pids, _ := codexAppServersOn(lctx, home) + cancel() + err := errNoRelaunch + if CodexAppRelaunch != nil { + err = CodexAppRelaunch(ctx) + } + if err == nil { + log.Printf("codex: the Codex app showed its error page after magpie restarted its app-server; quit it and opened it again") + return + } + log.Printf("codex: the Codex app showed its error page after magpie restarted its app-server; reopening it: %v", err) + c.Lock() + c.snag, c.snagPids = true, pids + c.Unlock() +} + +func codexAppUnsnag() { + c := &codexApp + c.Lock() + c.snag, c.snagPids = false, nil + c.Unlock() +} + +var errNoRelaunch = errors.New("magpie doesn't reopen the Codex app here") diff --git a/internal/provider/codex_app_crash_test.go b/internal/provider/codex_app_crash_test.go new file mode 100644 index 000000000..fbab88cd9 --- /dev/null +++ b/internal/provider/codex_app_crash_test.go @@ -0,0 +1,279 @@ +package provider + +import ( + "context" + "errors" + "slices" + "testing" + "time" + + "github.com/yetone/magpie/internal/proc" +) + +// crashStub has the Codex app's logs say it showed its error page at at, +// from the end on, and counts the relaunches. +type crashStub struct { + page bool + at time.Time + sinces []time.Time + relaunch int + err error + unknown bool +} + +func stubCodexCrash(t *testing.T) *crashStub { + t.Helper() + c := &crashStub{} + CodexAppCrashed = func(since time.Time) (time.Time, bool, bool) { + c.sinces = append(c.sinces, since) + if c.unknown { + return time.Time{}, false, false + } + if c.page && !c.at.Before(since) { + return c.at, true, true + } + return time.Time{}, false, true + } + CodexAppRelaunch = func(context.Context) error { + c.relaunch++ + return c.err + } + return c +} + +// ysm119 on Discord: each restart magpie made of the Codex app's +// app-server left a signed-in ChatGPT app on its "ChatGPT hit a snag" +// page, which only quitting and opening it again ends (#4550). magpie +// reads the app's logs after its end and reopens the app once, when no +// turn has started since; it does nothing when the app logged no page. +func TestCodexAppReopenedWhenItShowsItsErrorPage(t *testing.T) { + signIn(t) + s := stubCodexApp(t) + c := stubCodexCrash(t) + now := time.Now() + idle := func() (int, time.Time) { return 0, now.Add(-time.Minute) } + step := func() []int { return codexAppStep(context.Background(), now, idle) } + + s.running = []int{60} + step() + if len(c.sinces) > 0 { + t.Fatalf("the logs read with nothing ended: %v", c.sinces) + } + s.on = true + if got := step(); !slices.Equal(got, []int{60}) { + t.Fatalf("ended %v, want [60]", got) + } + ended := now + // no page: nothing done, and the watch ends with its window + now = now.Add(3 * time.Second) + step() + if c.relaunch != 0 || len(c.sinces) != 1 || !c.sinces[0].Equal(ended) { + t.Fatalf("no page: relaunched %d, logs read since %v", c.relaunch, c.sinces) + } + now = ended.Add(codexAppCrashWait) + step() + n := len(c.sinces) + now = now.Add(3 * time.Second) + step() + if len(c.sinces) != n { + t.Fatal("the logs still read after the watch's window") + } + + // the page, logged two seconds after the end: reopened once + s.on = false + ended = now + if got := step(); !slices.Equal(got, []int{100}) { + t.Fatalf("ended %v, want [100]", got) + } + c.page, c.at = true, ended.Add(2*time.Second) + now = now.Add(3 * time.Second) + step() + if c.relaunch != 1 || CodexAppSnagged() { + t.Fatalf("the error page: relaunched %d, snag %v", c.relaunch, CodexAppSnagged()) + } + now = now.Add(3 * time.Second) + step() + if c.relaunch != 1 { + t.Fatalf("relaunched %d times for one page", c.relaunch) + } +} + +// A page logged before magpie's end is none of magpie's: the app showed +// it for its own reasons, and the user has it in front of them. +func TestCodexAppErrorPageBeforeTheEndIsLeft(t *testing.T) { + signIn(t) + s := stubCodexApp(t) + c := stubCodexCrash(t) + now := time.Now() + idle := func() (int, time.Time) { return 0, now.Add(-time.Minute) } + s.running, s.on = []int{60}, true + c.page, c.at = true, now.Add(-time.Minute) + codexAppStep(context.Background(), now, idle) + now = now.Add(3 * time.Second) + codexAppStep(context.Background(), now, idle) + if c.relaunch != 0 { + t.Fatalf("relaunched %d for a page before the end", c.relaunch) + } +} + +// The app that came back by itself (its Try again) or is in use is never +// quit: a Codex turn open since the page, or a request through magpie +// since or in flight, leaves it running. +func TestCodexAppInUseAfterItsErrorPageIsLeft(t *testing.T) { + for _, tc := range []struct { + name string + turn bool + busy func(at time.Time) (int, time.Time) + }{ + {name: "turn open", turn: true}, + {name: "request in flight", busy: func(at time.Time) (int, time.Time) { return 1, at.Add(-time.Minute) }}, + {name: "request since", busy: func(at time.Time) (int, time.Time) { return 0, at.Add(time.Second) }}, + } { + t.Run(tc.name, func(t *testing.T) { + signIn(t) + s := stubCodexApp(t) + c := stubCodexCrash(t) + now := time.Now() + idle := func() (int, time.Time) { return 0, now.Add(-time.Minute) } + s.running, s.on = []int{60}, true + codexAppStep(context.Background(), now, idle) + c.page, c.at = true, now.Add(time.Second) + var since []time.Time + codexTurnRunning = func(_ string, _, from time.Time) bool { + since = append(since, from) + return tc.turn + } + busy := idle + if tc.busy != nil { + busy = func() (int, time.Time) { return tc.busy(c.at) } + } + now = now.Add(3 * time.Second) + codexAppStep(context.Background(), now, busy) + if c.relaunch != 0 { + t.Fatalf("relaunched an app in use") + } + if tc.turn && (len(since) == 0 || !since[0].Equal(c.at)) { + t.Fatalf("turns read since %v, want the page's time %v", since, c.at) + } + }) + } +} + +// Where the app can't be reopened (Linux, a quit it didn't take) the +// Agents row says to quit it and open it again, until the app-servers +// that ran at the page are gone or the app is closed. +func TestCodexAppSnagSaidTillTheAppRestarts(t *testing.T) { + signIn(t) + s := stubCodexApp(t) + c := stubCodexCrash(t) + c.err = errors.New("still open") + now := time.Now() + idle := func() (int, time.Time) { return 0, now.Add(-time.Minute) } + step := func() { codexAppStep(context.Background(), now, idle) } + s.running, s.on = []int{60}, true + step() + c.page, c.at = true, now.Add(time.Second) + now = now.Add(3 * time.Second) + step() + if c.relaunch != 1 || !CodexAppSnagged() { + t.Fatalf("relaunched %d, snag %v", c.relaunch, CodexAppSnagged()) + } + // a listing that fails is unknown: still said + s.listErr = errors.New("ps") + now = now.Add(3 * time.Second) + step() + if !CodexAppSnagged() { + t.Fatal("a failed listing cleared the snag") + } + s.listErr = nil + step() + if !CodexAppSnagged() || c.relaunch != 1 { + t.Fatalf("the same app-server running: snag %v, relaunched %d", CodexAppSnagged(), c.relaunch) + } + s.running = []int{200} // quit and opened by the user + now = now.Add(3 * time.Second) + step() + if CodexAppSnagged() { + t.Fatal("still said after the app started again") + } + + // closed: no longer said + codexApp.Lock() + codexApp.snag, codexApp.snagPids = true, []int{200} + codexApp.Unlock() + CodexAppOpen = func(context.Context) (bool, bool) { return false, true } + step() + if CodexAppSnagged() { + t.Fatal("still said with the app closed") + } +} + +// The Agents row's Restart and the switch notice's Restart end the +// app-server themselves: the logs are read after them too. +func TestCodexAppRestartsWatchForTheErrorPage(t *testing.T) { + signIn(t) + s := stubCodexApp(t) + c := stubCodexCrash(t) + oldWait, oldGone := codexAppBackWait, codexAppGoneWait + t.Cleanup(func() { codexAppBackWait, codexAppGoneWait = oldWait, oldGone }) + codexAppBackWait, codexAppGoneWait = time.Second, time.Second + s.running = []int{60} + before := time.Now() + if err := RestartSwitchedCodexApp(context.Background()); err != nil { + t.Fatal(err) + } + c.page, c.at = true, time.Now() + now := time.Now().Add(3 * time.Second) + codexAppStep(context.Background(), now, func() (int, time.Time) { return 0, before.Add(-time.Minute) }) + if c.relaunch != 1 { + t.Fatalf("the switch notice's Restart: relaunched %d", c.relaunch) + } + if len(c.sinces) == 0 || c.sinces[0].Before(before) { + t.Fatalf("logs read since %v, want from the end on", c.sinces) + } +} + +// A watch whose logs can't be read is kept to its window and never +// reopens the app. +func TestCodexAppUnreadLogsReopenNothing(t *testing.T) { + signIn(t) + s := stubCodexApp(t) + c := stubCodexCrash(t) + c.unknown = true + now := time.Now() + idle := func() (int, time.Time) { return 0, now.Add(-time.Minute) } + s.running, s.on = []int{60}, true + codexAppStep(context.Background(), now, idle) + for range 3 { + now = now.Add(codexAppCrashWait) + codexAppStep(context.Background(), now, idle) + } + if c.relaunch != 0 || CodexAppSnagged() { + t.Fatalf("unread logs: relaunched %d, snag %v", c.relaunch, CodexAppSnagged()) + } +} + +// ysm119's case: the Agents row's Restart (RestartCodexApp) ends the app's +// own app-server, and the page the app shows after it is read and the app +// reopened. +func TestCodexAppRowRestartWatchesForTheErrorPage(t *testing.T) { + signIn(t) + stubCodexApp(t) + c := stubCodexCrash(t) + const bundle = "/Applications/ChatGPT.app" + ps := []proc.Process{{PID: 2, Args: bundle + "/Contents/Resources/codex app-server --analytics-default-enabled"}} + oldList, oldEnd, oldPoll := listProcesses, endCodexAppServer, codexAppPoll + t.Cleanup(func() { listProcesses, endCodexAppServer, codexAppPoll = oldList, oldEnd, oldPoll }) + codexAppPoll = time.Millisecond + listProcesses = func(context.Context) ([]proc.Process, error) { return slices.Clone(ps), nil } + endCodexAppServer = func(pid int) error { ps[0].PID = 102; return nil } + before := time.Now() + if err := RestartCodexApp(context.Background(), bundle); err != nil { + t.Fatal(err) + } + c.page, c.at = true, time.Now() + codexAppStep(context.Background(), time.Now().Add(3*time.Second), func() (int, time.Time) { return 0, before.Add(-time.Minute) }) + if c.relaunch != 1 { + t.Fatalf("the Agents row's Restart: relaunched %d", c.relaunch) + } +} diff --git a/internal/provider/codex_app_server.go b/internal/provider/codex_app_server.go index c6d84d288..cc52be751 100644 --- a/internal/provider/codex_app_server.go +++ b/internal/provider/codex_app_server.go @@ -47,7 +47,8 @@ import ( // a new list at its next launch, or on the Agents row's Restart. // // The app-server is ended as a clean exit (proc.End): the app reads any -// other exit as a crash and shows it. +// other exit as a crash and shows it. A signed-in ChatGPT app can show its +// error page all the same; codex_app_crash.go reopens it then. // CodexAppRoute is set by the agent package: what in Codex's config the // app-server reads as it starts and magpie writes (its provider and base @@ -288,6 +289,14 @@ var codexApp struct { // were last listed back map[int]bool backAt time.Time + // crashSince, crashBy: magpie last ended the app's app-server at + // crashSince, and until crashBy its logs are read for the page the + // app shows when it can't take another (codexAppCrashStep); snag: + // the app showed that page and magpie couldn't reopen it, while the + // app-servers in snagPids (those running then) run + crashSince, crashBy time.Time + snag bool + snagPids []int } // codexAppBackEvery is how often the app-servers left on the takeover @@ -406,6 +415,7 @@ func KeepCodexAppOnItsProvider(ctx context.Context, busy func() (int, time.Time) // have opened before: its app-servers are ended too. It says which pids it // ended. func codexAppStep(ctx context.Context, now time.Time, busy func() (int, time.Time)) []int { + codexAppCrashStep(ctx, now, busy) if CodexAppRoute == nil { return nil } @@ -614,6 +624,7 @@ func codexAppStep(ctx context.Context, now time.Time, busy func() (int, time.Tim } if len(ended) > 0 { log.Printf("codex: ended the Codex app's app-server %v for the app to start another: %s", ended, c.why) + watchCodexAppCrashLocked(now) } return ended } @@ -757,6 +768,7 @@ func RestartCodexApp(ctx context.Context, bundle string) error { return err } ended = append(ended, p.PID) + watchCodexAppCrash(time.Now()) } if len(ended) == 0 { return errors.New("the Codex app's app-server isn't running") @@ -905,6 +917,7 @@ func RestartSwitchedCodexApp(ctx context.Context) error { log.Printf("codex: restarting the Codex app's app-server %d for the account switched to: %v", p, err) return ErrCodexAppNoEnd } + watchCodexAppCrash(time.Now()) } // waitFor lists the app-servers until ok holds of them, for at most limit waitFor := func(limit time.Duration, ok func([]int) bool) (bool, error) { diff --git a/internal/provider/codex_app_server_test.go b/internal/provider/codex_app_server_test.go index 2ed5f2e35..7fc6d8bdb 100644 --- a/internal/provider/codex_app_server_test.go +++ b/internal/provider/codex_app_server_test.go @@ -48,13 +48,22 @@ func stubCodexApp(t *testing.T) *codexAppStub { codexApp.seen, codexApp.route, codexApp.stale, codexApp.stuck, codexApp.switched, codexApp.auto = false, "", nil, false, false, false codexApp.ended, codexApp.backBy, codexApp.spent, codexApp.why = nil, time.Time{}, false, "" codexApp.back, codexApp.backAt = nil, time.Time{} + codexApp.crashSince, codexApp.crashBy, codexApp.snag, codexApp.snagPids = time.Time{}, time.Time{}, false, nil codexApp.Unlock() } + oldCrashed, oldRelaunch := CodexAppCrashed, CodexAppRelaunch t.Cleanup(func() { CodexAppRoute, codexAppServersOn, endCodexAppServer, codexTurnRunning = oldOn, oldList, oldEnd, oldTurn CodexAppOpen, CodexAppReopen, codexSessionsQuiet, codexRestartsApp = oldOpen, oldReopen, oldQuiet, oldRestarts + CodexAppCrashed, CodexAppRelaunch = oldCrashed, oldRelaunch reset() }) + // the app's logs as tests find them: no error page, and never reopened + CodexAppCrashed = func(time.Time) (time.Time, bool, bool) { return time.Time{}, false, true } + CodexAppRelaunch = func(context.Context) error { + t.Error("the Codex app relaunched") + return errors.New("not in this test") + } reset() // the user asked magpie to restart the app for its own changes too // (RestartApp); TestCodexAppLeftRunningForMagpiesOwnChanges is without