Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
gateway: an exhausted ChatGPT account no longer greys Codex app's Send while magpie can serve the turn (MasterYi on Discord)
yetoneef37b6fb764d
diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.mdindex 06654089a..7fb2e02b2 100644--- a/docs/subsystems/agent-wiring.md+++ b/docs/subsystems/agent-wiring.md@@ -71,7 +71,7 @@ something else shows up as drift.- Grok App (RongleCat/grok-app, a desktop front end that starts Grok Build over ACP) keeps its provider channels in `agent-home/config.toml` under its data folder: `$GROK_APP_HOME`, else where its `directories` crate puts it, or its `~/.grok-app` fallback when that is the one there (`grokApp` in [`grokapp.go`](../../internal/agent/grokapp.go)). Its composer lists only Grok Build's official catalog, never the `[model."magpie/…"]` tables of Grok Build's row, so magpie adds itself as a channel, `[model.magpie]`, with the keys the App's Providers page writes: the gateway's `/v1`, a key naming Grok App, `api_backend = "chat_completions"`, `app_provider_mode = "generic"`, and `app_models`, a JSON list of magpie's models with `contextWindow`, `supportsVision` and their effort levels (no `none`; a default the user marks in the App stays, else medium). The picked model's `context_window` (a bare integer) and `supports_reasoning_effort` (a bare bool, Grok Build's gate for `--reasoning-effort`) are on the channel, as the App puts them there when a model is picked in its composer. `[models] default` is the route, and magpie does not set it: setting it to `"magpie"` makes the App drop its own sign-in (`ensure_independent_for_custom_route`). The route stays whatever the App had. Pressing Use on magpie under Accounts is what switches it. A magpie that already set the route puts the old one back once, on the next sync or connect (`grokAppReleased`); a Use after that stays. Disconnect drops only the channel, and puts the route back only when it is still `"magpie"`: the one stashed at connect, else the one `connect.was` holds. One of the App's own routes picked in magpie's model field is written as the route and takes magpie's channel out, as picking another provider does elsewhere. A sync with no channel and a route other than `"magpie"` writes nothing, magpie's stash included, and Check says so when the route is `"magpie"` with the channel gone. A model picked in the App's composer since is the user's and stays through a sync, and a sync with nothing to change doesn't write. Shared mode keeps `GROK_HOME` at `~/.grok` (Grok Build's library row). Independent mode, which Use turns on, reads agent-home: the Library writes `AGENTS.md`, `[mcp_servers]` in the same `config.toml`, and `skills/` there, and Grok App also reads `~/.agents/skills`. RTK has no Grok hook, so the Library lists Grok App with the switch off. The notice, while the App runs, says magpie is a custom provider in Settings › Account, a chat can pick its models in the model picker, and the App stays on its current route until Use.- JSON/JSONC config edits and their previews reject malformed input rather than editing a partially parsed document. Object edits and VS Code's model-group array edits leave the original file untouched on a parse error; valid comments and trailing commas remain supported (`internal/edit`).- 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 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).+- 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. The Codex app reads its sign-in only as it opens (`authMethod`, told again only on `account/updated`), so a running app stays greyed after the switch: `provider.CodexAppOut` keeps the app open as the account ran out (its app-server's pid), and on macOS the GUI reopens it once per time out (`keepCodexAppSending`, through `ReopenCodexApp`) when magpie is the provider for it (`Agent.AppOut`), the account is still out, no turn is in flight through the gateway and none ended in the last 30s; the app's bundled code keeps an unsent draft (`composer-prompt-drafts-v2`) across a quit, not watched in a real app. Off macOS, or once tried, Codex's accounts say to quit and reopen it (`codexAppOut`, `renderCodexAppOut`; `TestCodexAppOutReopenedOnce`, `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.- 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).- A Claude Code tier or its subagents given a model of their own keep it when the main model moves onto that model and on again (`ownKey` in `claudeIn`), whether the main model is picked in magpie or in Claude Code's `/model`. Same as model, picked for them, has them follow again.diff --git a/internal/agent/agent.go b/internal/agent/agent.goindex 384b064d3..b26d475f2 100644--- a/internal/agent/agent.go+++ b/internal/agent/agent.go@@ -176,6 +176,11 @@ type Agent struct {// "" for none: Connect keeps the agent on that model through magpie// where it can't Join (#940: Codex went to an unrelated model).OwnVia func(model string) string+ // AppOut reports magpie made Codex's provider for a ChatGPT sign-in+ // whose account is used up (codex.out): the Codex app, which reads+ // its sign-in only as it opens, sends nothing on it till it is opened+ // again (MasterYi on Discord).+ AppOut func() bool// Routed reports that the agent's config sends whatever model it// names to magpie's gateway (Codex's openai_base_url or magpie as its// provider), so a model's name the gateway takes as a routing groupdiff --git a/internal/agent/codex.go b/internal/agent/codex.goindex 6c5d1d21d..151cb9399 100644--- a/internal/agent/codex.go+++ b/internal/agent/codex.go@@ -1243,6 +1243,7 @@ func codexIn(at place) *Agent {// 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" },Beside: beside,Routed: routed,FailingOver: failingOver,@@ -1298,6 +1299,45 @@ func codexIn(at place) *Agent {if m := get("model"); isMagpie(m) && viaBase() && get("model_provider") == "" && !chatGPT() {return set(m)}+ // the ChatGPT account ran out on one of Codex's own models,+ // joined beside the sign-in (MasterYi on Discord: the Codex+ // app greyed Send, a magpie model's turn too), as in #540+ // below: magpie becomes Codex's provider on that model as+ // magpie serves it, the one picked kept (codex.out_own) to go+ // back to once the account has room. One magpie serves on no+ // account of its own is left as it is.+ if m := get("model"); !isMagpie(m) && !api() && chatGPT() && joined() && out() {+ if id := codexOwnViaMagpie(m); id != "" {+ stash(map[string]string{at.key("codex.out_own"): m})+ return set(id)+ }+ }+ // put back before #540's way back, which would take+ // codex/<model> for a magpie model picked beside the sign-in+ if own := stashLoad()[at.key("codex.out_own")]; own != "" {+ m := get("model")+ switch {+ case stashLoad()[at.key("codex.out")] != "1" || !asProvider() || codexOwnOf(m) != own:+ // moved since (another model picked, magpie API, a+ // disconnect): that stands+ forget(at.key("codex.out_own"))+ case !out():+ // back beside the sign-in on the one picked, as Join+ // leaves it: Codex's own sign-in, magpie's models joined+ forget(at.key("codex.out_own"), at.key("codex.out"))+ if err := edit.DelTOMLTop(path, "model_provider", "model_catalog_json"); err != nil {+ return err+ }+ if err := edit.SetTOMLTop(path,+ edit.KV{Path: "openai_base_url", Value: at.codexURL()},+ edit.KV{Path: "model", Value: own},+ ); err != nil {+ return err+ }+ stash(map[string]string{at.key("codex.joined"): "1"})+ return settle()+ }+ }// the ChatGPT account ran out (of its allowance and its// credits) after a magpie model was picked beside its sign-in:// the Codex app then sends nothing, a magpie model's turndiff --git a/internal/agent/codex_usedup_test.go b/internal/agent/codex_usedup_test.goindex 2bfd5a104..416bc8ca9 100644--- a/internal/agent/codex_usedup_test.go+++ b/internal/agent/codex_usedup_test.go@@ -1,6 +1,8 @@package agentimport (+ "os"+ "path/filepath""strings""testing")@@ -108,3 +110,93 @@ func TestCodexKeptOnChatGPT(t *testing.T) {t.Fatalf("ChatGPT again, used up:\n%s", cfg)}}++// The same on one of Codex's own models picked beside the sign-in+// (MasterYi on Discord: the Codex app greyed Send on a used-up account,+// and the third-party models it was joined with couldn't be used either).+// Sync makes magpie Codex's provider on that model as magpie serves it,+// and once the account has room puts Codex back on the one picked, beside+// its sign-in.+func TestCodexOwnModelGoesThroughMagpieWhileUsedUp(t *testing.T) {+ home, read := codexHome(t, `{"tokens":{"access_token":"x","id_token":"x.e30.x"}}`, "model = \"gpt-a\"\n")+ os.WriteFile(filepath.Join(home, ".codex", "models_cache.json"),+ []byte(`{"models":[{"slug":"gpt-a","display_name":"A","priority":1}]}`), 0o644)+ cx := codex(home)+ if ok, err := cx.Join(); err != nil || !ok {+ t.Fatalf("join: %v %v", ok, err)+ }+ if cfg := read(); strings.Contains(cfg, "model_provider =") || !strings.Contains(cfg, `model = "gpt-a"`) {+ t.Fatalf("joined:\n%s", cfg)+ }+ if cx.AppOut() {+ t.Fatal("joined with room: AppOut")+ }+ codexUsedUp = func() bool { return true }+ if err := cx.Sync(); err != nil {+ t.Fatal(err)+ }+ if cfg := read(); !strings.Contains(cfg, `model_provider = "magpie"`) || !strings.Contains(cfg, `model = "codex/gpt-a"`) {+ t.Fatalf("used up:\n%s", cfg)+ }+ if !cx.AppOut() {+ t.Fatal("used up, magpie its provider: not AppOut")+ }+ if err := cx.Sync(); err != nil { // still out: stays+ t.Fatal(err)+ }+ if cfg := read(); !strings.Contains(cfg, `model = "codex/gpt-a"`) {+ t.Fatalf("used up, synced again:\n%s", cfg)+ }+ codexUsedUp = func() bool { return false }+ if err := cx.Sync(); err != nil {+ t.Fatal(err)+ }+ if cfg := read(); strings.Contains(cfg, "model_provider =") || strings.Contains(cfg, "model_catalog_json") ||+ !strings.Contains(cfg, "openai_base_url") || !strings.Contains(cfg, `model = "gpt-a"`) {+ t.Fatalf("allowance back:\n%s", cfg)+ }+ if cx.AppOut() || !cx.Joined() {+ t.Fatalf("allowance back: AppOut %v, Joined %v", cx.AppOut(), cx.Joined())+ }++ // a model the user picked while out stays theirs when room comes back+ codexUsedUp = func() bool { return true }+ if err := cx.Sync(); err != nil {+ t.Fatal(err)+ }+ if err := cx.Fields[0].Set("fake/m1"); err != nil {+ t.Fatal(err)+ }+ codexUsedUp = func() bool { return false }+ if err := cx.Sync(); err != nil {+ t.Fatal(err)+ }+ if cfg := read(); !strings.Contains(cfg, `model = "fake/m1"`) {+ t.Fatalf("picked while out, allowance back:\n%s", cfg)+ }+}++// Kept on ChatGPT, a used-up account on one of Codex's own models leaves+// Codex as it is: the user chose the sign-in.+func TestCodexOwnModelKeptOnChatGPT(t *testing.T) {+ home, read := codexHome(t, `{"tokens":{"access_token":"x","id_token":"x.e30.x"}}`, "model = \"gpt-a\"\n")+ os.WriteFile(filepath.Join(home, ".codex", "models_cache.json"),+ []byte(`{"models":[{"slug":"gpt-a","display_name":"A","priority":1}]}`), 0o644)+ cx := codex(home)+ if ok, err := cx.Join(); err != nil || !ok {+ t.Fatalf("join: %v %v", ok, err)+ }+ if err := cx.Field("login").Set("chatgpt"); err != nil {+ t.Fatal(err)+ }+ codexUsedUp = func() bool { return true }+ if err := cx.Sync(); err != nil {+ t.Fatal(err)+ }+ if cfg := read(); strings.Contains(cfg, "model_provider =") || !strings.Contains(cfg, `model = "gpt-a"`) {+ t.Fatalf("kept on ChatGPT, used up:\n%s", cfg)+ }+ if cx.AppOut() {+ t.Fatal("kept on ChatGPT: AppOut")+ }+}diff --git a/internal/gateway/codex_app_out_test.go b/internal/gateway/codex_app_out_test.gonew file mode 100644index 000000000..4c014ae26--- /dev/null+++ b/internal/gateway/codex_app_out_test.go@@ -0,0 +1,33 @@+package gateway++import (+ "strings"+ "sync"+ "testing"+)++// A turn refused with usage_limit_reached on the account Codex is signed+// in to has that account read again at once (provider.CodexMayBeUsedUp),+// for magpie to become Codex's provider before the next five-minute look:+// the Codex app greys its Send on the account meanwhile (MasterYi on+// Discord).+func TestCodexUsedUpReplyAsksAtOnce(t *testing.T) {+ codexSignedIn(t, "[email protected]")+ var tried, models []string+ usedUp(t, &tried, &models)+ var mu sync.Mutex+ var asked []string+ old := codexMayBeUsedUp+ codexMayBeUsedUp = func(user string) { mu.Lock(); asked = append(asked, user); mu.Unlock() }+ t.Cleanup(func() { codexMayBeUsedUp = old })++ code, body := codexPost(t, `{"model":"gpt-5.5","stream":true,"input":"ping"}`)+ if code != 200 || !strings.Contains(body, "pong") {+ t.Fatalf("status %d: %s", code, body)+ }+ mu.Lock()+ defer mu.Unlock()+ if strings.Join(asked, ",") != "[email protected]" {+ t.Fatalf("asked %v, want [email protected]", asked)+ }+}diff --git a/internal/gateway/routing.go b/internal/gateway/routing.goindex 14e9393ed..2e3e47c7f 100644--- a/internal/gateway/routing.go+++ b/internal/gateway/routing.go@@ -535,6 +535,9 @@ func init() { provider.OnRenewed(renewed) }// staleAllowance is provider.StaleAllowance, swapped in tests.var staleAllowance = provider.StaleAllowance+// codexMayBeUsedUp is provider.CodexMayBeUsedUp, swapped in tests.+var codexMayBeUsedUp = provider.CodexMayBeUsedUp+// awaitAllowance is provider.AwaitAllowance, swapped in tests.var awaitAllowance = provider.AwaitAllowance@@ -1042,6 +1045,11 @@ func (s *Server) restAfterMarked(c candidate, status int, header http.Header, bo// by the plugin's provider ("plugin:grok"), not by "plugin"if a := c.p.Account; a != nil && why != failOther && why != failVerify && why != failRestricted {staleAllowance(a.UsageAgent(), a.User) // ask again what it has left+ if why == failQuota && a.UsageAgent() == "codex" {+ // the account Codex is signed in to may be out: the Codex app+ // greys its Send till it knows magpie is its provider+ codexMayBeUsedUp(a.User)+ }} else if a == nil && why != failOther && why != failVerify && why != failRestricted {staleKeyAllowance(c.p) // a key that reads its windows, too}diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.jsindex 21b03b0be..6b11b0cb0 100644--- a/internal/gui/assets/app.js+++ b/internal/gui/assets/app.js@@ -13149,8 +13149,10 @@ function renderAccounts(a, p) {box.append(only);list.append(box);}- if (a.agent === "codex" && providers?.codexDaemon) list.append(renderCodexDaemon(providers.codexDaemon));- if (a.agent === "codex" && providers?.codexApp) list.append(renderCodexApp(providers.codexApp));+ const pv = a.agent === "codex" ? providers || {} : {};+ if (pv.codexDaemon) list.append(renderCodexDaemon(pv.codexDaemon));+ if (pv.codexApp) list.append(renderCodexApp(pv.codexApp));+ if (pv.codexAppOut) list.append(renderCodexAppOut(pv.codexAppOut));if (signing?.agent === a.agent) list.append(renderSigning(sub));else {const add = el("button", "acc add");@@ -13178,12 +13180,8 @@ function renderAccounts(a, p) {// on the account before (user) until it restarts. magpie doesn't restart it// unasked: that ends the Codex sessions running on it.function renderCodexDaemon(user) {- const box = el("div", "signing daemon");- box.append(el("span", "mark", "!"));- const tt = el("span", "tt");- tt.append(el("span", "n", t("Codex's background service is still signed in as {user}", { user })),- el("span", "s", t("Restart it to use the new account. Running Codex sessions will be interrupted.")));- box.append(tt);+ const box = codexNote("", t("Codex's background service is still signed in as {user}", { user }),+ t("Restart it to use the new account. Running Codex sessions will be interrupted."));const later = el("button", "text", t("Later"));later.onclick = () => accountAction("codex/daemon/dismiss", {});const go = el("button", "text primary", t("Restart"));@@ -13198,18 +13196,31 @@ function renderCodexDaemon(user) {// that account's limits and, once they are spent, sends in no thread. Only// quitting and opening it again moves it; magpie doesn't quit it unasked.function renderCodexApp(user) {- const box = el("div", "signing daemon");- box.append(el("span", "mark", "!"));- const tt = el("span", "tt");- tt.append(el("span", "n", t("The Codex app is still signed in as {user}", { user })),- el("span", "s", t("It shows that account's usage limits until it is quit and opened again. Quit it and open it again to use the new account.")));- box.append(tt);+ const box = codexNote("", t("The Codex app is still signed in as {user}", { user }),+ t("It shows that account's usage limits until it is quit and opened again. Quit it and open it again to use the new account."));const ok = el("button", "text", t("Got it"));ok.onclick = () => accountAction("codex/daemon/dismiss-app", {});box.append(ok);return box;}+// codexNote: a Codex notice's box, its line (n) and what to do (s).+function codexNote(cls, n, s) {+ const box = el("div", "signing daemon" + cls), tt = el("span", "tt");+ tt.append(el("span", "n", n), el("span", "s", s));+ box.append(el("span", "mark", "!"), tt);+ return box;+}++// renderCodexAppOut: the account the Codex app is on ran out, which greys+// its Send for magpie's models too till it reopens: magpie reopens it on+// macOS once idle (reopening), else the user does.+function renderCodexAppOut(out) {+ return codexNote(" app-out", t("The Codex app can't send on {user}'s used-up account", { user: out.user }), out.reopening+ ? t("magpie serves its turns now, but the app reads that only as it opens. magpie quits it and opens it again once no turn is running.")+ : t("magpie serves its turns now, but the app reads that only as it opens. Quit it and open it again to send."));+}+// Accounts brought in from another tool's export instead of signing in// again: the files' text (or what is pasted) goes to magpie, which checks// each account with the vendor before keeping it, and says what became ofdiff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.jsindex cc56aec63..5b502a629 100644--- a/internal/gui/assets/i18n.js+++ b/internal/gui/assets/i18n.js@@ -1777,6 +1777,9 @@ const I18N = {"Codex's background service is still signed in as {user}": "Codex 的后台服务仍登录着 {user}","The Codex app is still signed in as {user}": "Codex 应用仍登录着 {user}","It shows that account's usage limits until it is quit and opened again. Quit it and open it again to use the new account.": "在退出并重新打开之前,它显示的一直是该账号的用量限额。退出后重新打开即可使用新账号。",+ "The Codex app can't send on {user}'s used-up account": "Codex 应用无法用已用完的 {user} 账号发送",+ "magpie serves its turns now, but the app reads that only as it opens. magpie quits it and opens it again once no turn is running.": "magpie 现已接管它的对话,但应用只在打开时读取这一点。没有对话在进行时,magpie 会退出并重新打开它。",+ "magpie serves its turns now, but the app reads that only as it opens. Quit it and open it again to send.": "magpie 现已接管它的对话,但应用只在打开时读取这一点。退出后重新打开即可发送。","Restart it to use the new account. Running Codex sessions will be interrupted.": "重启后才会使用新账号,正在运行的 Codex 会话将中断。","Restart Zed if it still asks for an API key: magpie has configured its gateway credential in the system credential store.": "若 Zed 仍要求输入 API 密钥,请重启 Zed:网关凭据已写入系统凭据存储。","In Air, start a new task and pick Magpie in its agent menu: magpie's models and routing groups are in its model menu.": "在 Air 中新建任务并在智能体菜单选 Magpie:模型菜单中即有 magpie 的模型和路由组。",@@ -5664,6 +5667,9 @@ const I18N = {"Codex's background service is still signed in as {user}": "Codex 的後臺服務仍登入著 {user}","The Codex app is still signed in as {user}": "Codex 應用仍登入著 {user}","It shows that account's usage limits until it is quit and opened again. Quit it and open it again to use the new account.": "在結束並重新開啟之前,它顯示的一直是該帳號的用量限額。結束後重新開啟即可使用新帳號。",+ "The Codex app can't send on {user}'s used-up account": "Codex 應用無法用已用完的 {user} 帳號傳送",+ "magpie serves its turns now, but the app reads that only as it opens. magpie quits it and opens it again once no turn is running.": "magpie 現已接管它的對話,但應用只在開啟時讀取這一點。沒有對話在進行時,magpie 會結束並重新開啟它。",+ "magpie serves its turns now, but the app reads that only as it opens. Quit it and open it again to send.": "magpie 現已接管它的對話,但應用只在開啟時讀取這一點。結束後重新開啟即可傳送。","Restart it to use the new account. Running Codex sessions will be interrupted.": "重啟後才會使用新帳號,正在執行的 Codex 會話將中斷。","Restart Zed if it still asks for an API key: magpie has configured its gateway credential in the system credential store.": "若 Zed 仍要求輸入 API 金鑰,請重啟 Zed:閘道憑據已寫入系統憑據儲存。","In Air, start a new task and pick Magpie in its agent menu: magpie's models and routing groups are in its model menu.": "在 Air 中新增任務並在智慧體選單選 Magpie:模型選單中即有 magpie 的模型和路由組。",@@ -9528,6 +9534,9 @@ const I18N = {"Codex's background service is still signed in as {user}": "Codex のバックグラウンドサービスはまだ {user} としてサインインしています","The Codex app is still signed in as {user}": "Codex アプリはまだ {user} としてサインインしています","It shows that account's usage limits until it is quit and opened again. Quit it and open it again to use the new account.": "終了して開き直すまで、そのアカウントの使用上限を表示し続けます。新しいアカウントを使うには、終了してもう一度開いてください。",+ "The Codex app can't send on {user}'s used-up account": "Codex アプリは使い切った {user} のアカウントでは送信できません",+ "magpie serves its turns now, but the app reads that only as it opens. magpie quits it and opens it again once no turn is running.": "magpie がそのターンを処理するようになりましたが、アプリはそれを起動時にしか読み込みません。実行中のターンがなくなると、magpie がアプリを終了して開き直します。",+ "magpie serves its turns now, but the app reads that only as it opens. Quit it and open it again to send.": "magpie がそのターンを処理するようになりましたが、アプリはそれを起動時にしか読み込みません。送信するには、アプリを終了して開き直してください。","Restart it to use the new account. Running Codex sessions will be interrupted.": "新しいアカウントを使うには再起動してください。実行中の Codex セッションは中断されます。","Restart Zed if it still asks for an API key: magpie has configured its gateway credential in the system credential store.": "Zed がまだ APIキーを求める場合は Zed を再起動してください。magpie はシステムの資格情報ストアにゲートウェイの資格情報を設定済みです。","In Air, start a new task and pick Magpie in its agent menu: magpie's models and routing groups are in its model menu.": "Air で新しいタスクを開始し、エージェントメニューで Magpie を選んでください。magpie のモデルとルーティンググループはモデルメニューにあります。",@@ -13422,6 +13431,9 @@ const I18N = {"Codex's background service is still signed in as {user}": "Der Hintergrunddienst von Codex ist noch als {user} angemeldet","The Codex app is still signed in as {user}": "Die Codex-App ist noch als {user} angemeldet","It shows that account's usage limits until it is quit and opened again. Quit it and open it again to use the new account.": "Sie zeigt die Nutzungslimits dieses Kontos, bis sie beendet und neu geöffnet wird. Beenden Sie sie und öffnen Sie sie erneut, um das neue Konto zu verwenden.",+ "The Codex app can't send on {user}'s used-up account": "Die Codex-App kann mit dem aufgebrauchten Konto {user} nicht senden",+ "magpie serves its turns now, but the app reads that only as it opens. magpie quits it and opens it again once no turn is running.": "magpie bedient ihre Anfragen jetzt, doch die App liest das erst beim Öffnen. magpie beendet sie und öffnet sie wieder, sobald keine Anfrage läuft.",+ "magpie serves its turns now, but the app reads that only as it opens. Quit it and open it again to send.": "magpie bedient ihre Anfragen jetzt, doch die App liest das erst beim Öffnen. Beende sie und öffne sie wieder, um zu senden.","Restart it to use the new account. Running Codex sessions will be interrupted.": "Starten Sie ihn neu, um das neue Konto zu verwenden. Laufende Codex-Sitzungen werden unterbrochen.","Restart Zed if it still asks for an API key: magpie has configured its gateway credential in the system credential store.": "Starten Sie Zed neu, falls es weiterhin nach einem API-Schlüssel fragt: magpie hat die Anmeldedaten des Zugangspunkts im Anmeldeinformationsspeicher des Systems hinterlegt.","In Air, start a new task and pick Magpie in its agent menu: magpie's models and routing groups are in its model menu.": "Starten Sie in Air eine neue Aufgabe und wählen Sie im Agentenmenü Magpie: Die Modelle und Weiterleitungsgruppen von magpie stehen im Modellmenü.",diff --git a/internal/gui/backend.go b/internal/gui/backend.goindex 96f3436dd..02a5831b1 100644--- a/internal/gui/backend.go+++ b/internal/gui/backend.go@@ -43,6 +43,9 @@ func startBackend() (gw *gateway.Server) {// Codex's background app-server, restarted when it has the list from// before a change and no codex session is on it (luci)go agent.KeepCodexDaemonCurrent(backendCtx)+ // the Codex app, reopened once its account is used up and magpie is+ // its provider, which it reads only as it opens (MasterYi)+ go keepCodexAppSending(backendCtx)// the compactions magpie made in Codex's threads written as Codex's// own, so a thread goes on when Codex talks to OpenAI itselfgo agent.KeepCodexRolloutsPortable(backendCtx)diff --git a/internal/gui/codex_app_out.go b/internal/gui/codex_app_out.gonew file mode 100644index 000000000..f55412ced--- /dev/null+++ b/internal/gui/codex_app_out.go@@ -0,0 +1,114 @@+package gui++import (+ "context"+ "log"+ "runtime"+ "time"++ "github.com/yetone/magpie/internal/agent"+ "github.com/yetone/magpie/internal/provider"+)++// The Codex app reads its sign-in only as it opens. When the ChatGPT+// account it is on runs out, it greys its Send for every model, magpie's+// too, and making magpie Codex's provider (agent AppOut) reaches it only+// once it is quit and opened again (MasterYi on Discord). On macOS magpie+// does that itself, once each time the account runs out: only while the+// app open then still runs (provider.CodexAppOut, its app-server's pid+// unchanged, so it hasn't read the provider), the account is out, and no+// turn has gone through magpie for codexAppOutIdle. The app's own code+// keeps an unsent message's draft (its composer-prompt-drafts-v2 store)+// and its threads across a quit. Elsewhere, or when the quit didn't take,+// Codex's accounts say to reopen it.++var (+ codexAppOutEvery = 10 * time.Second+ codexAppOutIdle = 30 * time.Second+ // codexAppOutReopen quits the Codex app at bundle and opens it again+ codexAppOutReopen = agent.ReopenCodexApp+ // codexAppOutBundles are the Codex apps open from before Codex's+ // config last changed+ codexAppOutBundles = func() []string {+ a, err := agent.Find("codex")+ if err != nil {+ return nil+ }+ var out []string+ for _, c := range a.StaleCopies() {+ if c.Kind == "app" && c.Bundle != "" {+ out = append(out, c.Bundle)+ }+ }+ return out+ }+ // codexAgentOut is whether magpie is Codex's provider for its used-up+ // ChatGPT account+ codexAgentOut = func() bool {+ a, err := agent.Find("codex")+ return err == nil && a.AppOut != nil && a.AppOut()+ }+ codexAppOutOS = runtime.GOOS+ // what provider keeps of the app open as the account ran out+ codexAppOutUser = provider.CodexAppOut+ codexAppOutTried = provider.CodexAppReopenTried+ codexAppOutOnce = provider.CodexAppReopenOnce+ codexAppOutUsedUp = provider.CodexUsedUpKnown+)++// codexAppOutJSON is a Codex app left unable to send: the account it is+// signed in to, and whether magpie is still to reopen it.+type codexAppOutJSON struct {+ User string `json:"user"`+ Reopening bool `json:"reopening,omitempty"`+}++// codexAppOutState is what Codex's accounts say of it; nil for none.+func codexAppOutState() *codexAppOutJSON {+ u := codexAppOutUser()+ if u == "" || !codexAgentOut() {+ return nil+ }+ return &codexAppOutJSON{User: u, Reopening: codexAppOutOS == "darwin" && !codexAppOutTried()}+}++// reopenCodexAppOut reopens the Codex app left unable to send, if every+// condition above holds now; it says whether it tried.+func reopenCodexAppOut(ctx context.Context, now time.Time) bool {+ if codexAppOutOS != "darwin" || codexAppOutUser() == "" || codexAppOutTried() {+ return false+ }+ if !codexAgentOut() || !codexAppOutUsedUp() {+ return false+ }+ if b := gatewayBusy(); b.Any() || now.Sub(b.Last) < codexAppOutIdle {+ return false+ }+ bundles := codexAppOutBundles()+ if len(bundles) == 0 || !codexAppOutOnce() {+ return false+ }+ for _, b := range bundles {+ c, cancel := context.WithTimeout(ctx, time.Minute)+ if err := codexAppOutReopen(c, b); err != nil {+ log.Printf("codex: reopening %s for its used-up account: %v", b, err)+ }+ cancel()+ }+ return true+}++// keepCodexAppSending runs reopenCodexAppOut every codexAppOutEvery until+// ctx ends.+func keepCodexAppSending(ctx context.Context) {+ t := time.NewTicker(codexAppOutEvery)+ defer t.Stop()+ for {+ select {+ case <-ctx.Done():+ return+ case now := <-t.C:+ reopenCodexAppOut(ctx, now)+ }+ }+}diff --git a/internal/gui/codex_app_out_test.go b/internal/gui/codex_app_out_test.gonew file mode 100644index 000000000..16827b962--- /dev/null+++ b/internal/gui/codex_app_out_test.go@@ -0,0 +1,93 @@+package gui++import (+ "context"+ "testing"+ "time"++ "github.com/yetone/magpie/internal/gateway"+)++// The Codex app left unable to send on its used-up ChatGPT account is+// reopened by magpie on macOS (MasterYi on Discord), once each time the+// account runs out, and only while: the app open then still runs, magpie+// is Codex's provider for the account, the account is out, and no turn is+// in flight through magpie or ended in the last codexAppOutIdle. Nothing+// real is quit: the reopen is a stub.+func TestCodexAppOutReopenedOnce(t *testing.T) {+ var (+ user = "[email protected]"+ tried, agentOut = false, true+ usedUp = true+ busy gateway.Busy+ bundles = []string{"/Applications/ChatGPT.app"}+ goos = "darwin"+ reopened []string+ )+ saved := []any{codexAppOutUser, codexAppOutTried, codexAppOutOnce, codexAppOutUsedUp, codexAgentOut, codexAppOutBundles, codexAppOutReopen, gatewayBusy, codexAppOutOS}+ t.Cleanup(func() {+ codexAppOutUser, codexAppOutTried, codexAppOutOnce = saved[0].(func() string), saved[1].(func() bool), saved[2].(func() bool)+ codexAppOutUsedUp, codexAgentOut, codexAppOutBundles = saved[3].(func() bool), saved[4].(func() bool), saved[5].(func() []string)+ codexAppOutReopen, gatewayBusy, codexAppOutOS = saved[6].(func(context.Context, string) error), saved[7].(func() gateway.Busy), saved[8].(string)+ })+ codexAppOutUser = func() string { return user }+ codexAppOutTried = func() bool { return tried }+ codexAppOutOnce = func() bool {+ if tried {+ return false+ }+ tried = true+ return true+ }+ codexAppOutUsedUp = func() bool { return usedUp }+ codexAgentOut = func() bool { return agentOut }+ codexAppOutBundles = func() []string { return bundles }+ codexAppOutReopen = func(_ context.Context, b string) error { reopened = append(reopened, b); return nil }+ gatewayBusy = func() gateway.Busy { return busy }+ codexAppOutOS = goos+ now := time.Now()++ check := func(when string, want bool) {+ t.Helper()+ if got := reopenCodexAppOut(context.Background(), now); got != want {+ t.Fatalf("%s: tried %v, want %v (reopened %v)", when, got, want, reopened)+ }+ }+ if s := codexAppOutState(); s == nil || s.User != user || !s.Reopening {+ t.Fatalf("the notice before: %+v", s)+ }+ busy = gateway.Busy{Requests: 1}+ check("a turn in flight", false)+ busy = gateway.Busy{Last: now.Add(-10 * time.Second)}+ check("a turn ended 10s ago", false)+ busy = gateway.Busy{Last: now.Add(-codexAppOutIdle)}+ agentOut = false+ check("magpie not Codex's provider for it", false)+ agentOut, usedUp = true, false+ check("the account has room", false)+ usedUp, user = true, ""+ check("no app open as it ran out", false)+ user, bundles = "[email protected]", nil+ check("no app open from before the change", false)+ bundles = []string{"/Applications/ChatGPT.app"}+ codexAppOutOS = "linux"+ check("not macOS", false)+ if s := codexAppOutState(); s == nil || s.Reopening {+ t.Fatalf("the notice off macOS: %+v", s)+ }+ codexAppOutOS = "darwin"+ if len(reopened) != 0 {+ t.Fatalf("reopened before every condition held: %v", reopened)+ }+ check("all hold", true)+ if len(reopened) != 1 || reopened[0] != "/Applications/ChatGPT.app" {+ t.Fatalf("reopened %v", reopened)+ }+ check("again, the same time out", false)+ if len(reopened) != 1 {+ t.Fatalf("reopened twice: %v", reopened)+ }+ if s := codexAppOutState(); s == nil || s.Reopening {+ t.Fatalf("the notice after a reopen that didn't take: %+v", s)+ }+}diff --git a/internal/gui/providers.go b/internal/gui/providers.goindex 5ba3dfd3a..7413bb6a9 100644--- a/internal/gui/providers.go+++ b/internal/gui/providers.go@@ -487,6 +487,9 @@ type providersJSON struct {// after Codex was switched to another, until it is quit and opened// again (provider.CodexAppStale)CodexApp string `json:"codexApp,omitempty"`+ // CodexAppOut is a Codex app left unable to send on its used-up+ // ChatGPT account until it is opened again (codexAppOutState)+ CodexAppOut *codexAppOutJSON `json:"codexAppOut,omitempty"`// Plugins are the providers the plugins sign in to, for the add sheetPlugins []pluginSubJSON `json:"plugins"`// OnPlugins are the built-in subscriptions moved onto their plugins,@@ -955,6 +958,7 @@ func providersState() providersJSON {s.Gateway.Archive = archiveState()s.CodexDaemon = provider.CodexDaemonStale()s.CodexApp = provider.CodexAppStale()+ s.CodexAppOut = codexAppOutState()s.Plugins = pluginSubs()s.Fetching = provider.FetchingNew()return sdiff --git a/internal/gui/tests/codex-app-out.test.cjs b/internal/gui/tests/codex-app-out.test.cjsnew file mode 100644index 000000000..0295201ac--- /dev/null+++ b/internal/gui/tests/codex-app-out.test.cjs@@ -0,0 +1,84 @@+// Run with Node's test runner and Playwright on the module path; see README.md.+// The Codex app reads its sign-in only as it opens. When the ChatGPT+// account it is on runs out it greys its Send for every model, magpie's+// too, even after magpie became Codex's provider (MasterYi on Discord).+// Codex's accounts say so with the account, and what happens next: on+// macOS magpie reopens the app once no turn is running; elsewhere, or once+// that was tried, the user quits it and opens it again.+// In every language, Chromium and WebKit, wide and narrow.+const assert = require("node:assert/strict");+const fs = require("node:fs/promises");+const path = require("node:path");+const { test } = require("node:test");+const { chromium, webkit } = require("playwright");++const assets = path.resolve(__dirname, "../assets");+const codex = {+ id: "codex", name: "Codex", icon: "codex-color", chat: "", responses: "", anthropic: "", catalog: "", routing: "smart",+ models: [{ id: "gpt-6", name: "GPT-6", on: true }], agents: [], fallback: [], headers: {}, keyList: [],+ account: {+ agent: "codex", agentName: "Codex", user: "[email protected]", plan: "PLUS",+ logins: [{ user: "[email protected]", plan: "PLUS", active: true, on: true }],+ },+};++function serve(lang, reopening) {+ const providers = () => ({ providers: [codex], presets: [], excluded: [], gateway: { running: true, window: true }, codexAppOut: { user: "[email protected]", reopening } });+ const state = { agents: [], profiles: [], settings: { lang, theme: "light" } };+ return async (route) => {+ const url = new URL(route.request().url());+ const json = (data) => route.fulfill({ json: data });+ if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });+ if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });+ if (url.pathname === "/api/state") return json(state);+ if (url.pathname === "/api/providers") return json(providers());+ if (url.pathname === "/api/groups") return json({ groups: [] });+ if (url.pathname === "/api/plugins") return json({ plugins: [] });+ if (url.pathname.startsWith("/api/")) return json({});+ const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);+ const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];+ await route.fulfill({ body: await fs.readFile(file), contentType });+ };+}++const keys = [+ "The Codex app can't send on {user}'s used-up account",+ "magpie serves its turns now, but the app reads that only as it opens. magpie quits it and opens it again once no turn is running.",+ "magpie serves its turns now, but the app reads that only as it opens. Quit it and open it again to send.",+];++for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {+ for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {+ for (const width of [900, 480]) {+ for (const reopening of [true, false]) {+ test(`${engine} ${lang} ${width}px ${reopening ? "reopening" : "by hand"}: Codex's accounts say the Codex app can't send on its used-up account`, async (t) => {+ const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));+ t.after(() => browser.close());+ const page = await (await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" })).newPage();+ page.setDefaultTimeout(5000);+ const errors = [];+ page.on("pageerror", (e) => errors.push(e.message));+ await page.route("**/*", serve(lang, reopening));+ await page.goto("http://magpie.test/?view=providers");+ await page.locator(".row.provider", { hasText: "Codex" }).first().click();+ const box = page.locator(".editor .signing.app-out");+ await box.waitFor();+ const text = await box.textContent();+ assert.match(text, /spent@example\.com/);+ if (lang === "en") {+ assert.match(text, reopening ? /magpie quits it and opens it again/ : /Quit it and open it again to send/);+ assert.doesNotMatch(text, reopening ? /Quit it and open it again to send/ : /magpie quits it/);+ } else {+ const missing = await page.evaluate(([l, ks]) => ks.filter((k) => !I18N[l][k]), [lang, keys]);+ assert.deepEqual(missing, [], `every string has its ${lang}`);+ assert.doesNotMatch(text, /open it again/);+ }+ const fits = await box.evaluate((b) => [...b.querySelectorAll("*")].every((e) => e.getBoundingClientRect().right <= b.getBoundingClientRect().right + 0.5));+ assert.ok(fits, "nothing in the notice runs past it");+ assert.equal(await page.evaluate(() => document.scrollingElement.scrollWidth <= innerWidth), true, "no sideways scroll");+ assert.deepEqual(errors, []);+ });+ }+ }+ }+}diff --git a/internal/provider/codex_app_out.go b/internal/provider/codex_app_out.gonew file mode 100644index 000000000..52505fac5--- /dev/null+++ b/internal/provider/codex_app_out.go@@ -0,0 +1,158 @@+package provider++import (+ "context"+ "strings"+ "sync"+ "sync/atomic"+ "time"+)++// The Codex app reads its sign-in only as it opens: an account used up+// while it runs greys its Send for every model, magpie's included, and+// stays so after magpie becomes Codex's provider (MasterYi on Discord),+// till the app is quit and opened again. What follows tells the account+// is out as soon as a reply says so, not at the next look five minutes+// on, and keeps which Codex app was open when it ran out, for the GUI to+// reopen (once) or name.++// codexLiveChecks counts the running loops that keep Codex on an account+// with room (KeepOnAnAccountWithRoom) past their first reading: while one+// does, a reply that says Codex's account is out has it read again at+// once (CodexMayBeUsedUp). A test's gateway, gone within the minute+// before that first reading, never turns it on, so tests never ask the+// vendor.+var codexLiveChecks atomic.Int32++// codexRecheckEvery is the least time between two such readings.+var codexRecheckEvery = 20 * time.Second++var codexRecheck struct {+ sync.Mutex+ at time.Time+}++// codexReadNow reads whether Codex's account is out; a var for tests.+var codexReadNow = func(user string) {+ StaleAllowance("codex", user)+ ctx, cancel := context.WithTimeout(context.Background(), time.Minute)+ defer cancel()+ noteCodexUsedUp(CodexUsedUp(ctx))+}++// CodexMayBeUsedUp is a reply's word that user's ChatGPT account may be+// out (usage_limit_reached, or a window heard at 100%): for the account+// Codex is signed in to, its allowance is read again at once, at most+// every codexRecheckEvery, and a change told as the five-minute look tells+// it (noteCodexUsedUp).+func CodexMayBeUsedUp(user string) {+ if codexLiveChecks.Load() <= 0 || user == "" {+ return+ }+ active := ""+ for _, l := range Logins("codex") {+ if l.Active && strings.EqualFold(l.User, user) {+ active = l.User+ }+ }+ if active == "" {+ return+ }+ c := &codexRecheck+ c.Lock()+ if time.Since(c.at) < codexRecheckEvery {+ c.Unlock()+ return+ }+ c.at = time.Now()+ c.Unlock()+ go codexReadNow(active)+}++// codexAppOut is the Codex app open when the account it is signed in to+// ran out: its app-server's pid, and whether the GUI tried reopening it.+var codexAppOut struct {+ sync.Mutex+ user string+ pid int+ tried bool+ checked time.Time+}++// noteCodexAppOut keeps, as the account Codex is signed in to runs out+// (out) or has room again, which Codex app was open then.+func noteCodexAppOut(out bool) {+ user, pid := "", 0+ if out {+ for _, l := range Logins("codex") {+ if l.Active {+ user = l.User+ }+ }+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ ps, err := listProcesses(ctx)+ cancel()+ if err == nil {+ pid = findCodexApp(ps)+ }+ }+ c := &codexAppOut+ c.Lock()+ defer c.Unlock()+ if pid == 0 {+ // none open: one opened from now reads the sign-in afresh+ c.user, c.pid, c.tried = "", 0, false+ return+ }+ c.user, c.pid, c.tried, c.checked = user, pid, false, time.Now()+}++// CodexAppOut is the ChatGPT account of a Codex app that was open when+// that account ran out and hasn't been opened again since, "" for none:+// it sends nothing till it is (the agent package's AppOut says whether+// magpie is Codex's provider for it, which the app needs too).+func CodexAppOut() string {+ c := &codexAppOut+ c.Lock()+ defer c.Unlock()+ if c.pid == 0 {+ return ""+ }+ if time.Since(c.checked) > codexDaemonRecheck {+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ ps, err := listProcesses(ctx)+ cancel()+ // what was known stays when the processes can't be listed+ if err == nil {+ c.checked = time.Now()+ if findCodexApp(ps) != c.pid {+ c.user, c.pid, c.tried = "", 0, false+ return ""+ }+ }+ }+ return c.user+}++// CodexAppReopenOnce is whether the Codex app CodexAppOut names may be+// reopened by magpie: true once for each time the account runs out, so+// a reopen that didn't take is never tried again.+func CodexAppReopenOnce() bool {+ c := &codexAppOut+ c.Lock()+ defer c.Unlock()+ if c.pid == 0 || c.tried {+ return false+ }+ c.tried = true+ return true+}++// CodexAppReopenTried is whether magpie tried reopening the Codex app+// CodexAppOut names already, which it doesn't do twice.+func CodexAppReopenTried() bool {+ c := &codexAppOut+ c.Lock()+ defer c.Unlock()+ return c.tried+}diff --git a/internal/provider/codex_app_out_test.go b/internal/provider/codex_app_out_test.gonew file mode 100644index 000000000..da6544d8c--- /dev/null+++ b/internal/provider/codex_app_out_test.go@@ -0,0 +1,119 @@+package provider++import (+ "context"+ "testing"+ "time"++ "github.com/yetone/magpie/internal/proc"+)++// A reply that says the account Codex is signed in to is out has its+// allowance read again at once, not at the next look five minutes on+// (MasterYi on Discord: the Codex app greyed Send meanwhile): once per+// codexRecheckEvery, for the active account alone, and only in a magpie+// that keeps Codex on an account with room.+func TestCodexMayBeUsedUpReadsAtOnce(t *testing.T) {+ signIn(t) // [email protected], active+ rememberLogins(true)+ reads := make(chan string, 8)+ oldRead, oldEvery := codexReadNow, codexRecheckEvery+ codexReadNow = func(user string) { reads <- user }+ t.Cleanup(func() {+ codexReadNow, codexRecheckEvery = oldRead, oldEvery+ codexLiveChecks.Store(0)+ codexRecheck.Lock()+ codexRecheck.at = time.Time{}+ codexRecheck.Unlock()+ })+ none := func(when string) {+ t.Helper()+ select {+ case u := <-reads:+ t.Fatalf("%s: read %q", when, u)+ case <-time.After(50 * time.Millisecond):+ }+ }+ read := func(when string) {+ t.Helper()+ select {+ case u := <-reads:+ if u != "[email protected]" {+ t.Fatalf("%s: read %q", when, u)+ }+ case <-time.After(10 * time.Second):+ t.Fatalf("%s: not read", when)+ }+ }+ full := []CodexLimit{{Used: 100, Span: 5 * time.Hour}}++ NoteCodexLimits("codex", "[email protected]", full)+ none("live checks off")++ codexLiveChecks.Store(1)+ NoteCodexLimits("codex", "[email protected]", []CodexLimit{{Used: 99, Span: 5 * time.Hour}})+ none("a window with room")+ NoteCodexLimits("codex", "[email protected]", full)+ none("an account Codex isn't on")+ NoteCodexLimits("codex", "[email protected]", full)+ read("a window full")+ CodexMayBeUsedUp("[email protected]")+ none("again at once")++ codexRecheckEvery = 0+ CodexMayBeUsedUp("[email protected]")+ read("usage_limit_reached")+}++// The Codex app open when its account ran out is kept till it is opened+// again (its app-server's pid changes) or the account has room, and may+// be reopened once for each time the account runs out.+func TestCodexAppOutEpisode(t *testing.T) {+ signIn(t)+ rememberLogins(true)+ app := new(int)+ old := listProcesses+ t.Cleanup(func() {+ listProcesses = old+ noteCodexAppOut(false)+ })+ listProcesses = func(context.Context) ([]proc.Process, error) {+ ps := []proc.Process{{PID: 7, Args: "codex"}}+ if *app > 0 {+ ps = append(ps, proc.Process{PID: *app, Args: "/Applications/ChatGPT.app/Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS/codex app-server"})+ }+ return ps, nil+ }+ recheck := func() { codexAppOut.Lock(); codexAppOut.checked = time.Time{}; codexAppOut.Unlock() }++ noteCodexAppOut(true)+ if got := CodexAppOut(); got != "" || CodexAppReopenOnce() {+ t.Fatalf("no app open: %q", got)+ }+ *app = 60+ noteCodexAppOut(true)+ if got := CodexAppOut(); got != "[email protected]" {+ t.Fatalf("app open as it ran out: %q", got)+ }+ if !CodexAppReopenOnce() || CodexAppReopenOnce() {+ t.Fatal("reopened other than once")+ }+ recheck()+ if got := CodexAppOut(); got != "[email protected]" {+ t.Fatalf("still the same app: %q", got)+ }+ *app = 61+ recheck()+ if got := CodexAppOut(); got != "" {+ t.Fatalf("opened again: %q", got)+ }++ noteCodexAppOut(true) // out again: a new time, reopened once more+ if CodexAppOut() == "" || !CodexAppReopenOnce() {+ t.Fatal("out again: not kept")+ }+ noteCodexAppOut(false)+ if got := CodexAppOut(); got != "" {+ t.Fatalf("room again: %q", got)+ }+}diff --git a/internal/provider/codex_limits.go b/internal/provider/codex_limits.goindex 88a36ed41..b2b08c30c 100644--- a/internal/provider/codex_limits.go+++ b/internal/provider/codex_limits.go@@ -1,6 +1,7 @@package providerimport (+ "slices""strings""time")@@ -31,6 +32,11 @@ func NoteCodexLimits(agent, user string, heard []CodexLimit) {if len(heard) == 0 || user == "" {return}+ // a window full: Codex's own account may be out, which the Codex app+ // is told only as it opens (CodexMayBeUsedUp)+ if agent == "codex" && slices.ContainsFunc(heard, func(h CodexLimit) bool { return h.Used >= 100 }) {+ CodexMayBeUsedUp(user)+ }key := agent + "/" + strings.ToLower(user)c := &loginUsageCachec.Lock()diff --git a/internal/provider/codex_switch.go b/internal/provider/codex_switch.goindex f80371f21..aa0e5cf1c 100644--- a/internal/provider/codex_switch.go+++ b/internal/provider/codex_switch.go@@ -323,6 +323,7 @@ var codexWasUsedUp atomic.Bool// (#540). Only a change is told.func noteCodexUsedUp(now bool) {if codexWasUsedUp.Swap(now) != now {+ noteCodexAppOut(now)catalog.Touched()}}@@ -334,12 +335,25 @@ func noteCodexUsedUp(now bool) {func KeepOnAnAccountWithRoom(ctx context.Context) {t := time.NewTimer(time.Minute)defer t.Stop()+ live := false+ defer func() {+ if live {+ codexLiveChecks.Add(-1)+ }+ }()for {select {case <-ctx.Done():returncase <-t.C:}+ // a reply's word that the account is out is read at once only+ // while this loop, which reads the vendor itself, has started+ // reading and still runs: a test's short-lived gateway never does+ if !live {+ live = true+ codexLiveChecks.Add(1)+ }for _, agent := range switchedAgents {c, cancel := context.WithTimeout(ctx, time.Minute)if _, err := SwitchWhenSpent(c, agent); err != nil {