providers: a ChatGPT account's row says when its paid plan ends (danzi002)
danzi002 on Discord (#general, 11-02): 「codex 账号什么是可以加一个 plus 账号到期时间」. The Usage page, the tray panel, the TUI and `magpie quota` have shown "Until …" for the signed-in Codex account sinced8200dfe5. The Providers → Codex editor's account rows showed only "ChatGPT Plus", for every account, saved ones included. Now each Codex and ChatGPT API account in /api/providers carries `until`, from its own sign-in's id token claim https://api.openai.com/auth → chatgpt_subscription_active_until (no new network call). The row puts "Until Nov 19" on the line under its name, beside its allowance, the whole date and time in its tooltip. - Codex: the sign-in Codex holds when it holds that account (through readCodexLogin, which it refreshes), else logins.json's copy. - ChatGPT API: its saved id token, then its access token. - No claim, an unparsable one, or a date gone by: nothing shown, never a guess. A real Pro token issued today carried an until weeks in the past (its last_checked was older still): OpenAI updates the claim now and then, so a past date says nothing true about the plan. - chatgptUntil is the one reader; codexUntil (the usage card) uses it. The core scripts' budget is not raised: two account-row comments in app.js were cut to pay for the line (1,533,739 of 1,533,802). Checked on real tokens (key names only, read-only from ~/.config/magpie/logins.json): the auth claim's keys are chatgpt_account_id, chatgpt_plan_type, chatgpt_subscription_active_start, chatgpt_subscription_active_until, chatgpt_subscription_last_checked, chatgpt_user_id, groups, localhost, organizations, user_id; the until is RFC3339 with +00:00. The tests' claims are written in that shape. Run at this tree on mote (macOS 27): - gofmt -l internal: nothing. - go test -count=1 -timeout 45m ./internal/provider ./internal/gui ./internal/tui .: provider, tui and root ok; gui red only on TestMainWindowCorners/macOS_26_SDK (#3949, macOS 27 only, the same on main). TestCoreScriptBudget ok. - go vet ./internal/provider ./internal/gui; GOOS=linux go vet -tags nogui; GOOS=windows go vet: ok. - New TestCodexLoginUntil (signed-in and saved accounts, a past date, no claim, the JSON the GUI reads) and TestSIWCLoginUntil: ok. - New account-plan-until.test.cjs: Chromium and WebKit, 1000, 560 and a 390 phone browser, en zh zh-TW ja de; the date is whole, inside its row, translated, the first line stays one line, no sideways scroll. - GUI files account-*, codex-*, i18n-keys, lane-limit, login-*, providers-*: 892 of 894 ok. The two reds are codex-auto-reset webkit de 1100 and 420 ("the click moved the page", Usage page), red the same way run alone at origin/maine156fdd03on mote (#4790). Rebased on origin/maine156fdd03(three mover-min commits since the base): ./internal/provider and TestCoreScriptBudget run again there, ok. Broken by hand: dropping lg.Until's assignment in loginsNow turns TestCodexLoginUntil red; dropping the line in siwcLoginList turns TestSIWCLoginUntil red; dropping the aq.append in renderAccounts turns account-plan-until red in both engines. Not tried: a Codex account held in another home (codexHeldIn) has no test; no real ChatGPT API account's token was read, so its claim is assumed from the Codex one; no Team plan token was seen; the real app was not opened, only Playwright's Chromium and WebKit.
This commit is contained in:
@@ -43,7 +43,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
|
||||
| Amazon Bedrock Mantle | `bedrock-mantle` ("Amazon Bedrock (Mantle)", @marktoown on X) is a vendor preset beside the runtime's `bedrock`, with the same Bedrock API key and seventeen regions of its own (`mantleRegions`: the `bedrock-mantle.{region}.api.aws` hosts that answered on 2026-10-16). Chat completions and Responses are at `/v1`, Messages at `/anthropic`; unlike the runtime it lists its models (`GET /v1/models`; `NoList` stays the runtime's alone). Its OpenAI APIs serve each model under one of two prefixes: OpenAI's closed GPTs and xAI's Grok under `/openai/v1`, the rest under `/v1` (`MantleBase`, used by the gateway and the provider test's `tinyBody`). `IsBedrockMantle` is the preset or a provider added at a Mantle host (`mantleHost`), and `IsBedrock` includes it, so every Bedrock rule holds there too: Claude on Messages alone, the key as `x-api-key` alone, `max_completion_tokens`, no metadata, no Priority. A provider added at a Mantle address is given the APIs it wasn't (`mantleEndpoints`, in `normalize`), and a chat or Responses URL given at `/openai/v1` is moved to `/v1`, where the list is. | [`presets.go`](../../internal/provider/presets.go), [`provider.go`](../../internal/provider/provider.go), [`test.go`](../../internal/provider/test.go) |
|
||||
| Subscription accounts | `Accounts` reads the credentials each agent keeps on disk or in the macOS Keychain; nothing is stored twice. With account discovery off (#1535, below) none of them is read. A built-in that has moved to its plugin is dropped (`Moved`), and plugin accounts are placed in its slot (`placeMoved`). `Sign` adds the account's own auth, then the user's `Headers`. | [`account.go`](../../internal/provider/account.go) |
|
||||
| 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`, the usage card's `codexUntil`, 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 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 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) |
|
||||
|
||||
@@ -3001,6 +3001,7 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; }
|
||||
/* its refresh always shown, after its plan on the line that never wraps: on the readings' line it added a line where the meters filled it (the owner asked for a button here) */
|
||||
.acc-line > .quota-refresh { width: 14px; margin: 0 0 0 -5px; opacity: 1; }
|
||||
.acc .aq-w { display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; }
|
||||
.acc .aq-until { white-space: nowrap; }
|
||||
.acc .aq-track { width: 54px; height: 4px; border-radius: 2px; background: var(--pill); overflow: hidden; }
|
||||
.acc .aq-track i { display: block; height: 100%; border-radius: inherit; background: var(--fg-2); }
|
||||
/* the account's usage cap: a tick across the meter where it stands */
|
||||
|
||||
@@ -13110,9 +13110,8 @@ function renderAccounts(a, p) {
|
||||
b.onclick = () => { b.classList.add("busy"); accountAction("provider/arrange", { id: p.id, accountOrder: [l.user, ...ls.filter((x) => x !== l).map((x) => x.user)] }, t("The gateway now uses {user} first", { user: l.user })); };
|
||||
return b;
|
||||
};
|
||||
// the account Claude Code or Codex is signed in to can be paused while
|
||||
// another is on: the gateway passes over it, the agent staying signed in
|
||||
// to it (#263)
|
||||
// the agent's account can be paused while another is on: the gateway
|
||||
// passes over it, the agent staying signed in (#263)
|
||||
const pausable = (a.agent === "claude" || a.agent === "codex") && ls.some((l) => !unusable(l) && !l.active && l.on);
|
||||
const quota = loginUsageOf(a.agent);
|
||||
// the first, which magpie signed the agent out of while it was spent:
|
||||
@@ -13157,10 +13156,8 @@ function renderAccounts(a, p) {
|
||||
if (amPill) pill(amPill);
|
||||
// its usage cap: the share of each window it is used to at most
|
||||
const cap = accountCapOf(p, l.user);
|
||||
// Claude Code or Codex signed in to it asks its vendor itself, not
|
||||
// through magpie: with no other account to sign it in to, the cap
|
||||
// holds back only what goes through magpie (𝕏 on Discord: a 90% cap
|
||||
// and the five hours run to 100%)
|
||||
// the agent signed in to it asks its vendor itself: with no other
|
||||
// account, the cap holds back only magpie's (𝕏 on Discord)
|
||||
const direct = l.active && !several && (a.agent === "claude" || a.agent === "codex") ? a.agentName : "";
|
||||
if (p) pill(accountCapPill(p, l.user, cap, direct));
|
||||
// and each window's own, set on its meter (willz on Discord)
|
||||
@@ -13242,7 +13239,10 @@ function renderAccounts(a, p) {
|
||||
}
|
||||
}
|
||||
if (quota && !l.lapsed) line.querySelector(".plan").after(accountRefresh(a.agent, p, l.user));
|
||||
row.append(accountQuota(l.lapsed ? { [l.user]: { error: t(l.lapsed) } } : quota, l.user, capFor, p ? (m, w) => windowCapMeter(m, p, l.user, w) : null, a.agent));
|
||||
const aq = accountQuota(l.lapsed ? { [l.user]: { error: t(l.lapsed) } } : quota, l.user, capFor, p ? (m, w) => windowCapMeter(m, p, l.user, w) : null, a.agent);
|
||||
// its plan's end, under its line (danzi002)
|
||||
if (l.until) aq.append(Object.assign(planSpan({ until: l.until }), { className: "aq-until" }));
|
||||
row.append(aq);
|
||||
row.classList.add("with-aq"); // not :has(.aq), which Safari 15.0 lacks (#220)
|
||||
// Remove goes under ⋯ too, but beside Sign in again while signed out
|
||||
if (!row.classList.contains("signed-out")) tools.append(...line.querySelectorAll(":scope > .text.quiet"));
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,88 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// danzi002 on Discord: a Codex (ChatGPT) account's row on Providers says
|
||||
// when its paid plan ends, "Until Nov 19" on the line under its name
|
||||
// beside its allowance, the whole date and time in its tooltip, from the
|
||||
// until /api/providers gives the account (its sign-in's
|
||||
// chatgpt_subscription_active_until). An account with no until says none,
|
||||
// never a guessed date. In every language, Chromium and WebKit, at the
|
||||
// window's narrowest and in a phone's browser, the date is shown whole,
|
||||
// inside the row, and the first line stays one line.
|
||||
// No backend; the API is faked here.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
const { test } = require("node:test");
|
||||
const { chromium, webkit } = require("playwright");
|
||||
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
const until = "2099-11-19T16:12:01Z";
|
||||
const soon = new Date(Date.now() + 3 * 3600e3).toISOString();
|
||||
const codex = () => ({
|
||||
id: "codex", name: "Codex", icon: "codex-color", chat: "", responses: "", anthropic: "", catalog: "", routing: "",
|
||||
models: [{ id: "gpt-6", name: "GPT-6", on: true }], agents: [], fallback: [], headers: {}, keyList: [],
|
||||
account: {
|
||||
agent: "codex", agentName: "Codex", agentIcon: "codex-color", user: "plus@example.com", plan: "plus",
|
||||
logins: [
|
||||
{ user: "plus@example.com", plan: "plus", active: true, on: true, until },
|
||||
{ user: "pro@example.com", plan: "pro", 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:"dark",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: "dark" } });
|
||||
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({
|
||||
"plus@example.com": { windows: [{ name: "5 hours", used: 10, resetsAt: soon }, { name: "7 days", used: 40, resetsAt: soon }] },
|
||||
"pro@example.com": { windows: [{ name: "5 hours", used: 0, resetsAt: soon }, { name: "7 days", used: 5, resetsAt: soon }] },
|
||||
});
|
||||
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: "" }); }
|
||||
};
|
||||
|
||||
const langs = ["en", "zh", "zh-TW", "ja", "de"];
|
||||
for (const [engine, browserType] of [["chromium", chromium], ["webkit", webkit]]) {
|
||||
test(engine + ": a ChatGPT account's row says when its plan ends", async (t) => {
|
||||
const browser = await browserType.launch();
|
||||
t.after(() => browser.close());
|
||||
for (const [web, width] of [[false, 1000], [false, 560], [true, 390]]) for (const lang of langs) {
|
||||
const at = `${lang} ${web ? "web " : ""}${width}`;
|
||||
const context = await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: "reduce" });
|
||||
const page = await context.newPage();
|
||||
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(1).waitFor();
|
||||
const want = await page.evaluate((u) => ({
|
||||
short: t("Until {date}", { date: new Date(u).toLocaleDateString(intlLang(), { month: "short", day: "numeric" }) }),
|
||||
long: t("Until {date}", { date: new Date(u).toLocaleString(intlLang()) }),
|
||||
}), until);
|
||||
if (lang !== "en") assert.notEqual(want.short.replace(/[^A-Za-z ]/g, "").trim(), "Until", `${at}: "Until {date}" is translated`);
|
||||
const row = (who) => page.locator(`.editor .accts .acc[data-account-id="${who}"]`);
|
||||
const plus = row("plus@example.com").locator(".aq .aq-until");
|
||||
await row("plus@example.com").locator(".aq .aq-w").first().waitFor();
|
||||
assert.equal(await plus.textContent(), want.short, `${at}: when the plan ends`);
|
||||
assert.equal(await plus.getAttribute("title"), want.long, `${at}: the whole date in its tooltip`);
|
||||
assert.equal(await row("pro@example.com").locator(".aq-until").count(), 0, `${at}: no until, no date`);
|
||||
assert.equal(await row("plus@example.com").locator(".acc-line > .plan").textContent(), "ChatGPT Plus", `${at}: the plan as before`);
|
||||
const m = await plus.evaluate((e) => {
|
||||
const b = e.getBoundingClientRect(), r = e.closest(".acc").getBoundingClientRect(), line = e.closest(".acc").querySelector(".acc-line").getBoundingClientRect();
|
||||
return { cut: e.scrollWidth - e.clientWidth, w: b.width, inside: b.left >= r.left - 1 && b.right <= r.right + 1, line: line.height, vis: getComputedStyle(e).visibility };
|
||||
});
|
||||
assert.ok(m.w > 0 && m.cut <= 0 && m.vis === "visible", `${at}: the date is shown whole (${m.cut}px cut)`);
|
||||
assert.ok(m.inside, `${at}: the date stays inside its row`);
|
||||
assert.ok(m.line <= (web ? 48 : 24), `${at}: the first line is one line (${m.line}px)`);
|
||||
const wide = await page.evaluate(() => { const b = document.querySelector(".modal .ebody"); return b.scrollWidth - b.clientWidth; });
|
||||
assert.ok(wide <= 0, `${at}: the sheet doesn't scroll sideways (${wide}px)`);
|
||||
await context.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -114,6 +114,9 @@ func siwcLoginList() []Login {
|
||||
if ls[i].Lapsed == "" {
|
||||
ls[i].Lapsed = ls[i].saved.Lapsed
|
||||
}
|
||||
if c, ok := siwcSaved(ls[i].saved); ok {
|
||||
ls[i].Until = chatgptUntil(time.Now(), c.IDToken, c.Access)
|
||||
}
|
||||
}
|
||||
return loginsOf(ls)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// claimsToken is an id token carrying claims as written, byte for byte.
|
||||
func claimsToken(claims string) string {
|
||||
return "e30." + base64.RawURLEncoding.EncodeToString([]byte(claims)) + ".sig"
|
||||
}
|
||||
|
||||
// codexClaimsSignIn signs Codex in to email with an id token of claims,
|
||||
// the auth claim's keys as a real ChatGPT sign-in's are (2026-11-02).
|
||||
func codexClaimsSignIn(t *testing.T, home, email, plan, auth string) {
|
||||
t.Helper()
|
||||
claims := `{"email":"` + email + `","email_verified":true,"https://api.openai.com/auth":{` +
|
||||
`"chatgpt_account_id":"acct-` + email + `","chatgpt_plan_type":"` + plan + `",` + auth +
|
||||
`"chatgpt_user_id":"user-x","groups":[],"organizations":[],"user_id":"user-x"}}`
|
||||
writeFile(t, filepath.Join(home, ".codex", "auth.json"), map[string]any{
|
||||
"auth_mode": "chatgpt",
|
||||
"tokens": map[string]any{
|
||||
"id_token": claimsToken(claims),
|
||||
"access_token": fakeJWT(map[string]any{"exp": float64(time.Now().Add(time.Hour).Unix())}),
|
||||
"refresh_token": "r-" + email, "account_id": "acct-" + email,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func untilOf(ls []Login) map[string]*time.Time {
|
||||
out := map[string]*time.Time{}
|
||||
for _, l := range ls {
|
||||
out[l.User] = l.Until
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Each ChatGPT account's row says when its paid plan ends, as its sign-in's
|
||||
// chatgpt_subscription_active_until says: the one Codex is signed in to and
|
||||
// a saved one alike. A date gone by (OpenAI checks the plan now and then,
|
||||
// so a token refreshed today can carry last month's) and a sign-in with no
|
||||
// such claim say nothing (danzi002 on Discord).
|
||||
func TestCodexLoginUntil(t *testing.T) {
|
||||
home := signIn(t) // me@example.com: no subscription claims
|
||||
rememberLogins(true)
|
||||
codexClaimsSignIn(t, home, "pro@example.com", "pro",
|
||||
`"chatgpt_subscription_active_start":"2020-08-18T04:45:15+00:00","chatgpt_subscription_active_until":"2020-09-18T04:45:15+00:00","chatgpt_subscription_last_checked":"2020-09-15T17:30:44.647759+00:00",`)
|
||||
rememberLogins(true)
|
||||
codexClaimsSignIn(t, home, "plus@example.com", "plus",
|
||||
`"chatgpt_subscription_active_start":"2099-10-19T15:12:01+00:00","chatgpt_subscription_active_until":"2099-11-19T16:12:01+00:00","chatgpt_subscription_last_checked":"2099-10-27T19:16:18.236460+00:00",`)
|
||||
rememberLogins(true)
|
||||
|
||||
want := time.Date(2099, 11, 19, 16, 12, 1, 0, time.UTC)
|
||||
check := func(when string) {
|
||||
t.Helper()
|
||||
u := untilOf(Logins("codex"))
|
||||
if len(u) != 3 {
|
||||
t.Fatalf("%s: accounts %v", when, u)
|
||||
}
|
||||
if u["plus@example.com"] == nil || !u["plus@example.com"].Equal(want) {
|
||||
t.Errorf("%s: plus@ until %v, want %v", when, u["plus@example.com"], want)
|
||||
}
|
||||
if u["pro@example.com"] != nil {
|
||||
t.Errorf("%s: pro@'s date gone by is shown: %v", when, u["pro@example.com"])
|
||||
}
|
||||
if u["me@example.com"] != nil {
|
||||
t.Errorf("%s: me@ has no such claim, shown %v", when, u["me@example.com"])
|
||||
}
|
||||
}
|
||||
check("signed in")
|
||||
if err := SwitchLogin("codex", "me@example.com"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
check("saved")
|
||||
|
||||
b, _ := json.Marshal(Logins("codex"))
|
||||
if !strings.Contains(string(b), `"until":"2099-11-19T16:12:01Z"`) {
|
||||
t.Fatalf("the list the GUI reads has no until: %s", b)
|
||||
}
|
||||
}
|
||||
|
||||
// A ChatGPT API account's row says it too, from its own sign-in's tokens.
|
||||
func TestSIWCLoginUntil(t *testing.T) {
|
||||
signIn(t)
|
||||
c := siwcCreds{ClientID: "c", HostID: "h", Email: "api@example.com", Access: "a", Refresh: "r", Expires: time.Now().Add(time.Hour),
|
||||
IDToken: claimsToken(`{"email":"api@example.com","https://api.openai.com/auth":{"chatgpt_plan_type":"plus","chatgpt_subscription_active_until":"2099-11-19T16:12:01+00:00"}}`)}
|
||||
auth, _ := json.Marshal(c)
|
||||
if err := writeLogins([]savedLogin{{Agent: ChatGPTAPIID, User: "api@example.com", Auth: auth}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ls := Logins(ChatGPTAPIID)
|
||||
if len(ls) != 1 || ls[0].Until == nil || !ls[0].Until.Equal(time.Date(2099, 11, 19, 16, 12, 1, 0, time.UTC)) {
|
||||
t.Fatalf("ChatGPT API rows: %+v", ls)
|
||||
}
|
||||
}
|
||||
@@ -49,6 +49,10 @@ type Login struct {
|
||||
// Lapsed says the vendor refused to refresh a saved account's sign-in:
|
||||
// it has to be signed in again before it can be used.
|
||||
Lapsed string `json:"lapsed,omitempty"`
|
||||
// Until is when the account's paid plan ends, as its sign-in says (a
|
||||
// ChatGPT one's chatgpt_subscription_active_until, codexUntil): nil
|
||||
// when it doesn't, or names a time gone by.
|
||||
Until *time.Time `json:"until,omitempty"`
|
||||
// Own is the agent's own sign-in, which magpie only reads: removed, it
|
||||
// is hidden rather than deleted (side_logins.go).
|
||||
Own bool `json:"own,omitempty"`
|
||||
@@ -1027,9 +1031,13 @@ func loginsNow(agent string) []Login {
|
||||
loginsMu.Lock()
|
||||
defer loginsMu.Unlock()
|
||||
active := map[string]string{}
|
||||
var liveCodex json.RawMessage
|
||||
for _, a := range loginAgents {
|
||||
if l, ok := liveLogin(a); ok {
|
||||
active[a] = l.User
|
||||
if a == "codex" {
|
||||
liveCodex = l.Auth
|
||||
}
|
||||
}
|
||||
}
|
||||
var out []Login
|
||||
@@ -1059,6 +1067,19 @@ func loginsNow(agent string) []Login {
|
||||
if !using && l.Agent == "codex" {
|
||||
lg.home = l.Home
|
||||
}
|
||||
if l.Agent == "codex" {
|
||||
// from the sign-in Codex holds, where it holds this one: it
|
||||
// refreshes it there, and logins.json's copy may be older
|
||||
auth := l.Auth
|
||||
if using {
|
||||
auth = liveCodex
|
||||
} else if home := codexHeldIn(l); home != "" {
|
||||
if in, ok := codexLoginIn(home); ok {
|
||||
auth = in.Auth
|
||||
}
|
||||
}
|
||||
lg.Until = codexUntil(auth, time.Now())
|
||||
}
|
||||
if l.Agent == "claude" {
|
||||
lg.Lapsed = claudeSignedOut(l)
|
||||
lg.Token = claudeSetupToken(l.Auth) != ""
|
||||
|
||||
@@ -1016,12 +1016,25 @@ func codexUntil(auth []byte, now time.Time) *time.Time {
|
||||
if json.Unmarshal(auth, &a) != nil {
|
||||
return nil
|
||||
}
|
||||
s := claimString(jwtClaims(a.Tokens.IDToken), "https://api.openai.com/auth", "chatgpt_subscription_active_until")
|
||||
t, err := time.Parse(time.RFC3339, s)
|
||||
if err != nil || !t.After(now) {
|
||||
return nil
|
||||
return chatgptUntil(now, a.Tokens.IDToken)
|
||||
}
|
||||
|
||||
// chatgptUntil is when the ChatGPT plan the first of tokens to name one
|
||||
// is paid until (chatgpt_subscription_active_until), nil when none does
|
||||
// or the time it names is gone by.
|
||||
func chatgptUntil(now time.Time, tokens ...string) *time.Time {
|
||||
for _, tok := range tokens {
|
||||
s := claimString(jwtClaims(tok), "https://api.openai.com/auth", "chatgpt_subscription_active_until")
|
||||
if s == "" {
|
||||
continue
|
||||
}
|
||||
t, err := time.Parse(time.RFC3339, s)
|
||||
if err != nil || !t.After(now) {
|
||||
return nil
|
||||
}
|
||||
return &t
|
||||
}
|
||||
return &t
|
||||
return nil
|
||||
}
|
||||
|
||||
// codexWindows is the plan, allowance, rate-limit resets and credits of
|
||||
|
||||
Reference in New Issue
Block a user