From 1dead5dc7b97638ded0176caca41b909cc3dfc0f Mon Sep 17 00:00:00 2001 From: yetone Date: Tue, 3 Nov 2026 16:11:35 +0800 Subject: [PATCH] provider: magpie's own Codex account switches leave the Codex app running unless Restart the app is ticked (atom0964) atom0964 on Discord (#help) has two ChatGPT Plus accounts in magpie, with Codex always signed in to the first and Only switch Codex's sign-in both off, on Smart routing. The Codex desktop app kept restarting by itself. They tried several combinations of the ticks and it still did. Why: with both off, SwitchWhenSpent signs Codex in to the next account at 98% and back to the first below 90%. Each switch was noted for the Codex app (codexAppSpentSwitch), and KeepCodexAppOnItsProvider ended its app-server once no turn ran; the ChatGPT app shows that as an error and relaunches (#4550). With Codex kept on the first account there is no switch, but the used-up takeover (magpie made Codex's provider for a used-up account and given back once it has room; f37742e14 only limits it to when another account can serve, which two accounts always can) changed Codex's route, and that ended it too. So every combination restarted the app. What changed: - Provider.RestartApp (restartApp), off by default, set by provider/restartapp (SetRestartApp, Codex only). This computer's own, like KeepLogin: Mirror keeps it and davsync's hash leaves it out. - switchLoginBy(agent, user, byMagpie): SwitchWhenSpent marks its switch magpie's own (codexApp.auto). In codexAppStep, a change that is magpie's own (its switch, the takeover in or out, the first look at an app on a used-up account) ends nothing unless RestartApp is on; it logs why and the app follows once restarted. The switch notice's Restart, the Agents row's Restart, and uninstall are unchanged. - Still restarted: a switch the user makes (Switch, the Agents row, the CLI), a Connect or Disconnect, failover written or taken out (any route change while the takeover state is unchanged), and a user's switch pending when magpie's comes. - GUI: under Codex's accounts, with more than one on (or the tick set), "Restart the Codex app when magpie switches its account", with a tip and toasts in en, zh, zh-TW, ja and de. app.js paid for it with five account-row comments cut; TestCoreScriptBudget is not raised. - docs/subsystems/agent-wiring.md says which changes restart the app. Known edge: a takeover flip in the same 3s tick as a Connect is taken as the Connect's (restarted), since the route changed by the user. Run at the pushed head (on mote, rebased on b967b1620; then rebased on 2a19043af, a Library change touching none of these files, with the core budget checked again: 160 bytes under): - gofmt -l clean; GOOS=linux (-tags nogui) and GOOS=windows go vet of provider, gui, davsync clean. - go test -count=1 -timeout 45m ./internal/provider ./internal/davsync ./internal/backup: ok. ./internal/gui: ok except TestMainWindowCorners/macOS_26_SDK, red alone on origin/main 694f4a6d6 too (#3949). ./internal/cli: ok except TestEveryRouteHasACommandOrIsNamed on GET /api/context/reply (#5026). - GUI (chromium + webkit, 1100 and 420 wide, en/zh/ja/de): restart-app (new), switch-only, claude-switch-only, keep-login, codex-accounts-via, account-arrange, i18n-keys: 110/110 and 94/94. account-arrange's webkit case went red once in a 5-file run on an aborted /api/lanes request; it passes alone on origin/main and at this head. Broken by hand: - codexAppStep's guard turned off: TestCodexAppLeftRunningForMagpiesOwnChanges and TestCodexAppFirstLookLeftRunning go red (ended [60]). - SwitchWhenSpent marking its switch as the user's: TestCodexSwitchedWhenUsedUp goes red ("magpie's own switch is counted the user's"). Not tried: a real ChatGPT desktop app on a real used-up account (the app-server end is stubbed as before); Windows, where the app is quit and reopened (CodexAppReopen runs only after an end, so leaving it running skips it too); no CLI command for the tick (switch-only has none either). --- docs/subsystems/agent-wiring.md | 2 +- internal/davsync/davsync.go | 2 +- internal/davsync/keep_login_test.go | 2 +- internal/gui/assets/app.css | 4 +- internal/gui/assets/app.js | 22 ++-- internal/gui/assets/i18n.js | 16 +++ internal/gui/core_budget_test.go | 2 +- internal/gui/providers.go | 18 ++- internal/gui/tests/restart-app.test.cjs | 120 ++++++++++++++++++++ internal/provider/backup.go | 5 +- internal/provider/codex_app_server.go | 40 +++++-- internal/provider/codex_app_server_test.go | 91 ++++++++++++++- internal/provider/codex_daemon.go | 12 +- internal/provider/codex_switch.go | 10 +- internal/provider/codex_switch_test.go | 24 ++++ internal/provider/logins.go | 9 +- internal/provider/mirror_keep_login_test.go | 7 +- internal/provider/provider.go | 12 +- internal/provider/routing.go | 32 ++++++ 19 files changed, 378 insertions(+), 52 deletions(-) create mode 100644 internal/gui/tests/restart-app.test.cjs diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index 7fbed2e6e..a1557b89a 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -99,7 +99,7 @@ something else shows up as drift. - Codex's model picker tags each of its own models by where a pick on the Agents page sends it: via magpie while routed, joined, or failing over, and direct while it is only beside its sign-in on one of magpie's models (`beside`, not joined, failover off), where such a pick takes magpie out (#940) and the GUI asks first (`TestCodexBesideOwnModelsSayDirect`). - Every other agent's own models (`ownProvider` in [`agents.go`](../../internal/agent/agents.go), the provider list read from its own auth file or config: Pi, OpenCode, Goose, Crush, Cline, Hermes, the WSL twins and the rest; omp's `ompOwnOptions`) say `Direct` with the provider's name: each is asked of that vendor on the agent's own sign-in or key, so a pick takes the agent off magpie. The picker tags them direct, lists them after magpie's, and asks before such a pick turns 「接入」 off (maxleebeta on Discord: Pi's own OpenCode Go model switched it off with nothing said; `TestOwnModelsSayTheyGoDirect`, `agent-own-direct.test.cjs`). - A line magpie writes into an agent's TOML, YAML or dotenv config gets a comment line of its own just above it, `# magpie: ; ` (`edit.Mark`, set to `agent.lineNote` by the CLI's `run` in [`mark.go`](../../internal/agent/mark.go); the edit side in [`internal/edit/mark.go`](../../internal/edit/mark.go)). Jevik_AI on X deleted magpie's folders by hand, and Codex's `config.toml` kept `openai_base_url` on the gateway with nothing in it naming magpie: every turn was a 502. Only a one-line scalar that points at the gateway or names magpie's model list gets one, and only when the write adds or changes that line, or it had a note already; a line of the user's own that magpie leaves as it is gets none. The note is never on the value's line: Grok App's `providers.rs` reads the rest of a line as the value. Every write takes the notes out first and puts them back over the lines that still need one, so a note goes with its line and a Disconnect leaves none. A YAML note that would change what the file reads as isn't added (`sameYAMLValue`). JSON has no comments and gets none. Tests set no `Mark`, so their exact bytes stay; `TestMarkedLinesEveryAgent` connects every agent with notes on and checks each gateway line has one, a second sync writes nothing, and Disconnect leaves none; `TestCodexMarkedLines`, `internal/edit`'s `TestMark*`. -- Codex signed in to ChatGPT stays beside its sign-in (`openai_base_url`) unless the user picks magpie API. magpie becomes its provider only while the Codex app holds the active account, which it sends nothing for: `/wham/usage` says it isn't allowed, and it has no credits and isn't a workspace still within its overage (`codexHeld`, read by `provider.CodexUsedUp`). With Codex switched off or removed in magpie (`leftAlone`), whose allowance magpie otherwise reads nothing of, the active account is still read for this alone while Codex takes magpie's models beside its sign-in or magpie is its provider for the held account (`Agent.HoldMatters`, through the `provider.CodexHoldMatters` hook; `codexHoldReading`): once a minute at most, with the token as Codex keeps it, never renewed or written (`codexTokenAsKept`), and nothing shown on the Usage page. Before, turning Codex off in magpie after its allowance ran out left the Codex app greying Send for magpie's models through restarts, and one already moved was put back on the held account (sherlock_23333 on X; `TestCodexHoldReadLeftAlone`, `TestCodexHoldMatters`). Where the app goes by what usage can't show (an experiment's gate, a reserve, a Team plan's overage under the reserve experiment), it counts as held: a wrong move costs ChatGPT extras, a missed one every turn. A saved reading kept through a failed read stops saying held once its used-up window has started again; a hold with no window used up stays till a fresh read. The app then loses its ChatGPT state (durable threads, remote control), so a window at 100% alone, which credits get past, doesn't move it (`codex.out` marks the move, and Sync undoes it once the account has room). The same holds on one of Codex's own models joined beside the sign-in (MasterYi on Discord: the Codex app greyed Send for every model on a used-up account): Sync makes magpie the provider on that model as magpie serves it (`codexOwnViaMagpie`, `codex/`), keeps the model picked in `codex.out_own`, and once the account has room puts Codex back joined on it; a model the user picked meanwhile stays theirs. With no ChatGPT account in magpie to serve it, Codex is left as it is (`TestCodexOwnModelGoesThroughMagpieWhileUsedUp`, `TestCodexOwnModelKeptOnChatGPT`). Nor does it move when magpie would serve that model on the same used-up account alone: no fallback on the Codex subscription and no other ChatGPT account not known out (`provider.CodexServesWhileOut`). Every turn would be refused there too, and the move only hid the account, its usage and its reset from the app's menu (down to "magpie") and ended the app's app-server at the limit and again at the reset, which the ChatGPT app shows as an error and relaunches (#4550; xiaoq6285 on Discord, one Plus account in the Windows app; `TestCodexOwnModelOneSpentAccountStaysOnItsSignIn`, `TestCodexServesWhileOut`). The account is read again at once when a reply says it may be out (a `usage_limit_reached` rest, or an `x-codex-*` window heard at 100%; `provider.CodexMayBeUsedUp`, at most every 20s, the active account only), not only on the five-minute look. A turn relayed to Codex's own sign-in, the one account on (`codexUpstreamOn` with no account, the gateway's `codexRelayedAccount`), is heard the same way: its `x-codex-*` windows and `codex.rate_limits` event kept as the sign-in's usage (`heardCodexLimits`), and a `usage_limit_reached` refusal reading it again. Before, only turns served through magpie's accounts were, so with one account magpie learned the account was out only at the next look, minutes on, and the Codex app kept Send greyed until it was restarted (unsplashz on Discord; `TestCodexUsedUpRelayedAsksAtOnce`, `TestCodexRelayedWindowsHeard`). A Codex started before magpie became its provider keeps sending its own model's turns to its built-in provider; while the sign-in is known out (`provider.CodexUsedUpKnown`) and the request signs as it, those go through routing as `codex/` (`codexAccounts`), as a restarted Codex's do (`TestCodexHeldSignInServedWithoutRestart`). The Codex app greys Send for every model, magpie's too, while its `authMethod` is `chatgpt` and its rate limit says not allowed (its composer's gate in ChatGPT.app 26.1013), and reads `authMethod` from its app-server's `account/read` only as the app-server starts; with magpie the provider (`requires_openai_auth` false) that answers no account, so the gate lifts. So the gateway process restarts the app's own app-server each time magpie becomes Codex's provider for the used-up account (`Agent.AppOut`) and again when Codex is put back on the account after its reset, and likewise whenever what the app-server reads as it starts and magpie writes changes, which is where its requests go (`model_provider`, `openai_base_url` and the magpie table's `base_url`, and its `requires_openai_auth` while that table is Codex's `model_provider`: beside the sign-in the app-server reads the built-in provider's account, so the key following the account out and back is nothing it reads; `codexAppRoute`, through the `provider.CodexAppRoute` hook): a Disconnect, a Connect, failover written or taken out. The model list is not part of it: neither `model_catalog_json` nor what the catalog holds. The catalog follows magpie's names and the effort new sessions start at, which the Codex app saves on each pick, and the ChatGPT app takes an ended app-server as a crash and relaunches, so a route that hashed the catalog (from lucis0116 on X until #4550) ended the app every few minutes (indekkusu141209 on X). A new list is read at the app's next launch or on the Agents row's Restart (`StaleCopies`) A list that drops a model and has it back at the next fetch, the same list in another order, and a catalog read half-written leave the route as it was (`TestCodexEffortPickKeepsTheAppRunning`, `TestCodexAppRouteIgnoresARename`, `TestCodexAppRouteKeepsThroughListFlaps`). Before this an app-server started while Codex was connected kept sending to the gateway after Disconnect until the app was restarted (JiangLiuer222 on X). At the watcher's first look only a used-up account's app-servers are ended, since what the others read before magpie started isn't known. It runs on every system (`KeepCodexAppOnItsProvider`, every 3s; Ethereal499 and Isdavexxx on X, MasterYi on Discord, #540: the earlier once-only reopen ran on macOS from the GUI process only, so Windows, Linux, a GUI-less magpie and the switch back stayed greyed). It ends only app-servers on magpie's Codex home (`codexAppHomeIs`: the process's `CODEX_HOME`, else `HOME/.codex`, read by `proc.EnvOf`; Windows can't tell and counts every one), only once no Codex request is in flight through the gateway nor ended in the last 10s (`Server.CodexBusy`) and no session under the Codex home has a turn started and not ended (`codexTurnOpen`), and with a clean exit (`proc.End`: SIGTERM, `TerminateProcess` with code 0), since the app shows any other exit as a crash. Each end is logged with what made the app-server stale: the account switched, the route changed, or the used-up takeover (`codex: ended the Codex app's app-server [pid] for the app to start another: `), so a crash a user reports can be put down to one of them (#4550, `TestCodexAppEndSaysWhy`). The app starts another app-server at once and keeps its window, threads and drafts (tried in the real app in a sandbox `CODEX_HOME`, both ways). An app-server that outlives three ends, or may not be ended, leaves the row saying to quit and reopen the app (`CodexAppStuck`). An ended app-server's pid gone doesn't mean the app has another: the Windows app (MSIX `OpenAI.Codex`, stdio) starts one only once the old one's stdout closes, and a child it left (an MCP server, a tool command) holds that pipe open, so the app answered "Codex app-server process is not available" until it was restarted (蛋仔 on Discord). The watcher waits `codexAppBackWait` (30s) for another app-server; when none came and the app is still open (`CodexAppOpen`), it quits and opens the app as the Agents row's Restart does (`CodexAppReopen`, Windows only), else the row says to (`CodexAppStuck`). `RestartCodexApp`, uninstall's `RestartCodexAppWhenIdle` and the switch notice's Restart (`RestartSwitchedCodexApp`) wait for it the same way and reopen or say so alike, and `recheckLeft` keeps the record while the app is open with no app-server. A turn left open in Codex's sessions holds the restart for up to `codexTurnWindow` (30m), except where the app-server is on a used-up account: after a switch off one (`SwitchWhenSpent` → `codexAppSpentSwitch`, or a switch by hand off an account last read held, `codexHeldKnown` in `noteCodexSwitch`) and when magpie becomes Codex's provider for one (`codexAppStep`'s `into`; xiaoq6285 on Discord: quota out, then another account or provider picked, and Send stayed grey; `TestCodexAppServerRestartedPastATurnStuckWhenMagpieTakesOver`, `TestCodexHandSwitchOffAHeldAccountIsSpent`). There a turn that has written no session file and sent nothing through magpie for `codexTurnStuckAfter` (2m) counts stuck and the app-server is restarted past it, since its next request would be refused on that account (蛋仔 on Discord: quota ran out mid-task and the app hung till restarted; `TestCodexAppServerRestartedPastATurnStuckOnTheSpentAccount`). An account switch restarts nothing, and neither the app nor the background daemon is said to be left on the old account (`CodexAppStale`, `CodexDaemonStale`, the CLI's switch line), while the provider Codex's config.toml names takes no ChatGPT account (`provider.CodexNoAccount`, `codexNoAccount` in [`agents.go`](../../internal/agent/agents.go)): a top-level `model_provider` other than `openai` whose `[model_providers]` table doesn't say `requires_openai_auth = true`, such as magpie's with the user's own `false` (danzi002 on Discord). Codex then sends the table's key and its app-server reads no account (codex-rs `account_state`, `resolve_provider_auth`); tried with codex-cli 0.165.0 in a sandbox `CODEX_HOME`: `account/read` and `getAuthStatus` said no account before and after auth.json was switched, and `codex exec` sent `Bearer` the table's key on both accounts. A route change still restarts it, and so does a switch under a profile, the built-in provider, a provider with no table or a config that can't be read (`TestCodexNoAccountSwitchRestartsNothing`, `TestCodexNoAccountOfEachConfig`, `TestCodexNoAccountFollowsRequiresOpenAIAuth`). Until the reset the app's ChatGPT side is off (cloud tasks, its usage meter, Log out); the Agents row says so with the reset's time (`appOut` in `/api/state`, `CodexOutUntil`), and it all comes back at the reset. While the active account is held or a window is at 90% or more, its usage is read every minute rather than every five (`codexLookEvery`). `TestCodexAppServerRestartedEachWay`, `TestCodexAppServerRestartedOnDisconnect`, `TestCodexAppRouteFollowsConnectAndDisconnect`, `TestCodexEffortPickKeepsTheAppRunning`, `TestCodexAppRouteIgnoresARename`, `TestCodexAppServerUnknown`, `TestCodexAppServerStuck`, `TestCodexAppServersOnHome`, `TestCodexTurnOpen`, `TestCodexBusy`, `codex-app-out.test.cjs`. +- Codex signed in to ChatGPT stays beside its sign-in (`openai_base_url`) unless the user picks magpie API. magpie becomes its provider only while the Codex app holds the active account, which it sends nothing for: `/wham/usage` says it isn't allowed, and it has no credits and isn't a workspace still within its overage (`codexHeld`, read by `provider.CodexUsedUp`). With Codex switched off or removed in magpie (`leftAlone`), whose allowance magpie otherwise reads nothing of, the active account is still read for this alone while Codex takes magpie's models beside its sign-in or magpie is its provider for the held account (`Agent.HoldMatters`, through the `provider.CodexHoldMatters` hook; `codexHoldReading`): once a minute at most, with the token as Codex keeps it, never renewed or written (`codexTokenAsKept`), and nothing shown on the Usage page. Before, turning Codex off in magpie after its allowance ran out left the Codex app greying Send for magpie's models through restarts, and one already moved was put back on the held account (sherlock_23333 on X; `TestCodexHoldReadLeftAlone`, `TestCodexHoldMatters`). Where the app goes by what usage can't show (an experiment's gate, a reserve, a Team plan's overage under the reserve experiment), it counts as held: a wrong move costs ChatGPT extras, a missed one every turn. A saved reading kept through a failed read stops saying held once its used-up window has started again; a hold with no window used up stays till a fresh read. The app then loses its ChatGPT state (durable threads, remote control), so a window at 100% alone, which credits get past, doesn't move it (`codex.out` marks the move, and Sync undoes it once the account has room). The same holds on one of Codex's own models joined beside the sign-in (MasterYi on Discord: the Codex app greyed Send for every model on a used-up account): Sync makes magpie the provider on that model as magpie serves it (`codexOwnViaMagpie`, `codex/`), keeps the model picked in `codex.out_own`, and once the account has room puts Codex back joined on it; a model the user picked meanwhile stays theirs. With no ChatGPT account in magpie to serve it, Codex is left as it is (`TestCodexOwnModelGoesThroughMagpieWhileUsedUp`, `TestCodexOwnModelKeptOnChatGPT`). Nor does it move when magpie would serve that model on the same used-up account alone: no fallback on the Codex subscription and no other ChatGPT account not known out (`provider.CodexServesWhileOut`). Every turn would be refused there too, and the move only hid the account, its usage and its reset from the app's menu (down to "magpie") and ended the app's app-server at the limit and again at the reset, which the ChatGPT app shows as an error and relaunches (#4550; xiaoq6285 on Discord, one Plus account in the Windows app; `TestCodexOwnModelOneSpentAccountStaysOnItsSignIn`, `TestCodexServesWhileOut`). The account is read again at once when a reply says it may be out (a `usage_limit_reached` rest, or an `x-codex-*` window heard at 100%; `provider.CodexMayBeUsedUp`, at most every 20s, the active account only), not only on the five-minute look. A turn relayed to Codex's own sign-in, the one account on (`codexUpstreamOn` with no account, the gateway's `codexRelayedAccount`), is heard the same way: its `x-codex-*` windows and `codex.rate_limits` event kept as the sign-in's usage (`heardCodexLimits`), and a `usage_limit_reached` refusal reading it again. Before, only turns served through magpie's accounts were, so with one account magpie learned the account was out only at the next look, minutes on, and the Codex app kept Send greyed until it was restarted (unsplashz on Discord; `TestCodexUsedUpRelayedAsksAtOnce`, `TestCodexRelayedWindowsHeard`). A Codex started before magpie became its provider keeps sending its own model's turns to its built-in provider; while the sign-in is known out (`provider.CodexUsedUpKnown`) and the request signs as it, those go through routing as `codex/` (`codexAccounts`), as a restarted Codex's do (`TestCodexHeldSignInServedWithoutRestart`). The Codex app greys Send for every model, magpie's too, while its `authMethod` is `chatgpt` and its rate limit says not allowed (its composer's gate in ChatGPT.app 26.1013), and reads `authMethod` from its app-server's `account/read` only as the app-server starts; with magpie the provider (`requires_openai_auth` false) that answers no account, so the gate lifts. So the gateway process restarts the app's own app-server each time magpie becomes Codex's provider for the used-up account (`Agent.AppOut`) and again when Codex is put back on the account after its reset, and likewise whenever what the app-server reads as it starts and magpie writes changes, which is where its requests go (`model_provider`, `openai_base_url` and the magpie table's `base_url`, and its `requires_openai_auth` while that table is Codex's `model_provider`: beside the sign-in the app-server reads the built-in provider's account, so the key following the account out and back is nothing it reads; `codexAppRoute`, through the `provider.CodexAppRoute` hook): a Disconnect, a Connect, failover written or taken out. The model list is not part of it: neither `model_catalog_json` nor what the catalog holds. The catalog follows magpie's names and the effort new sessions start at, which the Codex app saves on each pick, and the ChatGPT app takes an ended app-server as a crash and relaunches, so a route that hashed the catalog (from lucis0116 on X until #4550) ended the app every few minutes (indekkusu141209 on X). A new list is read at the app's next launch or on the Agents row's Restart (`StaleCopies`) A list that drops a model and has it back at the next fetch, the same list in another order, and a catalog read half-written leave the route as it was (`TestCodexEffortPickKeepsTheAppRunning`, `TestCodexAppRouteIgnoresARename`, `TestCodexAppRouteKeepsThroughListFlaps`). Before this an app-server started while Codex was connected kept sending to the gateway after Disconnect until the app was restarted (JiangLiuer222 on X). At the watcher's first look only a used-up account's app-servers are ended, since what the others read before magpie started isn't known. What magpie changes by itself waits for the user, though, unless they ticked Restart the Codex app when magpie switches its account (`Provider.RestartApp`, `provider/restartapp`, off by default, this computer's own like KeepLogin): the used-up takeover in and out, the first look, and its own account switches (`SwitchWhenSpent` → `switchLoginBy(…, true)`, `codexApp.auto`). 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. atom0964 on Discord had both sign-in ticks off and the ChatGPT app relaunched at every switch between two Plus accounts (`TestCodexAppLeftRunningForMagpiesOwnChanges`, `TestCodexAppFirstLookLeftRunning`, `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`. - 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/davsync/davsync.go b/internal/davsync/davsync.go index d9c59ba9d..01641289b 100644 --- a/internal/davsync/davsync.go +++ b/internal/davsync/davsync.go @@ -829,7 +829,7 @@ func hashes(b backup.Bundle) map[string]string { } ps := slices.Clone(b.Providers) for i := range ps { // this computer's own: kept by Mirror, never synced - ps[i].KeepLogin, ps[i].KeepLoginAs, ps[i].SwitchOnly = false, "", false + ps[i].KeepLogin, ps[i].KeepLoginAs, ps[i].SwitchOnly, ps[i].RestartApp = false, "", false, false } providers := []any{ps, b.Icons, b.Groups} if b.Searches != nil && len(*b.Searches) > 0 { // as before them, without one diff --git a/internal/davsync/keep_login_test.go b/internal/davsync/keep_login_test.go index 09b3a0e93..7ce56ace5 100644 --- a/internal/davsync/keep_login_test.go +++ b/internal/davsync/keep_login_test.go @@ -13,7 +13,7 @@ import ( func TestKeepLoginIsNoChange(t *testing.T) { p := provider.Provider{ID: "codex", Name: "Codex"} home := backup.Bundle{Providers: []provider.Provider{p}} - p.KeepLogin, p.KeepLoginAs, p.SwitchOnly = true, "work@example.com", true + p.KeepLogin, p.KeepLoginAs, p.SwitchOnly, p.RestartApp = true, "work@example.com", true, true office := backup.Bundle{Providers: []provider.Provider{p}} if hashes(home)["providers"] != hashes(office)["providers"] { t.Fatal("the account kept signed in changed the providers hash") diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index edc7afa58..93116fc5d 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -2728,8 +2728,8 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; } .acc + .acc, .accts .signing { border-top: 1px solid var(--line-2); } /* every row of the box ruled off from the one above it, a setting's too (the owner, 10-29: Add another sat unruled under Only switch) */ -.accts > :is(.keep-login, .switch-only, .pool-ends) + .acc { border-top: 1px solid var(--line-2); } -.editor .accts .keep-login, .editor .accts .switch-only, .editor .accts .pool-ends { display: flex; align-items: center; flex-wrap: wrap; gap: 6px; min-height: 34px; padding: 6px 11px; font-size: 12px; border-top: 1px solid var(--line-2); } +.accts > :is(.keep-login, .switch-only, .restart-app, .pool-ends) + .acc { border-top: 1px solid var(--line-2); } +.editor .accts .keep-login, .editor .accts .switch-only, .editor .accts .restart-app, .editor .accts .pool-ends { display: flex; align-items: center; flex-wrap: wrap; gap: 6px; min-height: 34px; padding: 6px 11px; font-size: 12px; border-top: 1px solid var(--line-2); } .editor .accts .keep-login .keep-as { max-width: 240px; } /* Claude Code's interactive mode or -p, with why (claudeModeRow) */ .claude-mode { display: contents; } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index d64665d58..0aed50b31 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -13064,9 +13064,7 @@ function renderAccounts(a, p) { const list = el("div", "accts"); const ls = loginsInOrder(a, p); if (p) list.dataset.provider = p.id, list.classList.toggle("weighted", (draft?.routing ?? (p.routing || "")) === "weight"); - // a Claude account whose sign-in Anthropic refused, or that has none, - // can't be used till it is signed in again; another subscription's lapse - // shows on its quota line only, as before + // a Claude account refused or with no sign-in waits to sign in again const unusable = (l) => a.agent === "claude" && !!l.lapsed; // one whose sign-in its vendor refused (a plugin's, #1363; Copilot's // revoked token; #1793's token_revoked) keeps Sign in again and Remove @@ -13185,10 +13183,7 @@ function renderAccounts(a, p) { out.onclick = () => askSignOutLogin(a, l); line.append(out); } else if (a.agent === "codex" || a.agent === "claude" && ls.some((o) => o !== l && !o.token)) { - // the agent is signed in to another of its accounts first, then - // this one goes (ForgetLogin), rather than Codex signed out or the - // removal refused (#4532); Claude Code's only one it can be signed - // in to has no Remove: magpie never signs it out + // switched to another first, then removed (ForgetLogin, #4532) line.append(forgetOf(t("{agent} is signed in to another of its accounts, and magpie forgets this one; the account itself is untouched", { agent: a.agentName }))); } } else { @@ -13239,15 +13234,11 @@ function renderAccounts(a, p) { if (amBox) row.append(amBox); list.append(row); } - // magpie signs Codex or Claude Code in to the next account when the - // first runs low (#209, #408); this keeps it on the first instead, or on - // an account of the user's choosing, the gateway still spreading requests - // over the ticked ones in their order (#524) + // one account (#209, #408, #524) if ((a.agent === "codex" || a.agent === "claude") && several && p && !p.switchOnly) { const box = el("div", "keep-login"); const [keep, cb] = tick(t("Keep {agent} signed in to", { agent: a.agentName }), !!p.keepLogin); keep.title = t("magpie won't sign {agent} in to another account when the first runs low; requests through magpie still go to the other ticked accounts as Routing says", { agent: a.agentName }); - // the app's own menu, as every other pick in it, not a native select let keepAs = kept; const opts = [{ v: "", name: t("the first account"), note: "", literalName: true }]; for (const l of ls) if (!l.lapsed) opts.push({ v: l.user, name: l.user, note: "", literalName: true }); @@ -13265,7 +13256,6 @@ function renderAccounts(a, p) { : keepAs ? t("{agent} stays signed in to {user}", { agent: a.agentName, user: keepAs }) : t("{agent} stays signed in to the first account", { agent: a.agentName })); }; cb.onchange = () => post(cb.checked); - // picking one keeps it so, ticked or not as.onclick = (e) => { e.stopPropagation(); if (as.classList.contains("open")) return closeProtoMenu(); @@ -13291,6 +13281,12 @@ function renderAccounts(a, p) { cb.onchange = () => accountAction("provider/switchonly", { id: p.id, switchOnly: cb.checked }, cb.checked ? on : off); list.append(el("div", "switch-only", only)); } + if (p && cx && (several || p.restartApp)) { + const [re, cb] = tick(t("Restart the {agent} app when magpie switches its account", ag), !!p.restartApp); + re.title = t("Off, the {agent} app stays on its account until you restart it.", ag); + cb.onchange = () => accountAction("provider/restartapp", { id: p.id, restartApp: cb.checked }, t(cb.checked ? "magpie restarts the {agent} app when it switches accounts" : "magpie leaves the {agent} app running when it switches accounts", ag)); + list.append(el("div", "restart-app", re)); + } // how a pool ends at its caps (plugins#349) const capped = (l) => accountCapOf(p, l.user) || windowCapsOf(p, l.user); if (p && (ls.some(capped) || p.capStop || p.capCareful)) { diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index ebe7b60f3..f0d0fa620 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -1808,6 +1808,10 @@ const I18N = { "Keep {agent} signed in to the first account": "{agent} 始终登录首选账号", "Keep {agent} signed in to": "{agent} 始终登录", "Only switch {agent}'s sign-in": "只切换 {agent} 的登录", + "Restart the {agent} app when magpie switches its account": "magpie 切换账号时自动重启 {agent} 应用", + "Off, the {agent} app stays on its account until you restart it.": "关闭时,{agent} 应用会停留在原来的账号上,直到你重启它。", + "magpie restarts the {agent} app when it switches accounts": "magpie 切换账号时会重启 {agent} 应用", + "magpie leaves the {agent} app running when it switches accounts": "magpie 切换账号时不再重启 {agent} 应用", "Switch accounts only": "仅切换账号", "Switch accounts only: {agent} is signed in as {user}. Pick another of its accounts to sign {agent} in to it, without connecting it to magpie.": "仅切换账号:{agent} 当前登录的是 {user}。选另一个账号,即可把 {agent} 切换过去,无需接入 magpie。", "Not signed in": "未登录", @@ -6324,6 +6328,10 @@ const I18N = { "Keep {agent} signed in to the first account": "{agent} 始終登入首選帳號", "Keep {agent} signed in to": "{agent} 始終登入", "Only switch {agent}'s sign-in": "只切換 {agent} 的登入", + "Restart the {agent} app when magpie switches its account": "magpie 切換帳號時自動重新啟動 {agent} 應用程式", + "Off, the {agent} app stays on its account until you restart it.": "關閉時,{agent} 應用程式會停留在原來的帳號上,直到你重新啟動它。", + "magpie restarts the {agent} app when it switches accounts": "magpie 切換帳號時會重新啟動 {agent} 應用程式", + "magpie leaves the {agent} app running when it switches accounts": "magpie 切換帳號時不再重新啟動 {agent} 應用程式", "Switch accounts only": "僅切換帳號", "Switch accounts only: {agent} is signed in as {user}. Pick another of its accounts to sign {agent} in to it, without connecting it to magpie.": "僅切換帳號:{agent} 目前登入的是 {user}。選另一個帳號,即可把 {agent} 切換過去,無需接入 magpie。", "Not signed in": "未登入", @@ -10816,6 +10824,10 @@ const I18N = { "Keep {agent} signed in to the first account": "{agent} を最初のアカウントにサインインしたままにする", "Keep {agent} signed in to": "{agent} のサインイン先を固定:", "Only switch {agent}'s sign-in": "{agent} のサインインだけを切り替える", + "Restart the {agent} app when magpie switches its account": "magpie がアカウントを切り替えたら {agent} アプリを再起動する", + "Off, the {agent} app stays on its account until you restart it.": "オフのとき、{agent} アプリは再起動するまで元のアカウントのままです。", + "magpie restarts the {agent} app when it switches accounts": "magpie はアカウントを切り替えると {agent} アプリを再起動します", + "magpie leaves the {agent} app running when it switches accounts": "magpie はアカウントを切り替えても {agent} アプリを再起動しません", "Switch accounts only": "アカウント切り替えのみ", "Switch accounts only: {agent} is signed in as {user}. Pick another of its accounts to sign {agent} in to it, without connecting it to magpie.": "アカウント切り替えのみ:{agent} は {user} としてサインイン中です。別のアカウントを選ぶと、{agent} を magpie に接続せずにそのアカウントへ切り替えます。", "Not signed in": "未サインイン", @@ -15339,6 +15351,10 @@ const I18N = { "Keep {agent} signed in to the first account": "{agent} beim ersten Konto angemeldet lassen", "Keep {agent} signed in to": "{agent} angemeldet lassen bei", "Only switch {agent}'s sign-in": "Nur die Anmeldung von {agent} wechseln", + "Restart the {agent} app when magpie switches its account": "{agent}-App neu starten, wenn magpie das Konto wechselt", + "Off, the {agent} app stays on its account until you restart it.": "Aus bleibt die {agent}-App beim bisherigen Konto, bis du sie neu startest.", + "magpie restarts the {agent} app when it switches accounts": "magpie startet die {agent}-App neu, wenn es das Konto wechselt", + "magpie leaves the {agent} app running when it switches accounts": "magpie lässt die {agent}-App laufen, wenn es das Konto wechselt", "Switch accounts only": "Nur Konten wechseln", "Switch accounts only: {agent} is signed in as {user}. Pick another of its accounts to sign {agent} in to it, without connecting it to magpie.": "Nur Konten wechseln: {agent} ist als {user} angemeldet. Wähle ein anderes seiner Konten, um {agent} dort anzumelden, ohne es mit magpie zu verbinden.", "Not signed in": "Nicht angemeldet", diff --git a/internal/gui/core_budget_test.go b/internal/gui/core_budget_test.go index d85de2a93..24d8e55fe 100644 --- a/internal/gui/core_budget_test.go +++ b/internal/gui/core_budget_test.go @@ -16,7 +16,7 @@ import ( // raises them and says why in its commit. const ( appScriptBudget = 1_316_874 // app.js: 1,198,239 after Usage left (P2); 1,218,098 with the 10-15 fixes to pages still in the core; 1,232,466 with the provider editor's Advanced fold and every dialog holding its place, the core's own (10-16); 1,250,533 with the quota refresh kept through redraws, the core's own since the tray panel draws it too, plus 1.5% (#2397); 1,269,083 with Free first's option in the provider editor's ROUTINGS, which the Routing page reads too, plus 1.5%; 1,272,726 with the Providers page drawing its last list at once (#1519), the core's page, and the Routing trace's account names read without Object.entries (#1481), plus 1.5%; a dialog growing out of the row that opened it and folding back into it, the core's own since every page's dialogs open through it (10-20); Codex's and Claude Code's own settings moved from Settings into the agent's row on the Agents page, the core's own since the tray panel and the window both draw them (10-20); 1,314,432 with Settings › Privacy's record of what was masked (its summary, the records view and the local model's controls), which belongs to Settings, the core's own, plus 1.5%; 1,336,481 with a provider's Names & levels saying Provider in model names is Settings' and opening it there (joe), and Settings' Image recognition saying where a custom provider's model is marked (nexnull), both in the core's own pages, with no room added (10-23); 1,337,633 with Settings › Models › Replies' Intent classifier timeout (#2934, reyoung), Settings' own row, drawn by waitRow, which the Image generation timeout's row now shares, with no room added; 1,337,735 with the provider editor's link naming a partner's page by its own host (siteHost) instead of usemagpie.ai's /go link, the core's own editor, with no room added (10-23); 1,338,084 with Check in now saying what the press came to (claimed +credits, already today, not available yet) where it said "refreshed" (#3326), the check-in row the tray panel draws too, the core's own, with no room added (10-23); 1,338,929 with a new partner's tile keeping a small dot until it is opened, in the add sheet, the core's own, with no room added (10-23); 1,343,324 with the sidebar's open-page row marked by one shape that moves on a spring (navTopGo), the window's own shell, which every page sits beside, with no room added (10-23); 1,343,465 with a dialog kept centred while its content comes in, until it is pressed (holdModal, every page's dialogs), the core's own, with no room added (10-24); 1,317,486 with what masking did moved out to Insights › Masking (plugins/redact), the budget lowered to it (10-24); 1,321,336 with Codex's one subagent model, its card's square saying plainly what each choice does and a row with a name in its sheet, where two squares read alike (the owner), the Agents page's, which the tray panel draws too, the core's own, with no room added (10-24); 1,321,424 with Settings › Models' Image generation MCP server row beside Image recognition's (JonahFu on X), the two drawn by one helper (mcpRow), Settings' own, with no room added (10-25); 1,321,994 with a provider of the user's set never to rest for a limit (zoecats), the provider editor's Advanced row, the core's own editor, with no room added (10-25); 1,322,289 with Settings › Privacy's Keep a key's form under Mask secrets (Charles Cao on X), Settings' own row, with no room added (10-25); 1,322,537 with no Codex squares beside its named settings rows (the owner), with no room added (10-25); 1,323,401 with the tray panel drawing its last allowances at once and asking for them beside the state (#3160, #3134), the tray panel's, the core's own, and the 4 bytes 84c50f032 added, with no room added (10-25); 1,326,105 with many releases' notes merged into one list by kind, each line with its version (the owner), in the update sheet and What's new, with no room added (10-25); 1,321,319 with Settings › Observability moved out to its plugin (plugins/otel/page.js) and its Langfuse setup there (an X user), the budget lowered to it (10-26); a quota card whose window is used but names no reset no longer saying "Not used yet" (windy on Discord) raised it to 1,321,347, and back to 1,321,319 with Settings' model pickers sharing one row helper (modelOpt) where six kept their own copy, no raise (10-26); 1,325,845 with every slow page's skeletons getting magpie's bird hopping bar to bar (skelBird, the owner after the Plugins page's README), one bird for the window over whatever page or dialog is loading, the core's own, with no room added (10-26); 1,310,129 with Settings › Network and sharing's gateway rows (its port, bare ids, local network, allowed addresses, web pages) moved out to the gateway plugin (plugins/gateway/settings.js), the budget lowered to it (10-27); 1,310,269 with Test models naming the first model that failed and its error in the status line, where it said only how many (ysm119 on Discord), the provider editor's, the core's own, with no room added (10-27); 1,310,460 with Settings › About's Website row linking usemagpie.ai (the owner), Settings' own row, with no room added (10-27); 1,309,669 with a pool's Stop at the caps and Check usage near a cap ticks under a provider's accounts (plugins#349), the core's own editor, its account rows' Remove and add rows each drawn by one helper (forgetOf, addRow), with no room added (10-28); 1,311,681 with Install another agent on the Agents page naming the agents Plugins has (More in Plugins) and opening Plugins at its Agents (the owner), the Agents page's, the core's own, with no room added (10-28); 1,311,735 with More in Plugins in sight while Install another agent is folded (the owner), with no room added (10-29); 1,313,704 with a window whose WebKit scrolls under wheels it never tells of (macOS 13) remembered once seen, a scroll at rest then waiting 120ms for a second the same way within 80ms before it is put back, kept for a late wheel to give back (waitsBack), and a load landing under the wheel keeping the reader's way (backAfterLoad, issennknight), the window's own scroll guard, with no room added (10-29); back to 1,311,735 with Settings › Models › Web search's rows (renderSearch, renderSearcher, the search APIs' keys) moved out to the search plugin (plugins/search/settings.js), app.js 1,292,527 after it, not lowered further since what is left plus 1.5% is over it (#4133, 10-29); 1,315,316 with the Agents row of a Claude Code or Codex not connected saying the account it is signed in to and switching it to another (Switch accounts only, the owner on X), in place of the failover line's ChatGPT accounts button, the Agents page's, the core's own, its comments cut down, with no room added (10-30); 1,317,705 with a Claude account added from a setup-token (sfss5362 on X): the sign-in's Use a setup-token instead…, its sheet, and its account row's magpie only, the provider editor's account rows, the core's own editor, its comments cut down, with no room added (10-30); back to 1,315,316 with the setup-token sheet and Copilot's GHE.com one moved out to signsheets.js, loaded when one is asked for (signAsk, 10-30); 1,315,479 with the provider editor lining its Advanced up with its fields (the owner: 高级这个折叠按钮为什么在一个前不着村后不着店的位置?) and a refresh on each of its accounts (在这里也要加上手动刷新用量的按钮), the core's own editor, with no room added (10-31); 1,315,603 with About's Log row, the path of the log the app writes and an Open for its folder (rayem1w on X), in app.js, its comment cut to one line, with no room added (10-31); 1,316,781 with a provider's model listed by an id of the user's (zeewell on X), the provider editor's Names & levels Listed as box beside Same as, the core's own editor, with no room added (10-31); 1,316,874 with a package manager's magpie (the AUR's magpie-bin) naming the command that updates it in Settings' Version row and lighting no Update pill (shuhai on Discord), the core's own update row, which the tray panel reads too, its comments cut to one line, with no room added (10-31); Settings › Sync's Kept on this computer row (hayden4608 on Discord) raised it to 1,317,497, which is no bound; the 1,316,874 it had came back once later trims left app.js at 1,308,363 (10-31) - coreScriptBudget = 1_533_802 // every core script: 1,358,034 after Usage left; 1,380,003 with them; 1,405,937 with the fold; 1,426,102 with 10-16's core work (the GitHub list loading, the move to plugins, Settings › Long conversations), plus 1.5% (#2612); 1,447,368 with loadBack, the window's one state read per return, which every page needs and so is the core's own (1,446,845 before it, 155 bytes under), plus 1.5%; OpenCode Zen's card saying OpenCode tells no key its balance adds ~390 bytes inside it; 1,472,589 with the dialog that grows out of its row and the agents' own settings in their rows, on main's 10-20 core work (the Providers page's last list, the Routing trace's names), plus 1.5% (10-20); 1,506,192 with Settings › Privacy's record of what was masked, plus 1.5%; 1,529,393 with the Intent classifier timeout row (#2934), with no room added; 1,529,495 with the editor's partner link host, with no room added; 1,529,844 with Check in now's press summary (#3326), with no room added; 1,530,689 with the new partner tile's dot, with no room added; 1,535,084 with the sidebar's spring, with no room added; 1,549,478 with the context window card's map (tiles by tokens, the default look, the block grid a switch away) and its text view showing an inline image, in context.js, which the Routing page draws as well as Usage, so the core's own, with no room added (10-24); 1,550,768 with a usage card's refresh opening after its text (#840's card, which the tray panel draws too), the Add key spinner, and a dialog kept centred while its content comes in, with no room added (10-24); 1,524,789 with what masking did moved out to Insights › Masking, lowered to it; 1,528,525 with Codex's one subagent model, with no room added (10-24); 1,528,972 with the Image generation MCP server row (JonahFu on X), with no room added (10-25); 1,529,542 with the limit-rest row (zoecats), with no room added (10-25); 1,529,837 with Keep a key's form (Charles Cao on X), with no room added (10-25); 1,530,050 with no Codex squares beside its named settings rows (the owner), with no room added (10-25); 1,530,631 with a plugin's page growing to its README on the dialog's spring instead of in one jump (the owner), the Plugins page's, in plugins.js, with no room added (10-25); 1,533,445 with the context map counting its tokens on as a live request grows, a tile pointed at keeping its tip, a tool's gathered results saying how many and the small files their folder (the owner, after flohoeller's map on X), in context.js, which the Routing page draws as well as Usage, and the 4 bytes 84c50f032 added to app.js (Settings' Version row) without a raise, with no room added (10-25); 1,534,312 with the tray panel's last allowances drawn at once (#3160, #3134), with no room added (10-25); 1,537,016 with many releases' notes merged into one list by kind (the owner), in app.js, with no room added (10-25); 1,542,244 with a plugin's README loading under magpie's bird bouncing down its lines instead of pulsing bars (the owner), the Plugins page's, in plugins.js, with no room added (10-26); 1,542,418 with a page plugin's sidebar tab coming and going as it is installed, switched on or off, or removed, instead of on the Plugins page's next load (the owner), in plugins.js, with no room added (10-26); 1,537,645 with Settings › Observability moved out to plugins/otel, lowered to it (10-26); 1,537,673 with a used window with no reset not "Not used yet" (windy on Discord), and back to 1,537,645 with Settings' model pickers sharing modelOpt (10-26); 1,541,967 with every slow page's skeletons getting magpie's bird (skelBird, the owner), in app.js, the README's bird sharing its drawing and styles, with no room added (10-26); 1,526,251 with Settings' gateway rows moved out to plugins/gateway/settings.js, lowered to it (10-27); 1,526,391 with Test models naming the first failed model and its error (ysm119 on Discord), in app.js, with no room added (10-27); 1,526,556 with About's Website row (the owner), in app.js, with no room added (10-27); 1,526,500 with a pool's cap ticks (plugins#349), in app.js, with no room added (10-28); 1,527,245 with About's Open-source licenses row and dialog (the owner), in app.js, with no room added (10-28); 1,528,076 with the Partners heading's light (the owner), in app.js, with no room added (10-28); 1,530,449 with Install another agent's More in Plugins row (the owner), in app.js, and Plugins opening at its Agents, in plugins.js, with no room added (10-28); 1,530,807 with layout.js measuring the scrollbar into --bar, which every page's right padding takes off so its sides match (the owner), the window's own shell, with no room added (10-28); 1,530,861 with More in Plugins in sight while Install another agent is folded (the owner), in app.js, with no room added (10-29); 1,532,830 with waitsBack and backAfterLoad (issennknight, macOS 13), the window's own scroll guard, in app.js, with no room added (10-29); the context map's tile wording (a4e929212) and Cindy's Add magpie (628ac36fc) had taken the core over it, and Web search's rows moved out to plugins/search/settings.js brought it back to 1,530,861 (#4133, 10-29); 1,532,459 with a provider editor's account rows on one line each, First or Make first at its right end and the settings that aren't set under ⋯ (the owner), the core's own editor, in app.js, which stays in its budget with its comments cut down, with no room added (10-29); 1,532,602 with a plugin's README waiting for its bird to land on three lines before it goes in, however soon it came (the owner, 10-30), in plugins.js, with no room added; 1,536,357 with Switch accounts only on the Agents row (the owner on X), in app.js, with no room added (10-30); 1,537,034 with a plugin's README read once shown at once, with no bird, when its page opens again and read again behind it, the last 20 kept (the owner), in plugins.js, with no room added (10-30); 1,539,423 with a Claude account added from a setup-token (sfss5362 on X), in app.js, with no room added (10-30); 1,538,975 with purposes.js written as compact JSON by genpurposes and the MCP tool purpose in it, 448 bytes less in all (ferock on Discord), lowered to it (10-30); 1,536,586 with the setup-token sheet and Copilot's GHE.com one moved out to signsheets.js, lowered by the 2,389 the setup-token raised it (10-30); 1,536,631 with the 45 bytes b62fa332f added to app.js (Send requests unmasked for subscriptions and plugin providers too) without a raise, with no room added (10-31); 1,537,356 with Settings › Models › Replies › Claude Code's interactive mode, a row beside Short Claude system prompt (the owner), in app.js, with no room added (10-31); Long conversations in Codex's row naming the config.toml keys Codex reads before it, with Take it out, and the window magpie tells Codex for the model it runs (zgjfjfl on Discord) raised it to 1,537,669, and it is back under 1,537,356 with the key list and the window's size written by the server (codexKeysText, tokensSize) and the row's words cut, no raise (10-31); 1,538,554 with the same two, with no room added (10-31); 1,538,678 with About's Log row (rayem1w on X), with no room added (10-31); 1,539,856 with a model's Listed as id (zeewell on X), in app.js, with no room added (10-31); Tuned for you's Codex row offering the advice to background compaction (herman_hong on Discord) and a package manager's magpie naming its command (shuhai on Discord) took it to 1,541,798, and the release notes' dialogs (What's new, the update's ask) moved out to whatsnew.js, loaded when one opens, brought it back under 1,539,856, no raise (10-31); 1,540,479 for Settings › Sync's Kept on this computer row (hayden4608 on Discord) was taken back to 1,539,856 once the core weighed 1,533,355, no raise (10-31); 1,532,958 with the context window card's head naming the agent and the model's lab (the owner), in context.js, after the card's part text viewer moved out to ctxtext.js (7,005 bytes), lowered to it (10-31); 1,533,105 with the provider editor's Claude Code runs as row moved above the accounts, its pill and hover card in claudemode.js, and Settings found at the row that draws anew (the owner), in app.js and i18n.js, with no room added (11-01); a Codex account's credits spent only after every other account, key and fallback (gokoshiki on Discord) fit in it with the Codex options' comments in app.js cut down, no raise (11-01); a plugin option's words in the window's language and the filtered-models note (plugins#590, anewuser6937 on Discord) fit in it with three of the provider editor's comments in app.js cut down, no raise (11-01); 1,533,802 with a closed Mac window telling its page it is out of sight (#4293, pipi-1997), in app.js, which every page needs, its comments cut to one line, with no room added (11-01); Warm up on a Codex or Claude account's Usage card (01huadalang on Discord), in plugins/usage/page.js, its one call in app.js paid for by two comments cut, no raise (11-01); Settings' Check in now for one account (xiaowu_95660), its row and press in checkinnow.js, loaded when Settings draws a check-in, its one call in app.js paid for by three check-in comments cut, no raise (11-02); a ChatGPT account's plan end under its row on Providers (danzi002 on Discord), its line in app.js paid for by two account-row comments cut, no raise (11-02); Scroll to top and Scroll to bottom (#1090, emo172), in scrollends.js, imported on the window's first scroll, its one line in app.js paid for by two comments cut, no raise (11-02); a new-api relay's User ID beside the balance token (zxc56823), in app.js, paid for by four comments cut, no raise (11-03); Air's opened rows saying whether Air's own Codex and Claude Agent go through magpie (jumy_18634 on Discord), in app.js, paid for by six Agents-page comments cut, no raise (11-03); a key's spend cap on its row (sparkling_lemur_62868 on Discord), its pill and held line in keyspend.js, loaded when the provider editor draws a key, its one call in app.js, no raise (11-03); Claude Code's status line square beside ultracode (steven_4422 on Discord), in app.js, paid for by foldSame's comment cut, no raise (11-03) + coreScriptBudget = 1_533_802 // every core script: 1,358,034 after Usage left; 1,380,003 with them; 1,405,937 with the fold; 1,426,102 with 10-16's core work (the GitHub list loading, the move to plugins, Settings › Long conversations), plus 1.5% (#2612); 1,447,368 with loadBack, the window's one state read per return, which every page needs and so is the core's own (1,446,845 before it, 155 bytes under), plus 1.5%; OpenCode Zen's card saying OpenCode tells no key its balance adds ~390 bytes inside it; 1,472,589 with the dialog that grows out of its row and the agents' own settings in their rows, on main's 10-20 core work (the Providers page's last list, the Routing trace's names), plus 1.5% (10-20); 1,506,192 with Settings › Privacy's record of what was masked, plus 1.5%; 1,529,393 with the Intent classifier timeout row (#2934), with no room added; 1,529,495 with the editor's partner link host, with no room added; 1,529,844 with Check in now's press summary (#3326), with no room added; 1,530,689 with the new partner tile's dot, with no room added; 1,535,084 with the sidebar's spring, with no room added; 1,549,478 with the context window card's map (tiles by tokens, the default look, the block grid a switch away) and its text view showing an inline image, in context.js, which the Routing page draws as well as Usage, so the core's own, with no room added (10-24); 1,550,768 with a usage card's refresh opening after its text (#840's card, which the tray panel draws too), the Add key spinner, and a dialog kept centred while its content comes in, with no room added (10-24); 1,524,789 with what masking did moved out to Insights › Masking, lowered to it; 1,528,525 with Codex's one subagent model, with no room added (10-24); 1,528,972 with the Image generation MCP server row (JonahFu on X), with no room added (10-25); 1,529,542 with the limit-rest row (zoecats), with no room added (10-25); 1,529,837 with Keep a key's form (Charles Cao on X), with no room added (10-25); 1,530,050 with no Codex squares beside its named settings rows (the owner), with no room added (10-25); 1,530,631 with a plugin's page growing to its README on the dialog's spring instead of in one jump (the owner), the Plugins page's, in plugins.js, with no room added (10-25); 1,533,445 with the context map counting its tokens on as a live request grows, a tile pointed at keeping its tip, a tool's gathered results saying how many and the small files their folder (the owner, after flohoeller's map on X), in context.js, which the Routing page draws as well as Usage, and the 4 bytes 84c50f032 added to app.js (Settings' Version row) without a raise, with no room added (10-25); 1,534,312 with the tray panel's last allowances drawn at once (#3160, #3134), with no room added (10-25); 1,537,016 with many releases' notes merged into one list by kind (the owner), in app.js, with no room added (10-25); 1,542,244 with a plugin's README loading under magpie's bird bouncing down its lines instead of pulsing bars (the owner), the Plugins page's, in plugins.js, with no room added (10-26); 1,542,418 with a page plugin's sidebar tab coming and going as it is installed, switched on or off, or removed, instead of on the Plugins page's next load (the owner), in plugins.js, with no room added (10-26); 1,537,645 with Settings › Observability moved out to plugins/otel, lowered to it (10-26); 1,537,673 with a used window with no reset not "Not used yet" (windy on Discord), and back to 1,537,645 with Settings' model pickers sharing modelOpt (10-26); 1,541,967 with every slow page's skeletons getting magpie's bird (skelBird, the owner), in app.js, the README's bird sharing its drawing and styles, with no room added (10-26); 1,526,251 with Settings' gateway rows moved out to plugins/gateway/settings.js, lowered to it (10-27); 1,526,391 with Test models naming the first failed model and its error (ysm119 on Discord), in app.js, with no room added (10-27); 1,526,556 with About's Website row (the owner), in app.js, with no room added (10-27); 1,526,500 with a pool's cap ticks (plugins#349), in app.js, with no room added (10-28); 1,527,245 with About's Open-source licenses row and dialog (the owner), in app.js, with no room added (10-28); 1,528,076 with the Partners heading's light (the owner), in app.js, with no room added (10-28); 1,530,449 with Install another agent's More in Plugins row (the owner), in app.js, and Plugins opening at its Agents, in plugins.js, with no room added (10-28); 1,530,807 with layout.js measuring the scrollbar into --bar, which every page's right padding takes off so its sides match (the owner), the window's own shell, with no room added (10-28); 1,530,861 with More in Plugins in sight while Install another agent is folded (the owner), in app.js, with no room added (10-29); 1,532,830 with waitsBack and backAfterLoad (issennknight, macOS 13), the window's own scroll guard, in app.js, with no room added (10-29); the context map's tile wording (a4e929212) and Cindy's Add magpie (628ac36fc) had taken the core over it, and Web search's rows moved out to plugins/search/settings.js brought it back to 1,530,861 (#4133, 10-29); 1,532,459 with a provider editor's account rows on one line each, First or Make first at its right end and the settings that aren't set under ⋯ (the owner), the core's own editor, in app.js, which stays in its budget with its comments cut down, with no room added (10-29); 1,532,602 with a plugin's README waiting for its bird to land on three lines before it goes in, however soon it came (the owner, 10-30), in plugins.js, with no room added; 1,536,357 with Switch accounts only on the Agents row (the owner on X), in app.js, with no room added (10-30); 1,537,034 with a plugin's README read once shown at once, with no bird, when its page opens again and read again behind it, the last 20 kept (the owner), in plugins.js, with no room added (10-30); 1,539,423 with a Claude account added from a setup-token (sfss5362 on X), in app.js, with no room added (10-30); 1,538,975 with purposes.js written as compact JSON by genpurposes and the MCP tool purpose in it, 448 bytes less in all (ferock on Discord), lowered to it (10-30); 1,536,586 with the setup-token sheet and Copilot's GHE.com one moved out to signsheets.js, lowered by the 2,389 the setup-token raised it (10-30); 1,536,631 with the 45 bytes b62fa332f added to app.js (Send requests unmasked for subscriptions and plugin providers too) without a raise, with no room added (10-31); 1,537,356 with Settings › Models › Replies › Claude Code's interactive mode, a row beside Short Claude system prompt (the owner), in app.js, with no room added (10-31); Long conversations in Codex's row naming the config.toml keys Codex reads before it, with Take it out, and the window magpie tells Codex for the model it runs (zgjfjfl on Discord) raised it to 1,537,669, and it is back under 1,537,356 with the key list and the window's size written by the server (codexKeysText, tokensSize) and the row's words cut, no raise (10-31); 1,538,554 with the same two, with no room added (10-31); 1,538,678 with About's Log row (rayem1w on X), with no room added (10-31); 1,539,856 with a model's Listed as id (zeewell on X), in app.js, with no room added (10-31); Tuned for you's Codex row offering the advice to background compaction (herman_hong on Discord) and a package manager's magpie naming its command (shuhai on Discord) took it to 1,541,798, and the release notes' dialogs (What's new, the update's ask) moved out to whatsnew.js, loaded when one opens, brought it back under 1,539,856, no raise (10-31); 1,540,479 for Settings › Sync's Kept on this computer row (hayden4608 on Discord) was taken back to 1,539,856 once the core weighed 1,533,355, no raise (10-31); 1,532,958 with the context window card's head naming the agent and the model's lab (the owner), in context.js, after the card's part text viewer moved out to ctxtext.js (7,005 bytes), lowered to it (10-31); 1,533,105 with the provider editor's Claude Code runs as row moved above the accounts, its pill and hover card in claudemode.js, and Settings found at the row that draws anew (the owner), in app.js and i18n.js, with no room added (11-01); a Codex account's credits spent only after every other account, key and fallback (gokoshiki on Discord) fit in it with the Codex options' comments in app.js cut down, no raise (11-01); a plugin option's words in the window's language and the filtered-models note (plugins#590, anewuser6937 on Discord) fit in it with three of the provider editor's comments in app.js cut down, no raise (11-01); 1,533,802 with a closed Mac window telling its page it is out of sight (#4293, pipi-1997), in app.js, which every page needs, its comments cut to one line, with no room added (11-01); Warm up on a Codex or Claude account's Usage card (01huadalang on Discord), in plugins/usage/page.js, its one call in app.js paid for by two comments cut, no raise (11-01); Settings' Check in now for one account (xiaowu_95660), its row and press in checkinnow.js, loaded when Settings draws a check-in, its one call in app.js paid for by three check-in comments cut, no raise (11-02); a ChatGPT account's plan end under its row on Providers (danzi002 on Discord), its line in app.js paid for by two account-row comments cut, no raise (11-02); Scroll to top and Scroll to bottom (#1090, emo172), in scrollends.js, imported on the window's first scroll, its one line in app.js paid for by two comments cut, no raise (11-02); a new-api relay's User ID beside the balance token (zxc56823), in app.js, paid for by four comments cut, no raise (11-03); Air's opened rows saying whether Air's own Codex and Claude Agent go through magpie (jumy_18634 on Discord), in app.js, paid for by six Agents-page comments cut, no raise (11-03); a key's spend cap on its row (sparkling_lemur_62868 on Discord), its pill and held line in keyspend.js, loaded when the provider editor draws a key, its one call in app.js, no raise (11-03); Claude Code's status line square beside ultracode (steven_4422 on Discord), in app.js, paid for by foldSame's comment cut, no raise (11-03); Codex's Restart the app when magpie switches its account tick (atom0964 on Discord), in app.js, paid for by five account-row comments cut, no raise (11-03) ) func TestCoreScriptBudget(t *testing.T) { diff --git a/internal/gui/providers.go b/internal/gui/providers.go index b91394c0e..56c5ba951 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -247,6 +247,9 @@ type providerJSON struct { // Claude's, the accounts are kept to Claude Code's own sign-in and // serve no request through magpie (myduso on Discord) SwitchOnly bool `json:"switchOnly,omitempty"` + // RestartApp: magpie restarts the Codex app's app-server for an + // account change it makes by itself (provider.Provider.RestartApp) + RestartApp bool `json:"restartApp,omitempty"` // CapStop and CapCareful: how its accounts end at their caps // (plugins#349), set on their own with capstop and capcareful CapStop bool `json:"capStop,omitempty"` @@ -686,7 +689,7 @@ func providerInfoWith(p provider.Provider, ls provider.Listing, agents []agentUs Catalog: p.Catalog, Website: p.Website, KeysURL: p.KeysURL, Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountNames: p.AccountNames, Headers: p.Headers, ExtraBody: p.ExtraBody, ReplyHeaders: p.ReplyHeaders, PassHeaders: p.PassHeaders, Searches: p.Searches, Cline: p.ClinePinnable(), PinUpstream: p.PinUpstream, Unredacted: p.Unredacted, CountFree: p.CountFree, InsecureTLS: p.InsecureTLS, TakesInsecureTLS: p.TakesInsecureTLS(), LimitRestOff: p.LimitRestOff, NativeCompaction: p.NativeCompaction, CarriesCompaction: p.CarriesCompaction(), PassUserAgent: p.PassUserAgent, OwnClient: p.OwnClient(), AuthHeader: p.AuthHeader, BothAuth: p.BothAuth(), BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, BalanceMethod: p.BalanceMethod, ModelsURL: p.ModelsURL, Ready: p.Ready(), Chosen: p.PicksOf(avail), Agents: make([]providerAgent, 0, len(agents)), - Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, CapStop: p.CapStop, CapCareful: p.CapCareful, Unlisted: p.Unlisted, NoModels: p.ServesNone(), BestInFamily: p.BestInFamily && len(p.Models) == 0 && !p.NoModels, Off: p.Off, Contexts: p.Contexts, + Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, RestartApp: p.RestartApp, CapStop: p.CapStop, CapCareful: p.CapCareful, Unlisted: p.Unlisted, NoModels: p.ServesNone(), BestInFamily: p.BestInFamily && len(p.Models) == 0 && !p.NoModels, Off: p.Off, Contexts: p.Contexts, MaxConcurrency: p.MaxConcurrency, PluginConcurrency: p.PluginConcurrency(), MaxAccounts: p.MaxAccounts, PluginAccounts: p.PluginAtOnce(), PriceRate: p.PriceRate, RateWindows: p.RateWindows, RateNow: rateNowOf(p, time.Now()), AccountConcurrency: p.AccountConcurrency, AccountWeights: p.AccountWeights, QueueLimit: p.QueueLimit, QueueWait: p.QueueWait, MaxRPM: p.MaxRPM, @@ -1969,9 +1972,9 @@ func providerRoutes(mux *http.ServeMux, w Windows) { in.RefreshEvery, in.AutoInclude = old.RefreshEvery, old.AutoInclude in.KeepLogin = old.KeepLogin // set on its own, with keeplogin in.KeepLoginAs = old.KeepLoginAs - in.SwitchOnly = old.SwitchOnly - in.CapStop, in.CapCareful = old.CapStop, old.CapCareful // capstop, capcareful - in.Off = old.Off // and this with off and on + in.SwitchOnly, in.RestartApp = old.SwitchOnly, old.RestartApp // switchonly, restartapp + in.CapStop, in.CapCareful = old.CapStop, old.CapCareful // capstop, capcareful + in.Off = old.Off // and this with off and on if in.Contexts == nil { in.Contexts = old.Contexts // a save that doesn't say } @@ -2202,6 +2205,13 @@ func providerRoutes(mux *http.ServeMux, w Windows) { return } agent.SyncCatalogSoon() + case "restartapp": + // the Codex app's app-server restarted for an account change + // magpie makes by itself, or left be (atom0964 on Discord) + if err := provider.SetRestartApp(in.ID, in.RestartApp); err != nil { + fail(rw, err) + return + } case "capstop": // a request ends at the accounts' caps, 429, or goes on to the // fallbacks (plugins#349) diff --git a/internal/gui/tests/restart-app.test.cjs b/internal/gui/tests/restart-app.test.cjs new file mode 100644 index 000000000..238ce5b08 --- /dev/null +++ b/internal/gui/tests/restart-app.test.cjs @@ -0,0 +1,120 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// atom0964 on Discord: with both of Codex's sign-in ticks off, magpie still +// restarted the Codex app (its app-server ended, which the ChatGPT app +// shows as an error and relaunches) whenever it switched Codex's account by +// itself. Now that is a tick of its own under Codex's accounts, off unless +// the user turns it on. Ticking it posts provider/restartapp, the redraw +// keeps it ticked, unticking posts it off; with one account it isn't shown. +// The page doesn't move. In English, Chinese, Japanese and German, +// Chromium and WebKit, at 1100 and 420 wide. +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 = ({ restartApp = false, spare = true } = {}) => ({ + id: "codex", name: "Codex", icon: "codex-color", chat: "", responses: "", anthropic: "", catalog: "", routing: "", restartApp, + models: [{ id: "gpt-6", name: "GPT-6", on: true }], agents: [], fallback: [], headers: {}, keyList: [], + account: { + agent: "codex", agentName: "Codex", user: "work@example.com", plan: "PLUS", + logins: [ + { user: "work@example.com", plan: "PLUS", active: true, on: true }, + { user: "spare@example.com", plan: "PRO", on: spare }, + ], + }, +}); + +function serve(lang, first, posts) { + let list = [first]; + const state = { agents: [], profiles: [], settings: { lang, theme: "light" } }; + const providers = () => ({ providers: list, presets: [], excluded: [], gateway: { running: true, window: true } }); + return async (route) => { + const url = new URL(route.request().url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json(state); + if (url.pathname === "/api/providers") return json(providers()); + if (url.pathname === "/api/provider/restartapp") { + const body = route.request().postDataJSON(); + posts.push(body); + list = [{ ...list[0], restartApp: body.restartApp }]; + return json(providers()); + } + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname.startsWith("/api/")) return 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 label = { + en: "Restart the Codex app when magpie switches its account", + zh: "magpie 切换账号时自动重启 Codex 应用", + ja: "magpie がアカウントを切り替えたら Codex アプリを再起動する", + de: "Codex-App neu starten, wenn magpie das Konto wechselt", +}; +const strings = [ + "Restart the {agent} app when magpie switches its account", + "Off, the {agent} app stays on its account until you restart it.", + "magpie restarts the {agent} app when it switches accounts", + "magpie leaves the {agent} app running when it switches accounts", +]; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const width of [1100, 420]) { + for (const lang of Object.keys(label)) { + const open = async (t, opts) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = [], posts = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, codex(opts), posts)); + await page.goto("http://magpie.test/?view=providers"); + await page.locator(".row.provider", { hasText: "Codex" }).first().click(); + await page.locator(".editor .acc").first().waitFor(); + return { page, errors, posts }; + }; + + test(`${engine} ${width} ${lang}: a tick has magpie restart the Codex app for its own switches`, async (t) => { + const { page, errors, posts } = await open(t, {}); + const only = page.locator(".editor .accts .restart-app label"); + assert.equal((await only.textContent()).trim(), label[lang]); + assert.ok(await only.getAttribute("title"), "it says what it does"); + assert.equal(await only.locator("input").isChecked(), false); + if (lang === "en") { + const missing = await page.evaluate((ks) => ["zh", "zh-TW", "ja", "de"].flatMap((l) => ks.filter((k) => !I18N[l][k]).map((k) => `${l}: ${k}`)), strings); + assert.deepEqual(missing, [], "every string has its translations"); + } + await only.scrollIntoViewIfNeeded(); + const box = await only.boundingBox(); + assert.ok(box.x >= 0 && box.x + box.width <= width, `the tick fits across ${width}`); + const scrollers = () => page.evaluate(() => [...document.querySelectorAll("*")].filter((e) => e.scrollTop).map((e) => e.scrollTop).concat(document.scrollingElement.scrollTop)); + const before = await scrollers(); + await only.locator("input").click(); + await page.waitForFunction(() => document.querySelector(".editor .accts .restart-app input")?.checked === true); + assert.deepEqual(posts, [{ id: "codex", restartApp: true }]); + assert.deepEqual(await scrollers(), before, "the page doesn't move"); + await page.locator(".editor .accts .restart-app input").click(); + await page.waitForFunction(() => document.querySelector(".editor .accts .restart-app input")?.checked === false); + assert.deepEqual(posts, [{ id: "codex", restartApp: true }, { id: "codex", restartApp: false }]); + assert.deepEqual(errors, []); + }); + + test(`${engine} ${width} ${lang}: restart-app is drawn ticked, and not at all with one account`, async (t) => { + const ticked = await open(t, { restartApp: true }); + assert.equal(await ticked.page.locator(".editor .accts .restart-app input").isChecked(), true); + const one = await open(t, { spare: false }); + assert.equal(await one.page.locator(".editor .accts .restart-app").count(), 0); + assert.deepEqual([...ticked.errors, ...one.errors], []); + }); + } + } +} diff --git a/internal/provider/backup.go b/internal/provider/backup.go index 09293538e..5c02f9281 100644 --- a/internal/provider/backup.go +++ b/internal/provider/backup.go @@ -92,7 +92,8 @@ func RestoreGroups(gs []Group) error { // from another computer: one not among them goes, one that came without // keys keeps the keys it has here, and an access key or balance token it // came without is kept too (KeepSecrets). Which account an agent is kept -// signed in to (KeepLogin, KeepLoginAs, SwitchOnly) is this computer's own: +// signed in to (KeepLogin, KeepLoginAs, SwitchOnly), and whether its app is +// restarted to follow (RestartApp), is this computer's own: // one person signs in to a personal account at home and a work account at // the office, and sync set each computer to the other's every day. func Mirror(ps []Provider, gs []Group) error { @@ -112,7 +113,7 @@ func Mirror(ps []Provider, gs []Group) error { } if h, ok := here[p.ID]; ok { p = KeepSecrets(p, h, p.Key == "" && len(p.Keys) == 0) - p.KeepLogin, p.KeepLoginAs, p.SwitchOnly = h.KeepLogin, h.KeepLoginAs, h.SwitchOnly + p.KeepLogin, p.KeepLoginAs, p.SwitchOnly, p.RestartApp = h.KeepLogin, h.KeepLoginAs, h.SwitchOnly, h.RestartApp } else { p.KeepLoginAs = "" // an account signed in on the other computer } diff --git a/internal/provider/codex_app_server.go b/internal/provider/codex_app_server.go index 2639db9c7..2fc195ac2 100644 --- a/internal/provider/codex_app_server.go +++ b/internal/provider/codex_app_server.go @@ -266,6 +266,9 @@ var codexApp struct { // switched: Codex's ChatGPT account changed since the app-servers were // last listed (codexAppAccountSwitched) switched bool + // auto: every switch since then magpie made by itself + // (SwitchWhenSpent), none the user made + auto bool // spent: the app-servers are on an account used up, so a turn they // left open can't be served by them any more: Codex was switched off // it (SwitchWhenSpent, or by hand off one known held, noteCodexSwitch), @@ -307,21 +310,23 @@ func CodexAppStuck() bool { // one, listed ahead of the app's on the owner's Mac) or none when ps was // slow, and then nothing was ended and the app stayed grey on the used-up // account till the user restarted it (danzi002 on Discord). -func codexAppAccountSwitched() { - c := &codexApp - c.Lock() - defer c.Unlock() - c.switched = true -} +func codexAppAccountSwitched() { codexAppSwitched(false, false) } // codexAppSpentSwitch is codexAppAccountSwitched for a switch off an // account that was used up: a turn the app-server left open is restarted // past too once it has gone quiet (codexTurnStuckAfter). -func codexAppSpentSwitch() { +func codexAppSpentSwitch() { codexAppSwitched(true, false) } + +// codexAppSwitched notes a switch of Codex's account: spent, off one used +// up; byMagpie, made by magpie itself (SwitchWhenSpent), which restarts +// the app only with RestartApp on. One the user made among them restarts +// it all the same. +func codexAppSwitched(spent, byMagpie bool) { c := &codexApp c.Lock() defer c.Unlock() - c.switched, c.spent = true, true + c.auto = byMagpie && (!c.switched || c.auto) + c.switched, c.spent = true, c.spent || spent } // KeepCodexAppOnItsProvider runs codexAppStep every codexAppEvery till @@ -377,6 +382,23 @@ func codexAppStep(ctx context.Context, now time.Time, busy func() (int, time.Tim // quota ran out mid-turn would hold their restart, and the app's grey // Send, for up to codexTurnWindow (xiaoq6285 on Discord) into := changed && out && (!c.seen || !c.out) + // what changed magpie changed by itself: the used-up takeover in or + // out, and its own account switches. The ChatGPT app shows the end of + // its app-server as an error and relaunches (#4550), so that waits for + // the user to restart it unless they asked magpie to (RestartApp; + // atom0964 on Discord: both of Codex's sign-in ticks off, and magpie + // still restarted the app to switch accounts). A switch the user made, + // a Connect or a Disconnect is theirs, and restarts it. + byHand := c.switched && !c.auto || c.seen && c.route != route && c.out == out + if changed && !byHand && !codexRestartsApp() { + why := "magpie switched Codex's ChatGPT account" + if !c.switched { + why = "magpie became Codex's provider for its used-up account, or gave it back" + } + log.Printf("codex: %s; the Codex app's app-server is left running (Restart the Codex app to follow is off), and the app follows once it is restarted", why) + c.switched, c.auto = false, false + changed = false + } if !changed { c.seen, c.route, c.out = true, route, out } @@ -400,7 +422,7 @@ func codexAppStep(ctx context.Context, now time.Time, busy func() (int, time.Tim c.why = "where Codex's config sends it changed" } c.spent = c.spent || into - c.seen, c.route, c.out, c.switched = true, route, out, false + c.seen, c.route, c.out, c.switched, c.auto = true, route, out, false, false c.stale, c.stuck = map[int]int{}, false for _, p := range pids { c.stale[p] = 0 diff --git a/internal/provider/codex_app_server_test.go b/internal/provider/codex_app_server_test.go index 796325e16..b2d01e9e1 100644 --- a/internal/provider/codex_app_server_test.go +++ b/internal/provider/codex_app_server_test.go @@ -42,19 +42,22 @@ func stubCodexApp(t *testing.T) *codexAppStub { t.Helper() s := &codexAppStub{known: true, next: 100} oldOn, oldList, oldEnd, oldTurn := CodexAppRoute, codexAppServersOn, endCodexAppServer, codexTurnRunning - oldOpen, oldReopen, oldQuiet := CodexAppOpen, CodexAppReopen, codexSessionsQuiet + oldOpen, oldReopen, oldQuiet, oldRestarts := CodexAppOpen, CodexAppReopen, codexSessionsQuiet, codexRestartsApp reset := func() { codexApp.Lock() - codexApp.seen, codexApp.route, codexApp.stale, codexApp.stuck, codexApp.switched = false, "", nil, false, false + 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.Unlock() } t.Cleanup(func() { CodexAppRoute, codexAppServersOn, endCodexAppServer, codexTurnRunning = oldOn, oldList, oldEnd, oldTurn - CodexAppOpen, CodexAppReopen, codexSessionsQuiet = oldOpen, oldReopen, oldQuiet + CodexAppOpen, CodexAppReopen, codexSessionsQuiet, codexRestartsApp = oldOpen, oldReopen, oldQuiet, oldRestarts reset() }) reset() + // the user asked magpie to restart the app for its own changes too + // (RestartApp); TestCodexAppLeftRunningForMagpiesOwnChanges is without + codexRestartsApp = func() bool { return true } // the app as tests find it: open, and never reopened CodexAppOpen = func(context.Context) (bool, bool) { return true, true } CodexAppReopen = func(context.Context) error { @@ -1074,3 +1077,85 @@ func TestCodexSessionsQuietFor(t *testing.T) { t.Fatal("a session last written 5 minutes ago: not quiet") } } + +// With both of Codex's sign-in ticks off magpie switches Codex's ChatGPT +// account by itself (SwitchWhenSpent, and back at the reset), and becomes +// Codex's provider for a used-up account and gives it back. Ending the +// Codex app's app-server for any of them makes the ChatGPT app show an +// error and relaunch (#4550), which atom0964 on Discord could not turn +// off. Those leave the app running unless the user ticked RestartApp. A +// switch the user makes, and a Connect or Disconnect, still restart it. +func TestCodexAppLeftRunningForMagpiesOwnChanges(t *testing.T) { + signIn(t) + s := stubCodexApp(t) + restarts := false + codexRestartsApp = func() bool { return restarts } + now := time.Now() + idle := func() (int, time.Time) { return 0, now.Add(-time.Minute) } + step := func() []int { return codexAppStep(context.Background(), now, idle) } + none := func(what string) { + t.Helper() + for range 2 { + if got := step(); got != nil { + t.Fatalf("%s: ended %v", what, got) + } + } + } + + s.running = []int{60} + none("nothing changed") + codexAppSwitched(true, true) + none("magpie switched off the used-up account") + codexAppSwitched(false, true) + none("magpie switched back at the reset") + s.on = true + none("magpie became Codex's provider for the used-up account") + s.on = false + none("magpie gave Codex back its account") + + // a switch the user made, alone or after one of magpie's + codexAppSwitched(false, true) + codexAppAccountSwitched() + if got := step(); !slices.Equal(got, []int{60}) { + t.Fatalf("switched by the user after magpie: ended %v, want [60]", got) + } + none("the new app-server read the account as it started") + codexAppAccountSwitched() + codexAppSwitched(false, true) + if got := step(); !slices.Equal(got, []int{100}) { + t.Fatalf("switched by the user, then magpie: ended %v, want [100]", got) + } + // a Connect: where Codex's config sends it changed, not by the takeover + s.route = "connected" + if got := step(); !slices.Equal(got, []int{101}) { + t.Fatalf("connected: ended %v, want [101]", got) + } + none("after the connect") + + // ticked: magpie's own changes restart it as before + restarts = true + codexAppSwitched(true, true) + if got := step(); !slices.Equal(got, []int{102}) { + t.Fatalf("RestartApp on, magpie switched: ended %v, want [102]", got) + } + s.on = true + if got := step(); !slices.Equal(got, []int{103}) { + t.Fatalf("RestartApp on, magpie took over: ended %v, want [103]", got) + } +} + +// At magpie's first look, an app opened before it on a used-up account +// was restarted at once; that is magpie's own change too, and waits for +// RestartApp. +func TestCodexAppFirstLookLeftRunning(t *testing.T) { + signIn(t) + s := stubCodexApp(t) + codexRestartsApp = func() bool { return false } + now := time.Now() + s.running, s.on = []int{60}, true + for range 2 { + if got := codexAppStep(context.Background(), now, func() (int, time.Time) { return 0, now.Add(-time.Minute) }); got != nil { + t.Fatalf("first look on the used-up account: ended %v", got) + } + } +} diff --git a/internal/provider/codex_daemon.go b/internal/provider/codex_daemon.go index f6bc6271d..d8c568270 100644 --- a/internal/provider/codex_daemon.go +++ b/internal/provider/codex_daemon.go @@ -164,7 +164,11 @@ const codexDaemonRecheck = 5 * time.Second // noteCodexSwitch remembers, when Codex's account changes from one to // another, the app-server left running on the one before. -func noteCodexSwitch(from, to string) { +func noteCodexSwitch(from, to string) { noteCodexSwitchBy(from, to, false) } + +// noteCodexSwitchBy is noteCodexSwitch, byMagpie saying magpie made the +// switch by itself (switchLoginBy). +func noteCodexSwitchBy(from, to string, byMagpie bool) { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() // the Codex app's app-servers are found and restarted on @@ -172,11 +176,7 @@ func noteCodexSwitch(from, to string) { // A switch by hand off an account known held is one off a used-up // account, as SwitchWhenSpent's is: a turn left open on it when quota // ran out mid-turn is restarted past once quiet (xiaoq6285 on Discord) - if codexHeldKnown(from) { - codexAppSpentSwitch() - } else { - codexAppAccountSwitched() - } + codexAppSwitched(codexHeldKnown(from), byMagpie) ps, err := listProcesses(ctx) known := err == nil codexDaemonMu.Lock() diff --git a/internal/provider/codex_switch.go b/internal/provider/codex_switch.go index d0002bfda..83c875d8b 100644 --- a/internal/provider/codex_switch.go +++ b/internal/provider/codex_switch.go @@ -464,7 +464,7 @@ func SwitchWhenSpent(ctx context.Context, agent string) (string, error) { } // the first moved off, not one moved to on the way r, _ := loginReturnOf(agent, from) - if err := switchLogin(agent, to); err != nil { + if err := switchLoginBy(agent, to, true); err != nil { return "", err } if back { @@ -483,12 +483,16 @@ func SwitchWhenSpent(ctx context.Context, agent string) (string, error) { share, _ := loginSwitching(agent) log.Printf("%s: %s has used %g%% or more of its allowance; signed it in to %s", agent, from, share, to) if agent == "codex" { - codexAppSpentSwitch() + codexAppSwitched(true, true) } } if agent == "codex" { if was := CodexAppStale(); was != "" { - log.Printf("codex: the Codex app is still signed in to %s, and shows its limits, until its app-server is restarted once no Codex turn runs", was) + if codexRestartsApp() { + log.Printf("codex: the Codex app is still signed in to %s, and shows its limits, until its app-server is restarted once no Codex turn runs", was) + } else { + log.Printf("codex: the Codex app is still signed in to %s, and shows its limits, until it is restarted: magpie restarts it for a switch of its own only with \"Restart the Codex app to follow\" on", was) + } } } // the models the agent is offered are the new account's plan's diff --git a/internal/provider/codex_switch_test.go b/internal/provider/codex_switch_test.go index 34ceec5f1..01ba83c36 100644 --- a/internal/provider/codex_switch_test.go +++ b/internal/provider/codex_switch_test.go @@ -65,6 +65,10 @@ func TestCodexSwitchedWhenUsedUp(t *testing.T) { codexApp.switched, codexApp.spent = false, false codexApp.Unlock() }) + // the sign-ins above were the user's switches, as if taken already + codexApp.Lock() + codexApp.switched, codexApp.spent, codexApp.auto = false, false, false + codexApp.Unlock() if to := switched(); to != "spare@example.com" { t.Fatalf("switched to %q", to) } @@ -76,6 +80,26 @@ func TestCodexSwitchedWhenUsedUp(t *testing.T) { if !spent { t.Fatal("the switch off a used-up account isn't marked spent for the Codex app") } + // it is magpie's own: the Codex app is left running unless the user + // asked magpie to restart it (RestartApp; atom0964 on Discord) + codexApp.Lock() + auto := codexApp.auto + codexApp.Unlock() + if !auto { + t.Fatal("magpie's own switch is counted the user's: the Codex app would be restarted for it") + } + if codexRestartsApp() { + t.Fatal("the Codex app is restarted for magpie's own switches with RestartApp never set") + } + if err := SetRestartApp("codex", true); err != nil { + t.Fatal(err) + } + if !codexRestartsApp() { + t.Fatal("RestartApp set, and still not read") + } + if err := SetRestartApp("codex", false); err != nil { + t.Fatal(err) + } var live codexAuth readJSON(filepath.Join(home, ".codex", "auth.json"), &live) if live.Tokens.RefreshToken != "r-spare" { diff --git a/internal/provider/logins.go b/internal/provider/logins.go index 67079f7dc..de14e69c2 100644 --- a/internal/provider/logins.go +++ b/internal/provider/logins.go @@ -1224,7 +1224,12 @@ func SwitchLogin(agent, user string) error { return nil } -func switchLogin(agent, user string) error { +func switchLogin(agent, user string) error { return switchLoginBy(agent, user, false) } + +// switchLoginBy is switchLogin, byMagpie saying magpie made the switch by +// itself (SwitchWhenSpent) rather than the user: the Codex app is then +// restarted to follow it only when the user asked for that (RestartApp). +func switchLoginBy(agent, user string, byMagpie bool) error { if pp, ok := pluginOfAgent(agent); ok { return switchPluginLogin(pp, user) } @@ -1238,7 +1243,7 @@ func switchLogin(agent, user string) error { } from, err := switchSavedLogin(agent, user) if err == nil && agent == "codex" && from != "" { - noteCodexSwitch(from, user) + noteCodexSwitchBy(from, user, byMagpie) } if err == nil && agent == "claude" { // the account's own way out goes with it (#1807) diff --git a/internal/provider/mirror_keep_login_test.go b/internal/provider/mirror_keep_login_test.go index a307884a2..1534d12f2 100644 --- a/internal/provider/mirror_keep_login_test.go +++ b/internal/provider/mirror_keep_login_test.go @@ -18,12 +18,13 @@ func TestMirrorKeepsKeepLogin(t *testing.T) { t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache")) t.Setenv("PATH", h) here := Provider{ID: "relay", Name: "Relay", Chat: "https://example.com/v1", Key: "sk-here", - KeepLogin: true, KeepLoginAs: "home@example.com"} + KeepLogin: true, KeepLoginAs: "home@example.com", RestartApp: true} if err := Save(here); err != nil { t.Fatal(err) } office := Provider{ID: "relay", Name: "Relay renamed", Chat: "https://example.com/v1", Key: "sk-here", KeepLoginAs: "work@example.com", SwitchOnly: true} + // and whether the Codex app is restarted for magpie's own switches fresh := Provider{ID: "other", Name: "Other", Chat: "https://example.org/v1", Key: "sk-other", KeepLogin: true, KeepLoginAs: "work@example.com"} if err := Mirror([]Provider{office, fresh}, nil); err != nil { @@ -33,8 +34,8 @@ func TestMirrorKeepsKeepLogin(t *testing.T) { if len(ps) != 2 { t.Fatalf("providers: %+v", ps) } - if got := ps[0]; got.Name != office.Name || !got.KeepLogin || got.KeepLoginAs != here.KeepLoginAs || got.SwitchOnly { - t.Fatalf("mirrored: name %q keepLogin %v as %q switchOnly %v, want the other's name and this computer's sign-in", got.Name, got.KeepLogin, got.KeepLoginAs, got.SwitchOnly) + if got := ps[0]; got.Name != office.Name || !got.KeepLogin || got.KeepLoginAs != here.KeepLoginAs || got.SwitchOnly || !got.RestartApp { + t.Fatalf("mirrored: name %q keepLogin %v as %q switchOnly %v restartApp %v, want the other's name and this computer's sign-in", got.Name, got.KeepLogin, got.KeepLoginAs, got.SwitchOnly, got.RestartApp) } if got := ps[1]; !got.KeepLogin || got.KeepLoginAs != "" { t.Fatalf("new provider: keepLogin %v as %q, want kept on and no account from the other computer", got.KeepLogin, got.KeepLoginAs) diff --git a/internal/provider/provider.go b/internal/provider/provider.go index d48017c1f..132412b2e 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -166,6 +166,16 @@ type Provider struct { // Code's own sign-in, which magpie still moves: the gateway serves no // request on them (KeptToAgent; myduso on Discord). SwitchOnly bool `json:"switchOnly,omitempty"` + // RestartApp, on Codex's subscription, has magpie restart the Codex + // app's own app-server when it changes Codex's account by itself: a + // switch off an account running out (SwitchWhenSpent) or back, and + // becoming Codex's provider for a used-up account or giving it back. + // The ChatGPT app shows an ended app-server as an error and relaunches + // (#4550), so it is off unless the user turns it on (atom0964 on + // Discord); the app then stays on its account until it is restarted, + // from the switch notice or by hand. A switch the user makes, and a + // Connect or Disconnect, restart it either way. + RestartApp bool `json:"restartApp,omitempty"` // MaxConcurrency is how many requests may be out at the vendor at once // on each of its keys or accounts (Discord, Lemon: a Codex account is @@ -890,7 +900,7 @@ func withPicks(a, pk Provider) Provider { func accountSettings(a, pk Provider) Provider { a.PickedFrom, a.Delisted, a.DelistedAt = pk.PickedFrom, pk.Delisted, pk.DelistedAt a.Models, a.Unlisted, a.Off, a.Fallback, a.Routing, a.Affinity, a.KeepLogin, a.KeepLoginAs, a.Contexts, a.Family = pk.Models, pk.Unlisted, pk.Off, pk.Fallback, pk.Routing, pk.Affinity, pk.KeepLogin, pk.KeepLoginAs, pk.Contexts, pk.Family - a.SwitchOnly = pk.SwitchOnly + a.SwitchOnly, a.RestartApp = pk.SwitchOnly, pk.RestartApp a.Sink, a.NoModels, a.BestInFamily = pk.Sink, pk.NoModels, pk.BestInFamily a.NativeCompaction = pk.NativeCompaction a.PromptAsWritten = pk.PromptAsWritten diff --git a/internal/provider/routing.go b/internal/provider/routing.go index 58b0e0a30..5057478b8 100644 --- a/internal/provider/routing.go +++ b/internal/provider/routing.go @@ -162,6 +162,38 @@ func SetSwitchOnly(id string, on bool) error { return Save(*p) } +// SetRestartApp has magpie restart the Codex app's app-server when it +// changes Codex's account by itself, or leave the app on its account till +// it is restarted (Provider.RestartApp). +func SetRestartApp(id string, on bool) error { + p, err := Find(id) + if err != nil { + return err + } + if p.ID != "codex" || p.Account == nil || p.Account.Agent != p.ID { + return fmt.Errorf("magpie restarts no app of %s's", p.Name) + } + p.RestartApp = on + return Save(*p) +} + +// codexRestartsApp is whether the user had magpie restart the Codex app's +// app-server for a change it makes by itself (Provider.RestartApp). While +// providers.json can't be read it is unknown, and the app is left be: a +// restart missed is the user's to make, one made shows as a crash. +var codexRestartsApp = func() bool { + f, err := read() + if err != nil { + return false + } + for _, p := range f.Providers { + if p.ID == "codex" { + return p.RestartApp + } + } + return false +} + // SwitchOnly reports whether magpie only moves agent's own sign-in between // its accounts, sending none of its requests through the gateway for // account failover (Provider.SwitchOnly). While providers.json can't be