provider: a Codex account the Codex app still sends for keeps Codex signed in — spend cap or overage with credits, limit_reached alone; a hold survives a failed read (#996)

* provider: a Codex account at a spend cap or past its overage with credits left keeps Codex signed in, as the Codex app's composer still sends for it

#966 held such an account (and one whose limit_reached alone was true),
following the readiness check Tht in ChatGPT.app 26.930. Tht has one
caller, the work-credit-restriction-recovery poller; it isn't the
composer's gate. The composer's submit is disabled only by hP (search
"n.rate_limit?.allowed!==!1||Jpe(n)||SIe(") and hardBlocked (search
"hardBlocked:r.rate_limit?.allowed===!1"): both read rate_limit.allowed
alone and let credits (has_credits or unlimited) through before any spend
cap or overage. So the app sends for that account, and holding it gains
nothing: CodexUsedUp only moves Codex to magpie as provider while Codex is
on a magpie model, whose turns already reach magpie through
openai_base_url. It only takes the app out of ChatGPT (durable threads,
remote control), the loss #966 set out to stop.

codexHeld is back to that gate: held when allowed is false, no credits,
and not a workspace within its overage (no spend cap, an ordinary
reason). Its comment names the build, both gates and why Tht isn't one,
each with a string to search for. The spend-cap and overage subcases now
expect not held; new subcases pin allowed as the only trigger. Five
subcases fail on the merged codexHeld. agent-wiring.md and reference.md
say the same.

Follow-up to #966.

* provider: a Sci, Law, FinServ or Enterprise trial/view-only workspace within its overage keeps Codex signed in

codexHeld lets a workspace with no credits through while it is within
its overage, as the Codex app's composer does, but the workspace list
came from codex-rs's PlanType alone. The app's own plan_type switch for
its usage banner (ChatGPT.app 26.930.61225, app-initial) also names sci,
law, finserv, enterprise_cbp_trial and enterprise_cbp_view_only, so such
an account read held and magpie took Codex off its ChatGPT sign-in while
the app still sent. They are added; the comment cites that switch. guest
there is a personal plan and stays out, and a plan not listed still
counts as no workspace (held).

Verification: "Law without credits, within its overage" in
TestCodexUsedUpIsWhatTheAppHolds fails without the list change
(CodexUsedUp = true, want false) and passes with it.

* provider: a held Codex reading with no window at 100% stays held through a failed read

A reading kept for when /wham/usage fails dropped Held whenever none of
its windows read 100%. That is right for a hold that came with a used-up
window which has since started again, but a hold with no window used up
(the backend says not allowed, no credits, every window under 100%) has
no reset to wait for: the first 503 after it read not held and put Codex
back on its ChatGPT sign-in for an account its app sends nothing for.
Held is now cleared only when the saved reading had a window used up and
none is after the passed resets are applied; any other hold stands till
a fresh read.

Verification: TestCodexHeldWithNoWindowUpKeptTillAFreshRead (the real Pro
reply, credits spent, its window at 40%: a good read, then a 503) fails
without the change ("CodexUsedUp = false on the kept held reading, no
window used up") and passes with it. TestCodexHeldKeptOnlyTillTheReset
still passes; both share their setup now. -race -count=10 passes.

* agent, gui, docs: Codex's sign-in notes say magpie steps in while the Codex app blocks the account, not whenever it is used up

#981's sign-in notes said magpie becomes Codex's provider "while its
account is used up". Since codexHeld, a ChatGPT account at 100% with
credits left keeps Codex signed in; magpie steps in only while the Codex
app blocks the account (out of allowance, no credits left), and the notes
now say that, Always ChatGPT's to match, in English, Chinese, Japanese
and German. agent-wiring.md's sign-in line and reference.md's Codex
paragraph say when the app holds an account as codexHeld reads it: OpenAI
no longer allows it and it has no credits left, a workspace still within
its overage excepted; at 100% with credits Codex stays signed in.

Verification: codex-signin-always (Chromium and WebKit, en/zh/ja/de, 1100
and 440px) 8/8, i18n-keys 1/1, gui-ja 3/3, gui-de 3/3. git grep finds the
old English notes nowhere under internal/gui/tests or internal/gui/assets.
This commit is contained in:
forever
2026-10-06 15:28:41 +08:00
committed by GitHub
parent b0aef80f6c
commit a7c4e5ddde
9 changed files with 172 additions and 137 deletions
+6 -4
View File
@@ -868,10 +868,12 @@ tool leaves that state behind, magpie writes the table back the next time
it syncs. Signed in to ChatGPT (the sign-in field's default), Codex keeps
its own provider and sign-in, and magpie's models join its list through
`openai_base_url`. magpie becomes Codex's provider then only while the
Codex app holds the account (OpenAI no longer allows it, and it has no
credits left or is at a spend cap), since the app sends nothing for it, and steps back once the
account has room again. A window at 100% with credits left doesn't count:
Codex keeps sending on those. Your ChatGPT sign-in is never touched.
Codex app holds the account: OpenAI no longer allows it and it has no
credits left, except a workspace account still within its overage. The
app sends nothing for a held account, so magpie steps in, and it steps
back once the account has room again. A window at 100% with credits left
doesn't count: Codex stays signed in and keeps sending on those. Your
ChatGPT sign-in is never touched.
Codex reads its model list at start-up, so restart it after a switch.
**OpenCode, Pi, Crush** get a `magpie` provider entry and `magpie/provider/model`.
+2 -2
View File
@@ -34,11 +34,11 @@ something else shows up as drift.
## Constraints and failure behavior
- magpie only removes what it wrote. Anything else in an agent's config stays as it was.
- 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 (`allowed` false or `limit_reached` true), and it is at a spend cap or past its overage, credits or not, or 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. The app then loses its ChatGPT state (durable threads, remote control), so a window at 100% alone, which credits get past, doesn't move it (`codex.out` marks the move, and Sync undoes it once the account has room).
- Codex signed in to ChatGPT stays beside its sign-in (`openai_base_url`) unless the user picks magpie API. magpie becomes its provider only while the Codex app holds the active account, which it sends nothing for: `/wham/usage` says it isn't allowed, and it has no credits and isn't a workspace still within its overage (`codexHeld`, read by `provider.CodexUsedUp`). Where the app goes by what usage can't show (an experiment's gate, a reserve, a Team plan's overage under the reserve experiment), it counts as held: a wrong move costs ChatGPT extras, a missed one every turn. A saved reading kept through a failed read stops saying held once its used-up window has started again; a hold with no window used up stays till a fresh read. The app then loses its ChatGPT state (durable threads, remote control), so a window at 100% alone, which credits get past, doesn't move it (`codex.out` marks the move, and Sync undoes it once the account has room).
- Moving a field from one of magpie's models to another (the agent's own picker) is not drift. Moving it off magpie is.
- A value an agent spells as its own provider's model is never taken for one of magpie's, even when magpie has a provider of the same name (`Spelled`, #835).
- Listing never starts a stopped WSL distro. A stopped distro's agent shows what was last seen there (`asleep`, `wsl.json`); setting one of its fields writes its files, which starts the distro.
- Codex's sign-in (`login`) is ChatGPT (`""`, the default), Always ChatGPT (`chatgpt`) or magpie API (`api`). With ChatGPT, magpie's models join Codex's own beside the sign-in (`openai_base_url`), and while the ChatGPT account Codex is signed in to is used up (`codexUsedUp`), magpie is made Codex's provider (`codex.out`): the Codex app sends nothing at all on an account it knows is out, a magpie model's turn included (#540), and as a provider of its own magpie is past that. Sync puts it back beside the sign-in once the account has room. Always ChatGPT never does that: Codex stays in its ChatGPT state, and the Codex app may send nothing till the account has room, while Codex CLI's turns still reach magpie by the base URL, and its routing and other accounts serve them.
- Codex's sign-in (`login`) is ChatGPT (`""`, the default), Always ChatGPT (`chatgpt`) or magpie API (`api`). With ChatGPT, magpie's models join Codex's own beside the sign-in (`openai_base_url`), and while the Codex app holds the ChatGPT account Codex is signed in to (`codexUsedUp`, `provider.CodexUsedUp`: OpenAI no longer allows the account and it has no credits left, a workspace still within its overage excepted), magpie is made Codex's provider (`codex.out`): the Codex app sends nothing at all on an account it holds, a magpie model's turn included (#540), and as a provider of its own magpie is past that. A window at 100% with credits left doesn't count, and Codex stays signed in. Sync puts it back beside the sign-in once the account has room. Always ChatGPT never does that: Codex stays in its ChatGPT state, and the Codex app may send nothing till the account has room, while Codex CLI's turns still reach magpie by the base URL, and its routing and other accounts serve them.
- Tests never touch the real machine. `TestMain` uses `testenv`, which points HOME, USERPROFILE, the XDG folders and APPDATA into a temporary folder, clears `agentenv.Vars` and puts failing stand-ins for keychain tools and agent CLIs on PATH. Agent-specific side effects (Aside, the Zed keychain, Codex's usage check) are also stubbed in `TestMain`.
## Verification
+9 -9
View File
@@ -301,11 +301,11 @@ func codexIn(at place) *Agent {
// api: the user wants magpie as Codex's provider even while Codex is
// signed in to ChatGPT
api := func() bool { return stashLoad()[at.key("codex.login")] == "api" }
// out reports whether the ChatGPT account Codex is signed in to has
// used its allowance up, for magpie to become Codex's provider while it
// is (#540): never with the sign-in kept on ChatGPT (chatgpt), where
// the user would rather the Codex app wait for the account than leave
// its ChatGPT state
// out reports whether the Codex app holds the ChatGPT account Codex is
// signed in to (codexUsedUp), for magpie to become Codex's provider
// while it does (#540): never with the sign-in kept on ChatGPT
// (chatgpt), where the user would rather the Codex app wait for the
// account than leave its ChatGPT state
out := func() bool { return stashLoad()[at.key("codex.login")] != "chatgpt" && codexUsedUp() }
dropBase := func() error {
forget(at.key("codex.failover"))
@@ -974,8 +974,8 @@ func codexIn(at place) *Agent {
{
// how Codex takes magpie's models: beside its ChatGPT
// sign-in (openai_base_url), magpie its provider only while
// the account is used up (""); beside it always, the
// account used up or not (chatgpt); or with magpie as its provider,
// the Codex app holds the account (""); beside it always,
// held or not (chatgpt); or with magpie as its provider,
// the Codex app in its API state. Kept in the stash, where
// set("") leaves it.
Key: "login", Label: "sign-in", Quiet: true,
@@ -1002,8 +1002,8 @@ func codexIn(at place) *Agent {
},
Options: func(map[string]string) []Option {
return []Option{
{Value: "", Label: "ChatGPT", Note: "magpie's models join Codex's own; Codex stays signed in to ChatGPT, and while its account is used up magpie is Codex's provider, so the Codex app still sends"},
{Value: "chatgpt", Label: "Always ChatGPT", Note: "as ChatGPT, and kept so when its account is used up: magpie never becomes Codex's provider. The Codex app may then send nothing till the account has room; Codex CLI goes on through magpie"},
{Value: "", Label: "ChatGPT", Note: "magpie's models join Codex's own; Codex stays signed in to ChatGPT, and while the Codex app blocks its account (out of allowance, no credits left) magpie is Codex's provider, so the app still sends"},
{Value: "chatgpt", Label: "Always ChatGPT", Note: "as ChatGPT, and kept so while the Codex app blocks its account: magpie never becomes Codex's provider. The Codex app may then send nothing till the account has room; Codex CLI goes on through magpie"},
{Value: "api", Label: "magpie API", Note: "magpie is Codex's provider; the Codex app is in its API state, with magpie's models only"},
}
},
+7 -7
View File
@@ -14,8 +14,8 @@ import (
// (its /model, or a Codex app still running on its old pick): its own
// models are in its list beside magpie's, as when it joined (#940: Codex
// read as not connected then, its config still on magpie's gateway).
// Disconnect leaves it on that model. Made magpie's provider (its
// allowance used up), it is not beside the sign-in.
// Disconnect leaves it on that model. Made magpie's provider (the Codex
// app blocking its account), it is not beside the sign-in.
func TestCodexOwnPickAfterMagpieModelStaysConnected(t *testing.T) {
home, read := codexHome(t, `{"tokens":{"access_token":"x","id_token":"x.e30.x"}}`, "model = \"gpt-5.5\"\n")
cx := codex(home)
@@ -60,11 +60,11 @@ func TestCodexOwnPickAfterMagpieModelStaysConnected(t *testing.T) {
}
}
// Connected while Codex can't join (its ChatGPT account used up, or a
// provider of its own in config.toml), Codex stays on the model it was on
// as magpie serves it on the ChatGPT account, not the first of magpie's
// other models (#940: it went to Grok 4.7, "magpie doesn't serve the model
// it was on").
// Connected while Codex can't join (the Codex app blocking its ChatGPT
// account, or a provider of its own in config.toml), Codex stays on the
// model it was on as magpie serves it on the ChatGPT account, not the first
// of magpie's other models (#940: it went to Grok 4.7, "magpie doesn't
// serve the model it was on").
func TestCodexConnectKeepsItsOwnModelThroughMagpie(t *testing.T) {
home, read := codexHome(t, `{"tokens":{"access_token":"x","id_token":"x.e30.x"}}`, "model = \"gpt-b\"\n")
os.WriteFile(filepath.Join(home, ".codex", "models_cache.json"), []byte(`{"models":[
+6 -6
View File
@@ -374,9 +374,9 @@ const I18N = {
"{agent} ultracode → {value}": "{agent} ultracode → {value}",
"an open Claude Code session keeps the effort it started with — restart it to use this.": "已打开的 Claude Code 会话仍用启动时的推理强度,重开后生效。",
"an open Claude Code session keeps the ultracode it started with — restart it to use this.": "已打开的 Claude Code 会话仍用启动时的 ultracode 设置,重开后生效。",
"magpie's models join Codex's own; Codex stays signed in to ChatGPT, and while its account is used up magpie is Codex's provider, so the Codex app still sends": "默认。Codex 保持 ChatGPT 登录,magpie 的模型与 Codex 自带模型并列;账号额度用尽期间,magpie 临时作为 Codex 的供应商,让 Codex 应用仍能发送",
"magpie's models join Codex's own; Codex stays signed in to ChatGPT, and while the Codex app blocks its account (out of allowance, no credits left) magpie is Codex's provider, so the app still sends": "默认。Codex 保持 ChatGPT 登录,magpie 的模型与 Codex 自带模型并列;当 Codex 应用拦下该账号(额度用尽且没有剩余积分)时,magpie 临时作为 Codex 的供应商,让 Codex 应用仍能发送",
"Always ChatGPT": "始终 ChatGPT",
"as ChatGPT, and kept so when its account is used up: magpie never becomes Codex's provider. The Codex app may then send nothing till the account has room; Codex CLI goes on through magpie": "同 ChatGPT,且账号额度用尽时也不切换:magpie 不会成为 Codex 的供应商。此时 Codex 应用可能无法发送,直到账号恢复额度;Codex CLI 仍通过 magpie 继续",
"as ChatGPT, and kept so while the Codex app blocks its account: magpie never becomes Codex's provider. The Codex app may then send nothing till the account has room; Codex CLI goes on through magpie": "同 ChatGPT,且 Codex 应用拦下该账号时也不切换:magpie 不会成为 Codex 的供应商。此时 Codex 应用可能无法发送,直到账号恢复额度;Codex CLI 仍通过 magpie 继续",
"magpie is Codex's provider; the Codex app is in its API state, with magpie's models only": "magpie 作为 Codex 的供应商,Codex 应用显示为 API 登录状态,只列出 magpie 的模型",
"same as model": "同主模型",
"same as model ({model})": "同主模型({model})",
@@ -3844,9 +3844,9 @@ const I18N = {
"{agent} ultracode → {value}": "{agent} ultracode → {value}",
"an open Claude Code session keeps the effort it started with — restart it to use this.": "開いている Claude Code セッションは起動時の推論レベルのままです。反映するには再起動してください。",
"an open Claude Code session keeps the ultracode it started with — restart it to use this.": "開いている Claude Code セッションは起動時の ultracode のままです。反映するには再起動してください。",
"magpie's models join Codex's own; Codex stays signed in to ChatGPT, and while its account is used up magpie is Codex's provider, so the Codex app still sends": "magpie のモデルが Codex 独自のモデルに加わります。Codex は ChatGPT にサインインしたままで、アカウントの使用量を使い切っている間は magpie が Codex のプロバイダーになり、Codex アプリは送信を続けられます",
"magpie's models join Codex's own; Codex stays signed in to ChatGPT, and while the Codex app blocks its account (out of allowance, no credits left) magpie is Codex's provider, so the app still sends": "magpie のモデルが Codex 独自のモデルに加わります。Codex は ChatGPT にサインインしたままで、Codex アプリがアカウントを止めている間(使用量を使い切り、クレジットも残っていないとき)は magpie が Codex のプロバイダーになり、Codex アプリは送信を続けられます",
"Always ChatGPT": "常に ChatGPT",
"as ChatGPT, and kept so when its account is used up: magpie never becomes Codex's provider. The Codex app may then send nothing till the account has room; Codex CLI goes on through magpie": "ChatGPT と同じで、アカウントの使用量を使い切っても切り替えません。magpie が Codex のプロバイダーになることはありません。その間 Codex アプリはアカウントに余裕が戻るまで送信できないことがあります。Codex CLI は magpie 経由で続行します",
"as ChatGPT, and kept so while the Codex app blocks its account: magpie never becomes Codex's provider. The Codex app may then send nothing till the account has room; Codex CLI goes on through magpie": "ChatGPT と同じで、Codex アプリがアカウントを止めても切り替えません。magpie が Codex のプロバイダーになることはありません。その間 Codex アプリはアカウントに余裕が戻るまで送信できないことがあります。Codex CLI は magpie 経由で続行します",
"magpie is Codex's provider; the Codex app is in its API state, with magpie's models only": "magpie が Codex のプロバイダになります。Codex アプリは API 状態になり、magpie のモデルのみが表示されます",
"same as model": "モデルと同じ",
"same as model ({model})": "モデルと同じ({model})",
@@ -7313,9 +7313,9 @@ const I18N = {
"{agent} ultracode → {value}": "{agent} ultracode → {value}",
"an open Claude Code session keeps the effort it started with — restart it to use this.": "eine offene Claude-Code-Sitzung behält den Reasoning-Effort vom Start — zum Übernehmen neu starten.",
"an open Claude Code session keeps the ultracode it started with — restart it to use this.": "eine offene Claude-Code-Sitzung behält die ultracode-Einstellung vom Start — zum Übernehmen neu starten.",
"magpie's models join Codex's own; Codex stays signed in to ChatGPT, and while its account is used up magpie is Codex's provider, so the Codex app still sends": "magpie-Modelle kommen zu den eigenen von Codex hinzu; Codex bleibt bei ChatGPT angemeldet, und solange das Konto aufgebraucht ist, ist magpie der Anbieter von Codex, damit die Codex-App weiter senden kann",
"magpie's models join Codex's own; Codex stays signed in to ChatGPT, and while the Codex app blocks its account (out of allowance, no credits left) magpie is Codex's provider, so the app still sends": "magpie-Modelle kommen zu den eigenen von Codex hinzu; Codex bleibt bei ChatGPT angemeldet, und solange die Codex-App das Konto blockiert (Kontingent aufgebraucht, keine Credits mehr), ist magpie der Anbieter von Codex, damit die Codex-App weiter senden kann",
"Always ChatGPT": "Immer ChatGPT",
"as ChatGPT, and kept so when its account is used up: magpie never becomes Codex's provider. The Codex app may then send nothing till the account has room; Codex CLI goes on through magpie": "Wie ChatGPT, auch wenn das Konto aufgebraucht ist: magpie wird nie der Anbieter von Codex. Die Codex-App sendet dann womöglich nichts, bis das Konto wieder Kontingent hat; Codex CLI läuft über magpie weiter",
"as ChatGPT, and kept so while the Codex app blocks its account: magpie never becomes Codex's provider. The Codex app may then send nothing till the account has room; Codex CLI goes on through magpie": "Wie ChatGPT, auch wenn die Codex-App das Konto blockiert: magpie wird nie der Anbieter von Codex. Die Codex-App sendet dann womöglich nichts, bis das Konto wieder Kontingent hat; Codex CLI läuft über magpie weiter",
"magpie is Codex's provider; the Codex app is in its API state, with magpie's models only": "magpie ist der Anbieter von Codex; die Codex-App ist im API-Modus, nur mit magpie-Modellen",
"same as model": "wie Modell",
"same as model ({model})": "wie Modell ({model})",
+11 -10
View File
@@ -1,12 +1,13 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// Codex's sign-in has three ways: ChatGPT (the default), which says that
// magpie is Codex's provider while the ChatGPT account is used up, so the
// Codex app still sends; Always ChatGPT, which never does that and says
// what it costs; and magpie API. The square opens the app's picker with
// each way's sentence whole, in the page's language; Always ChatGPT is
// posted as "chatgpt" and lights the square, ChatGPT posts "" again. A
// click scrolls nothing. At 1100px and 440px, English, Chinese, Japanese
// and German, Chromium and WebKit; no backend, the API is faked here.
// magpie is Codex's provider while the Codex app blocks the ChatGPT account
// (out of allowance, no credits left), so the app still sends; Always
// ChatGPT, which never does that and says what it costs; and magpie API.
// The square opens the app's picker with each way's sentence whole, in
// the page's language; Always ChatGPT is posted as "chatgpt" and lights the
// square, ChatGPT posts "" again. A click scrolls nothing. At 1100px and
// 440px, English, Chinese, Japanese and German, Chromium and WebKit; no
// backend, the API is faked here.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
@@ -17,8 +18,8 @@ const assets = path.resolve(__dirname, "../assets");
const models = [{ value: "gpt-5.5", label: "GPT-5.5", ref: "openai/gpt-5.5" }];
// as internal/agent/codex.go has them
const ways = [
{ value: "", label: "ChatGPT", note: "magpie's models join Codex's own; Codex stays signed in to ChatGPT, and while its account is used up magpie is Codex's provider, so the Codex app still sends" },
{ value: "chatgpt", label: "Always ChatGPT", note: "as ChatGPT, and kept so when its account is used up: magpie never becomes Codex's provider. The Codex app may then send nothing till the account has room; Codex CLI goes on through magpie" },
{ value: "", label: "ChatGPT", note: "magpie's models join Codex's own; Codex stays signed in to ChatGPT, and while the Codex app blocks its account (out of allowance, no credits left) magpie is Codex's provider, so the app still sends" },
{ value: "chatgpt", label: "Always ChatGPT", note: "as ChatGPT, and kept so while the Codex app blocks its account: magpie never becomes Codex's provider. The Codex app may then send nothing till the account has room; Codex CLI goes on through magpie" },
{ value: "api", label: "magpie API", note: "magpie is Codex's provider; the Codex app is in its API state, with magpie's models only" },
];
const fresh = () => ({
@@ -62,7 +63,7 @@ const codex = '.row.agent[data-id="codex"]';
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh", "ja", "de"]) {
test(`${engine} ${lang}: Codex's sign-in can be kept on ChatGPT when its account is used up`, async (t) => {
test(`${engine} ${lang}: Codex's sign-in can be kept on ChatGPT while the Codex app blocks its account`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const pages = [];
t.after(async () => {
+91 -63
View File
@@ -13,9 +13,8 @@ import (
// The account Codex is signed in to is out (CodexUsedUp, which makes magpie
// Codex's provider and the Codex app lose its ChatGPT sign-in) only when the
// Codex app itself holds it: the backend says it isn't allowed, and it is at
// a spend cap or past its overage, credits or not, or has no credits to go
// on with, a workspace one past its overage too. A window at
// Codex app itself holds it: the backend says it isn't allowed and it has no
// credits to go on with, a workspace one past its overage too. A window at
// 100% alone isn't: a Pro account with credits read 100% on its week and
// "allowed": false, and the app kept sending, the backend answering 200,
// while magpie had taken Codex out of ChatGPT ("Sign in to ChatGPT to start
@@ -39,6 +38,7 @@ func TestCodexUsedUpIsWhatTheAppHolds(t *testing.T) {
return m
}
credits := func(m map[string]any) map[string]any { return m["credits"].(map[string]any) }
rateLimit := func(m map[string]any) map[string]any { return m["rate_limit"].(map[string]any) }
// a workspace on no credits that the app sends for: within its overage,
// not at a spend cap, held for its allowance alone
within := func(plan string, edit func(m map[string]any)) map[string]any {
@@ -57,13 +57,7 @@ func TestCodexUsedUpIsWhatTheAppHolds(t *testing.T) {
want bool
}{
{"Pro at 100% on its week, with credits", read("codex_usage_pro_credits.json"), false},
{"Team at its spend cap, with credits", read("codex_usage_team_spend_cap.json"), true},
{"Pro at 100%, with credits, past its overage", with(read("codex_usage_pro_credits.json"), func(m map[string]any) {
credits(m)["overage_limit_reached"] = true
}), true},
{"Pro at 100%, with credits, at a spend cap", with(read("codex_usage_pro_credits.json"), func(m map[string]any) {
m["spend_control"].(map[string]any)["reached"] = true
}), true},
{"Team at its spend cap, with credits", read("codex_usage_team_spend_cap.json"), false},
{"Pro at 100%, credits spent", with(read("codex_usage_pro_credits.json"), func(m map[string]any) {
credits(m)["has_credits"], credits(m)["balance"] = false, "0"
}), true},
@@ -73,35 +67,35 @@ func TestCodexUsedUpIsWhatTheAppHolds(t *testing.T) {
{"Pro at 100%, no credits said", with(read("codex_usage_pro_credits.json"), func(m map[string]any) {
delete(m, "credits")
}), true},
{"allowed not said", with(read("codex_usage_pro_credits.json"), func(m map[string]any) {
delete(m, "credits")
delete(m["rate_limit"].(map[string]any), "allowed")
delete(m["rate_limit"].(map[string]any), "limit_reached")
// the app reads the spend cap and the overage only for a workspace
// with no credits: credits carry a Pro account on past both
{"Pro with credits, past its overage", with(read("codex_usage_pro_credits.json"), func(m map[string]any) {
credits(m)["overage_limit_reached"] = true
}), false},
{"allowed", with(read("codex_usage_pro_credits.json"), func(m map[string]any) {
delete(m, "credits")
m["rate_limit"].(map[string]any)["allowed"] = true
m["rate_limit"].(map[string]any)["limit_reached"] = false
{"Pro with credits, at a spend cap", with(read("codex_usage_pro_credits.json"), func(m map[string]any) {
m["spend_control"].(map[string]any)["reached"] = true
}), false},
{"allowed, its limit reached, no credits", with(read("codex_usage_pro_credits.json"), func(m map[string]any) {
// only allowed false holds it: limit_reached alone doesn't
{"limit reached but allowed, no credits", with(read("codex_usage_pro_credits.json"), func(m map[string]any) {
delete(m, "credits")
m["rate_limit"].(map[string]any)["allowed"] = true
}), true},
{"allowed, its limit reached, with credits", with(read("codex_usage_pro_credits.json"), func(m map[string]any) {
m["rate_limit"].(map[string]any)["allowed"] = true
rateLimit(m)["limit_reached"], rateLimit(m)["allowed"] = true, true
}), false},
{"limit reached, allowed not said, no credits", with(read("codex_usage_pro_credits.json"), func(m map[string]any) {
delete(m, "credits")
delete(m["rate_limit"].(map[string]any), "allowed")
}), true},
// a workspace's included usage still served past its spend cap
{"Business at its spend cap, still allowed", within("business", func(m map[string]any) {
m["spend_control"].(map[string]any)["reached"] = true
m["rate_limit"].(map[string]any)["allowed"] = true
m["rate_limit"].(map[string]any)["limit_reached"] = false
rateLimit(m)["limit_reached"] = true
delete(rateLimit(m), "allowed")
}), false},
{"not allowed, limit not reached, no credits", with(read("codex_usage_pro_credits.json"), func(m map[string]any) {
delete(m, "credits")
rateLimit(m)["limit_reached"], rateLimit(m)["allowed"] = false, false
}), true},
{"Business without credits, within its overage", within("business", as), false},
{"K12 without credits, within its overage", within("k12", as), false},
{"Law without credits, within its overage", within("law", as), false},
{"Sci without credits, within its overage", within("sci", as), false},
{"FinServ without credits, within its overage", within("finserv", as), false},
{"Enterprise trial without credits, within its overage", within("enterprise_cbp_trial", as), false},
{"Enterprise view-only without credits, within its overage", within("enterprise_cbp_view_only", as), false},
{"Pro without credits, its overage open", within("pro", as), true},
// the app's reserve experiment holds these on no credits, overage
// or not, and magpie can't see whether it is on
@@ -146,40 +140,9 @@ func TestCodexUsedUpIsWhatTheAppHolds(t *testing.T) {
// the window that held it has started again, as its usage does: else a
// 503 after the reset kept Codex on magpie, out of ChatGPT, with room.
func TestCodexHeldKeptOnlyTillTheReset(t *testing.T) {
signIn(t)
rememberLogins(true)
lastQuotas.Lock()
lastQuotas.m, lastQuotas.loaded = nil, false
lastQuotas.Unlock()
b, err := os.ReadFile("testdata/codex_usage_pro_credits.json")
if err != nil {
t.Fatal(err)
}
var body map[string]any
if err := json.Unmarshal(b, &body); err != nil {
t.Fatal(err)
}
cr := body["credits"].(map[string]any)
cr["has_credits"], cr["balance"] = false, "0"
body := heldUsage(t)
body["rate_limit"].(map[string]any)["primary_window"].(map[string]any)["reset_at"] = time.Now().Add(time.Hour).Unix()
var down atomic.Bool
fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if down.Load() {
http.Error(w, "upstream", http.StatusServiceUnavailable)
return
}
json.NewEncoder(w).Encode(body)
}))
defer fake.Close()
old := CodexBase
CodexBase = fake.URL + "/backend-api/codex"
t.Cleanup(func() { CodexBase = old })
read := func() bool {
loginUsageCache.Lock()
loginUsageCache.m = nil
loginUsageCache.Unlock()
return CodexUsedUp(context.Background())
}
read, down := servedUsage(t, body)
if !read() {
t.Fatal("CodexUsedUp = false on a held reading")
}
@@ -200,3 +163,68 @@ func TestCodexHeldKeptOnlyTillTheReset(t *testing.T) {
t.Fatal("CodexUsedUp = true on the kept reading after its window started again")
}
}
// A hold with no window used up (the backend says not allowed, no credits,
// every window under 100%) has no reset to end it: the kept reading stays
// held through a failed read, till a fresh one says otherwise. Else a 503
// put Codex back on an account its app sends nothing for.
func TestCodexHeldWithNoWindowUpKeptTillAFreshRead(t *testing.T) {
body := heldUsage(t)
body["rate_limit"].(map[string]any)["primary_window"].(map[string]any)["used_percent"] = 40
read, down := servedUsage(t, body)
if !read() {
t.Fatal("CodexUsedUp = false on a held reading")
}
down.Store(true)
if !read() {
t.Fatal("CodexUsedUp = false on the kept held reading, no window used up")
}
}
// heldUsage is the real Pro reply with its credits spent: not allowed, no
// credits, so held.
func heldUsage(t *testing.T) map[string]any {
t.Helper()
b, err := os.ReadFile("testdata/codex_usage_pro_credits.json")
if err != nil {
t.Fatal(err)
}
var body map[string]any
if err := json.Unmarshal(b, &body); err != nil {
t.Fatal(err)
}
cr := body["credits"].(map[string]any)
cr["has_credits"], cr["balance"] = false, "0"
return body
}
// servedUsage signs in the account Codex is on and serves body as its
// /wham/usage, or a 503 once down is set. read is CodexUsedUp on a fresh
// read, which falls back on the kept reading when it fails.
func servedUsage(t *testing.T, body map[string]any) (read func() bool, down *atomic.Bool) {
t.Helper()
signIn(t)
rememberLogins(true)
lastQuotas.Lock()
lastQuotas.m, lastQuotas.loaded = nil, false
lastQuotas.Unlock()
down = new(atomic.Bool)
fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if down.Load() {
http.Error(w, "upstream", http.StatusServiceUnavailable)
return
}
json.NewEncoder(w).Encode(body)
}))
t.Cleanup(fake.Close)
old := CodexBase
CodexBase = fake.URL + "/backend-api/codex"
t.Cleanup(func() { CodexBase = old })
read = func() bool {
loginUsageCache.Lock()
loginUsageCache.m = nil
loginUsageCache.Unlock()
return CodexUsedUp(context.Background())
}
return read, down
}
+4 -3
View File
@@ -133,10 +133,11 @@ func (c *lastQuotasT) load() {
func (c *lastQuotasT) reading(key string) (SubscriptionQuota, bool) {
out, ok := c.reported(key)
if ok {
wasUp := usedUp(out)
out.Windows = elapsed(out.Windows, time.Now())
// held went with a window used up: once none is, the reading
// can't say the account is still held
if out.Held && !usedUp(out) {
// a hold that came with a window used up ends when that window
// starts again; one with no window used up stands till a fresh read
if out.Held && wasUp && !usedUp(out) {
out.Held = false
}
}
+36 -33
View File
@@ -844,12 +844,11 @@ type codexUsage struct {
OverageReached *bool `json:"overage_limit_reached"`
} `json:"credits"`
RateLimit struct {
// false, or limit_reached true, once its allowance is used up;
// held only with no credits to go on with (codexHeld)
Allowed *bool `json:"allowed"`
LimitReached *bool `json:"limit_reached"`
Primary *codexWindow `json:"primary_window"`
Secondary *codexWindow `json:"secondary_window"`
// false once its allowance is used up; held only with no credits
// to go on with (codexHeld)
Allowed *bool `json:"allowed"`
Primary *codexWindow `json:"primary_window"`
Secondary *codexWindow `json:"secondary_window"`
} `json:"rate_limit"`
SpendControl *struct {
Reached bool `json:"reached"`
@@ -865,10 +864,14 @@ type codexUsage struct {
}
// codexWorkspacePlans are the plans of a ChatGPT workspace: every plan
// /wham/usage names (codex-rs codex-backend-openapi-models PlanType) but
// guest, free, go, plus, pro, prolite and promax, and Codex's own "hc".
// /wham/usage names (codex-rs codex-backend-openapi-models PlanType, and
// the Codex app's own plan_type switch for its usage banner, search
// "case`enterprise_cbp_trial`:" in ChatGPT.app 26.930.61225 app-initial)
// but guest, free, go, plus, pro, prolite and promax. A plan not listed
// isn't a workspace, so it is held on no credits.
var codexWorkspacePlans = []string{"free_workspace", "team", "self_serve_business_prolite", "self_serve_business_usage_based",
"business", "ent26", "enterprise_cbp_automation", "enterprise_cbp_usage_based", "enterprise", "hc",
"business", "ent26", "enterprise_cbp_automation", "enterprise_cbp_trial", "enterprise_cbp_usage_based",
"enterprise_cbp_view_only", "enterprise", "hc", "finserv", "law", "sci",
"education", "edu", "edu_plus", "edu_pro", "quorum", "k12"}
// codexReservePlans are the workspace plans the Codex app's reserve
@@ -878,41 +881,41 @@ var codexReservePlans = []string{"team", "self_serve_business_prolite"}
// codexHeld reports whether the Codex app (ChatGPT Desktop) holds its
// composer for the account, sending nothing at all, whichever model the
// turn is on: the backend says the account isn't allowed now (allowed
// false or limit_reached true), and it is at a spend cap or past its
// overage, or has no credits to go on with (has_credits or unlimited) and
// isn't a workspace one still within its overage. A window's percent never
// says it: a Pro account reads 100% on its week and is not allowed, while
// its credits carry every turn on (the app's composer stays open and the
// backend answers). Not said is not held.
// turn is on, as the app itself decides it: the backend says the account
// isn't allowed now (rate_limit.allowed false; limit_reached alone isn't
// read), and it has no credits to go on with (has_credits or unlimited),
// and isn't a workspace one still within its overage (overage not
// reached, no spend cap, an ordinary rate_limit_reached). A window's
// percent never says it: a Pro account reads 100% on its week and is not
// allowed, while its credits carry every turn on (the app's composer
// stays open and the backend answers). Not said is not held.
//
// A spend cap or a reached overage holds it whatever its credits say, as
// the app's readiness check reads it (26.930: `spend_control?.reached||
// credits?.overage_limit_reached` is `limited` before `has_credits`), where
// its composer gate alone (`hP`) lets credits through first: the backend
// refuses an account at its cap, and magpie as Codex's provider can serve
// the turn elsewhere. Where the app goes by what usage can't show (an
// experiment's gate, the reserve it may send on, a reset redeemed in the
// app), this says held too: wrongly held costs the app its ChatGPT extras
// while magpie serves the turn, wrongly not held leaves it sending nothing
// at all.
// This is the composer's own gate in ChatGPT.app 26.930.61225, either of
// two checks: hP in app-primary (search "n.rate_limit?.allowed!==!1||Jpe(n)"),
// which lets credits through, then a workspace within its overage, and
// hardBlocked in app-initial (search "hardBlocked:r.rate_limit?.allowed===!1"),
// which lets credits through but no overage, for the reserve experiment's
// plans. Tht (search "spend_control?.reached||e.credits?.overage_limit_reached"),
// which reads a spend cap before credits, is not the gate: it only tells a
// poller when to read usage again.
//
// Where the app goes by what usage can't show (the reserve experiment's
// gate, the reserve it may send on, a reset redeemed in the app), this
// says held: wrongly held costs the app its ChatGPT extras while magpie
// serves the turn, wrongly not held leaves it sending nothing at all.
func codexHeld(u codexUsage) bool {
r := u.RateLimit
if (r.Allowed == nil || *r.Allowed) && (r.LimitReached == nil || !*r.LimitReached) {
if u.RateLimit.Allowed == nil || *u.RateLimit.Allowed {
return false
}
c := u.Credits
spent := u.SpendControl != nil && u.SpendControl.Reached
if spent || c != nil && c.OverageReached != nil && *c.OverageReached {
return true
}
if c != nil && (c.Has || c.Unlimited) {
return false
}
spent := u.SpendControl != nil && u.SpendControl.Reached
why := u.ReachedType != nil && u.ReachedType.Type != nil && *u.ReachedType.Type != "rate_limit_reached"
plan := strings.ToLower(u.PlanType)
workspace := slices.Contains(codexWorkspacePlans, plan) && !slices.Contains(codexReservePlans, plan)
if workspace && c != nil && c.OverageReached != nil && !why {
if workspace && c != nil && c.OverageReached != nil && !*c.OverageReached && !spent && !why {
return false
}
return true