Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

codex: a Codex switched off in magpie still has its held ChatGPT account read, so the Codex app sends magpie's models (sherlock_23333 on X)

yetoneadc618bbf956
diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md
index 8479e8a70..8ba13938e 100644
--- a/docs/subsystems/agent-wiring.md
+++ b/docs/subsystems/agent-wiring.md
@@ -85,7 +85,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: <what it is>; <how to undo it>` (`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`). 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/<model>`), 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/<model>` (`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/<model>`), 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/<model>` (`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`.
- 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`.
- A field that follows another while empty (`Follows`: Claude Code's tiers and subagents on its main model) is read by `Drift` as on that field's model. The main model moved, in Claude Code's own `/model`, onto the model magpie had set a tier to is not drift (#1050). The tier keeps that model as its own through the move and the next one (`tier_own` in the stash), whatever it would follow on the new main model: fable, which follows no model that is no Fable, and haiku, which follows a Claude model on its Haiku, read as following and lost their model on the next move (#2257).
diff --git a/internal/agent/agent.go b/internal/agent/agent.go
index 10ccc4d61..ebcede4ea 100644
--- a/internal/agent/agent.go
+++ b/internal/agent/agent.go
@@ -187,6 +187,12 @@ type Agent struct {
// its sign-in only as it opens, sends nothing on it till it is opened
// again (MasterYi on Discord).
AppOut func() bool
+ // HoldMatters reports Codex takes magpie's models beside a ChatGPT
+ // sign-in, so that magpie is its provider while the Codex app holds
+ // the account (out), or is that already: what the app holds is read
+ // for it even with Codex switched off in magpie
+ // (provider.CodexHoldMatters).
+ HoldMatters func() bool
// SideModel is the model Codex is set to when it is one of magpie's,
// picked beside its ChatGPT sign-in (by the base URL, magpie not its
// provider), "" otherwise: the gateway answers the Codex app's hidden
diff --git a/internal/agent/agents.go b/internal/agent/agents.go
index 1967e0e5b..f9ada2e66 100644
--- a/internal/agent/agents.go
+++ b/internal/agent/agents.go
@@ -52,6 +52,13 @@ 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 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 {
+ home, _ := homes()
+ a := codex(home)
+ return a.HoldMatters != nil && a.HoldMatters()
+ }
}
// codexAppRoute is where Codex's config sends it, as the app-server reads
diff --git a/internal/agent/codex.go b/internal/agent/codex.go
index 58e4965f8..7d5c3f978 100644
--- a/internal/agent/codex.go
+++ b/internal/agent/codex.go
@@ -1525,8 +1525,12 @@ func codexIn(at place) *Agent {
// mark stays for Sync to put it back beside the sign-in: the
// Agents row said "its own models stay in /model" while the Codex
// app was meant to be in its API state (#2267)
- Joined: func() bool { return joined() && !asProvider() },
- AppOut: func() bool { return asProvider() && !api() && chatGPT() && stashLoad()[at.key("codex.out")] == "1" },
+ Joined: func() bool { return joined() && !asProvider() },
+ AppOut: func() bool { return asProvider() && !api() && chatGPT() && stashLoad()[at.key("codex.out")] == "1" },
+ HoldMatters: func() bool {
+ return stashLoad()[at.key("codex.login")] == "" && chatGPT() &&
+ (viaBase() || asProvider() && stashLoad()[at.key("codex.out")] == "1")
+ },
Beside: beside,
Routed: routed,
FailingOver: failingOver,
diff --git a/internal/agent/codex_hold_matters_test.go b/internal/agent/codex_hold_matters_test.go
new file mode 100644
index 000000000..f9f8f9174
--- /dev/null
+++ b/internal/agent/codex_hold_matters_test.go
@@ -0,0 +1,46 @@
+package agent
+
+import (
+ "testing"
+
+ "github.com/yetone/magpie/internal/provider"
+)
+
+// What the Codex app holds is read, Codex switched off in magpie or not,
+// while it decides where Codex sends (sherlock_23333 on X): Codex on
+// magpie's models beside its ChatGPT sign-in, or magpie its provider for
+// the held account. Not for a Codex kept on ChatGPT, on magpie's API, or
+// not on magpie at all.
+func TestCodexHoldMatters(t *testing.T) {
+ home, _ := codexHome(t, `{"tokens":{"access_token":"x","id_token":"x.e30.x"}}`, "")
+ t.Cleanup(func() { codexUsedUp = func() bool { return false } })
+ cx := codex(home)
+ if cx.HoldMatters() {
+ t.Fatal("not on magpie: HoldMatters")
+ }
+ if err := cx.Fields[0].Set("fake/m1"); err != nil {
+ t.Fatal(err)
+ }
+ if !cx.HoldMatters() {
+ t.Fatal("beside the sign-in: not HoldMatters")
+ }
+ codexUsedUp = func() bool { return true }
+ if err := cx.Sync(); err != nil {
+ t.Fatal(err)
+ }
+ if !cx.AppOut() || !cx.HoldMatters() {
+ t.Fatalf("held, magpie its provider: AppOut %v, HoldMatters %v", cx.AppOut(), cx.HoldMatters())
+ }
+ // the hook the provider package asks
+ if provider.CodexHoldMatters == nil {
+ t.Fatal("provider.CodexHoldMatters not set")
+ }
+ for _, v := range []string{"chatgpt", "api"} {
+ if err := cx.Field("login").Set(v); err != nil {
+ t.Fatal(err)
+ }
+ if cx.HoldMatters() {
+ t.Fatalf("login %s: HoldMatters", v)
+ }
+ }
+}
diff --git a/internal/provider/account.go b/internal/provider/account.go
index 196441a4a..3b628af8e 100644
--- a/internal/provider/account.go
+++ b/internal/provider/account.go
@@ -1054,6 +1054,24 @@ func codexToken(ctx context.Context, dir string) (tok, accountID string, err err
return codexTokenRenewing(ctx, dir, "")
}
+// codexTokenAsKept is the access token Codex keeps in dir, as it is: an
+// expired one is an error, not refreshed, for a sign-in magpie leaves to
+// Codex (leftAlone), which renews it itself.
+func codexTokenAsKept(dir string) (tok, accountID string, err error) {
+ b, _, err := readCodexLogin(dir, false)
+ if err != nil {
+ return "", "", err
+ }
+ var a codexAuth
+ if json.Unmarshal(b, &a) != nil || a.Tokens.AccessToken == "" {
+ return "", "", errors.New("Codex is signed out; run codex login")
+ }
+ if exp, _ := jwtClaims(a.Tokens.AccessToken)["exp"].(float64); exp != 0 && !time.Now().Before(time.Unix(int64(exp), 0)) {
+ return "", "", errors.New("Codex's sign-in has expired; Codex renews it as it runs")
+ }
+ return a.Tokens.AccessToken, codexAccountID(a), nil
+}
+
// codexTokenRenewing is codexToken, and with stale, the access token the
// backend just answered 401 "token expired" for while its exp was still
// ahead (willz on Discord, #2973: a Team account's), refreshes the
diff --git a/internal/provider/codex_hold_left_alone_test.go b/internal/provider/codex_hold_left_alone_test.go
new file mode 100644
index 000000000..3293e25de
--- /dev/null
+++ b/internal/provider/codex_hold_left_alone_test.go
@@ -0,0 +1,102 @@
+package provider
+
+import (
+ "bytes"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+// sherlock_23333 on X: the ChatGPT account Codex is signed in to ran out,
+// and the Codex app greyed Send for magpie's models too, through restarts.
+// With Codex switched off or removed in magpie nothing read the account,
+// so magpie never became Codex's provider while the app held it. Its hold
+// is read still, while Codex takes magpie's models, and only then: the
+// account Codex is on alone, its sign-in never renewed by magpie.
+func TestCodexHoldReadLeftAlone(t *testing.T) {
+ home := signIn(t)
+ rememberLogins(true)
+ body := heldUsage(t)
+ var usage, refresh atomic.Int64
+ fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/backend-api/wham/usage":
+ usage.Add(1)
+ json.NewEncoder(w).Encode(body)
+ case "/oauth/token":
+ refresh.Add(1)
+ w.WriteHeader(500)
+ default:
+ w.WriteHeader(404)
+ }
+ }))
+ t.Cleanup(fake.Close)
+ oldBase, oldTok := CodexBase, codexTokenURL
+ CodexBase, codexTokenURL = fake.URL+"/backend-api/codex", fake.URL+"/oauth/token"
+ matters := false
+ oldHook := CodexHoldMatters
+ CodexHoldMatters = func() bool { return matters }
+ t.Cleanup(func() { CodexBase, codexTokenURL, CodexHoldMatters = oldBase, oldTok, oldHook })
+ fresh := func() {
+ loginUsageCache.Lock()
+ loginUsageCache.m, loginUsageCache.pending = nil, nil
+ loginUsageCache.Unlock()
+ }
+
+ for _, c := range []struct {
+ name string
+ p map[string]any
+ }{
+ {"switched off", map[string]any{"id": "codex", "off": true}},
+ {"removed from magpie", map[string]any{"id": "codex", "hidden": true}},
+ } {
+ writeFile(t, Path(), map[string]any{"providers": []map[string]any{c.p}})
+ // not taking magpie's models: left alone, nothing read
+ matters = false
+ fresh()
+ usage.Store(0)
+ if CodexUsedUp(t.Context()) || usage.Load() != 0 {
+ t.Fatalf("%s, Codex not on magpie: read %d times", c.name, usage.Load())
+ }
+ // taking them: the app's hold is read, and known after
+ matters = true
+ fresh()
+ if !CodexUsedUp(t.Context()) {
+ t.Fatalf("%s: CodexUsedUp = false on a held account", c.name)
+ }
+ if usage.Load() != 1 {
+ t.Fatalf("%s: read %d times, want 1", c.name, usage.Load())
+ }
+ if !CodexUsedUpKnown() {
+ t.Fatalf("%s: CodexUsedUpKnown = false after the read", c.name)
+ }
+ // the Usage page still reads nothing of it
+ if u := LoginUsage(t.Context(), "codex"); len(u) != 0 {
+ t.Fatalf("%s: LoginUsage = %v, want nothing", c.name, u)
+ }
+ }
+
+ // a sign-in about to expire is left to Codex: not refreshed, not
+ // written, the hold unknown
+ auth := filepath.Join(home, ".codex", "auth.json")
+ var a map[string]any
+ b, _ := os.ReadFile(auth)
+ json.Unmarshal(b, &a)
+ a["tokens"].(map[string]any)["access_token"] = fakeJWT(map[string]any{"exp": float64(time.Now().Add(-time.Minute).Unix())})
+ writeFile(t, auth, a)
+ before, _ := os.ReadFile(auth)
+ fresh()
+ usage.Store(0)
+ if CodexUsedUp(t.Context()) {
+ t.Fatal("expired sign-in: CodexUsedUp = true")
+ }
+ after, _ := os.ReadFile(auth)
+ if refresh.Load() != 0 || usage.Load() != 0 || !bytes.Equal(before, after) {
+ t.Fatalf("expired sign-in left alone: refreshed %d, read %d, auth.json rewritten %v", refresh.Load(), usage.Load(), !bytes.Equal(before, after))
+ }
+}
diff --git a/internal/provider/left_alone.go b/internal/provider/left_alone.go
index 2095f0345..7fbb7515e 100644
--- a/internal/provider/left_alone.go
+++ b/internal/provider/left_alone.go
@@ -9,6 +9,10 @@ package provider
// those ran every minute or so for a Claude switched off, and a request
// made just as a proxy came back up after a restart went out on the
// machine's own address (Riko on Discord).
+//
+// One read is kept for Codex: the account it is signed in to, while it
+// takes magpie's models, for whether the Codex app holds it
+// (codexHoldReading), which decides where Codex sends at all.
// leftAlone says whether magpie leaves provider id alone in the
// background: switched off, or its account removed from magpie.
diff --git a/internal/provider/login_usage.go b/internal/provider/login_usage.go
index 39f907e77..fa6d4a12c 100644
--- a/internal/provider/login_usage.go
+++ b/internal/provider/login_usage.go
@@ -378,6 +378,10 @@ func loginQuota(ctx context.Context, l Login) SubscriptionQuota {
var renew codexRenew
switch {
case l.Agent == "claude": // Claude Code reads its own (claudeWindows)
+ case l.Active && leftAlone(l.Agent):
+ // read for the Codex app's hold alone (codexHoldReading): the
+ // token as Codex keeps it, never renewed nor written by magpie
+ tok, accountID, err = codexTokenAsKept(codexHome())
case l.Active:
tok, accountID, err = codexToken(ctx, codexHome())
renew = func(ctx context.Context, stale string) (string, string, error) {
@@ -445,11 +449,41 @@ func codexSignInRead(l Login, tok string, err error) error {
// credits left isn't (the Codex app keeps sending, and the backend
// answers). False when that isn't known.
func CodexUsedUp(ctx context.Context) bool {
+ if leftAlone("codex") {
+ return codexReadingHeld(codexHoldReading(ctx))
+ }
// read as LoginUsage has it, fetched at most once a minute: the agent
// package asks on every catalog sync
return codexReadingHeld(LoginUsage(ctx, "codex"))
}
+// CodexHoldMatters is set by the agent package: whether Codex is wired to
+// magpie beside its ChatGPT sign-in, so that magpie becomes its provider
+// while the Codex app holds the account (codex.out), or is its provider
+// for that already. Nil or false: what the app holds changes nothing.
+var CodexHoldMatters func() bool
+
+// codexHoldReading is the reading CodexUsedUp goes by for a Codex switched
+// off or removed in magpie (leftAlone), which LoginUsage reads nothing
+// of: the account Codex is signed in to alone, only while Codex takes
+// magpie's models (CodexHoldMatters), at most once a minute (loginReading),
+// its sign-in never renewed (loginQuota). The Codex app greys Send for
+// every model, magpie's too, while it holds the account, and turning
+// Codex off in magpie once its allowance ran out left the app so for good:
+// nothing read, magpie never became its provider, and one that was
+// stopped being it (sherlock_23333 on X).
+func codexHoldReading(ctx context.Context) map[string]SubscriptionQuota {
+ if settings.AccountDiscoveryOff() || CodexHoldMatters == nil || !CodexHoldMatters() {
+ return nil
+ }
+ for _, l := range Logins("codex") {
+ if l.Active {
+ return map[string]SubscriptionQuota{l.User: loginReading(ctx, l).q}
+ }
+ }
+ return nil
+}
+
// CodexUsedUpKnown is CodexUsedUp over what was read already, asking no
// one and waiting for no one. False when nothing was read yet, which is
// CodexUsedUp's own answer for an account it can't tell about.