Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
codex: the Codex app sends again on every system as soon as magpie takes a used-up ChatGPT account over, and gets it back at the reset
yetone8b0132b3d2cf
diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.mdindex e1d04a8f1..6e5fe8bb7 100644--- a/docs/subsystems/agent-wiring.md+++ b/docs/subsystems/agent-wiring.md@@ -76,7 +76,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). 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`).+- 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 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`, through the `provider.CodexAppOnMagpie` hook) and again when Codex is put back on the account after its reset, 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`, `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/agents.go b/internal/agent/agents.goindex 2a154e980..0d0064e9a 100644--- a/internal/agent/agents.go+++ b/internal/agent/agents.go@@ -46,6 +46,20 @@ func init() {}// a Copilot CLI signed in inside a running distro (#723)provider.CopilotWSLHomes = copilotWSLHomes+ // the Codex app's app-server is restarted when magpie becomes Codex's+ // provider for its used-up ChatGPT account, and when it stops being it+ provider.CodexAppOnMagpie = codexAppOnMagpie+}++// codexAppOnMagpie is whether magpie is Codex's provider for its used-up+// ChatGPT account (AppOut); not known when Codex's config can't be read.+func codexAppOnMagpie() (on, known bool) {+ home, _ := homes()+ a := codex(home)+ if _, err := os.ReadFile(a.Path); err != nil && !errors.Is(err, fs.ErrNotExist) {+ return false, false+ }+ return a.AppOut != nil && a.AppOut(), true}// others are clients that reach the gateway without being agents magpiediff --git a/internal/gateway/busy.go b/internal/gateway/busy.goindex 41234ba8a..b1a1a4328 100644--- a/internal/gateway/busy.go+++ b/internal/gateway/busy.go@@ -46,6 +46,26 @@ func (s *Server) Busy() Busy {return b}+// CodexBusy is how many of Codex's requests are in flight and when its+// last ended: a turn of the Codex app's that a restart of its app-server+// would cut short (provider.KeepCodexAppOnItsProvider). Other agents'+// requests don't hold it.+func (s *Server) CodexBusy() (int, time.Time) {+ n := 0+ s.active.mu.Lock()+ for _, f := range s.active.m {+ if f.agent == "codex" {+ n+++ }+ }+ s.active.mu.Unlock()+ var last time.Time+ if d := s.codexDone.Load(); d != 0 {+ last = time.Unix(0, d)+ }+ return n, last+}+// bridgeTurn counts a turn served through the subscription bridge for// Busy.Bridge until done is called.func (s *Server) bridgeTurn() (done func()) {@@ -81,6 +101,9 @@ func (s *Server) counted(h http.Handler) http.Handler {unwatch()done()s.lastDone.Store(time.Now().UnixNano())+ if f := inflightOf(r.Context()); f != nil && f.agent == "codex" {+ s.codexDone.Store(time.Now().UnixNano())+ }if s.inFlight.Add(-1) == 0 {s.armRelease(s.idle.restFor())}@@ -97,6 +120,8 @@ type busyCounters struct {// the subscription bridge's turns among them, and when the last endedbridgeInFlight atomic.Int64bridgeDone atomic.Int64 // unix ns+ // when Codex's last request ended (CodexBusy)+ codexDone atomic.Int64 // unix ns// handing back what requests left once it rests (idle_memory.go)idle idleMemory}diff --git a/internal/gateway/busy_test.go b/internal/gateway/busy_test.goindex 1d46a2886..7016fab72 100644--- a/internal/gateway/busy_test.go+++ b/internal/gateway/busy_test.go@@ -309,3 +309,66 @@ func TestConcurrencyListsEachRequest(t *testing.T) {time.Sleep(10 * time.Millisecond)}}++// CodexBusy counts Codex's requests alone: a restart of the Codex app's+// app-server waits for a Codex turn, never for another agent's.+func TestCodexBusy(t *testing.T) {+ fresh(t)+ started, release := make(chan struct{}, 2), make(chan struct{})+ up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ io.Copy(io.Discard, r.Body)+ w.Header().Set("Content-Type", "text/event-stream")+ io.WriteString(w, `data: {"id":"c","object":"chat.completion.chunk","model":"m","choices":[{"index":0,"delta":{"role":"assistant","content":"hel"}}]}`+"\n\n")+ w.(http.Flusher).Flush()+ started <- struct{}{}+ <-release+ io.WriteString(w, `data: {"id":"c","object":"chat.completion.chunk","model":"m","choices":[{"index":0,"delta":{"content":"lo"},"finish_reason":"stop"}]}`+"\n\ndata: [DONE]\n\n")+ }))+ defer up.Close()+ if err := provider.Save(provider.Provider{ID: "up", Name: "Up", Key: "k", Chat: up.URL + "/v1", Models: []string{"m"}}); err != nil {+ t.Fatal(err)+ }+ s := New()+ gw := httptest.NewServer(s.Handler())+ defer gw.Close()+ var hold sync.WaitGroup+ let := sync.OnceFunc(func() { close(release) })+ defer hold.Wait()+ defer let()+ send := func(key string) {+ hold.Add(1)+ go func() {+ defer hold.Done()+ req, _ := http.NewRequest("POST", gw.URL+"/v1/chat/completions", strings.NewReader(`{"model":"up/m","stream":true,"messages":[{"role":"user","content":"hi"}]}`))+ req.Header.Set("Content-Type", "application/json")+ req.Header.Set("Authorization", "Bearer "+key)+ res, err := http.DefaultClient.Do(req)+ if err == nil {+ io.Copy(io.Discard, res.Body)+ res.Body.Close()+ }+ }()+ }+ if n, last := s.CodexBusy(); n != 0 || !last.IsZero() {+ t.Fatalf("before any request: %d %v", n, last)+ }+ send(Token + "-opencode")+ <-started+ if n, last := s.CodexBusy(); n != 0 || !last.IsZero() {+ t.Fatalf("another agent's request: %d %v", n, last)+ }+ send(Token + "-codex")+ <-started+ if n, _ := s.CodexBusy(); n != 1 {+ t.Fatalf("Codex's request in flight: %d, want 1 (%+v)", n, s.Active())+ }+ let()+ hold.Wait()+ deadline := time.Now().Add(5 * time.Second)+ for s.Busy().Requests != 0 && time.Now().Before(deadline) {+ time.Sleep(10 * time.Millisecond)+ }+ if n, last := s.CodexBusy(); n != 0 || time.Since(last) > 5*time.Second {+ t.Fatalf("after: %d %v", n, last)+ }+}diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.goindex a339ee5cc..e5347e75e 100644--- a/internal/gateway/gateway.go+++ b/internal/gateway/gateway.go@@ -628,6 +628,9 @@ func (s *Server) ListenAndServe(ctx context.Context) error {// and signs Codex and Claude Code in to their next account when the// one they are on is spentgo provider.KeepOnAnAccountWithRoom(ctx)+ // and has the Codex app read its provider again as magpie becomes it+ // for a used-up ChatGPT account, and after (its Send greys otherwise)+ go provider.KeepCodexAppOnItsProvider(ctx, s.CodexBusy)// and, when settings say to, starts its accounts' next windows as the last resetgo provider.KeepCodexWindowsWarm(ctx)go provider.KeepClaudeWindowsWarm(ctx, warmClaude)diff --git a/internal/gui/api.go b/internal/gui/api.goindex fb786a98b..fabf851d6 100644--- a/internal/gui/api.go+++ b/internal/gui/api.go@@ -224,6 +224,10 @@ type agentJSON struct {// Joined: connected with its own models still in its list (Codex// signed in with ChatGPT, agent.Agent.Join)Joined bool `json:"joined,omitempty"`+ // AppOut: magpie is Codex's provider while the ChatGPT account it is+ // signed in to is used up (agent.Agent.AppOut), which turns the Codex+ // app's ChatGPT side off until the reset+ AppOut *appOutJSON `json:"appOut,omitempty"`// Failover: not connected, yet its requests go through magpie for// account failover alone (agent.Agent.FailingOver, #1385)Failover bool `json:"failover,omitempty"`@@ -2459,6 +2463,9 @@ func state() stateJSON {aj.StaleCopies = a.StaleCopies()aj.Stale = len(aj.StaleCopies)aj.Joined = a.Joined != nil && a.Joined()+ if a.AppOut != nil && a.AppOut() {+ aj.AppOut = codexAppOut()+ }} else {aj.Source = a.Source()aj.Failover = a.FailingOver != nil && a.FailingOver()@@ -2830,3 +2837,26 @@ var bunSaid = map[string]string{"windows": "Bun, which runs plugins, can't start on this version of Windows: it needs Windows 10 version 1809 or later, or Windows Server 2019 or later. Update Windows to use plugins, or set MAGPIE_BUN to a bun that runs here.","cpu": "Bun, which runs plugins, can't start on this computer's processor: it needs an x64 processor with SSE4.2 (Intel or AMD from 2008 on; in a virtual machine, a CPU type that passes it through). Run magpie on such a processor to use plugins, or set MAGPIE_BUN to a bun that runs here.",}++// appOutJSON is Codex on magpie while its ChatGPT account is used up: the+// account, when it has room again (zero when the reading doesn't say), and+// whether a Codex app is left on the account, its app-server not+// restarted (provider.CodexAppStuck), for the user to reopen it.+type appOutJSON struct {+ User string `json:"user,omitempty"`+ Until *time.Time `json:"until,omitempty"`+ Stuck bool `json:"stuck,omitempty"`+}++func codexAppOut() *appOutJSON {+ o := &appOutJSON{Stuck: provider.CodexAppStuck()}+ for _, l := range provider.Logins("codex") {+ if l.Active {+ o.User = l.User+ }+ }+ if u := provider.CodexOutUntil(); !u.IsZero() {+ o.Until = &u+ }+ return o+}diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.jsindex c41574d39..8f9a1d58e 100644--- a/internal/gui/assets/app.js+++ b/internal/gui/assets/app.js@@ -1370,6 +1370,16 @@ function connectLine(a, kind) {return line;}line.classList.add("on");+ // Codex on magpie while its ChatGPT account is used up: the line says+ // until when, the hover (and the row opened) what is off till then+ if (a.appOut) {+ const o = a.appOut;+ if (o.stuck) say(t("On magpie · quit and reopen the {agent} app to send", { agent: a.name }), "wait");+ else if (o.until) say(t("On magpie until {when} · ChatGPT allowance used up", { when: resetClock(new Date(o.until)) }));+ else say(t("On magpie until the reset · ChatGPT allowance used up"));+ words.title = appOutSaid(a);+ return line;+ }if (a.appRestart) {say(t("Connected · restart {agent} to use it", { agent: a.name }), "wait");line.append(appRestart(a));@@ -1886,6 +1896,19 @@ function appReopen(bundle) {return go;}+// appOutSaid: why Codex is on magpie while its ChatGPT account is used up,+// and what of the Codex app is off till the reset (the app turns its+// ChatGPT side off with magpie its provider, and greys Send without)+function appOutSaid(a) {+ const o = a.appOut || {};+ let s = o.user+ ? t("{user}'s ChatGPT allowance is used up, so magpie serves {agent}'s turns until it resets.", { user: o.user, agent: a.name })+ : t("{agent}'s ChatGPT allowance is used up, so magpie serves its turns until it resets.", { agent: a.name });+ s += " " + t("Till then the {agent} app's ChatGPT side is off: cloud tasks, its usage meter and Log out. It all comes back on its own at the reset.", { agent: a.name });+ if (o.stuck) s += " " + t("magpie couldn't restart the {agent} app's app-server: quit the app and open it again to send.", { agent: a.name });+ return s;+}+// appRestart: a desktop app running on what it read before magpie's last// change (agent.AppBehind) is quit and opened againfunction appRestart(a) {@@ -1968,6 +1991,12 @@ function connectPanel(a, { fields, fieldBtn }) {parts.push(l);}}+ // on magpie while its ChatGPT account is used up, and what is off+ if (a.appOut) {+ const w = line(el("span", "ag-dot"), el("span", "", appOutSaid(a)));+ w.classList.add("ag-warn", "ag-app-out");+ parts.unshift(w);+ }kv(t("In {agent}", { agent: a.name }), ...parts);} else if (menuFromList(a)) {kv(t("In {agent}", { agent: a.name }), line(t("{agent}'s model menu lists the models picked here; switch among them there. It reads the list as it starts: quit and reopen it after a change.", { agent: a.name })));@@ -13027,7 +13056,6 @@ function renderAccounts(a, p) {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");@@ -13087,15 +13115,6 @@ function codexNote(cls, n, s) {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 5ac9b65a8..8342381e1 100644--- a/internal/gui/assets/i18n.js+++ b/internal/gui/assets/i18n.js@@ -1823,9 +1823,13 @@ 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 现已接管它的对话,但应用只在打开时读取这一点。退出后重新打开即可发送。",+ "On magpie · quit and reopen the {agent} app to send": "由 magpie 接管 · 退出并重新打开 {agent} 应用即可发送",+ "On magpie until {when} · ChatGPT allowance used up": "由 magpie 接管至 {when} · ChatGPT 额度已用完",+ "On magpie until the reset · ChatGPT allowance used up": "由 magpie 接管至额度重置 · ChatGPT 额度已用完",+ "{user}'s ChatGPT allowance is used up, so magpie serves {agent}'s turns until it resets.": "{user} 的 ChatGPT 额度已用完,重置前由 magpie 接管 {agent} 的对话。",+ "{agent}'s ChatGPT allowance is used up, so magpie serves its turns until it resets.": "{agent} 的 ChatGPT 额度已用完,重置前由 magpie 接管它的对话。",+ "Till then the {agent} app's ChatGPT side is off: cloud tasks, its usage meter and Log out. It all comes back on its own at the reset.": "在此之前,{agent} 应用的 ChatGPT 功能暂时关闭:云端任务、用量显示和退出登录。额度重置后会自动全部恢复。",+ "magpie couldn't restart the {agent} app's app-server: quit the app and open it again to send.": "magpie 无法重启 {agent} 应用的 app-server:退出应用并重新打开即可发送。","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 的模型和路由组。",@@ -5828,9 +5832,13 @@ 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 現已接管它的對話,但應用只在開啟時讀取這一點。結束後重新開啟即可傳送。",+ "On magpie · quit and reopen the {agent} app to send": "由 magpie 接管 · 結束並重新開啟 {agent} 應用即可傳送",+ "On magpie until {when} · ChatGPT allowance used up": "由 magpie 接管至 {when} · ChatGPT 額度已用完",+ "On magpie until the reset · ChatGPT allowance used up": "由 magpie 接管至額度重設 · ChatGPT 額度已用完",+ "{user}'s ChatGPT allowance is used up, so magpie serves {agent}'s turns until it resets.": "{user} 的 ChatGPT 額度已用完,重設前由 magpie 接管 {agent} 的對話。",+ "{agent}'s ChatGPT allowance is used up, so magpie serves its turns until it resets.": "{agent} 的 ChatGPT 額度已用完,重設前由 magpie 接管它的對話。",+ "Till then the {agent} app's ChatGPT side is off: cloud tasks, its usage meter and Log out. It all comes back on its own at the reset.": "在此之前,{agent} 應用的 ChatGPT 功能暫時關閉:雲端任務、用量顯示和登出。額度重設後會自動全部恢復。",+ "magpie couldn't restart the {agent} app's app-server: quit the app and open it again to send.": "magpie 無法重新啟動 {agent} 應用的 app-server:結束應用並重新開啟即可傳送。","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 的模型和路由組。",@@ -9810,9 +9818,13 @@ 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 がそのターンを処理するようになりましたが、アプリはそれを起動時にしか読み込みません。送信するには、アプリを終了して開き直してください。",+ "On magpie · quit and reopen the {agent} app to send": "magpie が処理中 · 送信するには {agent} アプリを終了して開き直してください",+ "On magpie until {when} · ChatGPT allowance used up": "{when} まで magpie が処理 · ChatGPT の利用枠を使い切りました",+ "On magpie until the reset · ChatGPT allowance used up": "リセットまで magpie が処理 · ChatGPT の利用枠を使い切りました",+ "{user}'s ChatGPT allowance is used up, so magpie serves {agent}'s turns until it resets.": "{user} の ChatGPT の利用枠を使い切ったため、リセットまで magpie が {agent} のターンを処理します。",+ "{agent}'s ChatGPT allowance is used up, so magpie serves its turns until it resets.": "{agent} の ChatGPT の利用枠を使い切ったため、リセットまで magpie がそのターンを処理します。",+ "Till then the {agent} app's ChatGPT side is off: cloud tasks, its usage meter and Log out. It all comes back on its own at the reset.": "それまで {agent} アプリの ChatGPT 機能(クラウドタスク、使用量の表示、ログアウト)はオフになります。リセット時にすべて自動で戻ります。",+ "magpie couldn't restart the {agent} app's app-server: quit the app and open it again to send.": "magpie は {agent} アプリの app-server を再起動できませんでした。送信するには、アプリを終了して開き直してください。","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 のモデルとルーティンググループはモデルメニューにあります。",@@ -13822,9 +13834,13 @@ 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.",+ "On magpie · quit and reopen the {agent} app to send": "Über magpie · beende die {agent}-App und öffne sie wieder, um zu senden",+ "On magpie until {when} · ChatGPT allowance used up": "Über magpie bis {when} · ChatGPT-Kontingent aufgebraucht",+ "On magpie until the reset · ChatGPT allowance used up": "Über magpie bis zum Zurücksetzen · ChatGPT-Kontingent aufgebraucht",+ "{user}'s ChatGPT allowance is used up, so magpie serves {agent}'s turns until it resets.": "Das ChatGPT-Kontingent von {user} ist aufgebraucht, daher bedient magpie die Anfragen von {agent}, bis es zurückgesetzt wird.",+ "{agent}'s ChatGPT allowance is used up, so magpie serves its turns until it resets.": "Das ChatGPT-Kontingent von {agent} ist aufgebraucht, daher bedient magpie seine Anfragen, bis es zurückgesetzt wird.",+ "Till then the {agent} app's ChatGPT side is off: cloud tasks, its usage meter and Log out. It all comes back on its own at the reset.": "Bis dahin ist die ChatGPT-Seite der {agent}-App aus: Cloud-Aufgaben, ihre Nutzungsanzeige und Abmelden. Beim Zurücksetzen kommt alles von selbst wieder.",+ "magpie couldn't restart the {agent} app's app-server: quit the app and open it again to send.": "magpie konnte den App-Server der {agent}-App nicht neu starten: beende die App 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 d5911ed31..cb2d76d01 100644--- a/internal/gui/backend.go+++ b/internal/gui/backend.go@@ -47,9 +47,6 @@ 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.godeleted file mode 100644index f55412ced..000000000--- a/internal/gui/codex_app_out.go+++ /dev/null@@ -1,114 +0,0 @@-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.godeleted file mode 100644index 16827b962..000000000--- a/internal/gui/codex_app_out_test.go+++ /dev/null@@ -1,93 +0,0 @@-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 97e233dba..25a1c7554 100644--- a/internal/gui/providers.go+++ b/internal/gui/providers.go@@ -490,9 +490,6 @@ 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,@@ -961,7 +958,6 @@ 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.cjsindex 0295201ac..4fb3f3e8d 100644--- a/internal/gui/tests/codex-app-out.test.cjs+++ b/internal/gui/tests/codex-app-out.test.cjs@@ -1,11 +1,12 @@// 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.+// Ethereal499, Isdavexxx and MasterYi (#540): the Codex app greys its Send+// while the ChatGPT account it is signed in to is used up. magpie becomes+// Codex's provider for that account and restarts the app's app-server, so+// the app sends again but turns its ChatGPT side off till the reset. The+// Agents row says so: on magpie until when, and (on hover and in the row+// opened) what is off and that it all comes back. When magpie couldn't+// restart the app-server, it says to quit and reopen the app. Every+// language, both engines, wide and narrow. No backend, the API is faked.const assert = require("node:assert/strict");const fs = require("node:fs/promises");const path = require("node:path");@@ -13,72 +14,97 @@ 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 }],- },+const until = new Date(Date.now() + 3 * 3600e3).toISOString();+const codex = (appOut) => ({+ id: "codex", name: "Codex", path: "/fixture/config.toml", wired: true,+ fields: [{ key: "model", label: "model", value: "sub/gpt-6.1-sol", options: [{ value: "sub/gpt-6.1-sol", label: "sub/gpt-6.1-sol", ref: "sub/gpt-6.1-sol" }] }],+ appOut,+});++const words = {+ en: { until: "On magpie until", reset: "On magpie until the reset", stuck: "quit and reopen the Codex app", off: "cloud tasks" },+ zh: { until: "由 magpie 接管至", reset: "由 magpie 接管至额度重置", stuck: "退出并重新打开 Codex 应用", off: "云端任务" },+ "zh-TW": { until: "由 magpie 接管至", reset: "由 magpie 接管至額度重設", stuck: "結束並重新開啟 Codex 應用", off: "雲端任務" },+ ja: { until: "まで magpie が処理", reset: "リセットまで magpie が処理", stuck: "Codex アプリを終了して開き直して", off: "クラウドタスク" },+ de: { until: "Über magpie bis", reset: "Über magpie bis zum Zurücksetzen", stuck: "beende die Codex-App", off: "Cloud-Aufgaben" },};-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" } };+function serve(lang, agents) {+ 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 === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:false};` });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({});+ if (url.pathname === "/api/state") return route.fulfill({ json: state });+ if (url.pathname === "/api/plugins") return route.fulfill({ json: { plugins: [] } });+ if (url.pathname === "/api/usage/quotas") return route.fulfill({ json: [] });+ if (url.pathname === "/api/groups") return route.fulfill({ json: { groups: [] } });+ if (url.pathname === "/api/agents/cli") return route.fulfill({ json: { agents: {}, pending: false } });+ if (url.pathname === "/api/providers") return route.fulfill({ json: { providers: [], presets: [], excluded: [], gateway: { running: true, window: true } } });+ if (url.pathname.startsWith("/api/")) return route.fulfill({ 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.",+const row = '.row.agent[data-id="codex"]';+const cases = [+ ["until the reset's time", { user: "[email protected]", until }, "until"],+ ["until the reset, its time unknown", { user: "[email protected]" }, "reset"],+ ["the app-server couldn't be restarted", { user: "[email protected]", until, stuck: true }, "stuck"],];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, []);- });- }+ for (const lang of Object.keys(words)) {+ const w = words[lang];+ for (const width of [980, 440]) {+ test(`${engine} ${lang} ${width}px: the Codex row says it is on magpie till the reset, and what is off`, async (t) => {+ const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));+ t.after(() => browser.close());+ for (const [name, appOut, kind] of cases) {+ await t.test(name, async () => {+ const page = await browser.newPage({ viewport: { width, height: 800 } });+ page.setDefaultTimeout(5000);+ const errors = [];+ page.on("pageerror", (e) => errors.push(e.message));+ await page.route("**/*", serve(lang, [codex(appOut)]));+ await page.goto("http://magpie.test/?view=agents");+ const st = page.locator(`${row} .ag-st-t`);+ await st.waitFor();+ const text = await st.textContent();+ assert.ok(text.includes(w[kind]), `${JSON.stringify(text)} lacks ${JSON.stringify(w[kind])}`);+ assert.doesNotMatch(text, /\{\w+\}/);+ const title = await page.locator(`${row} .ag-st-t`).getAttribute("title");+ assert.ok(title && title.includes(w.off), "the hover says what is off: " + title);+ assert.ok(title.includes("[email protected]"), "the hover names the account: " + title);+ assert.doesNotMatch(title, /\{\w+\}/);++ await page.locator(`${row} .ag-link`).click();+ const said = page.locator(`${row} .ag-app-out`);+ await said.waitFor();+ const s = await said.textContent();+ assert.ok(s.includes(w.off), "the row opened says what is off: " + s);+ assert.doesNotMatch(s, /\{\w+\}/);+ const side = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);+ assert.ok(side <= 1, "scrolls sideways: " + side);+ assert.deepEqual(errors, []);+ await page.close();+ });+ }+ });}}+ test(`${engine}: without appOut the row says nothing of it`, async (t) => {+ const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));+ t.after(() => browser.close());+ const page = await browser.newPage({ viewport: { width: 980, height: 800 } });+ await page.route("**/*", serve("en", [codex(undefined)]));+ await page.goto("http://magpie.test/?view=agents");+ await page.locator(`${row} .ag-st-t`).waitFor();+ assert.doesNotMatch(await page.locator(`${row} .ag-st-t`).textContent(), /On magpie until|ChatGPT allowance/);+ await page.locator(`${row} .ag-link`).click();+ await page.locator(`${row} .ag-exp`).waitFor();+ assert.equal(await page.locator(`${row} .ag-app-out`).count(), 0);+ });}diff --git a/internal/proc/env.go b/internal/proc/env.gonew file mode 100644index 000000000..bf4ee7295--- /dev/null+++ b/internal/proc/env.go@@ -0,0 +1,71 @@+package proc++import (+ "context"+ "errors"+ "regexp"+ "strings"+)++// End ends process pid as its own clean exit would look to its parent:+// SIGTERM where there are signals, on Windows TerminateProcess with exit+// code 0. The Codex app starts its app-server again after an exit 0 and+// shows an error for any other (its AppServerConnection: code === 0 is+// classifiedAsExpected). ErrDenied when this user may not; nil when pid+// is gone already.+func End(pid int) error { return end(pid) }++// ErrNoEnv is a system that doesn't tell another process's environment+// (Windows here).+var ErrNoEnv = errors.New("this system doesn't tell another process's environment")++// EnvOf is the value of each of names that process pid's environment has+// (a name it lacks is left out): on macOS as `ps -E` prints it, on Linux+// from /proc/<pid>/environ. ErrNoEnv elsewhere; an error too for another+// user's process, whose environment ps leaves out.+func EnvOf(ctx context.Context, pid int, names ...string) (map[string]string, error) {+ return envOf(ctx, pid, names)+}++// psEnvNameRe is where the next variable starts in `ps -E` output.+var psEnvNameRe = regexp.MustCompile(` [A-Za-z_][A-Za-z0-9_]*=`)++// parsePSEnv reads names out of the line `ps -E -ww -o command=` prints:+// the command line, then each variable as NAME=value, space-separated and+// unquoted. A value runs to the next " NAME=", so one holding such text+// reads short; the last time a name shows is its own (the command line+// comes first).+func parsePSEnv(line string, names []string) map[string]string {+ out := map[string]string{}+ line = strings.TrimRight(line, "\r\n")+ for _, n := range names {+ i := strings.LastIndex(line, " "+n+"=")+ if i < 0 {+ continue+ }+ v := line[i+len(n)+2:]+ if j := psEnvNameRe.FindStringIndex(v); j != nil {+ v = v[:j[0]]+ }+ out[n] = v+ }+ return out+}++// parseEnviron reads names out of /proc/<pid>/environ's NUL-separated+// NAME=value list.+func parseEnviron(b []byte, names []string) map[string]string {+ out := map[string]string{}+ for _, kv := range strings.Split(string(b), "\x00") {+ k, v, ok := strings.Cut(kv, "=")+ if !ok {+ continue+ }+ for _, n := range names {+ if k == n {+ out[n] = v+ }+ }+ }+ return out+}diff --git a/internal/proc/env_darwin.go b/internal/proc/env_darwin.gonew file mode 100644index 000000000..7e7798bb0--- /dev/null+++ b/internal/proc/env_darwin.go@@ -0,0 +1,20 @@+package proc++import (+ "context"+ "errors"+ "strconv"+ "strings"+)++func envOf(ctx context.Context, pid int, names []string) (map[string]string, error) {+ out, err := CommandContext(ctx, "ps", "-E", "-ww", "-o", "command=", "-p", strconv.Itoa(pid)).Output()+ if err != nil {+ return nil, err+ }+ line := strings.TrimSpace(string(out))+ if line == "" {+ return nil, errors.New("no such process")+ }+ return parsePSEnv(" "+line, names), nil+}diff --git a/internal/proc/env_linux.go b/internal/proc/env_linux.gonew file mode 100644index 000000000..f7dabc2a6--- /dev/null+++ b/internal/proc/env_linux.go@@ -0,0 +1,15 @@+package proc++import (+ "context"+ "os"+ "strconv"+)++func envOf(_ context.Context, pid int, names []string) (map[string]string, error) {+ b, err := os.ReadFile("/proc/" + strconv.Itoa(pid) + "/environ")+ if err != nil {+ return nil, err+ }+ return parseEnviron(b, names), nil+}diff --git a/internal/proc/env_other.go b/internal/proc/env_other.gonew file mode 100644index 000000000..59daee7e2--- /dev/null+++ b/internal/proc/env_other.go@@ -0,0 +1,7 @@+//go:build !darwin && !linux++package proc++import "context"++func envOf(context.Context, int, []string) (map[string]string, error) { return nil, ErrNoEnv }diff --git a/internal/proc/env_test.go b/internal/proc/env_test.gonew file mode 100644index 000000000..a794e28cc--- /dev/null+++ b/internal/proc/env_test.go@@ -0,0 +1,110 @@+package proc++import (+ "context"+ "errors"+ "os"+ "os/exec"+ "reflect"+ "runtime"+ "strings"+ "testing"+ "time"+)++// The Codex app's app-server is restarted only when it runs on magpie's+// Codex home: its HOME and CODEX_HOME are read from what ps -E prints+// (macOS) or /proc/<pid>/environ (Linux).+func TestParsePSEnv(t *testing.T) {+ line := " /Applications/ChatGPT.app/Contents/Resources/codex app-server --analytics-default-enabled TMPDIR=/var/folders/x/T/ HOME=/Users/me/sand box CODEX_HOME=/Users/me/sand box/.codex LANG=en_US.UTF-8"+ got := parsePSEnv(line, []string{"HOME", "CODEX_HOME", "PATH"})+ want := map[string]string{"HOME": "/Users/me/sand box", "CODEX_HOME": "/Users/me/sand box/.codex"}+ if !reflect.DeepEqual(got, want) {+ t.Fatalf("parsePSEnv = %v, want %v", got, want)+ }+ // a name in the command line is not the environment's: the last is+ got = parsePSEnv(" codex app-server -c HOME=/nope HOME=/Users/me", []string{"HOME"})+ if got["HOME"] != "/Users/me" {+ t.Fatalf("HOME = %q", got["HOME"])+ }+ // the last variable runs to the end of the line+ got = parsePSEnv(" codex app-server HOME=/Users/me\n", []string{"HOME"})+ if got["HOME"] != "/Users/me" {+ t.Fatalf("last HOME = %q", got["HOME"])+ }+}++func TestParseEnviron(t *testing.T) {+ b := []byte("PATH=/usr/bin\x00HOME=/home/me\x00CODEX_HOME=/home/me/x=y\x00junk\x00")+ got := parseEnviron(b, []string{"HOME", "CODEX_HOME", "LANG"})+ want := map[string]string{"HOME": "/home/me", "CODEX_HOME": "/home/me/x=y"}+ if !reflect.DeepEqual(got, want) {+ t.Fatalf("parseEnviron = %v, want %v", got, want)+ }+}++// TestEnvOfHelper is TestEnvOfChild's child: it waits to be ended. macOS+// keeps a system binary's environment (sleep's) from ps, so the child is+// this test binary, as the Codex app's codex is its own.+func TestEnvOfHelper(t *testing.T) {+ if os.Getenv("MAGPIE_ENV_HELPER") != "1" {+ return+ }+ time.Sleep(30 * time.Second)+}++// EnvOf reads a running child's own environment, not magpie's.+func TestEnvOfChild(t *testing.T) {+ if runtime.GOOS != "darwin" && runtime.GOOS != "linux" {+ t.Skip("EnvOf answers ErrNoEnv here")+ }+ ctx, cancel := context.WithCancel(context.Background())+ cmd := CommandContext(ctx, os.Args[0], "-test.run=^TestEnvOfHelper$")+ cmd.Env = []string{"MAGPIE_ENV_HELPER=1", "HOME=/sand box/h", "CODEX_HOME=/sand box/h/.codex"}+ if err := cmd.Start(); err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { cancel(); _ = cmd.Wait() })+ got, err := EnvOf(context.Background(), cmd.Process.Pid, "HOME", "CODEX_HOME", "LANG")+ if err != nil {+ t.Fatal(err)+ }+ want := map[string]string{"HOME": "/sand box/h", "CODEX_HOME": "/sand box/h/.codex"}+ if !reflect.DeepEqual(got, want) {+ t.Fatalf("EnvOf = %v, want %v", got, want)+ }+}++// End ends a process as a clean exit, which the Codex app takes for an+// app-server that quit, not one that crashed: code 0 on Windows (any other+// is shown as a fatal error), SIGTERM elsewhere.+func TestEndExitsClean(t *testing.T) {+ cmd := CommandContext(context.Background(), os.Args[0], "-test.run=^TestEnvOfHelper$")+ cmd.Env = append(os.Environ(), "MAGPIE_ENV_HELPER=1")+ if err := cmd.Start(); err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = cmd.Process.Kill() })+ time.Sleep(200 * time.Millisecond) // started, so the signal isn't taken before its handlers+ if err := End(cmd.Process.Pid); err != nil {+ t.Fatal(err)+ }+ done := make(chan error, 1)+ go func() { done <- cmd.Wait() }()+ var err error+ select {+ case err = <-done:+ case <-time.After(20 * time.Second):+ t.Fatal("still running 20s after End")+ }+ if runtime.GOOS == "windows" {+ if err != nil {+ t.Fatalf("exit after End: %v, want code 0", err)+ }+ return+ }+ var ee *exec.ExitError+ if !errors.As(err, &ee) || !strings.Contains(ee.String(), "terminated") {+ t.Fatalf("exit after End: %v, want terminated by SIGTERM", err)+ }+}diff --git a/internal/proc/listener_unix.go b/internal/proc/listener_unix.goindex 2eb58d997..ad93066db 100644--- a/internal/proc/listener_unix.go+++ b/internal/proc/listener_unix.go@@ -21,3 +21,7 @@ func signal(pid int, s syscall.Signal) error {}return err}++// end asks pid to end: SIGTERM, on which a program that handles it exits+// cleanly (codex app-server exits 0).+func end(pid int) error { return signal(pid, syscall.SIGTERM) }diff --git a/internal/proc/listener_windows.go b/internal/proc/listener_windows.goindex e263c210b..64e423266 100644--- a/internal/proc/listener_windows.go+++ b/internal/proc/listener_windows.go@@ -52,7 +52,13 @@ func executable(pid int) (string, error) {// and no window a close message would reach.func terminate(pid int) error { return kill(pid) }-func kill(pid int) error {+func kill(pid int) error { return exitWith(pid, 1) }++// end ends pid with exit code 0, which its parent reads as a clean exit:+// Windows has no SIGTERM for a console program without a window.+func end(pid int) error { return exitWith(pid, 0) }++func exitWith(pid int, code uint32) error {h, err := windows.OpenProcess(windows.PROCESS_TERMINATE, false, uint32(pid))if err != nil {if errors.Is(err, windows.ERROR_ACCESS_DENIED) {@@ -64,7 +70,7 @@ func kill(pid int) error {return err}defer windows.CloseHandle(h)- if err := windows.TerminateProcess(h, 1); err != nil {+ if err := windows.TerminateProcess(h, code); err != nil {if errors.Is(err, windows.ERROR_ACCESS_DENIED) {return ErrDenied}diff --git a/internal/provider/codex_app_out.go b/internal/provider/codex_app_out.goindex 52505fac5..f824b7598 100644--- a/internal/provider/codex_app_out.go+++ b/internal/provider/codex_app_out.go@@ -8,13 +8,11 @@ import ("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.+// The Codex app greys its Send for every model, magpie's included, while+// the ChatGPT account it is on is out (MasterYi on Discord), till magpie is+// its provider and its app-server restarted (codex_app_server.go). What+// follows tells the account is out as soon as a reply says so, not at the+// next look five minutes on.// codexLiveChecks counts the running loops that keep Codex on an account// with room (KeepOnAnAccountWithRoom) past their first reading: while one@@ -68,91 +66,3 @@ func CodexMayBeUsedUp(user string) {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.goindex da6544d8c..949e9f042 100644--- a/internal/provider/codex_app_out_test.go+++ b/internal/provider/codex_app_out_test.go@@ -1,11 +1,8 @@package providerimport (- "context""testing""time"-- "github.com/yetone/magpie/internal/proc")// A reply that says the account Codex is signed in to is out has its@@ -64,56 +61,3 @@ func TestCodexMayBeUsedUpReadsAtOnce(t *testing.T) {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_app_server.go b/internal/provider/codex_app_server.gonew file mode 100644index 000000000..59cdb07e3--- /dev/null+++ b/internal/provider/codex_app_server.go@@ -0,0 +1,306 @@+package provider++import (+ "bytes"+ "context"+ "errors"+ "io"+ "io/fs"+ "log"+ "os"+ "path/filepath"+ "strings"+ "sync"+ "time"++ "github.com/yetone/magpie/internal/proc"+)++// The Codex app greys its Send for every model, magpie's too, while the+// ChatGPT account it is signed in to is used up (its composer's gate,+// XP in ChatGPT.app 26.1013's app-primary: authMethod "chatgpt" and+// rate_limit.allowed false). It reads authMethod from its app-server's+// account/read, which answers no account once magpie is Codex's provider+// (requires_openai_auth false), but it asks only as the app-server+// starts. So when magpie becomes Codex's provider for the used-up+// account (the agent package's AppOut), and again when it puts Codex+// back on the account after its reset, magpie ends the app's own+// app-server, the one it started with: the app starts another at once,+// reads account/read again, and sends (tried in ChatGPT.app 26.1013 on+// macOS; its window, threads and drafts stay). It does that on every+// system the app runs on, with nothing for the user to do, once no Codex+// turn is running: none through magpie, none open in Codex's sessions.+//+// The app-server is ended as a clean exit (proc.End): the app reads any+// other exit as a crash and shows it.++// CodexAppOnMagpie is set by the agent package: whether magpie is Codex's+// provider for its used-up ChatGPT account (AppOut), known false when+// Codex's config can't be read.+var CodexAppOnMagpie func() (on, known bool)++// codexAppEvery is how often KeepCodexAppOnItsProvider looks; codexAppIdle+// how long after Codex's last request through magpie a turn counts ended+// (a tool runs between two of a turn's requests); codexAppTries how often+// one app-server is ended before magpie says it can't.+var (+ codexAppEvery = 3 * time.Second+ codexAppIdle = 10 * time.Second+ codexAppTries = 3+)++// codexTurnWindow is how long a session file written to last counts as a+// turn maybe still running when it has one started and not ended: a turn+// whose app-server died leaves one open for good.+const codexTurnWindow = 30 * time.Minute++// codexAppListWait bounds one listing of the app-servers and their homes:+// at a load of 200 a 10s bound ran out on the owner's Mac (the change was+// taken up at the next look, 9s later).+const codexAppListWait = 30 * time.Second++// codexAppServersOn are the pids of the Codex app's own app-servers that+// run on the Codex home home; vars for tests.+var (+ codexAppServersOn = func(ctx context.Context, home string) ([]int, error) {+ ps, err := listProcesses(ctx)+ if err != nil {+ return nil, err+ }+ var out []int+ for _, p := range ps {+ if isCodexAppOwnServer(p.Args) && codexAppHomeIs(ctx, p.PID, home) {+ out = append(out, p.PID)+ }+ }+ return out, nil+ }+ endCodexAppServer = proc.End+ codexTurnRunning = func(home string, now time.Time) bool { return codexTurnOpen(home, now) }+)++// isCodexAppOwnServer is whether a command line is the Codex app's own+// app-server, which it talks to over stdio: one another program starts+// from the app's bundled codex names where it listens (`app-server+// --listen stdio://`, Miyi Helper on macOS), and is that program's to end.+func isCodexAppOwnServer(args string) bool {+ if !isCodexAppServer(args) {+ return false+ }+ _, rest := splitExe(args)+ for _, f := range strings.Fields(rest) {+ if f == "--listen" || strings.HasPrefix(f, "--listen=") {+ return false+ }+ }+ return true+}++// codexAppHomeIs is whether app-server pid runs on Codex home home: its+// CODEX_HOME, else its HOME's .codex. A system that doesn't tell+// (Windows) counts as yes: one Codex home is the rule there.+func codexAppHomeIs(ctx context.Context, pid int, home string) bool {+ env, err := proc.EnvOf(ctx, pid, "CODEX_HOME", "HOME")+ if errors.Is(err, proc.ErrNoEnv) {+ return true+ }+ if err != nil {+ return false+ }+ h := env["CODEX_HOME"]+ if h == "" && env["HOME"] != "" {+ h = filepath.Join(env["HOME"], ".codex")+ }+ return h != "" && sameDir(h, home)+}++// sameDir is whether a and b name one folder, through links too.+func sameDir(a, b string) bool {+ a, b = filepath.Clean(a), filepath.Clean(b)+ if a == b {+ return true+ }+ ra, err1 := filepath.EvalSymlinks(a)+ rb, err2 := filepath.EvalSymlinks(b)+ return err1 == nil && err2 == nil && ra == rb+}++// codexApp is what KeepCodexAppOnItsProvider knows.+var codexApp struct {+ sync.Mutex+ seen, on bool+ // stale: the app-servers started before Codex's provider last changed,+ // each with how often it was ended+ stale map[int]int+ // stuck: one of them outlived codexAppTries ends, or may not be ended+ stuck bool+}++// CodexAppStuck is whether a Codex app is left on the provider it started+// with, which magpie couldn't restart: the user quits and opens it.+func CodexAppStuck() bool {+ c := &codexApp+ c.Lock()+ defer c.Unlock()+ return c.stuck+}++// KeepCodexAppOnItsProvider runs codexAppStep every codexAppEvery till+// ctx ends. busy says how many of Codex's requests are in flight through+// magpie and when the last ended.+func KeepCodexAppOnItsProvider(ctx context.Context, busy func() (int, time.Time)) {+ t := time.NewTicker(codexAppEvery)+ defer t.Stop()+ for {+ select {+ case <-ctx.Done():+ return+ case now := <-t.C:+ codexAppStep(ctx, now, busy)+ }+ }+}++// codexAppStep notes the app-servers running as magpie becomes Codex's+// provider for the used-up account, or stops being it, and ends each of+// them once no Codex turn is running. Started with magpie on, the app may+// have opened before: its app-servers are ended too. It says which pids it+// ended.+func codexAppStep(ctx context.Context, now time.Time, busy func() (int, time.Time)) []int {+ if CodexAppOnMagpie == nil {+ return nil+ }+ on, known := CodexAppOnMagpie()+ if !known {+ return nil+ }+ home := codexHome()+ c := &codexApp+ c.Lock()+ changed := !c.seen && on || c.seen && c.on != on+ if !changed {+ c.seen, c.on = true, on+ }+ c.Unlock()+ if changed {+ lctx, cancel := context.WithTimeout(ctx, codexAppListWait)+ pids, err := codexAppServersOn(lctx, home)+ cancel()+ if err != nil {+ // unknown: the change is taken up again at the next look+ log.Printf("codex: listing the Codex app's app-servers: %v", err)+ return nil+ }+ c.Lock()+ c.seen, c.on = true, on+ c.stale, c.stuck = map[int]int{}, false+ for _, p := range pids {+ c.stale[p] = 0+ }+ c.Unlock()+ }+ c.Lock()+ n := len(c.stale)+ c.Unlock()+ if n == 0 {+ return nil+ }+ lctx, cancel := context.WithTimeout(ctx, codexAppListWait)+ pids, err := codexAppServersOn(lctx, home)+ cancel()+ if err != nil {+ return nil+ }+ running := map[int]bool{}+ for _, p := range pids {+ running[p] = true+ }+ c.Lock()+ for p := range c.stale {+ if !running[p] {+ delete(c.stale, p) // it read the provider afresh as it started+ }+ }+ n = len(c.stale)+ c.Unlock()+ if n == 0 {+ return nil+ }+ if inFlight, last := busy(); inFlight > 0 || now.Sub(last) < codexAppIdle {+ return nil+ }+ if codexTurnRunning(home, now) {+ return nil+ }+ var ended []int+ c.Lock()+ defer c.Unlock()+ for p, tries := range c.stale {+ if tries >= codexAppTries {+ c.stuck = true+ continue+ }+ c.stale[p] = tries + 1+ if err := endCodexAppServer(p); err != nil {+ log.Printf("codex: restarting the Codex app's app-server %d on its provider: %v", p, err)+ if errors.Is(err, proc.ErrDenied) {+ c.stale[p], c.stuck = codexAppTries, true+ }+ continue+ }+ ended = append(ended, p)+ }+ return ended+}++// codexTurnOpen is whether a Codex session under home has a turn started+// and not ended (task_started after its last task_complete or+// turn_aborted) in a file written to within codexTurnWindow of now: the+// app-server running it would cut it short.+func codexTurnOpen(home string, now time.Time) bool {+ open := false+ _ = filepath.WalkDir(filepath.Join(home, "sessions"), func(path string, d fs.DirEntry, err error) error {+ if err != nil || open {+ if open {+ return fs.SkipAll+ }+ return nil+ }+ if d.IsDir() || !strings.HasSuffix(d.Name(), ".jsonl") {+ return nil+ }+ info, err := d.Info()+ if err != nil || now.Sub(info.ModTime()) > codexTurnWindow {+ return nil+ }+ open = sessionTurnOpen(path)+ return nil+ })+ return open+}++// sessionTurnTail is how much of a session file's end sessionTurnOpen reads.+const sessionTurnTail = 512 << 10++// sessionTurnOpen is whether the session file at path ends inside a turn.+// A file that can't be read counts as open: a turn cut short costs more+// than an app greyed a few seconds more.+func sessionTurnOpen(path string) bool {+ f, err := os.Open(path)+ if err != nil {+ return !errors.Is(err, fs.ErrNotExist)+ }+ defer f.Close()+ if info, err := f.Stat(); err == nil && info.Size() > sessionTurnTail {+ if _, err := f.Seek(info.Size()-sessionTurnTail, io.SeekStart); err != nil {+ return true+ }+ }+ b, err := io.ReadAll(f)+ if err != nil {+ return true+ }+ started := bytes.LastIndex(b, []byte(`"type":"task_started"`))+ ended := max(bytes.LastIndex(b, []byte(`"type":"task_complete"`)), bytes.LastIndex(b, []byte(`"type":"turn_aborted"`)))+ return started > ended+}diff --git a/internal/provider/codex_app_server_test.go b/internal/provider/codex_app_server_test.gonew file mode 100644index 000000000..249ad8781--- /dev/null+++ b/internal/provider/codex_app_server_test.go@@ -0,0 +1,346 @@+package provider++import (+ "context"+ "errors"+ "os"+ "path/filepath"+ "runtime"+ "slices"+ "testing"+ "time"++ "github.com/yetone/magpie/internal/proc"+)++// codexAppStub stands in for Codex's provider, the running app-servers+// and their ends, for codexAppStep.+type codexAppStub struct {+ on, known bool+ running []int+ listErr error+ endErr error+ turnOpen bool+ ended []int+ // next: the app-server the app starts after one is ended+ next int+}++func stubCodexApp(t *testing.T) *codexAppStub {+ t.Helper()+ s := &codexAppStub{known: true, next: 100}+ oldOn, oldList, oldEnd, oldTurn := CodexAppOnMagpie, codexAppServersOn, endCodexAppServer, codexTurnRunning+ t.Cleanup(func() {+ CodexAppOnMagpie, codexAppServersOn, endCodexAppServer, codexTurnRunning = oldOn, oldList, oldEnd, oldTurn+ codexApp.Lock()+ codexApp.seen, codexApp.on, codexApp.stale, codexApp.stuck = false, false, nil, false+ codexApp.Unlock()+ })+ codexApp.Lock()+ codexApp.seen, codexApp.on, codexApp.stale, codexApp.stuck = false, false, nil, false+ codexApp.Unlock()+ CodexAppOnMagpie = func() (bool, bool) { return s.on, s.known }+ codexAppServersOn = func(context.Context, string) ([]int, error) {+ if s.listErr != nil {+ return nil, s.listErr+ }+ return slices.Clone(s.running), nil+ }+ endCodexAppServer = func(pid int) error {+ if s.endErr != nil {+ return s.endErr+ }+ s.ended = append(s.ended, pid)+ // the app starts another app-server, which reads the provider anew+ if i := slices.Index(s.running, pid); i >= 0 {+ s.running[i] = s.next+ s.next+++ }+ return nil+ }+ codexTurnRunning = func(string, time.Time) bool { return s.turnOpen }+ return s+}++// When magpie becomes Codex's provider for its used-up ChatGPT account the+// Codex app's own app-server is restarted, so the app reads its account+// again and lifts the grey on Send (Ethereal499, MasterYi), and again when+// magpie puts Codex back on the account at its reset, so the app's ChatGPT+// side comes back. Never while a Codex turn runs: one in flight through+// magpie, one ended under codexAppIdle ago (a tool between two requests),+// or one open in Codex's sessions.+func TestCodexAppServerRestartedEachWay(t *testing.T) {+ signIn(t)+ s := stubCodexApp(t)+ now := time.Now()+ idle := func() (int, time.Time) { return 0, now.Add(-time.Minute) }+ step := func(busy func() (int, time.Time)) []int { return codexAppStep(context.Background(), now, busy) }++ s.running = []int{60}+ if got := step(idle); got != nil {+ t.Fatalf("on its account with room: ended %v", got)+ }+ s.on = true+ if got := step(func() (int, time.Time) { return 1, now.Add(-time.Minute) }); got != nil {+ t.Fatalf("a Codex request in flight: ended %v", got)+ }+ if got := step(func() (int, time.Time) { return 0, now.Add(-codexAppIdle / 2) }); got != nil {+ t.Fatalf("Codex's last request just ended: ended %v", got)+ }+ s.turnOpen = true+ if got := step(idle); got != nil {+ t.Fatalf("a turn open in Codex's sessions: ended %v", got)+ }+ s.turnOpen = false+ if got := step(idle); !slices.Equal(got, []int{60}) {+ t.Fatalf("on magpie, idle: ended %v, want [60]", got)+ }+ if got := step(idle); got != nil {+ t.Fatalf("the new app-server read magpie as it started: ended %v", got)+ }+ s.on = false // the reset: back on the account+ if got := step(idle); !slices.Equal(got, []int{100}) {+ t.Fatalf("back on the account: ended %v, want [100]", got)+ }+ if got := step(idle); got != nil || CodexAppStuck() {+ t.Fatalf("after: ended %v, stuck %v", got, CodexAppStuck())+ }+}++// A magpie started while it is Codex's provider for a used-up account+// restarts the app-servers it finds: they may have started before.+// Started with Codex on its account, it leaves them be.+func TestCodexAppServerFirstLook(t *testing.T) {+ signIn(t)+ s := stubCodexApp(t)+ now := time.Now()+ idle := func() (int, time.Time) { return 0, time.Time{} }+ s.running = []int{60}+ s.on = true+ if got := codexAppStep(context.Background(), now, idle); !slices.Equal(got, []int{60}) {+ t.Fatalf("first look on magpie: ended %v", got)+ }++ s2 := stubCodexApp(t)+ s2.running = []int{70}+ if got := codexAppStep(context.Background(), now, idle); got != nil {+ t.Fatalf("first look on the account: ended %v", got)+ }+}++// Codex's provider not known (its config unreadable) changes nothing, and+// app-servers that can't be listed as the provider changes are listed at+// the next look.+func TestCodexAppServerUnknown(t *testing.T) {+ signIn(t)+ s := stubCodexApp(t)+ now := time.Now()+ idle := func() (int, time.Time) { return 0, time.Time{} }+ s.running = []int{60}+ s.known = false+ s.on = true+ if got := codexAppStep(context.Background(), now, idle); got != nil {+ t.Fatalf("not known: ended %v", got)+ }+ s.known = true+ s.listErr = errors.New("ps failed")+ if got := codexAppStep(context.Background(), now, idle); got != nil {+ t.Fatalf("not listed: ended %v", got)+ }+ s.listErr = nil+ if got := codexAppStep(context.Background(), now, idle); !slices.Equal(got, []int{60}) {+ t.Fatalf("listed at the next look: ended %v", got)+ }+}++// An app-server that outlives codexAppTries ends, or that magpie may not+// end, is left to the user: CodexAppStuck says so for the Agents row.+func TestCodexAppServerStuck(t *testing.T) {+ signIn(t)+ s := stubCodexApp(t)+ now := time.Now()+ idle := func() (int, time.Time) { return 0, time.Time{} }+ s.running = []int{60}+ s.on = true+ oldEnd := endCodexAppServer+ tries := 0+ endCodexAppServer = func(int) error { tries++; return nil } // it doesn't end+ for range codexAppTries + 2 {+ codexAppStep(context.Background(), now, idle)+ }+ if tries != codexAppTries || !CodexAppStuck() {+ t.Fatalf("tries %d (want %d), stuck %v", tries, codexAppTries, CodexAppStuck())+ }+ endCodexAppServer = oldEnd++ s.on = false // a change starts afresh+ codexAppStep(context.Background(), now, idle)+ if CodexAppStuck() {+ t.Fatal("still stuck after the provider changed")+ }+ s.on = true+ s.endErr = proc.ErrDenied+ codexAppStep(context.Background(), now, idle)+ if !CodexAppStuck() {+ t.Fatal("denied: not stuck")+ }+}++// TestCodexAppHomeHelper is TestCodexAppServersOnHome's app-server: it+// waits to be ended (a system binary's environment is kept from ps).+func TestCodexAppHomeHelper(t *testing.T) {+ if os.Getenv("MAGPIE_CODEX_HOME_HELPER") != "1" {+ return+ }+ time.Sleep(30 * time.Second)+}++// Only the app-servers on magpie's Codex home are restarted: one under+// another HOME or CODEX_HOME (a sandbox, another user) is left be.+func TestCodexAppServersOnHome(t *testing.T) {+ if runtime.GOOS != "darwin" && runtime.GOOS != "linux" {+ t.Skip("no environment to tell homes by here: every app-server counts")+ }+ start := func(env ...string) int {+ ctx, cancel := context.WithCancel(context.Background())+ cmd := proc.CommandContext(ctx, os.Args[0], "-test.run=^TestCodexAppHomeHelper$")+ cmd.Env = append([]string{"MAGPIE_CODEX_HOME_HELPER=1"}, env...)+ if err := cmd.Start(); err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { cancel(); _ = cmd.Wait() })+ return cmd.Process.Pid+ }+ ctx := context.Background()+ a, b := t.TempDir(), t.TempDir()+ onHome := start("HOME=" + a)+ if !codexAppHomeIs(ctx, onHome, filepath.Join(a, ".codex")) {+ t.Fatal("HOME's .codex: not counted")+ }+ if codexAppHomeIs(ctx, onHome, filepath.Join(b, ".codex")) {+ t.Fatal("another HOME's: counted")+ }+ onCodexHome := start("HOME="+a, "CODEX_HOME="+b)+ if !codexAppHomeIs(ctx, onCodexHome, b) {+ t.Fatal("CODEX_HOME: not counted")+ }+ if codexAppHomeIs(ctx, onCodexHome, filepath.Join(a, ".codex")) {+ t.Fatal("HOME's .codex under another CODEX_HOME: counted")+ }+ if codexAppHomeIs(ctx, 1<<30, b) {+ t.Fatal("a process that isn't there counted")+ }+}++// A turn is open in Codex's sessions when the newest task event of a file+// written to lately is task_started.+func TestCodexTurnOpen(t *testing.T) {+ home := t.TempDir()+ dir := filepath.Join(home, "sessions", "2026", "10", "27")+ if err := os.MkdirAll(dir, 0o755); err != nil {+ t.Fatal(err)+ }+ now := time.Now()+ write := func(name, body string, at time.Time) {+ p := filepath.Join(dir, name)+ if err := os.WriteFile(p, []byte(body), 0o644); err != nil {+ t.Fatal(err)+ }+ if err := os.Chtimes(p, at, at); err != nil {+ t.Fatal(err)+ }+ }+ started := `{"type":"event_msg","payload":{"type":"task_started","turn_id":"1"}}` + "\n"+ done := `{"type":"event_msg","payload":{"type":"task_complete","turn_id":"1"}}` + "\n"+ aborted := `{"type":"event_msg","payload":{"type":"turn_aborted","turn_id":"1"}}` + "\n"+ if codexTurnOpen(home, now) {+ t.Fatal("no sessions: open")+ }+ write("rollout-a.jsonl", started+done, now)+ if codexTurnOpen(home, now) {+ t.Fatal("turn complete: open")+ }+ write("rollout-b.jsonl", started+aborted, now)+ if codexTurnOpen(home, now) {+ t.Fatal("turn aborted: open")+ }+ write("rollout-c.jsonl", started+done+started, now.Add(-codexTurnWindow-time.Minute))+ if codexTurnOpen(home, now) {+ t.Fatal("a turn left open long ago: open")+ }+ write("rollout-d.jsonl", started+done+started, now)+ if !codexTurnOpen(home, now) {+ t.Fatal("a turn running: not open")+ }+}++// While the account Codex is on is near out, or out, it is read every+// minute, not five: the app greys Send on its own reading, and magpie+// takes over only on its own (Ethereal499). At the reset, as soon.+func TestCodexLookEvery(t *testing.T) {+ signIn(t) // [email protected], active+ rememberLogins(true)+ at := func(used float64, held bool) map[string]SubscriptionQuota {+ return map[string]SubscriptionQuota{"[email protected]": {Held: held, Windows: []QuotaWindow{{Name: "5h", Used: 20}, {Name: "week", Used: used}}}}+ }+ if got := codexLookEvery(at(50, false)); got != loginSwitchEvery {+ t.Fatalf("half used: %v", got)+ }+ if got := codexLookEvery(at(91, false)); got != codexNearOutEvery {+ t.Fatalf("near out: %v", got)+ }+ if got := codexLookEvery(at(0, true)); got != codexNearOutEvery {+ t.Fatalf("out: %v", got)+ }+ if got := codexLookEvery(map[string]SubscriptionQuota{"[email protected]": {Held: true}}); got != loginSwitchEvery {+ t.Fatalf("another account out: %v", got)+ }+ if got := codexLookEvery(map[string]SubscriptionQuota{"[email protected]": {Held: true, Error: "x"}}); got != loginSwitchEvery {+ t.Fatalf("a failed read: %v", got)+ }+}++// The Agents row says until when Codex is on magpie: the latest reset of+// the windows used up.+func TestCodexOutUntil(t *testing.T) {+ signIn(t)+ rememberLogins(true)+ soon, later := time.Now().Add(time.Hour), time.Now().Add(48*time.Hour)+ u := map[string]SubscriptionQuota{"[email protected]": {Held: true, Windows: []QuotaWindow{+ {Name: "5h", Used: 100, ResetsAt: &soon},+ {Name: "week", Used: 100, ResetsAt: &later},+ }}}+ if got := codexOutUntil(u); !got.Equal(later) {+ t.Fatalf("both used up: %v, want %v", got, later)+ }+ u["[email protected]"].Windows[1].Used = 40+ if got := codexOutUntil(u); !got.Equal(soon) {+ t.Fatalf("5h used up: %v, want %v", got, soon)+ }+ q := u["[email protected]"]+ q.Held = false+ u["[email protected]"] = q+ if got := codexOutUntil(u); !got.IsZero() {+ t.Fatalf("not out: %v", got)+ }+}++// Only the app's own app-server is restarted: another program's, started+// from the app's bundled codex with --listen (Miyi Helper's, seen on the+// owner's Mac), is that program's.+func TestCodexAppOwnServer(t *testing.T) {+ own := "/Applications/ChatGPT.app/Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS/codex -c features.code_mode_host=true app-server --analytics-default-enabled -c [email protected]_servers.codex_app.enabled=true"+ if !isCodexAppOwnServer(own) {+ t.Fatalf("the app's own app-server not taken: %s", own)+ }+ for _, other := range []string{+ "/Applications/ChatGPT.app/Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS/codex app-server --listen stdio://",+ "/Applications/ChatGPT.app/Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS/codex app-server --listen=ws://127.0.0.1:4500",+ "/Applications/ChatGPT.app/Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS/codex -c forced_login_method=\"chatgpt\" exec-server --remote https://codex-cloud-environments.chatgpt.com/api",+ "/usr/local/bin/codex app-server",+ } {+ if isCodexAppOwnServer(other) {+ t.Errorf("taken for the app's own app-server: %s", other)+ }+ }+}diff --git a/internal/provider/codex_daemon.go b/internal/provider/codex_daemon.goindex 9853b274d..480b8210e 100644--- a/internal/provider/codex_daemon.go+++ b/internal/provider/codex_daemon.go@@ -263,28 +263,32 @@ func DismissCodexApp() {// proxy, nor an editor's codex.func findCodexApp(ps []proc.Process) int {for _, p := range ps {- if isManagedDaemon(p.Args) {- continue- }- // the program's own path: ps leaves a path's spaces unquoted, so- // "…/Codex Computer Use.app/Contents/MacOS/…" reads as one named Codex- exe, rest := splitExe(p.Args)- if !strings.Contains(exe, ".app/Contents/") && !strings.Contains(exe, `\WindowsApps\OpenAI.`) {- continue- }- if base := strings.ToLower(exe[strings.LastIndexAny(exe, `/\`)+1:]); base != "codex" && base != "codex.exe" {- continue+ if isCodexAppServer(p.Args) {+ return p.PID}- f := strings.Fields(rest)- i := slices.Index(f, "app-server")- if i < 0 || i+1 < len(f) && !strings.HasPrefix(f[i+1], "-") {- continue- }- return p.PID}return 0}+// isCodexAppServer is findCodexApp's test of one command line.+func isCodexAppServer(args string) bool {+ if isManagedDaemon(args) {+ return false+ }+ // the program's own path: ps leaves a path's spaces unquoted, so+ // "…/Codex Computer Use.app/Contents/MacOS/…" reads as one named Codex+ exe, rest := splitExe(args)+ if !strings.Contains(exe, ".app/Contents/") && !strings.Contains(exe, `\WindowsApps\OpenAI.`) {+ return false+ }+ if base := strings.ToLower(exe[strings.LastIndexAny(exe, `/\`)+1:]); base != "codex" && base != "codex.exe" {+ return false+ }+ f := strings.Fields(rest)+ i := slices.Index(f, "app-server")+ return i >= 0 && (i+1 >= len(f) || strings.HasPrefix(f[i+1], "-"))+}+// RestartCodexDaemon has Codex restart its app-server, which reads the// sign-in again: `codex app-server daemon restart`, run with the codex CLI// magpie finds and the Codex home it signs Codex in through. Codex 0.162'sdiff --git a/internal/provider/codex_switch.go b/internal/provider/codex_switch.goindex 913c4ee1a..840dfb246 100644--- a/internal/provider/codex_switch.go+++ b/internal/provider/codex_switch.go@@ -45,6 +45,64 @@ import (// loginSwitchEvery is how often the account each agent is on is looked at.const loginSwitchEvery = 5 * time.Minute+// codexNearOutEvery is how often the account Codex is signed in to is read+// while it is near out (codexNearOut) or out: the Codex app greys its Send+// from its own reading, and magpie takes the turns over only once its+// reading says the account is out too, so five minutes apart left Send+// grey for up to five (Ethereal499 on X). Read again as soon after the+// reset, magpie gives the app its ChatGPT side back as soon.+const codexNearOutEvery = time.Minute++// codexNearShare is the share of a window past which the account counts+// near out.+const codexNearShare = 90++// codexLookEvery is when KeepOnAnAccountWithRoom looks again, after+// reading u: codexNearOutEvery while the account Codex is signed in to is+// near out or out, else loginSwitchEvery.+func codexLookEvery(u map[string]SubscriptionQuota) time.Duration {+ for _, l := range Logins("codex") {+ q, ok := u[l.User]+ if !l.Active || !ok || q.Error != "" {+ continue+ }+ if q.Held {+ return codexNearOutEvery+ }+ for _, w := range q.Windows {+ if !w.Unlimited && !w.Text && w.Used >= codexNearShare {+ return codexNearOutEvery+ }+ }+ }+ return loginSwitchEvery+}++// CodexOutUntil is when the ChatGPT account Codex is signed in to has room+// again, as last read: the latest reset of the windows used up. Zero when+// it isn't out or the reading doesn't say.+func CodexOutUntil() time.Time { return codexOutUntil(knownLoginUsage("codex")) }++// codexOutUntil is CodexOutUntil over the readings u.+func codexOutUntil(u map[string]SubscriptionQuota) time.Time {+ var until time.Time+ for _, l := range Logins("codex") {+ q, ok := u[l.User]+ if !l.Active || !ok || q.Error != "" || !q.Held {+ continue+ }+ for _, w := range q.Windows {+ if w.Unlimited || w.Text || w.Used < 100 || w.ResetsAt == nil {+ continue+ }+ if w.ResetsAt.After(until) {+ until = *w.ResetsAt+ }+ }+ }+ return until+}+// SpentShare is the share of an allowance past which an account is all// but used up: Smart routing keeps it for when no other can take a// request, and the agent signed in to it is signed in to another.@@ -324,7 +382,6 @@ var codexWasUsedUp atomic.Bool// (#540). Only a change is told.func noteCodexUsedUp(now bool) {if codexWasUsedUp.Swap(now) != now {- noteCodexAppOut(now)catalog.Touched()}}@@ -368,6 +425,6 @@ func KeepOnAnAccountWithRoom(ctx context.Context) {c, cancel := context.WithTimeout(ctx, time.Minute)noteCodexUsedUp(CodexUsedUp(c))cancel()- t.Reset(loginSwitchEvery)+ t.Reset(codexLookEvery(knownLoginUsage("codex")))}}