diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index eb39e1325..ff7cecc2d 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -89,7 +89,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`). 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`). 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`. - 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 dda7f33e0..93413d4c9 100644 --- a/internal/agent/agents.go +++ b/internal/agent/agents.go @@ -52,6 +52,9 @@ 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 + // but not when Codex's account is switched while its provider takes + // no ChatGPT account: the app-server goes by none + provider.CodexNoAccount = codexNoAccount // 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 @@ -106,6 +109,37 @@ func codexAppRoute() (route string, out, known bool) { return b.String(), out, true } +// codexNoAccount is whether the provider Codex's config.toml names takes +// no ChatGPT account: a model_provider whose [model_providers] table +// doesn't say requires_openai_auth = true (magpie's with the user's own +// false, or magpie as the provider with no sign-in to keep). Codex then +// sends the table's own key and its app-server reads no account +// (codex-rs ModelProviderInfo::account_state, resolve_provider_auth), so +// switching the account in auth.json changes nothing a running Codex +// goes by. The built-in openai provider, a provider with no table here, a +// profile (which may name another provider) or a config that can't be +// read is false: those may go by the account. +func codexNoAccount() bool { + defer filememo.Hold()() + home, _ := homes() + a := codex(home) + if _, err := os.ReadFile(a.Path); err != nil { + return false + } + if p, _ := edit.GetTOMLTop(a.Path, "profile"); p != "" { + return false + } + id, _ := edit.GetTOMLTop(a.Path, "model_provider") + if id == "" || id == "openai" { + return false + } + t, err := edit.GetTOMLTable(a.Path, "model_providers."+id) + if err != nil || t == nil { + return false + } + return t["requires_openai_auth"] != "true" +} + // others are clients that reach the gateway without being agents magpie // sets up: known only by their requests, to be drawn with a logo. var others = []*Agent{ diff --git a/internal/agent/codex_noaccount_test.go b/internal/agent/codex_noaccount_test.go new file mode 100644 index 000000000..9ba985f4c --- /dev/null +++ b/internal/agent/codex_noaccount_test.go @@ -0,0 +1,88 @@ +package agent + +import ( + "os" + "path/filepath" + "testing" + + "github.com/yetone/magpie/internal/edit" +) + +// codexNoAccount says Codex's provider takes no ChatGPT account, so an +// account switch restarts nothing (danzi002 on Discord), only for a +// provider table without requires_openai_auth = true: magpie API beside a +// ChatGPT sign-in with room has magpie write true, and the Codex app keeps +// that account, so a switch there still restarts it. The user's own false +// stays through Sync and counts. +func TestCodexNoAccountFollowsRequiresOpenAIAuth(t *testing.T) { + home, read := codexHome(t, `{"tokens":{"access_token":"x","id_token":"x.e30.x"}}`, "") + path := filepath.Join(home, ".codex", "config.toml") + if codexNoAccount() { + t.Fatalf("Codex on its own ChatGPT sign-in takes no account:\n%s", read()) + } + cx := codex(home) + if err := cx.Field("login").Set("api"); err != nil { + t.Fatal(err) + } + if err := cx.Fields[0].Set("fake/m1"); err != nil { + t.Fatal(err) + } + if codexNoAccount() { + t.Fatalf("magpie API with requires_openai_auth = true takes no account:\n%s", read()) + } + if err := edit.SetTOMLKey(path, "model_providers."+magpieID, "requires_openai_auth", false); err != nil { + t.Fatal(err) + } + if err := cx.Sync(); err != nil { + t.Fatal(err) + } + if !codexNoAccount() { + t.Fatalf("the user's requires_openai_auth = false takes an account:\n%s", read()) + } + // a profile may name another provider: not known, so not none + if err := edit.SetTOMLTop(path, edit.KV{Path: "profile", Value: "work"}); err != nil { + t.Fatal(err) + } + if codexNoAccount() { + t.Fatalf("with a profile:\n%s", read()) + } +} + +// The provider's table decides it, whoever's it is; the built-in openai +// provider, one with no table and a config that can't be read don't +// count. +func TestCodexNoAccountOfEachConfig(t *testing.T) { + for _, c := range []struct { + name, config string + want bool + }{ + {"none", "", false}, + {"openai", "model_provider = \"openai\"\n", false}, + {"no table", "model_provider = \"ollama\"\n", false}, + {"magpie false", "model_provider = \"magpie\"\n[model_providers.magpie]\nbase_url = \"http://127.0.0.1:3425/v1\"\nrequires_openai_auth = false\n", true}, + {"magpie unset", "model_provider = \"magpie\"\n[model_providers.magpie]\nbase_url = \"http://127.0.0.1:3425/v1\"\n", true}, + {"magpie true", "model_provider = \"magpie\"\n[model_providers.magpie]\nbase_url = \"http://127.0.0.1:3425/v1\"\nrequires_openai_auth = true\n", false}, + {"theirs false", "model_provider = \"relay\"\n[model_providers.relay]\nbase_url = \"https://relay.example/v1\"\nrequires_openai_auth = false\n", true}, + {"table only", "[model_providers.magpie]\nrequires_openai_auth = false\n", false}, + } { + t.Run(c.name, func(t *testing.T) { + codexHome(t, `{"tokens":{"access_token":"x","id_token":"x.e30.x"}}`, c.config) + if got := codexNoAccount(); got != c.want { + t.Fatalf("got %v, want %v", got, c.want) + } + }) + } + t.Run("unreadable", func(t *testing.T) { + home, _ := codexHome(t, "", "model_provider = \"magpie\"\n[model_providers.magpie]\nrequires_openai_auth = false\n") + path := filepath.Join(home, ".codex", "config.toml") + if err := os.Remove(path); err != nil { + t.Fatal(err) + } + if err := os.Mkdir(path, 0o700); err != nil { + t.Fatal(err) + } + if codexNoAccount() { + t.Fatal("a config that can't be read takes no account") + } + }) +} diff --git a/internal/cli/accounts_cli.go b/internal/cli/accounts_cli.go index ae818cc91..a91444b36 100644 --- a/internal/cli/accounts_cli.go +++ b/internal/cli/accounts_cli.go @@ -208,6 +208,12 @@ func accountsCmd(args []string) error { fmt.Println(green.Render("✓"), "magpie now uses", args[3], "for", id) return nil } + if id == "codex" && provider.CodexNoAccount != nil && provider.CodexNoAccount() { + // Codex's provider takes no ChatGPT account: nothing running + // goes by it, and nothing needs a restart + fmt.Println(green.Render("✓"), id, "is now signed in as", args[3], muted.Render("· Codex's provider takes no ChatGPT account, so nothing needs restarting")) + return nil + } fmt.Println(green.Render("✓"), id, "is now signed in as", args[3], muted.Render("· sessions already running keep their account until restarted")) if id == "codex" { if was := provider.CodexDaemonStale(); was != "" { diff --git a/internal/provider/codex_app_noaccount_test.go b/internal/provider/codex_app_noaccount_test.go new file mode 100644 index 000000000..d87e7a6ae --- /dev/null +++ b/internal/provider/codex_app_noaccount_test.go @@ -0,0 +1,87 @@ +package provider + +import ( + "context" + "slices" + "testing" + "time" + + "github.com/yetone/magpie/internal/proc" +) + +// With Codex on a provider that takes no ChatGPT account (magpie's table +// with requires_openai_auth = false, danzi002 on Discord: "requires_openai_auth +// = false 的时候就不应该重启 codex 了"), the app-server sends the +// provider's own key and reads no account at all, so switching the account +// in auth.json changes nothing it goes by: neither a switch nor a switch +// off a spent account restarts the Codex app's app-server, and neither the +// app nor the background daemon is said to be left on the old account. A +// route change still restarts it, and with the provider taking the account +// again a switch does too. +func TestCodexNoAccountSwitchRestartsNothing(t *testing.T) { + signIn(t) + t.Setenv("HOME", t.TempDir()) + t.Setenv("USERPROFILE", t.TempDir()) + s := stubCodexApp(t) + old, oldHome, oldNo := listProcesses, processCodexHome, CodexNoAccount + t.Cleanup(func() { + listProcesses, processCodexHome, CodexNoAccount = old, oldHome, oldNo + DismissCodexDaemon() + DismissCodexApp() + }) + processCodexHome = func(int) (string, bool) { return "", false } + listProcesses = func(context.Context) ([]proc.Process, error) { + ps := []proc.Process{{PID: 9, Args: "codex app-server --managed-daemon"}} + for _, p := range s.running { + ps = append(ps, proc.Process{PID: p, Args: codexWindowsAppServer}) + } + return ps, nil + } + noAccount := true + CodexNoAccount = func() bool { return noAccount } + now := time.Now() + idle := func() (int, time.Time) { return 0, now.Add(-time.Minute) } + step := func() []int { return codexAppStep(context.Background(), now, idle) } + recheck := func() { + codexDaemonMu.Lock() + codexDaemonChecked = time.Now() + codexDaemonMu.Unlock() + } + + s.route, s.running = "magpie,noauth", []int{60} + if got := step(); got != nil { + t.Fatalf("nothing changed: ended %v", got) + } + noteCodexSwitch("a@x", "b@x") + recheck() + for range 3 { + if got := step(); got != nil { + t.Fatalf("switched on a provider that takes no account: ended %v", got) + } + } + if got := CodexAppStale(); got != "" { + t.Fatalf("the Codex app said to be left on %q", got) + } + if got := CodexDaemonStale(); got != "" { + t.Fatalf("the daemon said to be left on %q", got) + } + codexAppSpentSwitch() + if got := step(); got != nil { + t.Fatalf("switched off a spent account on a provider that takes no account: ended %v", got) + } + // where Codex sends its requests changed: restarted as ever + s.route = "magpie,auth" + if got := step(); !slices.Equal(got, []int{60}) { + t.Fatalf("route changed: ended %v, want [60]", got) + } + // on a provider that takes the account a switch restarts it + noAccount = false + noteCodexSwitch("b@x", "c@x") + recheck() + if got := CodexAppStale(); got != "b@x" { + t.Fatalf("on a provider that takes the account: app left on %q, want b@x", got) + } + if got := step(); !slices.Equal(got, []int{100}) { + t.Fatalf("switched on a provider that takes the account: ended %v, want [100]", got) + } +} diff --git a/internal/provider/codex_app_server.go b/internal/provider/codex_app_server.go index a7eb64a59..eb1933ab1 100644 --- a/internal/provider/codex_app_server.go +++ b/internal/provider/codex_app_server.go @@ -51,6 +51,22 @@ import ( // itself (its model pick) 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 +// config names takes no ChatGPT account at all (a [model_providers] table +// without requires_openai_auth = true, such as magpie's with the user's +// own requires_openai_auth = false; danzi002 on Discord). Such a provider +// sends its own key, and the app-server answers account/read with no +// account for it (codex-rs ModelProviderInfo::account_state and +// resolve_provider_auth), so which ChatGPT account auth.json holds is +// nothing the app-server, the Codex app or the daemon goes by: an account +// switch restarts none of them. false when it can't be told. +var CodexNoAccount func() bool + +// codexNoAccount is CodexNoAccount, false while it isn't set. +func codexNoAccount() bool { + return CodexNoAccount != nil && CodexNoAccount() +} + // 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 @@ -325,6 +341,18 @@ func codexAppStep(ctx context.Context, now time.Time, busy func() (int, time.Tim home := codexHome() c := &codexApp c.Lock() + switched := c.switched + c.Unlock() + // an account switch is nothing to an app-server on a provider that + // takes no ChatGPT account (CodexNoAccount): it is forgotten, and a + // route change later restarts it all the same + if switched && codexNoAccount() { + log.Printf("codex: Codex's account was switched while its provider takes no ChatGPT account; the Codex app's app-server is left running") + c.Lock() + c.switched, c.spent = false, false + c.Unlock() + } + c.Lock() // at the first look only a used-up account's app-servers are ended: // what the others read before magpie started isn't known changed := !c.seen && out || c.seen && c.route != route || c.switched diff --git a/internal/provider/codex_daemon.go b/internal/provider/codex_daemon.go index ed957645c..bb58a86f0 100644 --- a/internal/provider/codex_daemon.go +++ b/internal/provider/codex_daemon.go @@ -203,9 +203,20 @@ func noteLeft(left *leftDaemon, pid int, from, to string) { // it isn't running or is on the account Codex is. func CodexDaemonStale() string { codexDaemonMu.Lock() - defer codexDaemonMu.Unlock() recheckLeft() - return codexDaemonLeft.user + was := codexDaemonLeft.user + codexDaemonMu.Unlock() + return leftOnAccount(was) +} + +// leftOnAccount is was, the account an app-server is left on, or "" when +// Codex's provider takes no ChatGPT account (CodexNoAccount): the +// app-server goes by none, so nothing is to be restarted for it. +func leftOnAccount(was string) string { + if was == "" || codexNoAccount() { + return "" + } + return was } // CodexAppStale answers the account the Codex desktop app is still signed @@ -215,9 +226,10 @@ func CodexDaemonStale() string { // until it is quit and opened again. func CodexAppStale() string { codexDaemonMu.Lock() - defer codexDaemonMu.Unlock() recheckLeft() - return codexAppLeft.user + was := codexAppLeft.user + codexDaemonMu.Unlock() + return leftOnAccount(was) } // recheckLeft forgets an app-server left on an account before that has