diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index e665915c0..e134dc1fb 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -91,7 +91,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`). 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`). 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`, `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, which is where its requests go (`model_provider`, `openai_base_url` and the magpie table's `base_url`; `codexAppRoute`, through the `provider.CodexAppRoute` hook): a Disconnect, a Connect, failover written or taken out. The model list is not part of it: neither `model_catalog_json` nor what the catalog holds. The catalog follows magpie's names and the effort new sessions start at, which the Codex app saves on each pick, and the ChatGPT app takes an ended app-server as a crash and relaunches, so a route that hashed the catalog (from lucis0116 on X until #4550) ended the app every few minutes (indekkusu141209 on X). A new list is read at the app's next launch or on the Agents row's Restart (`StaleCopies`) (`TestCodexEffortPickKeepsTheAppRunning`, `TestCodexAppRouteIgnoresARename`). 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`). An account switch restarts nothing, and neither the app nor the background daemon is said to be left on the old account (`CodexAppStale`, `CodexDaemonStale`, the CLI's switch line), while the provider Codex's config.toml names takes no ChatGPT account (`provider.CodexNoAccount`, `codexNoAccount` in [`agents.go`](../../internal/agent/agents.go)): a top-level `model_provider` other than `openai` whose `[model_providers]` table doesn't say `requires_openai_auth = true`, such as magpie's with the user's own `false` (danzi002 on Discord). Codex then sends the table's key and its app-server reads no account (codex-rs `account_state`, `resolve_provider_auth`); tried with codex-cli 0.165.0 in a sandbox `CODEX_HOME`: `account/read` and `getAuthStatus` said no account before and after auth.json was switched, and `codex exec` sent `Bearer` the table's key on both accounts. A route change still restarts it, and so does a switch under a profile, the built-in provider, a provider with no table or a config that can't be read (`TestCodexNoAccountSwitchRestartsNothing`, `TestCodexNoAccountOfEachConfig`, `TestCodexNoAccountFollowsRequiresOpenAIAuth`). Until the reset the app's ChatGPT side is off (cloud tasks, its usage meter, Log out); the Agents row says so with the reset's time (`appOut` in `/api/state`, `CodexOutUntil`), and it all comes back at the reset. While the active account is held or a window is at 90% or more, its usage is read every minute rather than every five (`codexLookEvery`). `TestCodexAppServerRestartedEachWay`, `TestCodexAppServerRestartedOnDisconnect`, `TestCodexAppRouteFollowsConnectAndDisconnect`, `TestCodexEffortPickKeepsTheAppRunning`, `TestCodexAppRouteIgnoresARename`, `TestCodexAppServerUnknown`, `TestCodexAppServerStuck`, `TestCodexAppServersOnHome`, `TestCodexTurnOpen`, `TestCodexBusy`, `codex-app-out.test.cjs`. - Moving a field from one of magpie's models to another (the agent's own picker) is not drift. Moving it off magpie is. - Claude Desktop applying a configLibrary profile other than magpie's is not drift when that profile is a gateway profile for this magpie's gateway (`desktopAppliedGateway` in [`claudedesktop.go`](../../internal/agent/claudedesktop.go)): Desktop's "Import configuration" adds a file exported on another computer, magpie's profile there with the user's connectors (`managedMcpServers`), as a new entry under a random id (aa86222 on Discord). magpie keeps it applied on Reconnect and through Sync, and writes in it only `inferenceGatewayApiKey` (with a missing auth scheme) when the gateway would refuse its key (`desktopKeyApplied`; magpie's own keys count as taken, `desktopKeyTaken`). A profile for another gateway, CC Switch's among them, is still drift, and Reconnect applies magpie's. The first switch-on still starts magpie's profile from an applied one (#2035). `TestClaudeDesktopImportedProfileIsOnMagpie`. - Claude Desktop 4.4212 (10-29) seals the secrets of its configLibrary profiles at rest: at every start it writes `inferenceGatewayApiKey` (and every other string secret its schema drops on export) back as `__sealed__:v1:` + base64 of `{"configLibrary":{"key":…,"value":…}}` behind `anthropic.claude.crossProfileSecret.v1:`, protected with the user's DPAPI on Windows (entropy `anthropic.claude.crossProfileSecret.v1`, claude-native's `userDpapiProtect`) and Electron's safeStorage (the Keychain) on macOS, and it sends the gateway the key as it was. `desktopOpen` ([`desktopseal.go`](../../internal/agent/desktopseal.go)) reads the key as Desktop does: on Windows it opens the seal (`desktopUnprotect`, `CryptUnprotectData`, never prompting) and judges what is in it; a seal it can't open (macOS, another user's) is unknown, so Check doesn't call it changed and `desktopKeyApplied` doesn't write over it. Before this the key read as changed after every Desktop start and Reconnect only wrote it in the clear for Desktop to seal again (a Windows user on Discord). A key in the clear that isn't one the gateway takes, a missing key and another address are still drift (`TestClaudeDesktopSealedKeyIsNotChanged`, `TestClaudeDesktopImportedSealedKeyStays`, `TestClaudeDesktopSealedKeyOpened` on Windows). diff --git a/internal/agent/agents.go b/internal/agent/agents.go index 9dae5c302..a42a09595 100644 --- a/internal/agent/agents.go +++ b/internal/agent/agents.go @@ -70,9 +70,17 @@ func init() { // codexAppRoute is where Codex's config sends it, as the app-server reads // it at its start: the keys magpie writes for that, never one the Codex -// app writes itself (model); and whether magpie is Codex's provider for -// its used-up ChatGPT account (AppOut). Not known when Codex's config -// can't be read. +// app writes itself (model, model_reasoning_effort); and whether magpie +// is Codex's provider for its used-up ChatGPT account (AppOut). Not known +// when Codex's config can't be read. +// +// The model list (model_catalog_json, the file and what it holds) is not +// in it. A change of route ends the app's app-server, and the ChatGPT app +// takes that as a crash and relaunches. The catalog follows magpie's names +// and the effort new sessions start at, which the app saves on each pick, +// so a route that hashed it ended the app every few minutes +// (indekkusu141209 on X, #4550). A new list is read at the app's next +// launch, and the Agents row offers a Restart for it (StaleCopies). func codexAppRoute() (route string, out, known bool) { // asked every 3s for as long as magpie runs: the config looked at once // for its keys, not once for each (#1665) @@ -84,7 +92,7 @@ func codexAppRoute() (route string, out, known bool) { } out = a.AppOut != nil && a.AppOut() var b strings.Builder - for _, k := range []string{"model_provider", "openai_base_url", "model_catalog_json"} { + for _, k := range []string{"model_provider", "openai_base_url"} { v, _ := edit.GetTOMLTop(a.Path, k) b.WriteString(k + "=" + v + "\n") } @@ -94,15 +102,6 @@ func codexAppRoute() (route string, out, known bool) { // has its ChatGPT account at all (openaiAuth in codex.go): read as the // app-server starts, like the rest b.WriteString("magpie.requires_openai_auth=" + t["requires_openai_auth"] + "\n") - // and the list in that catalog, which the app-server also reads only - // as it starts: a provider or group renamed, or a model added, left - // the app on the names and models it started with (lucis0116 on X) - if c, _ := edit.GetTOMLTop(a.Path, "model_catalog_json"); c != "" { - if !filepath.IsAbs(c) { - c = filepath.Join(filepath.Dir(a.Path), c) - } - b.WriteString("catalog=" + codexCatalogTag(c) + "\n") - } if out { b.WriteString("out\n") } diff --git a/internal/agent/codex_app_route.go b/internal/agent/codex_app_route.go deleted file mode 100644 index d830ea2e7..000000000 --- a/internal/agent/codex_app_route.go +++ /dev/null @@ -1,45 +0,0 @@ -package agent - -import ( - "crypto/sha256" - "encoding/hex" - "os" - "sync" - "time" -) - -// codexCatalogTag stands for what the catalog file at path holds now, for -// codexAppRoute: a hash of its bytes, "" when it can't be read. The route -// is looked at every few seconds (provider.KeepCodexAppOnItsProvider) and -// the catalog holds each model's instructions, a few MB with many models, -// so the file is read again only when its size or time changed. A rewrite -// to the same bytes (a Connect writes it again) is the same tag, and -// restarts nothing. -func codexCatalogTag(path string) string { - st, err := os.Stat(path) - if err != nil { - return "" - } - c := &codexCatalogSeen - c.Lock() - defer c.Unlock() - if c.path == path && c.size == st.Size() && c.mod.Equal(st.ModTime()) { - return c.tag - } - b, err := os.ReadFile(path) - if err != nil { - return "" - } - sum := sha256.Sum256(b) - c.path, c.size, c.mod, c.tag = path, st.Size(), st.ModTime(), hex.EncodeToString(sum[:12]) - return c.tag -} - -// codexCatalogSeen is the last catalog codexCatalogTag read. -var codexCatalogSeen struct { - sync.Mutex - path string - size int64 - mod time.Time - tag string -} diff --git a/internal/agent/new_session_effort_test.go b/internal/agent/new_session_effort_test.go index 55cbdd12c..8fc65d1e6 100644 --- a/internal/agent/new_session_effort_test.go +++ b/internal/agent/new_session_effort_test.go @@ -100,6 +100,40 @@ func TestCodexNewSessionEffortLastsModelSwitch(t *testing.T) { } } +// An effort picked in the Codex app keeps the app running. The app saves +// it as model_reasoning_effort, the catalog's default_reasoning_level +// follows it (above), and the next sync rewrote the catalog. The route the +// app's app-server is ended on (codex_app_server.go) hashed the catalog's +// bytes, so each pick ended it a few minutes later, and the ChatGPT app +// read that as a crash and relaunched (indekkusu141209 on X, #4550). The +// route is where requests go, never the list: the app reads a new list at +// its next launch. +func TestCodexEffortPickKeepsTheAppRunning(t *testing.T) { + home, read := codexHome(t, "", "model_reasoning_effort = \"xhigh\"\n") + effortModels(t) + cx := codex(home) + if err := cx.Fields[0].Set("volc/all-five"); err != nil { + t.Fatal(err) + } + cat := filepath.Join(home, ".codex", "magpie-models.json") + listed, _ := os.ReadFile(cat) + before, _, known := codexAppRoute() + if !known { + t.Fatal("route not known") + } + // as the Codex app saves a pick of its own + if err := edit.SetTOMLTop(filepath.Join(home, ".codex", "config.toml"), edit.KV{Path: "model_reasoning_effort", Value: "low"}); err != nil { + t.Fatal(err) + } + SyncCatalog() + if now, _ := os.ReadFile(cat); string(now) == string(listed) { + t.Fatalf("the effort didn't reach the catalog, so this tests nothing:\n%s", read()) + } + if r, _, _ := codexAppRoute(); r != before { + t.Fatalf("an effort picked in the Codex app changed its route: its app-server is ended for it\n%s", read()) + } +} + // Grok Build: a model picked without the chosen level starts at its // nearest, not at Grok's default. func TestGrokNewSessionEffortLastsModelSwitch(t *testing.T) { diff --git a/internal/agent/rename_group_test.go b/internal/agent/rename_group_test.go index 6fbb1ade6..10cd7113c 100644 --- a/internal/agent/rename_group_test.go +++ b/internal/agent/rename_group_test.go @@ -70,26 +70,19 @@ func TestRenameGroupMovesTheAgentsOnIt(t *testing.T) { } } -// The Codex app's app-server reads its model catalog only as it starts, -// so the route it is restarted on (codex_app_server.go) follows what the -// catalog holds: a provider's name changed in magpie reached the file, and -// the app kept showing the old one (lucis0116 on X). The same bytes -// written again are no change. -func TestCodexAppRouteFollowsTheCatalog(t *testing.T) { +// A change to the list alone never restarts the Codex app's app-server: +// a provider renamed rewrites the catalog, and the app shows the new name +// at its next launch (TestCodexEffortPickKeepsTheAppRunning says why). +func TestCodexAppRouteIgnoresARename(t *testing.T) { home := syncHome(t) codexCat := filepath.Join(home, ".codex", "magpie-models.json") writeFile(t, filepath.Join(home, ".codex", "config.toml"), "model = \"relay/glm-4.6\"\nmodel_provider = \"magpie\"\nmodel_catalog_json = '"+codexCat+"'\n") writeFile(t, codexCat, `{"models":[]}`) SyncCatalog() - route := func() string { - t.Helper() - r, _, known := codexAppRoute() - if !known { - t.Fatal("route not known") - } - return r + before, _, known := codexAppRoute() + if !known { + t.Fatal("route not known") } - before := route() if !strings.Contains(readFile(codexCat), "GLM-4.6 · Relay") { t.Fatalf("catalog:\n%s", readFile(codexCat)) } @@ -100,15 +93,7 @@ func TestCodexAppRouteFollowsTheCatalog(t *testing.T) { if !strings.Contains(readFile(codexCat), "GLM-4.6 · Renamed") { t.Fatalf("catalog not rewritten:\n%s", readFile(codexCat)) } - renamed := route() - if renamed == before { - t.Fatal("a provider renamed left the Codex app's route as it was: its app-server keeps the old names") - } - // written again as it is (a Connect does): no restart for that - if err := writeOwnList(codexCat, []byte(readFile(codexCat))); err != nil { - t.Fatal(err) - } - if route() != renamed { - t.Error("the same catalog written again changed the route") + if r, _, _ := codexAppRoute(); r != before { + t.Fatal("a provider renamed changed the Codex app's route: its app-server is ended for a list") } } diff --git a/internal/provider/codex_app_server.go b/internal/provider/codex_app_server.go index eb1933ab1..000a8feee 100644 --- a/internal/provider/codex_app_server.go +++ b/internal/provider/codex_app_server.go @@ -40,15 +40,22 @@ import ( // sending to 127.0.0.1:3425 after Codex was disconnected (JiangLiuer222 on // X), so each such change restarts it the same way. // +// A change to the model list alone never does: the app takes an +// app-server's end as a crash and relaunches, and the list changes far +// more often than the route (an effort picked in the app, a provider +// renamed), which ended the app every few minutes (#4550). The app reads +// a new list at its next launch, or on the Agents row's Restart. +// // The app-server is ended as a clean exit (proc.End): the app reads any // other exit as a crash and shows it. // CodexAppRoute is set by the agent package: what in Codex's config the -// app-server reads as it starts and magpie writes (its provider, base URL -// and model list: route, compared, never parsed), and whether magpie is -// Codex's provider for its used-up ChatGPT account (out, AppOut); known -// false when Codex's config can't be read. Nothing the Codex app writes -// itself (its model pick) is in route, or a pick would restart it. +// app-server reads as it starts and magpie writes (its provider and base +// URL: route, compared, never parsed), and whether magpie is Codex's +// provider for its used-up ChatGPT account (out, AppOut); known false +// when Codex's config can't be read. Nothing the Codex app writes itself +// (its model or effort pick) and not the model list is in route, or a +// pick would restart it. var CodexAppRoute func() (route string, out, known bool) // CodexNoAccount is set by the agent package: whether the provider Codex's