usage: a ChatGPT card says why its allowance can't be read, and a ChatGPT API account says where it shows
hmy on Discord: five ChatGPT accounts each said only "暂时无法获取额度"
(Allowance unavailable). danzi002 on Discord: accounts added through the
API never show usage, ones added as ChatGPT do.
What changed:
- Codex's usage read (codexWindows) now words its failure
(codex_usage_words.go): a Cloudflare challenge names the proxy/VPN
address as the usual cause; any other HTTP answer names its status and
what ChatGPT said; a network error says chatgpt.com couldn't be
reached; a reply magpie can't decode says so. The error still unwraps
to accountStatusError, so expiry and passing logic is unchanged.
- A ChatGPT API account (chatgpt-api) was read as a Codex account: a
saved one said "chatgpt-api accounts can't be used side by side", the
one in use read Codex's own sign-in ("Codex is signed out", or another
account's allowance under its name). OpenAI's API tells no plan usage,
so its row now says so, names chatgpt.com/settings/usage (SeeAt) and
says the same account added as ChatGPT shows it here.
- GUI quotaError translates each of these (en, zh, zh-TW, ja, de), and
"not read yet" (errNotAsked) gets its own words. The generic fallback
now reads "Allowance unavailable — hover for why"; the row's tooltip
has always been the raw error. Comments in app.js were shortened to
stay under TestCoreScriptBudget, which is not raised.
- docs/subsystems/providers-accounts.md describes the words.
Endpoint: the real wham/usage read of the owner's accounts in a sandbox
HOME copy (read-only, ~/.codex untouched) answered 200 and parsed, so
the endpoint itself is not broken; the "error decoding response body"
work is another session's and is not touched here.
Run (on mote; provider and gui again at the pushed head, rebased on
18c69aa46; 2251ca1ce, new under it, changed app.js and the budget):
- gofmt -l clean; GOOS=linux -tags nogui and GOOS=windows go vet of
provider and gui clean.
- go test -timeout 45m ./...: ok except TestEveryRouteHasACommandOrIsNamed
(#4826, red on origin/main 2251ca1ce too), TestMainWindowCorners (#3949,
red on main too) and TestCodexPoolSaysTheClientsVersion (#4807, red in
the full run, ok alone here and on main). At the pushed head:
provider ok, gui ok but TestMainWindowCorners (#3949), core budget ok.
- GUI: chatgpt-usage-why.test.cjs (new; chromium and webkit, 560 and
390, en/zh/zh-TW/ja/de, each row's words, its status code, the raw
tooltip, no overflow) and the six tests whose generic line changed.
The whole GUI suite was not run before this push: another session's
full suite held mote. The change adds no API call and no layout, only
words; the whole suite runs after the push and its reds get issues.
Broken by hand:
- codexWindows returning the bare err: TestCodexUsageSaysWhy and
TestCodexLoginUsageSaysCloudflare red.
- the GUI ChatGPT patterns removed: chatgpt-usage-why 0/2.
- the chatgpt-api branch off: TestChatGPTAPIUsageSaysWhere red, the
row read "Codex is signed out; run codex login".
Not tried: a real Cloudflare challenge (the fixture is the start of its
page as Cloudflare serves it, not hmy's bytes, which magpie hasn't got); a real ChatGPT API account (none signed in here); making a
ChatGPT API account's usage readable, since its token is for
api.openai.com and OpenAI shows plan usage only on chatgpt.com.
This commit is contained in:
@@ -45,7 +45,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
|
||||
| Token refresh | Each account refreshes through its vendor. For example, `codexToken` refreshes within 5 minutes of expiry and writes the rotated tokens back where it read them (`codexStore.write`: `~/.codex/auth.json`, or Codex's keychain item), every other field kept, for Codex CLI. Before refreshing a sign-in read from the keychain it asks the item again, so a rotation Codex made since isn't spent twice. A 400 or 401 from the vendor's refresh endpoint means it was refused (`refreshFailed`). | [`account.go`](../../internal/provider/account.go) |
|
||||
| Codex's credential store | Codex 0.162 keeps its ChatGPT sign-in where `cli_auth_credentials_store` in `$CODEX_HOME/config.toml` says (`codex-rs/login/src/auth/storage.rs`): `file` (default) is `auth.json`; `keyring` the system keychain alone; `auto` the keychain, else `auth.json`, on read and on save; `ephemeral` Codex's memory. Saved to the keychain, Codex removes `auth.json` (#2312, #2367, Dony2050). On macOS magpie reads that item through `security`, as it reads Claude Code's: service `Codex Auth`, account `cli|` + the first 16 hex digits of SHA-256 of the canonical CODEX_HOME (`codexKeychainAccount`), the value auth.json's JSON on one line. `readCodexLogin` is the one reader: `codexAccount`, `codexToken`, `liveLogin`, `CodexAPIKeySignedIn`, `codexLoginAuth`, `codexUntil` (the usage card's and each saved account row's `Until`, from the sign-in Codex holds when it holds that one), session identities and the agent's wiring (`provider.CodexSignIn`: `codexChatGPT`, `Agent.Source`) go through it. `keyring` with no item is signed out; `auto` with no item, or one the keychain wouldn't give, is `auth.json`, as Codex does. An item the keychain wouldn't give under `keyring` is not known (`codexStoreError`), never signed out. With `[features] secret_auth_storage` on (Codex's default on Windows) keyring and auto mean Codex's encrypted auth storage, which magpie doesn't read; nor does it read the Linux or Windows keychain. There `keyring` and `ephemeral` are not known, `auto` is `auth.json` when Codex left one, and the saved accounts' reason says to set `file` (`codexSignedOutWhy`). Requirements an admin manages (`requirements.cli_auth_credentials_store`) aren't read. Reading the secret can put up to two macOS prompts in front of the user, who may type their password, so one read per item is in flight at a time and waits up to 2 minutes for them (`keychainAsk`, `askCodexKeychain`), outside the cache's lock. A reader waits at most 5s from when that ask started (`keychainHold`) and is otherwise told magpie is waiting for an answer (`errKeychainWaiting`); no request or page waits out the prompt. `security` exit 44 is no item; 51 (errSecAuthFailed) or 128 (errSecUserCanceled) is denied or cancelled (`errKeychainRefused`); the 2 minutes running out is no answer (`errKeychainNoAnswer`); anything else is `errKeychainUnread`. Each says so in the saved accounts' reason, and none of them is signed out. A read the keychain gave is kept while the item is unchanged: after 10s a reader asks only the item's modification date (`Stat`, `find-generic-password` without `-w`, which shows no prompt) and reads the secret again only when Codex or magpie changed it (#2367: with "Allow" once, background polls asked again every ~30s). A refusal or no answer is kept 10 minutes (#2408). magpie's own writes (`codexStore.write`, `keepCodexKeychain`) keep the date of what they wrote; a switch, sign-out or refresh forgets a read (`forgetCodexKeychain`) so the next one checks the date, but keeps a refusal; switching and refreshing read afresh. Beside a refusal, no answer or waiting, the saved accounts' line has Try again (`Exclusion.Retry`, `keychain-retry`, `RetryCodexKeychain`), which reads once past the refusal, and the reason says "Always Allow" lets `/usr/bin/security` read the item, so macOS stops asking each time Codex changes it. A switch or a first sign-in (`saveCodexLogin`) writes the store Codex reads, and refuses when that store couldn't be read, when config.toml doesn't parse, or when it is one magpie doesn't read; it leaves an `auth.json` beside the item to Codex. Signing the last account out (`deleteCodexLogin`) removes the item, then `auth.json`, as `codex logout`. Not tried against an item Codex itself wrote: macOS may ask whether magpie can read it, and Codex whether it can read one magpie rewrote. | [`codex_store.go`](../../internal/provider/codex_store.go), [`codex_store_test.go`](../../internal/provider/codex_store_test.go), [`codex_keychain_ask_unix_test.go`](../../internal/provider/codex_keychain_ask_unix_test.go) |
|
||||
| Codex's other folders | Codex keeps one ChatGPT sign-in a folder (`codex-rs/login/src/auth/storage.rs`: `$CODEX_HOME/auth.json`, or the keychain item named by the folder) and writes its sessions there (`rollout/src/lib.rs`); `--profile` only lays `$CODEX_HOME/<name>.config.toml` over `config.toml`, the sign-in shared (`config/src/loader/mod.rs`). So a second account is Codex run with `CODEX_HOME=~/.codex-work`. `appdir.CodexHomes` finds those folders: `CodexHome` first, then folders in the home folder or beside `CodexHome` named `codex*` or `.codex*`, or one folder down in one (`~/.codex-profiles/work`), that hold `auth.json` or `sessions/`. Sessions and the usage ledger read every one (`sessions.codexFiles`, `Dirs`). `rememberLogins` saves each folder's account with `Home` set to it (`codexHomeLogins`); the one `~/.codex` is signed in to is that one's. Such an account is renewed in its folder, as Codex's own (`codexHeldIn` in `renewSaved`, as `heldByCodex` does for `~/.codex`), so the quota, the gateway and the keep-alive never spend a copy's refresh token under that folder's Codex. It isn't switched into `~/.codex` (`switchSavedLogin`, `NextLogin`'s spares): the error names the folder and the `CODEX_HOME=… codex` command. A refresh OpenAI refuses there marks the account signed out (`codexHeldRefusal`, `codexSignInRead`), so its row has Sign in again, and magpie's sign-in writes the new tokens back to that folder (`codexHeldFolder` in `addLogin`), never to `~/.codex` (`TestCodexHeldInOtherFolderSignedOutThenSignedInAgain`). Remove forgets it and sets that folder's sign-in aside in `codex-homes-removed.json` (the folder to a SHA-256 of its refresh token, `setCodexAside`), the folder's files left as they are; `codexHomeLogins` passes over the folder while it holds that sign-in, and a sign-in made there again is listed again. An unreadable record reads no other folder's account that look (charliepu on Discord: a `.codex-db-backup-…` folder no Codex runs in, refused with "codex logout"; `TestCodexHeldFolderAccountRemoved`). phantom3792 on X: only the default folder's sessions counted, and an account added from another folder read no quota (`TestCodexOtherHome*`, `TestCodexHomesIn`). Not done: Codex's thread names (`session_index.jsonl`) and a `sqlite_home` are read from `CodexHome` only (#3530). | [`codex.go`](../../internal/appdir/codex.go), [`logins.go`](../../internal/provider/logins.go), [`codex_homes_test.go`](../../internal/provider/codex_homes_test.go) |
|
||||
| A revoked sign-in | A 401 whose words say the sign-in itself is gone (`SignInRevoked`: ChatGPT's `token_revoked`, `invalid_grant`, `refresh_token_reused`; never `token_expired`, a 403, a 5xx or a network error) marks the account for the credential it was sent with (`NoteRevokedSignIn`, #1793). A saved ChatGPT account is refreshed first, as Codex does on a 401, and a refresh that goes through marks nothing. The mark is a hash of the header, never the credential, kept in `logins.json` as `Refused: "revoked:<mark>"` with the account's `Lapsed`, and read back after a restart. While the account has that credential, the gateway doesn't send its requests (`RevokedSignIn`); its row says Sign-in required with Sign in again. A ChatGPT account's usage read marks it too (`codexSignInRead` in `loginQuota`, charliepu on Discord: an account OpenAI signed out showed only a blank allowance): `/wham/usage` answering 401 with those words is refreshed once (`codexWindowsRenewing`), and the account is marked for the token turned away when the refreshed read is turned away the same (`codexSignInGone`), or, for the one Codex is signed in to, when its refresh is refused (its row used to say nothing, its allowance line "run codex login"; a saved one's refused refresh is `savedRefreshFailed`'s). Any other 401, a 403, a 5xx or a network error is unknown and marks nothing. Sign in again runs magpie's own sign-in for the account (`addLogin`), which replaces its tokens, in Codex's `auth.json` too when Codex is signed in to it. Signed in anew (`upsertLogin` with another credential, `addSideLogin`), refreshed, served a request (`ServedSignIn`), or its usage read going through, it is clear. Claude (`claude_auth.go`), Copilot (`copilot_lapsed.go`: GitHub's 401/403 on the token exchange, the CLI's stand-in or the usage read, cleared when a token is served) and plugins keep their own marks. | [`signin_revoked.go`](../../internal/provider/signin_revoked.go), [`copilot_lapsed.go`](../../internal/provider/copilot_lapsed.go) |
|
||||
| A revoked sign-in | A 401 whose words say the sign-in itself is gone (`SignInRevoked`: ChatGPT's `token_revoked`, `invalid_grant`, `refresh_token_reused`; never `token_expired`, a 403, a 5xx or a network error) marks the account for the credential it was sent with (`NoteRevokedSignIn`, #1793). A saved ChatGPT account is refreshed first, as Codex does on a 401, and a refresh that goes through marks nothing. The mark is a hash of the header, never the credential, kept in `logins.json` as `Refused: "revoked:<mark>"` with the account's `Lapsed`, and read back after a restart. While the account has that credential, the gateway doesn't send its requests (`RevokedSignIn`); its row says Sign-in required with Sign in again. A ChatGPT account's usage read marks it too (`codexSignInRead` in `loginQuota`, charliepu on Discord: an account OpenAI signed out showed only a blank allowance): `/wham/usage` answering 401 with those words is refreshed once (`codexWindowsRenewing`), and the account is marked for the token turned away when the refreshed read is turned away the same (`codexSignInGone`), or, for the one Codex is signed in to, when its refresh is refused (its row used to say nothing, its allowance line "run codex login"; a saved one's refused refresh is `savedRefreshFailed`'s). Any other 401, a 403, a 5xx or a network error is unknown and marks nothing. Each failed read says why on the account's row (`codexUsageWords`, `codex_usage_words.go`; hmy on Discord: five ChatGPT accounts each said only "Allowance unavailable", the error being Go's bare status text or decode error, which the GUI read none of): Cloudflare's challenge page in place of an answer (a proxy or VPN address, usually), `HTTP <code>` with the backend's own `detail` or `error` words, chatgpt.com not reached, or a reply magpie doesn't read; `quotaError` in app.js turns each into a line of the card's language, the raw error in the row's tooltip. The words keep what was matched before: the status text that `passing` (`quota_last.go`) reads to keep the last reading over a 429 or a 5xx, and the answer itself under `Unwrap` for `codexExpired`. An error with no words of its own says "Allowance unavailable — hover for why". A ChatGPT API account (`chatgpt-api`, `chatgpt_api.go`) has no usage read: OpenAI's API tells none, only chatgpt.com/settings/usage does. `loginQuota` says so (`siwcNoUsage`, with that page as `SeeAt`) and asks nothing; it used to read the account as a Codex one, so an active one read Codex's own sign-in ("Codex is signed out; run codex login", or another account's allowance under its name) and the card said only that it couldn't be read (danzi002 on Discord). Guarded by `TestChatGPTAPIUsageSaysWhere`. Sign in again runs magpie's own sign-in for the account (`addLogin`), which replaces its tokens, in Codex's `auth.json` too when Codex is signed in to it. Signed in anew (`upsertLogin` with another credential, `addSideLogin`), refreshed, served a request (`ServedSignIn`), or its usage read going through, it is clear. Claude (`claude_auth.go`), Copilot (`copilot_lapsed.go`: GitHub's 401/403 on the token exchange, the CLI's stand-in or the usage read, cleared when a token is served) and plugins keep their own marks. | [`signin_revoked.go`](../../internal/provider/signin_revoked.go), [`copilot_lapsed.go`](../../internal/provider/copilot_lapsed.go) |
|
||||
| A token called expired | A ChatGPT 401 whose words say the access token has expired and ask for a refresh (`SignInExpired`: `token_expired`, "Provided authentication token is expired. Please try refreshing it."; never `refresh_token_expired`, which is revoked) while the token's own `exp` is still ahead (willz on Discord, #2973: two saved Team accounts) is mended by one refresh. `codexToken` refreshes only as `exp` nears, so before this the token went out as it was until the user signed in again, and the card said only Unauthorized. The usage read (`codexWindowsRenewing`: `loginQuota`, `codexSubscriptionUsage`, and the reset spenders through `codexUserWindows`) refreshes once and reads once more, never again: a refresh refused says to sign in again (a saved account is marked lapsed, `savedRefreshFailed`; Codex's own is marked revoked, see A revoked sign-in, through `loginQuota`, while `codexSubscriptionUsage`'s card still says `codex login`), and a token refreshed for it and still called expired says so too (`errCodexStillExpired`) and is marked revoked the same. The gateway renews the account a request went with (`NoteExpiredSignIn` from `noteSignIn`, 20s at most); the request itself fails over as before, and the next goes with the new token. Each refresh is keyed on the token turned away (`codexTokenRenewing`, `renewSavedLoginFrom`), under the lock signing waits on: a sign-in holding another token by then, renewed by Codex or another reply, is used as it is, so two replies for one token spend one rotation. Codex's own sign-in is read from its store afresh for it and written back through `codexStore.write` (temp and rename), a saved one's through `writeLogins`. Not tried against the real backend. | [`codex_expired.go`](../../internal/provider/codex_expired.go), [`account.go`](../../internal/provider/account.go), [`logins_on.go`](../../internal/provider/logins_on.go) |
|
||||
| Saved accounts | `logins.json` remembers every Codex and Claude Code account seen signed in. A switch moves the credentials into the agent's own store and saves the ones it replaces. A saved account that is on (`SetLoginOn`) stands behind the agent's own. Its tokens stay in `logins.json`. While Claude Code is signed out, a saved Claude account stands in for its own (`claudeStandIn`); with every saved account's sign-in gone, Claude Code is still listed, on the one seen last, signed out (`claudeListed`), its accounts each saying to sign in again, so it never leaves the Providers list (LeeHom on Discord). Claude Code's own account while still `Held` is never listed that way, since the sign-in it may have left on disk would be served. An account whose every login in use has lapsed is `Provider.SignedOut`: `magpie providers` and the TUI say "<user> is signed out", as the app's row does. | [`logins.go`](../../internal/provider/logins.go), [`logins_on.go`](../../internal/provider/logins_on.go), [`claude_dirs.go`](../../internal/provider/claude_dirs.go) |
|
||||
| Sign-in in magpie | `StartSignIn` runs the vendor's own browser OAuth with its client and takes the tokens at a callback on this machine. A browser that can't reach that callback (magpie on a server or in Docker) ends on a page that won't load; its address, pasted (`SubmitSignInCallback`), goes through the same callback handler (`pastedCallback`). ChatGPT's sign-in comes back only to port 1455; when that port can't be opened, the sign-in still starts and waits for the pasted address alone, and says why in `CallbackBlocked` with the port in `CallbackPort`: `reserved` for Windows' WSAEACCES on a port in a range it excludes for Hyper-V, WSL or Docker, `busy` for anything else, such as another program holding it (`callbackBlocked`, #1782). A plugin's browser sign-in (`auto`) whose page names a port on this machine to come back to takes its pasted address too: magpie opens it there on 127.0.0.1, for the plugin's own listener (`pluginCallback`, `loopbackPorts`); Command Code's page posts its key from script, so it offers the API key way instead. A Claude account is signed in by Claude Code itself. Signing in brings back an account removed from magpie (`ShowAccount`). A sign-in started in magpie (`StartSignIn`, `StartPluginSignIn`) reads as done (`SignInStatus`, `WaitSignIn`) only after `finish` has run `ShowAccount` for its account, so the window, which opens the account as soon as it sees done, finds it listed. If providers.json can't be written then, the account stays hidden and the sign-in still ends done. Signing in to a plugin's provider from the command line (`pluginLogin`, with a key or the browser) brings it back too. It also takes off the mark a sign-in its vendor turned away left on the account (`Lapsed`) and shows again the agent's own account removed in magpie (`clearPluginLapse`). The window's plugin sign-in does the same with the browser (`pluginDone`, then `finish`) or with a key (`PluginAPIKey`); a key and the command line share these steps in `PluginSignedIn`. A sign-in leaves through the proxy the account's own requests will use (#1663): `ProxyOfLogin` (the account's, else the subscription's, else the global one) for the account being signed in again, the subscription's for a new one. Every request of the flow goes through `signInFlow.via`, Claude Code's own login gets it as *_PROXY (`netproxy.EnvWith`), and a plugin's sign-in runs its fetch under that proxy (`via` in `host.js`; `plugins_cli.go` for the command line). The window's sign-in box shows it as a "Proxy: …" link (`signInProxyLink`, the app menu, no userinfo shown) with Global, Direct, the subscription's and each account's proxy, or a typed one; picking one starts the sign-in again through it (`SignInOptions.Proxy`), and when it ends the pick is kept as the account's (`keepSignInProxy`: the subscription's own when it is its only account, else the account's entry). Global isn't offered while the subscription has a proxy and other accounts, since nothing could keep it. The browser's own leg goes through the browser's network, not magpie's. The window or `magpie web` opens the sign-in page in the default browser (`openSignIn` in `internal/gui/api.go`; `openSignInPage` in `app.js` for a web tab), and the waiting box always shows the link with Copy link. With Settings › Privacy › Sign-in pages off (`SignInLinkOnly`, max2020 on Discord, who signs in from a separate fingerprint browser), magpie opens nothing: the reply carries `linkOnly`, the box says the page wasn't opened and offers Open, and `magpie accounts add` and a plugin's browser login from the command line (`pluginLogin`) print the link without opening it. A callback on this machine still comes back from another browser on it, and the pasted address covers one that can't reach it. A plugin whose own CLI opens the page (`opened`, Grok Build's device sign-in on macOS and Windows) still opens it. Signing out leaves through the same exit: a ChatGPT account's refresh token is revoked through its own proxy, read before the account is forgotten (`forgetSIWCLogin`), and Devin's CLI, asked who is signed in or for its models, runs with the account's proxy (`devinCommand`, `devinProxy`). | [`signin.go`](../../internal/provider/signin.go), [`claude_signin.go`](../../internal/provider/claude_signin.go), [`pluginsignin.go`](../../internal/provider/pluginsignin.go), [`pluginsignin_paste.go`](../../internal/provider/pluginsignin_paste.go), [`proxy.go`](../../internal/provider/proxy.go), [`plugins_cli.go`](../../internal/cli/plugins_cli.go) |
|
||||
|
||||
+22
-30
@@ -13529,8 +13529,7 @@ function renderLoginImport(sub) {
|
||||
return box;
|
||||
}
|
||||
|
||||
// Each account's allowance comes from the vendor and takes a moment, so it
|
||||
// loads on its own and fills the rows in when it's there.
|
||||
// Each account's allowance loads on its own and fills the rows in.
|
||||
const loginUsage = {}; // agent → { at, data: { user: quota }, loading }
|
||||
function loginUsageOf(agent) {
|
||||
const u = (loginUsage[agent] ||= {});
|
||||
@@ -13545,11 +13544,8 @@ function loginUsageOf(agent) {
|
||||
return u.data;
|
||||
}
|
||||
|
||||
// quotaError says why an allowance can't be read: a Google account with
|
||||
// no Cloud project named can't be used at all until one is, so that is
|
||||
// said outright; anything else is in the tooltip.
|
||||
// SIGN_IN_GONE: an allowance read saying the account's sign-in is gone,
|
||||
// as the gateway reads a plugin's (signInGone, plugin_usage.go)
|
||||
// quotaError says why an allowance can't be read, the raw error in the tooltip.
|
||||
// SIGN_IN_GONE: a read saying the sign-in is gone (signInGone)
|
||||
const SIGN_IN_GONE = /sign-in has (expired|lapsed)|sign in again/i;
|
||||
|
||||
function quotaError(err, q) {
|
||||
@@ -13576,12 +13572,10 @@ function quotaError(err, q) {
|
||||
if (/^this plan's usage is read with the account's access key/.test(err)) return t("This plan's usage needs the account's AccessKey ID and Secret — give them in the provider's settings");
|
||||
// ZCode with no plan left, not a failed read (#1001)
|
||||
if (/^this account has no GLM Coding Plan, and ZCode's Start Plan has ended or was never started$/.test(err)) return t("ZCode: no GLM Coding Plan, and no free Start Plan — subscribe to a GLM Coding Plan to use this account");
|
||||
// an OpenCode Go key's windows (planquota.go): only the subscribing
|
||||
// member's key reads them; said with the way out
|
||||
// an OpenCode Go key's windows (planquota.go)
|
||||
if (/^this key has no OpenCode Go subscription/.test(err)) return t("No OpenCode Go on this key — use a key made by the member who subscribed, in that workspace");
|
||||
if (/^OpenCode didn't take this key/.test(err)) return t("OpenCode didn't take this key — paste a current one in the provider's settings");
|
||||
// a GLM key Zhipu or Z.ai refused (zhipuRefused, planquota.go): the key
|
||||
// is what to change, not a reading that failed (@xanahopper on X)
|
||||
// a GLM key Zhipu or Z.ai refused (zhipuRefused)
|
||||
const glm = /^(Zhipu|Z\.ai) didn't take this key/.exec(err);
|
||||
if (glm) return t("{vendor} didn't take this key — it expired, was deleted or is mistyped; paste a current one in the provider's settings", { vendor: glm[1] });
|
||||
if (/^OpenCode Go's reply has no rolling/.test(err)) return t("OpenCode Go answered in a form magpie doesn't read — hover for what it sent");
|
||||
@@ -13594,24 +13588,27 @@ function quotaError(err, q) {
|
||||
// a remote magpie's gateway key card (#1547, remote_key_limits.go)
|
||||
if (/^remote magpie is too old to tell this key's limit/.test(err)) return t("That computer's magpie is too old to tell this key's limit — update magpie there");
|
||||
if (/answered its key's limit in a form magpie doesn't read$/.test(err)) return t("That computer answered this key's limit in a form magpie doesn't read — hover for more");
|
||||
// a ClinePass card with its balance but not its limits (#79): the key
|
||||
// card (cline_usage.go) and the Cline plugin both begin so
|
||||
// a ClinePass card with its balance but not its limits (#79)
|
||||
if (/^ClinePass limits couldn't be read/.test(err)) return t("ClinePass limits couldn't be read — hover for why");
|
||||
// ChatGPT's (errNotAsked, codex_usage_words.go, siwcNoUsage; hmy, danzi002 on Discord)
|
||||
if (/not read yet: magpie reads allowances only when you ask/.test(err)) return t("Not read yet — magpie reads allowances only when you ask; refresh this card to read it");
|
||||
if (/^ChatGPT's Cloudflare check turned the usage read away/.test(err)) return t("ChatGPT's Cloudflare check stopped the read — usually a proxy or VPN address; try another one");
|
||||
const chatgpt = /^ChatGPT answered the usage read with HTTP (\d{3})/.exec(err);
|
||||
if (chatgpt) return t("ChatGPT answered HTTP {status} — hover for what it said", { status: chatgpt[1] });
|
||||
if (/^couldn't reach chatgpt\.com for the usage read/.test(err)) return t("Couldn't reach ChatGPT — check the network or the proxy");
|
||||
if (/^ChatGPT's usage reply isn't one magpie reads/.test(err)) return t("ChatGPT answered in a form magpie doesn't read — hover for what it sent");
|
||||
if (/^a ChatGPT API account's usage isn't told through OpenAI's API/.test(err)) return t("OpenAI's API doesn't tell a ChatGPT API account's usage — see chatgpt.com/settings/usage, or add the account as ChatGPT to see it here");
|
||||
const bal = balanceError(err);
|
||||
if (bal) return bal;
|
||||
// a plugin's own usage read failed (pluginError, plugin_usage.go): magpie
|
||||
// has no better words for it than the plugin's, and hiding them in a
|
||||
// tooltip left the card saying only that nothing could be read
|
||||
// (aqiu817/magpie-sensenova#1), so its first line is said on the card
|
||||
// a plugin's own usage read failed: its first line (aqiu817/magpie-sensenova#1)
|
||||
if (q?.pluginError) {
|
||||
const why = String(err).split("\n")[0].trim();
|
||||
if (why) return t("Allowance unavailable: {why}", { why: why.length > 160 ? why.slice(0, 159) + "…" : why });
|
||||
}
|
||||
return t("Allowance unavailable");
|
||||
return t("Allowance unavailable — hover for why");
|
||||
}
|
||||
|
||||
// the Balance field magpie reads, left empty, from a query whose reply it
|
||||
// knows (balancePathOf in balance.go), shown as the field's placeholder
|
||||
// the Balance field's placeholder (balancePathOf in balance.go)
|
||||
function balanceFieldOf(raw) {
|
||||
let path = "";
|
||||
try { path = new URL((raw || "").trim()).pathname.replace(/\/+$/, ""); } catch { return "data.balance"; }
|
||||
@@ -13623,8 +13620,7 @@ function balanceFieldOf(raw) {
|
||||
return "data.balance";
|
||||
}
|
||||
|
||||
// balanceError: a balance that couldn't be read, said plainly where magpie
|
||||
// knows the fix (see balance.go); "" for any other.
|
||||
// balanceError: a balance read's fix where magpie knows it; "" for any other.
|
||||
function balanceError(err) {
|
||||
if (/takes the API key, not the access token/.test(err)) return t("The Balance URL …/api/usage/token takes the API key, not the access token — set it to …/api/user/self in the provider's settings");
|
||||
if (/takes the API key, not the login token/.test(err)) return t("The Balance URL …/v1/usage takes the API key, not the login token — set it to …/api/v1/user/profile in the provider's settings");
|
||||
@@ -13634,9 +13630,8 @@ function balanceError(err) {
|
||||
return "";
|
||||
}
|
||||
|
||||
// An account token is unused without a Balance URL and can't authenticate
|
||||
// /api/usage/token or sub2api's /v1/usage, which take API keys only. Other URLs may belong to
|
||||
// another relay and are left alone; both new-api and sub2api issue JWTs.
|
||||
// An account token needs a Balance URL; /api/usage/token and sub2api's
|
||||
// /v1/usage take API keys only. Other URLs are left alone.
|
||||
function balanceFix(p) {
|
||||
const box = el("div", "bal-fix");
|
||||
const origin = (u) => { try { const x = new URL(u); return /^https?:$/.test(x.protocol) ? x.origin : ""; } catch { return ""; } };
|
||||
@@ -13699,8 +13694,7 @@ function accountRefresh(agent, p, user) {
|
||||
return b;
|
||||
}
|
||||
|
||||
// accountQuota: an account's allowance as a line of small meters under its
|
||||
// name, the reset time on the ones nearly used up, credits and held resets.
|
||||
// accountQuota: an account's allowance as small meters under its name.
|
||||
function accountQuota(data, user, capFor = () => 0, settable = null, prov) {
|
||||
const line = el("div", "aq");
|
||||
if (!data) {
|
||||
@@ -13775,9 +13769,7 @@ function accountQuota(data, user, capFor = () => 0, settable = null, prov) {
|
||||
}
|
||||
|
||||
// poolLine: an account row's pools, each its name then its 5-hour and
|
||||
// weekly meters (Gemini 5h ▬ 95% 7d ▬ 75%), every pool Google reports:
|
||||
// one left to the tooltip was Claude's once Gemini 4 Argon had its own
|
||||
// (01huadalang on Discord). The line wraps.
|
||||
// weekly meters, every pool Google reports (01huadalang). The line wraps.
|
||||
function poolLine(line, ws, q, capFor = () => 0, settable = null) {
|
||||
const pools = [];
|
||||
for (const w of ws) {
|
||||
|
||||
@@ -3163,7 +3163,13 @@ const I18N = {
|
||||
"Cursor Models": "Cursor 模型",
|
||||
"Other Models": "其他模型",
|
||||
"Total": "合计",
|
||||
"Allowance unavailable": "暂时无法获取额度",
|
||||
"Allowance unavailable — hover for why": "暂时无法获取额度 — 悬停查看原因",
|
||||
"OpenAI's API doesn't tell a ChatGPT API account's usage — see chatgpt.com/settings/usage, or add the account as ChatGPT to see it here": "OpenAI 的 API 不提供 ChatGPT API 账号的用量 — 请到 chatgpt.com/settings/usage 查看,或把这个账号以 ChatGPT 方式添加,在这里查看",
|
||||
"Not read yet — magpie reads allowances only when you ask; refresh this card to read it": "还没读过 — magpie 只在你要求时读取额度;刷新这张卡片即可读取",
|
||||
"ChatGPT's Cloudflare check stopped the read — usually a proxy or VPN address; try another one": "ChatGPT 的 Cloudflare 验证拦下了这次读取 — 通常是代理或 VPN 的地址所致;换一个试试",
|
||||
"ChatGPT answered HTTP {status} — hover for what it said": "ChatGPT 返回了 HTTP {status} — 悬停查看它说了什么",
|
||||
"Couldn't reach ChatGPT — check the network or the proxy": "连不上 ChatGPT — 请检查网络或代理",
|
||||
"ChatGPT answered in a form magpie doesn't read — hover for what it sent": "ChatGPT 返回的格式 magpie 读不懂 — 悬停查看它返回了什么",
|
||||
"Finish Claude Code's first-run setup, then refresh. Run magpie claude-code to find its executable.": "请先完成 Claude Code 的首次启动引导,再刷新。运行 magpie claude-code 可查看应启动的程式路径。",
|
||||
"Allowance unavailable: {why}": "暂时无法获取额度:{why}",
|
||||
"Nothing read on that computer yet — refresh this card to have it read": "那台电脑还没有读过额度 — 刷新这张卡片让它读取",
|
||||
@@ -7562,7 +7568,13 @@ const I18N = {
|
||||
"Cursor Models": "Cursor 模型",
|
||||
"Other Models": "其他模型",
|
||||
"Total": "合計",
|
||||
"Allowance unavailable": "暫時無法取得額度",
|
||||
"Allowance unavailable — hover for why": "暫時無法取得額度 — 懸停查看原因",
|
||||
"OpenAI's API doesn't tell a ChatGPT API account's usage — see chatgpt.com/settings/usage, or add the account as ChatGPT to see it here": "OpenAI 的 API 不提供 ChatGPT API 帳號的用量 — 請到 chatgpt.com/settings/usage 查看,或把這個帳號以 ChatGPT 方式新增,在這裡查看",
|
||||
"Not read yet — magpie reads allowances only when you ask; refresh this card to read it": "還沒讀過 — magpie 只在你要求時讀取額度;重新整理這張卡片即可讀取",
|
||||
"ChatGPT's Cloudflare check stopped the read — usually a proxy or VPN address; try another one": "ChatGPT 的 Cloudflare 驗證擋下了這次讀取 — 通常是代理或 VPN 的位址所致;換一個試試",
|
||||
"ChatGPT answered HTTP {status} — hover for what it said": "ChatGPT 回傳了 HTTP {status} — 懸停查看它說了什麼",
|
||||
"Couldn't reach ChatGPT — check the network or the proxy": "連不上 ChatGPT — 請檢查網路或代理",
|
||||
"ChatGPT answered in a form magpie doesn't read — hover for what it sent": "ChatGPT 回傳的格式 magpie 讀不懂 — 懸停查看它回傳了什麼",
|
||||
"Finish Claude Code's first-run setup, then refresh. Run magpie claude-code to find its executable.": "請先完成 Claude Code 的首次啟動導引,再重新整理。執行 magpie claude-code 可查看應啟動的程式路徑。",
|
||||
"Allowance unavailable: {why}": "暫時無法取得額度:{why}",
|
||||
"Nothing read on that computer yet — refresh this card to have it read": "那臺電腦還沒有讀過額度 — 重新整理這張卡片讓它讀取",
|
||||
@@ -11965,7 +11977,13 @@ const I18N = {
|
||||
"Cursor Models": "Cursor モデル",
|
||||
"Other Models": "その他のモデル",
|
||||
"Total": "合計",
|
||||
"Allowance unavailable": "利用枠を取得できません",
|
||||
"Allowance unavailable — hover for why": "利用枠を取得できません — ホバーで理由を表示",
|
||||
"OpenAI's API doesn't tell a ChatGPT API account's usage — see chatgpt.com/settings/usage, or add the account as ChatGPT to see it here": "OpenAI の API は ChatGPT API アカウントの利用量を返しません — chatgpt.com/settings/usage で確認するか、このアカウントを ChatGPT として追加するとここに表示されます",
|
||||
"Not read yet — magpie reads allowances only when you ask; refresh this card to read it": "まだ読み取っていません — magpie は求められたときだけ利用枠を読み取ります。このカードを更新すると読み取ります",
|
||||
"ChatGPT's Cloudflare check stopped the read — usually a proxy or VPN address; try another one": "ChatGPT の Cloudflare チェックで読み取りが止められました — 多くはプロキシや VPN のアドレスが原因です。別のものを試してください",
|
||||
"ChatGPT answered HTTP {status} — hover for what it said": "ChatGPT が HTTP {status} を返しました — ホバーで内容を表示",
|
||||
"Couldn't reach ChatGPT — check the network or the proxy": "ChatGPT に接続できません — ネットワークかプロキシを確認してください",
|
||||
"ChatGPT answered in a form magpie doesn't read — hover for what it sent": "ChatGPT の応答は magpie が読めない形式です — ホバーで内容を表示",
|
||||
"Finish Claude Code's first-run setup, then refresh. Run magpie claude-code to find its executable.": "Claude Code の初回設定を完了してから更新してください。magpie claude-code を実行すると、起動する実行ファイルを確認できます。",
|
||||
"Allowance unavailable: {why}": "利用枠を取得できません:{why}",
|
||||
"Nothing read on that computer yet — refresh this card to have it read": "そのコンピューターではまだ読み取っていません — このカードを更新すると読み取ります",
|
||||
@@ -16379,7 +16397,13 @@ const I18N = {
|
||||
"Cursor Models": "Cursor-Modelle",
|
||||
"Other Models": "Andere Modelle",
|
||||
"Total": "Gesamt",
|
||||
"Allowance unavailable": "Kontingent nicht verfügbar",
|
||||
"Allowance unavailable — hover for why": "Kontingent nicht verfügbar — für den Grund darüberfahren",
|
||||
"OpenAI's API doesn't tell a ChatGPT API account's usage — see chatgpt.com/settings/usage, or add the account as ChatGPT to see it here": "OpenAIs API nennt die Nutzung eines ChatGPT-API-Kontos nicht — sieh unter chatgpt.com/settings/usage nach, oder füge das Konto als ChatGPT hinzu, um sie hier zu sehen",
|
||||
"Not read yet — magpie reads allowances only when you ask; refresh this card to read it": "Noch nicht gelesen — magpie liest Kontingente nur auf Anfrage; diese Karte aktualisieren, um es zu lesen",
|
||||
"ChatGPT's Cloudflare check stopped the read — usually a proxy or VPN address; try another one": "Die Cloudflare-Prüfung von ChatGPT hat das Lesen gestoppt — meist liegt es an der Adresse eines Proxys oder VPNs; probiere einen anderen",
|
||||
"ChatGPT answered HTTP {status} — hover for what it said": "ChatGPT hat mit HTTP {status} geantwortet — für den Inhalt darüberfahren",
|
||||
"Couldn't reach ChatGPT — check the network or the proxy": "ChatGPT ist nicht erreichbar — prüfe Netzwerk oder Proxy",
|
||||
"ChatGPT answered in a form magpie doesn't read — hover for what it sent": "ChatGPT hat in einer Form geantwortet, die magpie nicht liest — für den Inhalt darüberfahren",
|
||||
"Finish Claude Code's first-run setup, then refresh. Run magpie claude-code to find its executable.": "Schließe die Ersteinrichtung von Claude Code ab und aktualisiere dann erneut. Mit magpie claude-code findest du die zu startende Programmdatei.",
|
||||
"Allowance unavailable: {why}": "Kontingent nicht verfügbar: {why}",
|
||||
"Nothing read on that computer yet — refresh this card to have it read": "Auf diesem Computer wurde noch nichts gelesen — diese Karte aktualisieren, um es lesen zu lassen",
|
||||
|
||||
@@ -133,15 +133,15 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
]);
|
||||
assert.match(said[0], /set it to …\/api\/user\/self/);
|
||||
assert.match(said[1], /^Add the header New-Api-User = your user ID/);
|
||||
assert.equal(said[2], "Allowance unavailable");
|
||||
assert.equal(said[2], "Allowance unavailable — hover for why");
|
||||
// the card's own words for a ZCode account with nothing to spend, and
|
||||
// the action on the card itself (there is none in the error to hover for)
|
||||
for (const s of [said[3], said[4]]) {
|
||||
assert.match(s, /^ZCode: no GLM Coding Plan, and no free Start Plan/);
|
||||
assert.match(s, /subscribe to a GLM Coding Plan to use this account/);
|
||||
}
|
||||
assert.equal(said[5], "Allowance unavailable", "a Start Plan that couldn't be read is not a plan that ended");
|
||||
assert.equal(said[6], "Allowance unavailable", "a sign-in error names the address itself and is not the card's")
|
||||
assert.equal(said[5], "Allowance unavailable — hover for why", "a Start Plan that couldn't be read is not a plan that ended");
|
||||
assert.equal(said[6], "Allowance unavailable — hover for why", "a sign-in error names the address itself and is not the card's")
|
||||
const missing = await page.evaluate(() => [
|
||||
"…/api/usage/token takes the API key, not this token: for the account's balance, new-api uses /api/user/self; sub2api uses /api/v1/user/profile.",
|
||||
"The token needs a Balance URL: a new-api relay uses /api/user/self; a sub2api panel uses /api/v1/user/profile to read the account's balance.",
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// A ChatGPT account whose usage read failed says why on its row, in every
|
||||
// language, rather than only "Allowance unavailable" (hmy on Discord: five
|
||||
// ChatGPT accounts in use, each card saying only that). The errors are the
|
||||
// words codexUsageWords (codex_usage_words.go) gives the real replies in
|
||||
// TestCodexUsageSaysWhy; the raw error stays in the row's tooltip. An error
|
||||
// no one has words for says the tooltip is there. At the window's narrowest
|
||||
// and in a phone's browser. A ChatGPT API account, whose usage OpenAI's API
|
||||
// doesn't tell, says where it is told (danzi002 on Discord).
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
const { test } = require("node:test");
|
||||
const { chromium, webkit } = require("playwright");
|
||||
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
|
||||
// account, error as the gateway sends it, the English key and its values
|
||||
const cases = [
|
||||
["cf@example.com", "ChatGPT's Cloudflare check turned the usage read away (HTTP 403 Forbidden): chatgpt.com wants a browser check from this network; a proxy or VPN address is the usual cause",
|
||||
"ChatGPT's Cloudflare check stopped the read — usually a proxy or VPN address; try another one", {}],
|
||||
["401@example.com", "ChatGPT answered the usage read with HTTP 401 Unauthorized: Could not parse your authentication token. Please try signing in again.",
|
||||
"ChatGPT answered HTTP {status} — hover for what it said", { status: "401" }],
|
||||
["403@example.com", "ChatGPT answered the usage read with HTTP 403 Forbidden: deactivated_workspace",
|
||||
"ChatGPT answered HTTP {status} — hover for what it said", { status: "403" }],
|
||||
["net@example.com", "couldn't reach chatgpt.com for the usage read: dial tcp: lookup chatgpt.com: no such host",
|
||||
"Couldn't reach ChatGPT — check the network or the proxy", {}],
|
||||
["json@example.com", "ChatGPT's usage reply isn't one magpie reads: unexpected end of JSON input",
|
||||
"ChatGPT answered in a form magpie doesn't read — hover for what it sent", {}],
|
||||
["asked@example.com", "not read yet: magpie reads allowances only when you ask (Settings → Usage)",
|
||||
"Not read yet — magpie reads allowances only when you ask; refresh this card to read it", {}],
|
||||
["other@example.com", "something nobody has words for",
|
||||
"Allowance unavailable — hover for why", {}],
|
||||
];
|
||||
|
||||
const codex = () => ({
|
||||
id: "codex", name: "Codex", icon: "openai", chat: "", responses: "", anthropic: "", catalog: "", routing: "",
|
||||
models: [{ id: "gpt-5.5", name: "GPT-5.5", on: true }], agents: [], fallback: [], headers: {}, keyList: [],
|
||||
account: {
|
||||
agent: "codex", agentName: "Codex", user: cases[0][0], plan: "pro",
|
||||
logins: cases.map(([user], i) => ({ user, plan: "pro", active: i === 0, on: true })),
|
||||
},
|
||||
});
|
||||
|
||||
const serve = (lang, web) => 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:${JSON.stringify(lang)},theme:"light",web:${web}};` });
|
||||
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } });
|
||||
if (url.pathname === "/api/providers") return json({ providers: [codex()], presets: [], excluded: [], gateway: { running: true, window: true } });
|
||||
if (url.pathname === "/api/groups") return json({ groups: [] });
|
||||
if (url.pathname === "/api/plugins") return json({ plugins: [] });
|
||||
if (url.pathname === "/api/login/usage") return json(Object.fromEntries(cases.map(([user, error]) => [user, { error }])));
|
||||
if (url.pathname.startsWith("/api/")) return json({});
|
||||
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
|
||||
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
|
||||
try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }
|
||||
};
|
||||
|
||||
for (const [engine, browserType] of [["chromium", chromium], ["webkit", webkit]]) {
|
||||
test(engine + ": a ChatGPT account's failed usage read says why on its row", async (t) => {
|
||||
const browser = await browserType.launch();
|
||||
t.after(() => browser.close());
|
||||
for (const [web, width] of [[false, 560], [true, 390]]) for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
|
||||
const at = `${lang} ${web ? "web " : ""}${width}`;
|
||||
const context = await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: "reduce" });
|
||||
const page = await context.newPage();
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", serve(lang, web));
|
||||
await page.goto("http://magpie.test/?view=providers");
|
||||
await page.locator(".row.provider", { hasText: "Codex" }).first().click();
|
||||
const rows = page.locator(".editor .accts .acc[data-account-id]");
|
||||
await rows.nth(cases.length - 1).locator(".aq-none").waitFor();
|
||||
const generic = await page.evaluate(() => t("Allowance unavailable — hover for why"));
|
||||
for (const [user, error, key, vars] of cases) {
|
||||
const row = page.locator(`.editor .accts .acc[data-account-id="${user}"]`);
|
||||
const want = await page.evaluate(([k, v]) => t(k, v), [key, vars]);
|
||||
const said = await row.locator(".aq-none").textContent();
|
||||
assert.ok(said.endsWith(want), `${at}: ${user} says ${JSON.stringify(said)}, want ${JSON.stringify(want)}`);
|
||||
if (key !== "Allowance unavailable — hover for why") assert.ok(!said.includes(generic), `${at}: ${user} is not the generic line`);
|
||||
if (lang !== "en") assert.ok(!said.includes(key.replace("{status}", vars.status || "")), `${at}: ${lang} has its own words for ${user}`);
|
||||
if (vars.status) assert.ok(said.includes(vars.status), `${at}: ${user} names the status`);
|
||||
assert.equal(await row.locator(".aq").getAttribute("title"), error, `${at}: ${user}'s tooltip is the error itself`);
|
||||
// the words fit the row: nothing runs past its right edge
|
||||
const over = await row.evaluate((r) => { const b = r.getBoundingClientRect(), q = r.querySelector(".aq").getBoundingClientRect(); return Math.round(q.right - b.right); });
|
||||
assert.ok(over <= 0, `${at}: ${user}'s line runs ${over}px past its row`);
|
||||
}
|
||||
// a ChatGPT API account (siwcNoUsage): OpenAI's API tells no usage,
|
||||
// and the line says where it is told (danzi002 on Discord)
|
||||
const siwc = "a ChatGPT API account's usage isn't told through OpenAI's API, only at https://chatgpt.com/settings/usage; the same account added as ChatGPT shows it here";
|
||||
const siwcKey = "OpenAI's API doesn't tell a ChatGPT API account's usage — see chatgpt.com/settings/usage, or add the account as ChatGPT to see it here";
|
||||
const [siwcSaid, siwcWant] = await page.evaluate(([e, k]) => [quotaError(e), t(k)], [siwc, siwcKey]);
|
||||
assert.equal(siwcSaid, siwcWant, `${at}: a ChatGPT API account says where its usage is`);
|
||||
assert.ok(siwcSaid.includes("chatgpt.com/settings/usage"), at);
|
||||
if (lang !== "en") assert.notEqual(siwcSaid, siwcKey, `${at}: ${lang} has its own words`);
|
||||
assert.deepEqual(errors, [], at);
|
||||
await context.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -99,7 +99,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
panel: panelQuotaCard(q).querySelector(".pq-sub.err").textContent,
|
||||
}), state.cards[0]);
|
||||
for (const text of Object.values(siblings)) assert.ok(text.includes(want), text);
|
||||
assert.equal(await page.evaluate(() => quotaError("network is unreachable")), await page.evaluate(() => t("Allowance unavailable")), "unrelated errors keep their classification");
|
||||
assert.equal(await page.evaluate(() => quotaError("network is unreachable")), await page.evaluate(() => t("Allowance unavailable — hover for why")), "unrelated errors keep their classification");
|
||||
assert.equal(await page.evaluate(e => quotaError(e), olderError), want, "an older magpie's words are read too");
|
||||
// any other reason the helper gave, and a run that said none before
|
||||
// magpie stopped waiting, are said on the card, not "unavailable"
|
||||
|
||||
@@ -47,7 +47,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
await page.route("**/*", server(lang));
|
||||
await page.goto("http://magpie.test/?view=providers");
|
||||
await page.waitForFunction(() => typeof quotaError === "function");
|
||||
const generic = await page.evaluate(() => t("Allowance unavailable"));
|
||||
const generic = await page.evaluate(() => t("Allowance unavailable — hover for why"));
|
||||
for (const [vendor, err] of errs) {
|
||||
const said = await page.evaluate((e) => quotaError(e), err);
|
||||
const want = await page.evaluate(([k, v]) => t(k, { vendor: v }), [key, vendor]);
|
||||
|
||||
@@ -53,7 +53,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
await page.waitForFunction(() => typeof quotaError === "function");
|
||||
const said = await page.evaluate((errs) => errs.map((e) => quotaError(e)), errs);
|
||||
const want = await page.evaluate((keys) => keys.map((k) => t(k)), keys);
|
||||
const generic = await page.evaluate(() => t("Allowance unavailable"));
|
||||
const generic = await page.evaluate(() => t("Allowance unavailable — hover for why"));
|
||||
for (let i = 0; i < errs.length; i++) {
|
||||
assert.equal(said[i], want[i], errs[i]);
|
||||
assert.notEqual(said[i], generic);
|
||||
|
||||
@@ -73,7 +73,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
const err = page.locator(".subscription-card", { hasText: "OpenCode Zen" }).locator(".subscription-error");
|
||||
await err.waitFor();
|
||||
assert.equal(await err.getAttribute("title"), ZEN, "the reason in the tooltip");
|
||||
const [words, open, generic] = await page.evaluate(([a, b]) => [t(a), t(b), t("Allowance unavailable")], [said, button]);
|
||||
const [words, open, generic] = await page.evaluate(([a, b]) => [t(a), t(b), t("Allowance unavailable — hover for why")], [said, button]);
|
||||
if (lang !== "en") {
|
||||
assert.notEqual(words, said, `${lang} has its own words for the card`);
|
||||
assert.notEqual(open, button, `${lang} has its own words for the button`);
|
||||
|
||||
@@ -46,7 +46,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
await page.route("**/*", server(lang));
|
||||
await page.goto("http://magpie.test/?view=providers");
|
||||
await page.waitForFunction(() => typeof quotaError === "function");
|
||||
const generic = await page.evaluate(() => t("Allowance unavailable"));
|
||||
const generic = await page.evaluate(() => t("Allowance unavailable — hover for why"));
|
||||
const want = await page.evaluate((w) => t("Allowance unavailable: {why}", { why: w }), why);
|
||||
assert.ok(want.includes(why), want);
|
||||
if (lang !== "en") assert.notEqual(want, `Allowance unavailable: ${why}`, `${lang} has its own words`);
|
||||
|
||||
@@ -72,6 +72,11 @@ const (
|
||||
|
||||
var siwcClient = &http.Client{Timeout: 30 * time.Second}
|
||||
|
||||
// siwcNoUsage is what a ChatGPT API account's usage line says: OpenAI's
|
||||
// API tells no plan usage, and the account added as ChatGPT (Codex's
|
||||
// backend) does.
|
||||
const siwcNoUsage = "a ChatGPT API account's usage isn't told through OpenAI's API, only at " + SIWCUsageURL + "; the same account added as ChatGPT shows it here"
|
||||
|
||||
// ErrSIWCSignIn is an account OpenAI no longer refreshes: it must be
|
||||
// signed in again.
|
||||
var ErrSIWCSignIn = errors.New("the ChatGPT sign-in has expired — sign in again")
|
||||
|
||||
@@ -456,3 +456,26 @@ func TestChatGPTAPIExplain(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A ChatGPT API account's usage line says why there is none, and where it
|
||||
// is told, rather than a read that failed (danzi002 on Discord: accounts
|
||||
// added through the API show no allowance, ones signed in as ChatGPT do).
|
||||
// OpenAI's API is asked nothing for it.
|
||||
func TestChatGPTAPIUsageSaysWhere(t *testing.T) {
|
||||
claudeHome(t)
|
||||
f := newFakeOpenAI(t)
|
||||
if st := signInVia(t, f, "oaiapp_9", same); st.State != "done" {
|
||||
t.Fatalf("sign-in %+v", st)
|
||||
}
|
||||
n := len(f.forms)
|
||||
q, ok := LoginUsage(context.Background(), ChatGPTAPIID)["me@example.com"]
|
||||
if !ok || q.Error != siwcNoUsage || q.SeeAt != SIWCUsageURL || len(q.Windows) != 0 {
|
||||
t.Fatalf("read %+v (%v)", q, ok)
|
||||
}
|
||||
if !strings.Contains(q.Error, "chatgpt.com/settings/usage") || !strings.Contains(q.Error, "added as ChatGPT") || strings.Contains(q.Error, "side by side") {
|
||||
t.Fatalf("said %q", q.Error)
|
||||
}
|
||||
if len(f.forms) != n {
|
||||
t.Errorf("OpenAI was asked %d times for it", len(f.forms)-n)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -184,7 +184,7 @@ func TestCodexUsageOther401NotRenewed(t *testing.T) {
|
||||
}
|
||||
_, refreshes, _ := codexExpiredFakes(t, other, false)
|
||||
u := LoginUsage(context.Background(), "codex")
|
||||
if u["me@example.com"].Error != "Unauthorized" || len(refreshes()) != 0 {
|
||||
if u["me@example.com"].Error != "ChatGPT answered the usage read with HTTP 401 Unauthorized: Unauthorized" || len(refreshes()) != 0 {
|
||||
t.Fatalf("%+v, refreshes %q", u, refreshes())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
package provider
|
||||
|
||||
// Why a ChatGPT account's usage read failed, in words the account's row
|
||||
// can say (hmy on Discord: five ChatGPT accounts in use, each saying only
|
||||
// "Allowance unavailable"). The read's error used to be Go's: the bare
|
||||
// status text ("Forbidden", "Unauthorized"), a JSON decode error, or a
|
||||
// transport error naming the URL. The GUI read none of them, so the card
|
||||
// said nothing it could act on, and why was in a tooltip at best.
|
||||
//
|
||||
// The words keep what the old ones were matched for: the status text
|
||||
// (passing in quota_last.go, keeping the last reading over a 429 or a
|
||||
// 5xx), a transport error's own words ("timeout", "connection refused"),
|
||||
// and the vendor's answer itself (codexExpired, codexRevoked), which
|
||||
// errors.As still finds through Unwrap.
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// codexUsageFailed is a failed /wham/usage read: err as it was, and the
|
||||
// words it is said in.
|
||||
type codexUsageFailed struct {
|
||||
err error
|
||||
words string
|
||||
}
|
||||
|
||||
func (e *codexUsageFailed) Error() string { return e.words }
|
||||
func (e *codexUsageFailed) Unwrap() error { return e.err }
|
||||
|
||||
// codexUsageWords is err, a failed /wham/usage read, with words that say
|
||||
// why. A read held back (allowances read only when asked) is left as it
|
||||
// is: it isn't a failure, and readDeferred knows its words.
|
||||
func codexUsageWords(err error) error {
|
||||
if err == nil || errors.Is(err, errNotAsked) || strings.Contains(err.Error(), errNotAsked.Error()) {
|
||||
return err
|
||||
}
|
||||
var se *accountStatusError
|
||||
var ue *url.Error
|
||||
var syn *json.SyntaxError
|
||||
var te *json.UnmarshalTypeError
|
||||
switch {
|
||||
case errors.As(err, &se):
|
||||
return &codexUsageFailed{err, codexStatusWords(se)}
|
||||
case errors.As(err, &ue):
|
||||
return &codexUsageFailed{err, "couldn't reach chatgpt.com for the usage read: " + ue.Err.Error()}
|
||||
case errors.As(err, &syn), errors.As(err, &te):
|
||||
return &codexUsageFailed{err, "ChatGPT's usage reply isn't one magpie reads: " + err.Error()}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// codexStatusWords says what a non-2xx /wham/usage answer was: always
|
||||
// with its status as "HTTP <code> <text>", and the backend's own words
|
||||
// when it gave some. A 401 that says the token expired or the sign-in
|
||||
// is gone is renewed or marked by codexWindowsRenewing; any other is
|
||||
// unknown (TestCodexUsageOtherFailuresMarkNobody), so it is told as it
|
||||
// was, never as a sign-in to make again.
|
||||
func codexStatusWords(se *accountStatusError) string {
|
||||
status := strings.TrimSpace(fmt.Sprintf("HTTP %d %s", se.status, http.StatusText(se.status)))
|
||||
if cloudflareChallenge(se.body) {
|
||||
// Cloudflare's "Just a moment..." page, sent in place of the
|
||||
// backend's answer to a client it wants a browser check of
|
||||
return "ChatGPT's Cloudflare check turned the usage read away (" + status + "): chatgpt.com wants a browser check from this network; a proxy or VPN address is the usual cause"
|
||||
}
|
||||
said := codexSaid(se.body)
|
||||
if said != "" {
|
||||
said = ": " + said
|
||||
}
|
||||
return "ChatGPT answered the usage read with " + status + said
|
||||
}
|
||||
|
||||
// cloudflareChallenge says body is Cloudflare's challenge page rather
|
||||
// than anything the backend wrote.
|
||||
func cloudflareChallenge(body []byte) bool {
|
||||
b := bytes.ToLower(body)
|
||||
return bytes.Contains(b, []byte("<html")) && (bytes.Contains(b, []byte("just a moment")) ||
|
||||
bytes.Contains(b, []byte("challenge-platform")) || bytes.Contains(b, []byte("cf_chl")) ||
|
||||
bytes.Contains(b, []byte("cf-chl")) || bytes.Contains(b, []byte("attention required")))
|
||||
}
|
||||
|
||||
// codexSaid is the backend's own words in an error body: its detail, as
|
||||
// a string ({"detail":"…"}) or an object ({"detail":{"message","code"}}),
|
||||
// or an OpenAI-style {"error":{"message","code"}}; "" when it said none
|
||||
// magpie can find. Cut to a line's length.
|
||||
func codexSaid(body []byte) string {
|
||||
var v struct {
|
||||
Detail json.RawMessage `json:"detail"`
|
||||
Error json.RawMessage `json:"error"`
|
||||
}
|
||||
if json.Unmarshal(body, &v) != nil {
|
||||
return ""
|
||||
}
|
||||
said := ""
|
||||
for _, raw := range []json.RawMessage{v.Detail, v.Error} {
|
||||
if len(raw) == 0 || said != "" {
|
||||
continue
|
||||
}
|
||||
var s string
|
||||
if json.Unmarshal(raw, &s) == nil {
|
||||
said = s
|
||||
continue
|
||||
}
|
||||
var o struct {
|
||||
Message string `json:"message"`
|
||||
Code string `json:"code"`
|
||||
}
|
||||
if json.Unmarshal(raw, &o) == nil {
|
||||
said = o.Message
|
||||
if said == "" {
|
||||
said = o.Code
|
||||
}
|
||||
}
|
||||
}
|
||||
said = strings.Join(strings.Fields(said), " ")
|
||||
if r := []rune(said); len(r) > 200 {
|
||||
said = string(r[:199]) + "…"
|
||||
}
|
||||
return said
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// realCodexUsage is /wham/usage's answer for a Pro account on 2026-11-02,
|
||||
// as the backend sent it, its email and ids taken out and its reset
|
||||
// credits put at 0 (so no second call is made): one weekly window
|
||||
// and no second, credits held. The endpoint answered this shape that day,
|
||||
// so a card saying it couldn't read one is not the endpoint changing.
|
||||
const realCodexUsage = `{"plan_type": "pro", "rate_limit": {"allowed": true, "limit_reached": false, "primary_window": {"used_percent": 0, "limit_window_seconds": 604800, "reset_after_seconds": 155647, "reset_at": 1793774287}, "secondary_window": null}, "code_review_rate_limit": null, "additional_rate_limits": null, "model_usage": {"gpt-6-astra": {"available": true, "available_at": null, "credits_would_enable": false}}, "credits": {"has_credits": true, "unlimited": false, "overage_limit_reached": false, "balance": "62500.0000000000", "approx_local_messages": [15625, 81250], "approx_cloud_messages": [2500, 15625]}, "spend_control": {"reached": false, "individual_limit": null}, "rate_limit_reached_type": null, "promo": null, "rate_limit_reset_credits": {"available_count": 0, "applicable_available_count": 0}}`
|
||||
|
||||
// cloudflareChallengePage is Cloudflare's challenge as it begins, the
|
||||
// page it serves in place of an answer (the gateway's notapi_test.go,
|
||||
// #1012).
|
||||
const cloudflareChallengePage = `<!DOCTYPE html><html lang="en-US"><head><title>Just a moment...</title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></head><body><div class="main-wrapper" role="main"><div class="main-content"><noscript>Enable JavaScript and cookies to continue</noscript></div></div></body></html>`
|
||||
|
||||
// codexUsageServing has /wham/usage answer code and body.
|
||||
func codexUsageServing(t *testing.T, code int, body string) {
|
||||
t.Helper()
|
||||
fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/backend-api/wham/usage" {
|
||||
w.WriteHeader(404)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if strings.HasPrefix(body, "<") {
|
||||
w.Header().Set("Content-Type", "text/html; charset=UTF-8")
|
||||
}
|
||||
w.WriteHeader(code)
|
||||
w.Write([]byte(body))
|
||||
}))
|
||||
t.Cleanup(fake.Close)
|
||||
old := CodexBase
|
||||
CodexBase = fake.URL + "/backend-api/codex"
|
||||
t.Cleanup(func() { CodexBase = old })
|
||||
}
|
||||
|
||||
// A ChatGPT account's usage read that fails says why, in words the card
|
||||
// can tell apart, not Go's bare status text or decode error (hmy on
|
||||
// Discord: five ChatGPT accounts in use, each card "Allowance
|
||||
// unavailable"). What the old words were matched for still holds: a 429
|
||||
// or a 5xx keeps the last reading (passing), a 403 or a plain 401 doesn't,
|
||||
// and the answer itself is still found under the words (codexExpired).
|
||||
func TestCodexUsageSaysWhy(t *testing.T) {
|
||||
isolate(t)
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
code int
|
||||
body string
|
||||
want string
|
||||
passing bool
|
||||
}{
|
||||
{"cloudflare", 403, cloudflareChallengePage, "ChatGPT's Cloudflare check turned the usage read away (HTTP 403 Forbidden)", false},
|
||||
// the backend's own 401 words, as it answers a token it can't read
|
||||
{"401 parse", 401, `{"detail":"Could not parse your authentication token. Please try signing in again."}`, "ChatGPT answered the usage read with HTTP 401 Unauthorized: Could not parse your authentication token. Please try signing in again.", false},
|
||||
{"401 bare", 401, `{"detail":"Unauthorized"}`, "ChatGPT answered the usage read with HTTP 401 Unauthorized: Unauthorized", false},
|
||||
{"403 detail object", 403, `{"detail":{"code":"deactivated_workspace"}}`, "ChatGPT answered the usage read with HTTP 403 Forbidden: deactivated_workspace", false},
|
||||
{"429", 429, `{"detail":"Too many requests"}`, "ChatGPT answered the usage read with HTTP 429 Too Many Requests: Too many requests", true},
|
||||
{"502 empty", 502, ``, "ChatGPT answered the usage read with HTTP 502 Bad Gateway", true},
|
||||
// Cloudflare's own 52x has no status text in Go
|
||||
{"522", 522, cloudflareChallengePage[:40], "ChatGPT answered the usage read with HTTP 522", true},
|
||||
// the real answer, cut off
|
||||
{"cut short", 200, realCodexUsage[:300], "ChatGPT's usage reply isn't one magpie reads: unexpected end of JSON input", false},
|
||||
{"not an object", 200, `[]`, "ChatGPT's usage reply isn't one magpie reads: json: cannot unmarshal array", false},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
codexUsageServing(t, c.code, c.body)
|
||||
_, _, _, _, _, err := codexWindows(context.Background(), "tok", "acct")
|
||||
if err == nil || !strings.HasPrefix(err.Error(), c.want) {
|
||||
t.Fatalf("said %v, want it to begin %q", err, c.want)
|
||||
}
|
||||
if got := passing.MatchString(err.Error()); got != c.passing {
|
||||
t.Fatalf("passing %v, want %v: %q", got, c.passing, err)
|
||||
}
|
||||
var se *accountStatusError
|
||||
if c.code != 200 && (!errors.As(err, &se) || se.status != c.code) {
|
||||
t.Fatalf("the vendor's answer isn't under %q", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("network", func(t *testing.T) {
|
||||
old := CodexBase
|
||||
CodexBase = "http://127.0.0.1:1/backend-api/codex"
|
||||
t.Cleanup(func() { CodexBase = old })
|
||||
_, _, _, _, _, err := codexWindows(context.Background(), "tok", "acct")
|
||||
if err == nil || !strings.HasPrefix(err.Error(), "couldn't reach chatgpt.com for the usage read: ") || strings.Contains(err.Error(), "127.0.0.1:1/backend-api") || !passing.MatchString(err.Error()) {
|
||||
t.Fatalf("said %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("the real answer reads", func(t *testing.T) {
|
||||
codexUsageServing(t, 200, realCodexUsage)
|
||||
plan, ws, _, credits, held, err := codexWindows(context.Background(), "tok", "acct")
|
||||
if err != nil || plan != "pro" || len(ws) != 1 || ws[0].Used != 0 || credits != "62500 credits" || held {
|
||||
t.Fatalf("plan %q windows %+v credits %q held %v err %v", plan, ws, credits, held, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// The account's own row says it too: LoginUsage's reading of a saved
|
||||
// ChatGPT account turned away by Cloudflare carries the words.
|
||||
func TestCodexLoginUsageSaysCloudflare(t *testing.T) {
|
||||
codexExpiredFakes(t, func(string) (int, string) { return 403, cloudflareChallengePage }, false)
|
||||
u := LoginUsage(context.Background(), "codex")
|
||||
for _, user := range []string{"me@example.com", "work@example.com"} {
|
||||
if q := u[user]; !strings.HasPrefix(q.Error, "ChatGPT's Cloudflare check turned the usage read away") {
|
||||
t.Fatalf("%s: %+v", user, q)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -366,6 +366,18 @@ func loginQuota(ctx context.Context, l Login) SubscriptionQuota {
|
||||
if l.Agent == "gemini" || l.Agent == "antigravity" {
|
||||
return googleLoginQuota(ctx, l)
|
||||
}
|
||||
if l.Agent == ChatGPTAPIID {
|
||||
// a ChatGPT plan through OpenAI's API (chatgpt_api.go): OpenAI
|
||||
// tells its usage nowhere magpie can ask, only at SIWCUsageURL, so
|
||||
// its row says so and what does show it, the account added as
|
||||
// ChatGPT (danzi002 on Discord: accounts added through the API
|
||||
// show no allowance, ones signed in as ChatGPT do). It used to be
|
||||
// read below as a Codex account: a saved one said "chatgpt-api
|
||||
// accounts can't be used side by side", the one in use read
|
||||
// Codex's own sign-in ("Codex is signed out; run codex login", or
|
||||
// another account's allowance under its name).
|
||||
return SubscriptionQuota{Provider: l.Agent, Plan: l.Plan, Windows: []QuotaWindow{}, Error: siwcNoUsage, SeeAt: SIWCUsageURL}
|
||||
}
|
||||
if l.Agent == "copilot" {
|
||||
for _, c := range copilotLogins(copilotConfigDir()) {
|
||||
if strings.EqualFold(c.User, l.User) {
|
||||
|
||||
@@ -1047,7 +1047,7 @@ func codexWindows(ctx context.Context, token, accountID string) (plan string, ou
|
||||
base := strings.TrimSuffix(CodexBase, "/codex")
|
||||
out = []QuotaWindow{}
|
||||
if err = accountJSON(ctx, base+"/wham/usage", token, codexAccountHeaders(accountID), &data); err != nil {
|
||||
return "", out, nil, "", false, err
|
||||
return "", out, nil, "", false, codexUsageWords(err)
|
||||
}
|
||||
if c := data.Credits; c != nil && c.Has && !c.Unlimited {
|
||||
if n, perr := strconv.ParseFloat(strings.TrimSpace(c.Balance), 64); perr == nil && n > 0 {
|
||||
|
||||
Reference in New Issue
Block a user