diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index c39b50ebe..7fbbb1d99 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -86,7 +86,7 @@ something else shows up as drift. - A config that starts with a UTF-8 byte order mark (a Windows `settings.json` or `config.toml` saved by PowerShell, Notepad or a channel switcher, #1534) is read without it (`edit.Read`), and a write keeps it (`keepBOM` in `WriteAtomic`): the user's file keeps the encoding it was saved in. That covers every format `internal/edit` writes (JSON/JSONC and its arrays, TOML, YAML, env); Codex reads a TOML file through a BOM too, so magpie no longer refuses one. A file read some other way trims it with `edit.TrimBOM` (the Claude Code and CC Switch imports). A line an edit takes out of a CRLF file goes with its `\r\n`. - Codex's model picker tags each of its own models by where a pick on the Agents page sends it: via magpie while routed, joined, or failing over, and direct while it is only beside its sign-in on one of magpie's models (`beside`, not joined, failover off), where such a pick takes magpie out (#940) and the GUI asks first (`TestCodexBesideOwnModelsSayDirect`). - A line magpie writes into an agent's TOML, YAML or dotenv config gets a comment line of its own just above it, `# magpie: ; ` (`edit.Mark`, set to `agent.lineNote` by the CLI's `run` in [`mark.go`](../../internal/agent/mark.go); the edit side in [`internal/edit/mark.go`](../../internal/edit/mark.go)). Jevik_AI on X deleted magpie's folders by hand, and Codex's `config.toml` kept `openai_base_url` on the gateway with nothing in it naming magpie: every turn was a 502. Only a one-line scalar that points at the gateway or names magpie's model list gets one, and only when the write adds or changes that line, or it had a note already; a line of the user's own that magpie leaves as it is gets none. The note is never on the value's line: Grok App's `providers.rs` reads the rest of a line as the value. Every write takes the notes out first and puts them back over the lines that still need one, so a note goes with its line and a Disconnect leaves none. A YAML note that would change what the file reads as isn't added (`sameYAMLValue`). JSON has no comments and gets none. Tests set no `Mark`, so their exact bytes stay; `TestMarkedLinesEveryAgent` connects every agent with notes on and checks each gateway line has one, a second sync writes nothing, and Disconnect leaves none; `TestCodexMarkedLines`, `internal/edit`'s `TestMark*`. -- Codex signed in to ChatGPT stays beside its sign-in (`openai_base_url`) unless the user picks magpie API. magpie becomes its provider only while the Codex app holds the active account, which it sends nothing for: `/wham/usage` says it isn't allowed, and it has no credits and isn't a workspace still within its overage (`codexHeld`, read by `provider.CodexUsedUp`). With Codex switched off or removed in magpie (`leftAlone`), whose allowance magpie otherwise reads nothing of, the active account is still read for this alone while Codex takes magpie's models beside its sign-in or magpie is its provider for the held account (`Agent.HoldMatters`, through the `provider.CodexHoldMatters` hook; `codexHoldReading`): once a minute at most, with the token as Codex keeps it, never renewed or written (`codexTokenAsKept`), and nothing shown on the Usage page. Before, turning Codex off in magpie after its allowance ran out left the Codex app greying Send for magpie's models through restarts, and one already moved was put back on the held account (sherlock_23333 on X; `TestCodexHoldReadLeftAlone`, `TestCodexHoldMatters`). Where the app goes by what usage can't show (an experiment's gate, a reserve, a Team plan's overage under the reserve experiment), it counts as held: a wrong move costs ChatGPT extras, a missed one every turn. A saved reading kept through a failed read stops saying held once its used-up window has started again; a hold with no window used up stays till a fresh read. The app then loses its ChatGPT state (durable threads, remote control), so a window at 100% alone, which credits get past, doesn't move it (`codex.out` marks the move, and Sync undoes it once the account has room). The same holds on one of Codex's own models joined beside the sign-in (MasterYi on Discord: the Codex app greyed Send for every model on a used-up account): Sync makes magpie the provider on that model as magpie serves it (`codexOwnViaMagpie`, `codex/`), keeps the model picked in `codex.out_own`, and once the account has room puts Codex back joined on it; a model the user picked meanwhile stays theirs. With no ChatGPT account in magpie to serve it, Codex is left as it is (`TestCodexOwnModelGoesThroughMagpieWhileUsedUp`, `TestCodexOwnModelKeptOnChatGPT`). The account is read again at once when a reply says it may be out (a `usage_limit_reached` rest, or an `x-codex-*` window heard at 100%; `provider.CodexMayBeUsedUp`, at most every 20s, the active account only), not only on the five-minute look. A turn relayed to Codex's own sign-in, the one account on (`codexUpstreamOn` with no account, the gateway's `codexRelayedAccount`), is heard the same way: its `x-codex-*` windows and `codex.rate_limits` event kept as the sign-in's usage (`heardCodexLimits`), and a `usage_limit_reached` refusal reading it again. Before, only turns served through magpie's accounts were, so with one account magpie learned the account was out only at the next look, minutes on, and the Codex app kept Send greyed until it was restarted (unsplashz on Discord; `TestCodexUsedUpRelayedAsksAtOnce`, `TestCodexRelayedWindowsHeard`). A Codex started before magpie became its provider keeps sending its own model's turns to its built-in provider; while the sign-in is known out (`provider.CodexUsedUpKnown`) and the request signs as it, those go through routing as `codex/` (`codexAccounts`), as a restarted Codex's do (`TestCodexHeldSignInServedWithoutRestart`). The Codex app greys Send for every model, magpie's too, while its `authMethod` is `chatgpt` and its rate limit says not allowed (its composer's gate in ChatGPT.app 26.1013), and reads `authMethod` from its app-server's `account/read` only as the app-server starts; with magpie the provider (`requires_openai_auth` false) that answers no account, so the gate lifts. So the gateway process restarts the app's own app-server each time magpie becomes Codex's provider for the used-up account (`Agent.AppOut`) and again when Codex is put back on the account after its reset, and likewise whenever what the app-server reads as it starts and magpie writes changes (`model_provider`, `openai_base_url`, `model_catalog_json`, the magpie table's `base_url`, and a hash of what the catalog file holds, `codexCatalogTag` in [`codex_app_route.go`](../../internal/agent/codex_app_route.go), read again only when its size or time changes; `codexAppRoute`, through the `provider.CodexAppRoute` hook): a Disconnect, a Connect, failover written or taken out, a provider or group renamed or a model added. Without the catalog in it the app kept the names and models it started with until it was restarted (lucis0116 on X). 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. 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`). 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`, `TestCodexAppRouteFollowsTheCatalog`, `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`). 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 (`model_provider`, `openai_base_url`, `model_catalog_json`, the magpie table's `base_url`, and a hash of what the catalog file holds, `codexCatalogTag` in [`codex_app_route.go`](../../internal/agent/codex_app_route.go), read again only when its size or time changes; `codexAppRoute`, through the `provider.CodexAppRoute` hook): a Disconnect, a Connect, failover written or taken out, a provider or group renamed or a model added. Without the catalog in it the app kept the names and models it started with until it was restarted (lucis0116 on X). 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. 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 after a switch off a used-up account (`SwitchWhenSpent` → `codexAppSpentSwitch`): 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`). 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`, `TestCodexAppRouteFollowsTheCatalog`, `TestCodexAppServerUnknown`, `TestCodexAppServerStuck`, `TestCodexAppServersOnHome`, `TestCodexTurnOpen`, `TestCodexBusy`, `codex-app-out.test.cjs`. - Moving a field from one of magpie's models to another (the agent's own picker) is not drift. Moving it off magpie is. - Claude Desktop applying a configLibrary profile other than magpie's is not drift when that profile is a gateway profile for this magpie's gateway (`desktopAppliedGateway` in [`claudedesktop.go`](../../internal/agent/claudedesktop.go)): Desktop's "Import configuration" adds a file exported on another computer, magpie's profile there with the user's connectors (`managedMcpServers`), as a new entry under a random id (aa86222 on Discord). magpie keeps it applied on Reconnect and through Sync, and writes in it only `inferenceGatewayApiKey` (with a missing auth scheme) when the gateway would refuse its key (`desktopKeyApplied`; magpie's own keys count as taken, `desktopKeyTaken`). A profile for another gateway, CC Switch's among them, is still drift, and Reconnect applies magpie's. The first switch-on still starts magpie's profile from an applied one (#2035). `TestClaudeDesktopImportedProfileIsOnMagpie`. - Claude Desktop 4.4212 (10-29) seals the secrets of its configLibrary profiles at rest: at every start it writes `inferenceGatewayApiKey` (and every other string secret its schema drops on export) back as `__sealed__:v1:` + base64 of `{"configLibrary":{"key":…,"value":…}}` behind `anthropic.claude.crossProfileSecret.v1:`, protected with the user's DPAPI on Windows (entropy `anthropic.claude.crossProfileSecret.v1`, claude-native's `userDpapiProtect`) and Electron's safeStorage (the Keychain) on macOS, and it sends the gateway the key as it was. `desktopOpen` ([`desktopseal.go`](../../internal/agent/desktopseal.go)) reads the key as Desktop does: on Windows it opens the seal (`desktopUnprotect`, `CryptUnprotectData`, never prompting) and judges what is in it; a seal it can't open (macOS, another user's) is unknown, so Check doesn't call it changed and `desktopKeyApplied` doesn't write over it. Before this the key read as changed after every Desktop start and Reconnect only wrote it in the clear for Desktop to seal again (a Windows user on Discord). A key in the clear that isn't one the gateway takes, a missing key and another address are still drift (`TestClaudeDesktopSealedKeyIsNotChanged`, `TestClaudeDesktopImportedSealedKeyStays`, `TestClaudeDesktopSealedKeyOpened` on Windows). diff --git a/internal/agent/agents.go b/internal/agent/agents.go index ba9abb8f3..04650be8f 100644 --- a/internal/agent/agents.go +++ b/internal/agent/agents.go @@ -52,6 +52,10 @@ func init() { // and when Codex is connected or disconnected, or its route otherwise // changes, so a running app sends where its config now says provider.CodexAppRoute = codexAppRoute + // and when none starts in place of the one ended, the app is + // reopened on Windows, where its stdout was held open + provider.CodexAppOpen = codexAppOpen + provider.CodexAppReopen = codexAppReopen // and what the Codex app holds is read while Codex takes magpie's // models beside its sign-in, Codex switched off in magpie or not provider.CodexHoldMatters = func() bool { diff --git a/internal/agent/codex_app.go b/internal/agent/codex_app.go index 57ce2282f..3ca4c10d6 100644 --- a/internal/agent/codex_app.go +++ b/internal/agent/codex_app.go @@ -99,3 +99,54 @@ func RestartSwitchedCodexApp(ctx context.Context) error { } return errors.New(noticeSwitchAppUnknown.say("agent", "Codex")) } + +// codexWinApp is the Windows Codex app: the OpenAI.Codex Store package's +// ChatGPT.exe (26.1021 on the Windows box, under C:\Program Files\ +// WindowsApps\OpenAI.Codex_…\app\), never the ChatGPT chat app's. +var codexWinApp = restartable{winExe: "ChatGPT.exe", win: func(image string) bool { + return winBase(image, "ChatGPT.exe") && winHas(image, `\WindowsApps\OpenAI.Codex_`) +}} + +// codexWinAUMID opens the Windows Codex app when its main process's +// AppUserModelID can't be read: its package family and its one app. +const codexWinAUMID = "OpenAI.Codex_2p2nqsd0c76g0!App" + +// codexAppOpen is provider.CodexAppOpen: whether the Codex desktop app +// runs here, ChatGPT.app (com.openai.codex) on macOS, the Store app on +// Windows; not known elsewhere. +func codexAppOpen(context.Context) (open, known bool) { + switch { + case restartOnWindows: + _, ok := findRestartable(codexWinApp) + return ok, true + case restartOnMac: + _, ok := findRestartable(restartable{mac: desktopApps["codex"]}) + return ok, true + } + return false, false +} + +// codexAppReopen is provider.CodexAppReopen: on Windows it quits the +// Codex app and opens it again, as the Agents row's Restart does for +// Claude Desktop (restartWin), when the app started no app-server in +// place of the one magpie ended and so can't send. Its threads are kept +// by Codex; a draft not sent is lost, but nothing could be sent from it. +// macOS isn't reopened unasked: there the Agents row's Restart and the +// line magpie shows are the user's. +func codexAppReopen(ctx context.Context) error { + if !restartOnWindows { + return errors.New("magpie reopens only the Windows Codex app") + } + c, ok := findRestartable(codexWinApp) + if !ok { + return nil // quit meanwhile: it starts an app-server as it opens + } + if c.main.aumid == "" { + c.main.aumid = codexWinAUMID + } + a, err := Find("codex") + if err != nil { + a = &Agent{ID: "codex", Name: "Codex"} + } + return a.restartWin(ctx, codexWinApp, c) +} diff --git a/internal/agent/codex_app_test.go b/internal/agent/codex_app_test.go index abe5a7e38..fa761e8cb 100644 --- a/internal/agent/codex_app_test.go +++ b/internal/agent/codex_app_test.go @@ -3,9 +3,11 @@ package agent import ( "context" "errors" + "fmt" "os" "path/filepath" "runtime" + "slices" "strings" "testing" "time" @@ -96,3 +98,60 @@ func TestRestartSwitchedCodexAppSays(t *testing.T) { t.Fatal(err) } } + +// When the Windows Codex app starts no app-server in place of the one +// magpie ended (its stdout held open by a process that one started), it +// can't send till it is quit and opened again (蛋仔 on Discord, 10-30): +// magpie does that, to the OpenAI.Codex package's ChatGPT.exe only, by +// its AppUserModelID. macOS isn't reopened unasked. +func TestCodexAppReopenedOnWindows(t *testing.T) { + restartSandbox(t) + restartOnWindows = true + appCloseWait, appBackWait, appTrayGrace = time.Second, time.Second, 10*time.Millisecond + const image = `C:\Program Files\WindowsApps\OpenAI.Codex_26.1021.3705.0_x64__2p2nqsd0c76g0\app\ChatGPT.exe` + start := time.Now().Add(-time.Hour) + alive := true + winProcs = func(name string) []winProc { + if !strings.EqualFold(name, "ChatGPT.exe") { + return nil + } + // the ChatGPT chat app beside it, always running + ps := []winProc{{pid: 50, parent: 4, image: `C:\Program Files\WindowsApps\OpenAI.ChatGPT-Desktop_1.2025.1.0_x64__2p2nqsd0c76g0\app\ChatGPT.exe`, start: start}} + if alive { + ps = append(ps, + winProc{pid: 10, parent: 4, image: image, start: start, aumid: "OpenAI.Codex_2p2nqsd0c76g0!App"}, + winProc{pid: 11, parent: 10, image: image, start: start.Add(time.Second)}) + } + return ps + } + winShown = func([]int) bool { return false } // in the tray + var did []string + winClose = func(pids []int) error { did = append(did, fmt.Sprint("close ", pids)); return nil } + winEnd = func(pid int) error { did = append(did, fmt.Sprint("end ", pid)); alive = false; return nil } + winLaunch = func(p winProc) error { did = append(did, "open "+p.aumid); alive = true; return nil } + + if open, known := codexAppOpen(context.Background()); !open || !known { + t.Fatalf("open %v, known %v", open, known) + } + if err := codexAppReopen(context.Background()); err != nil { + t.Fatal(err) + } + if want := []string{"close [10 11]", "end 10", "open OpenAI.Codex_2p2nqsd0c76g0!App"}; !slices.Equal(did, want) { + t.Fatalf("did %q, want %q", did, want) + } + + // quit meanwhile: nothing to do, it starts one as it opens + alive, did = false, nil + if open, known := codexAppOpen(context.Background()); open || !known { + t.Fatalf("quit: open %v, known %v", open, known) + } + if err := codexAppReopen(context.Background()); err != nil || did != nil { + t.Fatalf("quit: %v, did %q", err, did) + } + + restartOnWindows = false + alive = true + if err := codexAppReopen(context.Background()); err == nil || did != nil { + t.Fatalf("not Windows: %v, did %q", err, did) + } +} diff --git a/internal/provider/codex_app_server.go b/internal/provider/codex_app_server.go index fbce7425c..a7eb64a59 100644 --- a/internal/provider/codex_app_server.go +++ b/internal/provider/codex_app_server.go @@ -51,6 +51,62 @@ import ( // itself (its model pick) is in route, or a pick would restart it. var CodexAppRoute func() (route string, out, known bool) +// An app-server ended is not yet one started in its place. The app starts +// another only once it has read the end of the old one's stdout and seen +// it exit (its StdioConnection closes on both, ChatGPT.exe 26.1021's +// app.asar). On Windows every process the app-server started inherits +// that stdout (Rust's Command creates children with bInheritHandles), so +// an MCP server or tool command left running after it holds the pipe +// open: the app never sees it close, starts no other, and every send says +// "Codex app-server process is not available" until Codex is quit and +// opened again (蛋仔 on Discord, 10-30; reproduced on the Windows box +// with codex 0.164's app-server and an MCP server that outlived it: its +// stdout ended only when the MCP server did). So once the ones ended are +// gone, magpie waits codexAppBackWait for a new one; when none comes +// while the app still runs, it has the agent package reopen the app +// (CodexAppReopen), and says it is stuck when that can't be done. +// +// CodexAppOpen, set by the agent package, says whether the Codex desktop +// app runs here; known false when that can't be told. CodexAppReopen +// quits it and opens it again, erring where magpie doesn't (macOS, where +// a reopen opens a new window: the user does it). +var ( + CodexAppOpen func(ctx context.Context) (open, known bool) + CodexAppReopen func(ctx context.Context) error + // codexAppBackWait is how long after the ended app-servers are gone a + // new one has to start: the app starts one within ~1.5s of the old + // one's end, hidden in the tray too (its own logs on the Windows box, + // 10-27 to 10-29) + codexAppBackWait = 30 * time.Second +) + +// codexAppGotNone is what codexAppStep does when no app-server started in +// place of the ones it ended: nothing when the app was quit meanwhile (it +// starts one as it opens), else reopen it. stuck says it runs with none +// and wasn't reopened: the user quits it and opens it again. +func codexAppGotNone(ctx context.Context) (stuck bool) { + if open, known := codexAppOpenNow(ctx); known && !open { + return false + } + if CodexAppReopen == nil { + return true + } + if err := CodexAppReopen(ctx); err != nil { + log.Printf("codex: the Codex app started no app-server in place of the one magpie ended; reopening it: %v", err) + return true + } + log.Printf("codex: the Codex app started no app-server in place of the one magpie ended; reopened it") + return false +} + +// codexAppOpenNow is CodexAppOpen, unknown while it isn't set. +func codexAppOpenNow(ctx context.Context) (open, known bool) { + if CodexAppOpen == nil { + return false, false + } + return CodexAppOpen(ctx) +} + // codexAppEvery is how often KeepCodexAppOnItsProvider looks; codexAppIdle // how long after Codex's last request through magpie a turn counts ended // (a tool runs between two of a turn's requests); codexAppTries how often @@ -66,6 +122,16 @@ var ( // whose app-server died leaves one open for good. const codexTurnWindow = 30 * time.Minute +// codexTurnStuckAfter is how long a turn left open on an app-server whose +// account was used up has to have written nothing to Codex's sessions, +// with no Codex request through magpie either, before it counts stuck and +// the app-server is restarted past it. Such a turn can't go on: its next +// request is refused on that account, and when quota ran out mid-turn +// the app sat on it and greyed every thread until restarted (蛋仔 on +// Discord). A tool still running in it loses only a reply that account +// would refuse. +var codexTurnStuckAfter = 2 * time.Minute + // codexTurnSlack is how much earlier than the app-servers' start a turn's // timestamp may be and still count as theirs: the two clocks are read by // different programs. @@ -92,9 +158,10 @@ var ( } return out, nil } - endCodexAppServer = proc.End - codexTurnRunning = func(home string, now, since time.Time) bool { return codexTurnOpen(home, now, since) } - codexServerStart = proc.Started + endCodexAppServer = proc.End + codexTurnRunning = func(home string, now, since time.Time) bool { return codexTurnOpen(home, now, since) } + codexSessionsQuiet = func(home string, now time.Time, d time.Duration) bool { return codexSessionsQuietFor(home, now, d) } + codexServerStart = proc.Started ) // codexServersSince is when the oldest of the app-servers pids started: a @@ -173,6 +240,13 @@ var codexApp struct { // switched: Codex's ChatGPT account changed since the app-servers were // last listed (codexAppAccountSwitched) switched bool + // spent: the switch was off an account used up (SwitchWhenSpent), so a + // turn the app-servers left open can't be served by them any more + spent bool + // ended: the app-servers ended and no new one seen since, and by when + // one has to start (codexAppBackWait after the last end) + ended map[int]bool + backBy time.Time } // CodexAppStuck is whether a Codex app is left on the provider it started @@ -208,6 +282,16 @@ func codexAppAccountSwitched() { c.switched = true } +// 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() { + c := &codexApp + c.Lock() + defer c.Unlock() + c.switched, c.spent = true, true +} + // KeepCodexAppOnItsProvider runs codexAppStep every codexAppEvery till // ctx ends. busy says how many of Codex's requests are in flight through // magpie and when the last ended. @@ -266,7 +350,7 @@ func codexAppStep(ctx context.Context, now time.Time, busy func() (int, time.Tim c.Unlock() } c.Lock() - n := len(c.stale) + n := len(c.stale) + len(c.ended) c.Unlock() if n == 0 { return nil @@ -284,15 +368,49 @@ func codexAppStep(ctx context.Context, now time.Time, busy func() (int, time.Tim c.Lock() for p := range c.stale { if !running[p] { - delete(c.stale, p) // it read the provider afresh as it started + // gone: the one the app starts in its place reads the + // provider afresh, once it starts (c.ended) + delete(c.stale, p) + } + } + none := false + if len(c.ended) > 0 { + // any other app-server running serves the app; one ended and + // still running is waited for, and the wait counts from its end + back, left := false, false + for _, p := range pids { + back = back || !c.ended[p] + left = left || c.ended[p] + } + switch { + case back: + c.ended = nil + case left: + c.backBy = now.Add(codexAppBackWait) + case !now.Before(c.backBy): + c.ended, none = nil, true } } n = len(c.stale) c.Unlock() - if n == 0 { + if none { + if codexAppGotNone(ctx) { + c.Lock() + c.stuck = true + c.Unlock() + } return nil } - if inFlight, last := busy(); inFlight > 0 || now.Sub(last) < codexAppIdle { + if n == 0 { + c.Lock() + if len(c.ended) == 0 { + c.spent = false + } + c.Unlock() + return nil + } + inFlight, last := busy() + if inFlight > 0 || now.Sub(last) < codexAppIdle { return nil } c.Lock() @@ -300,9 +418,13 @@ func codexAppStep(ctx context.Context, now time.Time, busy func() (int, time.Tim for p := range c.stale { stale = append(stale, p) } + spent := c.spent c.Unlock() if codexTurnRunning(home, now, codexServersSince(stale)) { - return nil + if !spent || now.Sub(last) < codexTurnStuckAfter || !codexSessionsQuiet(home, now, codexTurnStuckAfter) { + return nil + } + log.Printf("codex: a Codex turn left open on the used-up account has done nothing for %s; restarting the Codex app's app-server past it", codexTurnStuckAfter) } var ended []int c.Lock() @@ -321,6 +443,10 @@ func codexAppStep(ctx context.Context, now time.Time, busy func() (int, time.Tim continue } ended = append(ended, p) + if c.ended == nil { + c.ended = map[int]bool{} + } + c.ended[p], c.backBy = true, now.Add(codexAppBackWait) } return ended } @@ -358,6 +484,34 @@ func codexTurnOpen(home string, now, since time.Time) bool { return open } +// codexSessionsQuietFor is whether no Codex session file under home was +// written in the last d. A sessions folder that can't be read counts as +// written: a turn cut short costs more than a restart a little later. +func codexSessionsQuietFor(home string, now time.Time, d time.Duration) bool { + quiet := true + err := filepath.WalkDir(filepath.Join(home, "sessions"), func(path string, e fs.DirEntry, err error) error { + if err != nil { + if errors.Is(err, fs.ErrNotExist) { + return nil + } + return err + } + if e.IsDir() || !strings.HasSuffix(e.Name(), ".jsonl") { + return nil + } + info, err := e.Info() + if err != nil { + return err + } + if now.Sub(info.ModTime()) < d { + quiet = false + return fs.SkipAll + } + return nil + }) + return quiet && err == nil +} + // sessionTurnTail is how much of a session file's end sessionTurnOpen reads. const sessionTurnTail = 512 << 10 @@ -419,7 +573,8 @@ var codexAppGoneWait = 10 * time.Second // stay as they are. The Agents row's Restart quit the app and opened it // again, which opened a new window (yoshi037070 on Discord, 10-27). An // app-server another program runs from the bundle (--listen) is left -// alone. It waits until the ones ended are gone, and errs when none ran. +// alone. It waits until the ones ended are gone and the app has started +// another (codexAppBackWait), and errs when none ran or none started. func RestartCodexApp(ctx context.Context, bundle string) error { ps, err := listProcesses(ctx) if err != nil { @@ -439,19 +594,54 @@ func RestartCodexApp(ctx context.Context, bundle string) error { if len(ended) == 0 { return errors.New("the Codex app's app-server isn't running") } + gone, back, err := codexAppBack(ctx, func(ctx context.Context) ([]int, error) { + ps, err := listProcesses(ctx) + var pids []int + for _, p := range ps { + if strings.HasPrefix(strings.TrimSpace(p.Args), in) && isCodexAppOwnServer(p.Args) { + pids = append(pids, p.PID) + } + } + return pids, err + }, ended) + switch { + case err != nil: + return err + case !gone: + return errors.New("the Codex app's app-server didn't end") + case !back: + return errors.New("the Codex app started no new app-server: quit it and open it again") + } + return nil +} + +// codexAppPoll is how often codexAppBack lists the app-servers. +var codexAppPoll = 200 * time.Millisecond + +// codexAppBack waits for the app-servers ended to be gone, for +// codexAppGoneWait, and then for another of list's to run, for +// codexAppBackWait: gone and back say which came. A listing that fails +// is tried again. +func codexAppBack(ctx context.Context, list func(context.Context) ([]int, error), ended []int) (gone, back bool, err error) { end := time.Now().Add(codexAppGoneWait) for { - ps, err := listProcesses(ctx) - if err == nil && !slices.ContainsFunc(ps, func(p proc.Process) bool { return slices.Contains(ended, p.PID) }) { - return nil + pids, err := list(ctx) + if err == nil { + left := slices.ContainsFunc(pids, func(p int) bool { return slices.Contains(ended, p) }) + if !gone && !left { + gone, end = true, time.Now().Add(codexAppBackWait) + } + if slices.ContainsFunc(pids, func(p int) bool { return !slices.Contains(ended, p) }) && !left { + return true, true, nil + } } if time.Now().After(end) { - return errors.New("the Codex app's app-server didn't end") + return gone, false, nil } select { case <-ctx.Done(): - return ctx.Err() - case <-time.After(200 * time.Millisecond): + return gone, false, ctx.Err() + case <-time.After(codexAppPoll): } } } @@ -461,7 +651,8 @@ func RestartCodexApp(ctx context.Context, bundle string) error { // a new one, which reads Codex's config as it is now. It waits up to wait // for a running Codex turn to end, and cuts none short: left says an // app-server was still on the old config when it gave up, or couldn't be -// ended, so the user quits and opens the app. +// ended, or that the app started none in its place and couldn't be +// reopened (codexAppGotNone), so the user quits and opens the app. func RestartCodexAppWhenIdle(ctx context.Context, wait time.Duration) (ended int, left bool, err error) { home := codexHome() lctx, cancel := context.WithTimeout(ctx, codexAppListWait) @@ -482,21 +673,33 @@ func RestartCodexAppWhenIdle(ctx context.Context, wait time.Duration) (ended int case <-time.After(codexAppEvery): } } + var gone []int for _, p := range pids { if err := endCodexAppServer(p); err != nil { log.Printf("codex: restarting the Codex app's app-server %d: %v", p, err) left = true continue } - ended++ + gone = append(gone, p) } - return ended, left, nil + if len(gone) > 0 { + went, back, err := codexAppBack(ctx, func(ctx context.Context) ([]int, error) { + lctx, cancel := context.WithTimeout(ctx, codexAppListWait) + defer cancel() + return codexAppServersOn(lctx, home) + }, gone) + switch { + case err != nil: + return len(gone), true, err + case !went: + left = true + case !back: + left = left || codexAppGotNone(ctx) + } + } + return len(gone), left, nil } -// codexAppBackWait is how long RestartSwitchedCodexApp waits for the Codex -// app to start a new app-server after the old one ended; a var for tests. -var codexAppBackWait = 20 * time.Second - // What RestartSwitchedCodexApp found when it couldn't restart the app's // app-server; the agent package says each in the reader's language. var ( @@ -574,7 +777,14 @@ func RestartSwitchedCodexApp(ctx context.Context) error { if err != nil { return err } - return ErrCodexAppNotBack + // the Windows app whose old app-server's stdout is held open + // starts none till it is quit and opened again (codexAppGotNone) + if open, known := codexAppOpenNow(ctx); known && !open { + return ErrCodexAppGone + } + if codexAppGotNone(ctx) { + return ErrCodexAppNotBack + } } DismissCodexApp() return nil diff --git a/internal/provider/codex_app_server_test.go b/internal/provider/codex_app_server_test.go index 3349dc6bb..4c42813e7 100644 --- a/internal/provider/codex_app_server_test.go +++ b/internal/provider/codex_app_server_test.go @@ -25,24 +25,39 @@ type codexAppStub struct { listErr error endErr error turnOpen bool - ended []int - // next: the app-server the app starts after one is ended - next int + // written: a Codex session file was written in the last + // codexTurnStuckAfter + written bool + ended []int + // next: the app-server the app starts after one is ended; none when + // noNext (its stdout held open, the Windows app starts no other) + next int + noNext bool } func stubCodexApp(t *testing.T) *codexAppStub { t.Helper() s := &codexAppStub{known: true, next: 100} oldOn, oldList, oldEnd, oldTurn := CodexAppRoute, codexAppServersOn, endCodexAppServer, codexTurnRunning - t.Cleanup(func() { - CodexAppRoute, codexAppServersOn, endCodexAppServer, codexTurnRunning = oldOn, oldList, oldEnd, oldTurn + oldOpen, oldReopen, oldQuiet := CodexAppOpen, CodexAppReopen, codexSessionsQuiet + reset := func() { codexApp.Lock() codexApp.seen, codexApp.route, codexApp.stale, codexApp.stuck, codexApp.switched = false, "", nil, false, false + codexApp.ended, codexApp.backBy, codexApp.spent = nil, time.Time{}, false codexApp.Unlock() + } + t.Cleanup(func() { + CodexAppRoute, codexAppServersOn, endCodexAppServer, codexTurnRunning = oldOn, oldList, oldEnd, oldTurn + CodexAppOpen, CodexAppReopen, codexSessionsQuiet = oldOpen, oldReopen, oldQuiet + reset() }) - codexApp.Lock() - codexApp.seen, codexApp.route, codexApp.stale, codexApp.stuck, codexApp.switched = false, "", nil, false, false - codexApp.Unlock() + reset() + // the app as tests find it: open, and never reopened + CodexAppOpen = func(context.Context) (bool, bool) { return true, true } + CodexAppReopen = func(context.Context) error { + t.Error("the Codex app reopened") + return errors.New("not in this test") + } CodexAppRoute = func() (string, bool, bool) { r := s.route if s.on { @@ -63,12 +78,17 @@ func stubCodexApp(t *testing.T) *codexAppStub { s.ended = append(s.ended, pid) // the app starts another app-server, which reads the provider anew if i := slices.Index(s.running, pid); i >= 0 { - s.running[i] = s.next - s.next++ + if s.noNext { + s.running = slices.Delete(s.running, i, i+1) + } else { + s.running[i] = s.next + s.next++ + } } return nil } codexTurnRunning = func(string, time.Time, time.Time) bool { return s.turnOpen } + codexSessionsQuiet = func(string, time.Time, time.Duration) bool { return !s.written } return s } @@ -576,13 +596,22 @@ func TestRestartCodexAppEndsOnlyItsServer(t *testing.T) { {PID: 5, Args: "/opt/homebrew/bin/codex app-server"}, {PID: 6, Args: bundle + "/Contents/Resources/codex exec-server --remote x"}, } - oldList, oldEnd, oldWait := listProcesses, endCodexAppServer, codexAppGoneWait - t.Cleanup(func() { listProcesses, endCodexAppServer, codexAppGoneWait = oldList, oldEnd, oldWait }) + oldList, oldEnd, oldWait, oldBack, oldPoll := listProcesses, endCodexAppServer, codexAppGoneWait, codexAppBackWait, codexAppPoll + t.Cleanup(func() { + listProcesses, endCodexAppServer, codexAppGoneWait, codexAppBackWait, codexAppPoll = oldList, oldEnd, oldWait, oldBack, oldPoll + }) + codexAppPoll = time.Millisecond listProcesses = func(context.Context) ([]proc.Process, error) { return slices.Clone(ps), nil } var ended []int + respawn := true endCodexAppServer = func(pid int) error { ended = append(ended, pid) - ps = slices.DeleteFunc(ps, func(p proc.Process) bool { return p.PID == pid }) + i := slices.IndexFunc(ps, func(p proc.Process) bool { return p.PID == pid }) + if respawn { + ps[i].PID += 100 // the app starts another + } else { + ps = slices.Delete(ps, i, i+1) + } return nil } if err := RestartCodexApp(context.Background(), bundle); err != nil { @@ -592,6 +621,14 @@ func TestRestartCodexAppEndsOnlyItsServer(t *testing.T) { t.Fatalf("ended %v, want only the app's own app-server 2", ended) } + // gone, and the app started no other (its stdout held open): said, + // for the user to quit and open it, never taken as done + respawn, ended = false, nil + codexAppBackWait = 50 * time.Millisecond + if err := RestartCodexApp(context.Background(), bundle); err == nil || !slices.Equal(ended, []int{102}) { + t.Fatalf("no app-server came back: %v, ended %v", err, ended) + } + // none running: said ended = nil if err := RestartCodexApp(context.Background(), "/Applications/Other.app"); err == nil || len(ended) > 0 { @@ -627,6 +664,25 @@ func TestRestartCodexAppWhenIdle(t *testing.T) { if n, left, err := RestartCodexAppWhenIdle(context.Background(), time.Second); n != 2 || left || err != nil || !slices.Equal(s.ended, []int{7, 8}) { t.Fatalf("ended %v (%d), left %v, %v", s.ended, n, left, err) } + + // none started in their place: the app is reopened, and said left + // when it can't be + oldBack, oldPoll := codexAppBackWait, codexAppPoll + t.Cleanup(func() { codexAppBackWait, codexAppPoll = oldBack, oldPoll }) + codexAppBackWait, codexAppPoll = 20*time.Millisecond, time.Millisecond + s.noNext = true + reopened := 0 + CodexAppReopen = func(context.Context) error { reopened++; return nil } + if n, left, err := RestartCodexAppWhenIdle(context.Background(), time.Second); n != 2 || left || err != nil || reopened != 1 { + t.Fatalf("none came back, reopened: %d %v %v, reopened %d times", n, left, err, reopened) + } + s.running = []int{9} + CodexAppReopen = func(context.Context) error { return errors.New("not here") } + if _, left, _ := RestartCodexAppWhenIdle(context.Background(), time.Second); !left { + t.Fatal("none came back and the app not reopened: not said") + } + + s.running = []int{10} s.endErr = proc.ErrDenied if _, left, _ := RestartCodexAppWhenIdle(context.Background(), time.Second); !left { t.Fatal("an app-server not ended isn't said") @@ -705,3 +761,167 @@ func TestCodexAppSwitchRestartsTheAppsOwnServers(t *testing.T) { t.Fatalf("the new app-servers read the new account as they started: ended %v", got) } } + +// The Windows Codex app said "Codex app-server process is not available" +// on every send after magpie switched its account, until Codex was quit +// and opened again (蛋仔 on Discord, 10-30): magpie ended its app-server +// and took the old one gone as the switch done, but the app starts +// another only once the old one's stdout ends, and a process that +// app-server started holds that open on Windows. Once the ones ended are +// gone, a new one has to start within codexAppBackWait; when none does +// and the app still runs, the app is reopened, and said stuck when it +// can't be. +func TestCodexAppReopenedWhenNoServerComesBack(t *testing.T) { + signIn(t) + s := stubCodexApp(t) + s.noNext = true + open, reopened := true, 0 + var reopenErr error + CodexAppOpen = func(context.Context) (bool, bool) { return open, true } + CodexAppReopen = func(context.Context) error { + reopened++ + if reopenErr != nil { + return reopenErr + } + s.running = []int{500} // the app opened again, with its own + return nil + } + start := time.Now() + idle := func() (int, time.Time) { return 0, start.Add(-time.Minute) } + step := func(at time.Duration) []int { return codexAppStep(context.Background(), start.Add(at), idle) } + end := func(at time.Duration) { + t.Helper() + s.on = !s.on // a route change, as a switch is + if got := step(at); len(got) != 1 { + t.Fatalf("ended %v, want the one app-server", got) + } + } + + s.running = []int{60} + step(0) + end(0) + if step(codexAppBackWait / 2); reopened != 0 { + t.Fatal("reopened before a new app-server had its time") + } + if step(codexAppBackWait); reopened != 1 || CodexAppStuck() { + t.Fatalf("no app-server came back: reopened %d times, stuck %v", reopened, CodexAppStuck()) + } + if step(2 * codexAppBackWait); reopened != 1 { + t.Fatalf("the reopened app's app-server: reopened %d times", reopened) + } + + // the app started another in time: nothing more + s.noNext = false + end(3 * codexAppBackWait) + if step(5 * codexAppBackWait); reopened != 1 || CodexAppStuck() { + t.Fatalf("a new app-server started: reopened %d times, stuck %v", reopened, CodexAppStuck()) + } + + // one ended that takes its time to go: the wait counts from its end + s.noNext = true + slow := endCodexAppServer + endCodexAppServer = func(pid int) error { s.ended = append(s.ended, pid); return nil } + end(6 * codexAppBackWait) + endCodexAppServer = slow + if step(7*codexAppBackWait + time.Second); reopened != 1 { + t.Fatal("reopened while the one ended still ran") + } + s.running = nil + if step(8 * codexAppBackWait); reopened != 1 { + t.Fatal("reopened as the one ended went") + } + if step(8*codexAppBackWait + codexAppBackWait + 2*time.Second); reopened != 2 { + t.Fatalf("none came back after it went: reopened %d times", reopened) + } + + // quit meanwhile: it starts one as it opens + s.running = []int{600} + end(10 * codexAppBackWait) + open = false + if step(12 * codexAppBackWait); reopened != 2 || CodexAppStuck() { + t.Fatalf("the app quit: reopened %d times, stuck %v", reopened, CodexAppStuck()) + } + + // not reopened (macOS, or the reopen failed): said stuck + open, reopenErr = true, errors.New("magpie doesn't reopen it here") + s.running = []int{700} + end(13 * codexAppBackWait) + if step(15 * codexAppBackWait); reopened != 3 || !CodexAppStuck() { + t.Fatalf("not reopened: reopened %d times, stuck %v", reopened, CodexAppStuck()) + } +} + +// When quota ran out in the middle of a task the Codex app sat on it and +// had to be restarted (蛋仔 on Discord): the turn stays open in Codex's +// sessions, and an open turn held the restart for up to codexTurnWindow. +// After a switch off a used-up account, a turn that has written nothing +// and sent nothing through magpie for codexTurnStuckAfter is stuck, and +// the app-server is restarted past it. A switch for any other reason, or +// a turn still writing or sending, holds it as before. +func TestCodexAppServerRestartedPastATurnStuckOnTheSpentAccount(t *testing.T) { + signIn(t) + s := stubCodexApp(t) + now := time.Now() + quiet := func() (int, time.Time) { return 0, now.Add(-codexTurnStuckAfter - time.Second) } + step := func(busy func() (int, time.Time)) []int { return codexAppStep(context.Background(), now, busy) } + + s.running, s.turnOpen = []int{60}, true + step(quiet) + codexAppAccountSwitched() // switched back to an account with room + if got := step(quiet); got != nil { + t.Fatalf("a turn open after a switch not for spend: ended %v", got) + } + + codexAppSpentSwitch() + if got := step(func() (int, time.Time) { return 0, now.Add(-time.Minute) }); got != nil { + t.Fatalf("Codex's last request through magpie a minute ago: ended %v", got) + } + s.written = true + if got := step(quiet); got != nil { + t.Fatalf("the turn still writing to its session: ended %v", got) + } + s.written = false + if got := step(quiet); !slices.Equal(got, []int{60}) { + t.Fatalf("a turn stuck on the used-up account: ended %v, want [60]", got) + } + // the app's next app-server is on the new account: nothing more ended, + // and the spend is forgotten once it is back + if got := step(quiet); got != nil { + t.Fatalf("after the new app-server: ended %v", got) + } + codexApp.Lock() + spent := codexApp.spent + codexApp.Unlock() + if spent { + t.Fatal("the spend is still held after the app-server came back") + } +} + +// codexSessionsQuietFor reads the sessions' write times: a file written +// within d is not quiet, an older one or none is, and a sessions folder +// that can't be read is not. +func TestCodexSessionsQuietFor(t *testing.T) { + home := t.TempDir() + now := time.Now() + if !codexSessionsQuietFor(home, now, time.Minute) { + t.Fatal("no sessions folder: not quiet") + } + dir := filepath.Join(home, "sessions", "2026", "10", "30") + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + f := filepath.Join(dir, "rollout-x.jsonl") + if err := os.WriteFile(f, []byte("{}\n"), 0o644); err != nil { + t.Fatal(err) + } + if codexSessionsQuietFor(home, now, time.Minute) { + t.Fatal("a session written just now counts quiet") + } + old := now.Add(-5 * time.Minute) + if err := os.Chtimes(f, old, old); err != nil { + t.Fatal(err) + } + if !codexSessionsQuietFor(home, now, time.Minute) { + t.Fatal("a session last written 5 minutes ago: not quiet") + } +} diff --git a/internal/provider/codex_app_switch_restart_test.go b/internal/provider/codex_app_switch_restart_test.go index 14c5d767a..7c94bc03f 100644 --- a/internal/provider/codex_app_switch_restart_test.go +++ b/internal/provider/codex_app_switch_restart_test.go @@ -60,14 +60,33 @@ func TestRestartSwitchedCodexApp(t *testing.T) { t.Fatalf("one that stays: %v", err) } - // ended, and the app starts none: said, not success + // ended, and the app starts none: said, not success, where the app + // can't be reopened (macOS: the user does it) endCodexAppServer = func(pid int) error { s.running = slices.DeleteFunc(s.running, func(p int) bool { return p == pid }) return nil } - if err := RestartSwitchedCodexApp(ctx); !errors.Is(err, ErrCodexAppNotBack) { - t.Fatalf("none back: %v", err) + reopened := 0 + CodexAppReopen = func(context.Context) error { reopened++; return errors.New("not here") } + s.running = []int{7} + if err := RestartSwitchedCodexApp(ctx); !errors.Is(err, ErrCodexAppNotBack) || reopened != 1 { + t.Fatalf("none back: %v, reopened %d", err, reopened) } + // the Windows app, whose old app-server's stdout a leftover child + // holds open, starts none till it is quit and opened again (蛋仔 on + // Discord): reopened, it is on the new account + CodexAppReopen = func(context.Context) error { reopened++; return nil } + s.running = []int{7} + if err := RestartSwitchedCodexApp(ctx); err != nil || reopened != 2 { + t.Fatalf("none back on Windows: %v, reopened %d", err, reopened) + } + // the user quit the app meanwhile: it opens on the new account + CodexAppOpen = func(context.Context) (bool, bool) { return false, true } + s.running = []int{7} + if err := RestartSwitchedCodexApp(ctx); !errors.Is(err, ErrCodexAppGone) || reopened != 2 { + t.Fatalf("app quit: %v, reopened %d", err, reopened) + } + CodexAppOpen = func(context.Context) (bool, bool) { return true, true } // the listing fails: unknown, not success s.running, s.listErr = []int{9}, errors.New("ps failed") @@ -170,10 +189,11 @@ func TestRestartSwitchedCodexAppReal(t *testing.T) { t.Fatalf("app-server %d after the restart, first %d: want a new one", now, first) } - // the app doesn't start another: said + // the app doesn't start another, and can't be reopened: said f.mu.Lock() f.back = false f.mu.Unlock() + CodexAppReopen = func(context.Context) error { return errors.New("not here") } if err := RestartSwitchedCodexApp(context.Background()); !errors.Is(err, ErrCodexAppNotBack) { t.Fatalf("none back: %v", err) } diff --git a/internal/provider/codex_daemon.go b/internal/provider/codex_daemon.go index 8ab3d947a..ed957645c 100644 --- a/internal/provider/codex_daemon.go +++ b/internal/provider/codex_daemon.go @@ -238,11 +238,26 @@ func recheckLeft() { if findCodexDaemon(ps, codexHome()) != codexDaemonLeft.pid { codexDaemonLeft = leftDaemon{} } - if findCodexApp(ps) != codexAppLeft.pid { + // one that went with none in its place left an app still on nothing + // new while it runs (codexAppGotNone): the app read no sign-in + // afresh, so it is still said + if p := findCodexApp(ps); p != codexAppLeft.pid && (p != 0 || !codexAppStillOpen()) { codexAppLeft = leftDaemon{} } } +// codexAppStillOpen is whether the Codex desktop app is known to run +// (CodexAppOpen), for an app-server gone with none in its place. +func codexAppStillOpen() bool { + if CodexAppOpen == nil { + return false + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + open, known := CodexAppOpen(ctx) + return open && known +} + // DismissCodexDaemon stops saying the app-server is on another account. func DismissCodexDaemon() { codexDaemonMu.Lock() diff --git a/internal/provider/codex_daemon_test.go b/internal/provider/codex_daemon_test.go index 1f6bb326a..a6bbd61db 100644 --- a/internal/provider/codex_daemon_test.go +++ b/internal/provider/codex_daemon_test.go @@ -577,6 +577,55 @@ func TestCodexAppStale(t *testing.T) { } } +// An app-server that went with none started in its place left the app +// with nothing that read the new sign-in (蛋仔 on Discord, Windows: "Codex +// app-server process is not available" till Codex was reopened): while +// the app runs, that is still said; once it quits, or it starts another, +// it isn't. +func TestCodexAppStaleWhileNoServerCameBack(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + t.Setenv("USERPROFILE", t.TempDir()) + server, open := 60, true + oldList, oldOpen := listProcesses, CodexAppOpen + t.Cleanup(func() { + listProcesses, CodexAppOpen = oldList, oldOpen + DismissCodexDaemon() + DismissCodexApp() + codexApp.Lock() + codexApp.switched = false + codexApp.Unlock() + }) + listProcesses = func(context.Context) ([]proc.Process, error) { + if server == 0 { + return nil, nil + } + return []proc.Process{{PID: server, Args: codexWindowsAppServer}}, nil + } + CodexAppOpen = func(context.Context) (bool, bool) { return open, true } + recheck := func() { codexDaemonMu.Lock(); codexDaemonChecked = time.Time{}; codexDaemonMu.Unlock() } + DismissCodexApp() + + noteCodexSwitch("a@x", "b@x") + server = 0 // ended, and the app started none + recheck() + if got := CodexAppStale(); got != "a@x" { + t.Fatalf("app open with no app-server: got %q, want a@x", got) + } + open = false + recheck() + if got := CodexAppStale(); got != "" { + t.Fatalf("app quit: %q", got) + } + + open, server = true, 60 + noteCodexSwitch("a@x", "b@x") + server = 61 + recheck() + if got := CodexAppStale(); got != "" { + t.Fatalf("a new app-server: %q", got) + } +} + // The daemon magpie restarts runs with the login shell's proxy and PATH, // as one a terminal started would (guotianci6 on X): magpie opened from // the desktop has neither. diff --git a/internal/provider/codex_switch.go b/internal/provider/codex_switch.go index 4b05a683e..afe4191d2 100644 --- a/internal/provider/codex_switch.go +++ b/internal/provider/codex_switch.go @@ -340,6 +340,9 @@ func SwitchWhenSpent(ctx context.Context, agent string) (string, error) { setLoginReturn(agent, r) 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() + } } if agent == "codex" { if was := CodexAppStale(); was != "" { diff --git a/internal/provider/codex_switch_test.go b/internal/provider/codex_switch_test.go index 973718b11..34ceec5f1 100644 --- a/internal/provider/codex_switch_test.go +++ b/internal/provider/codex_switch_test.go @@ -60,9 +60,22 @@ func TestCodexSwitchedWhenUsedUp(t *testing.T) { if err := SetLoginOn("codex", "spare@example.com", true); err != nil { t.Fatal(err) } + t.Cleanup(func() { + codexApp.Lock() + codexApp.switched, codexApp.spent = false, false + codexApp.Unlock() + }) if to := switched(); to != "spare@example.com" { t.Fatalf("switched to %q", to) } + // the Codex app's app-server is restarted past a turn left stuck on + // the account used up (TestCodexAppServerRestartedPastATurnStuckOnTheSpentAccount) + codexApp.Lock() + spent := codexApp.spent + codexApp.Unlock() + if !spent { + t.Fatal("the switch off a used-up account isn't marked spent for the Codex app") + } var live codexAuth readJSON(filepath.Join(home, ".codex", "auth.json"), &live) if live.Tokens.RefreshToken != "r-spare" {