Files
magpie/internal/gui/tests/codex-credits-first.test.cjs
T
yetone ec104b8625 gateway: a Codex account can spend its credits before magpie moves to another account (jojonas_xyz on X)
jojonas_xyz on X: "我账号额度用完了自动给我切了别的号…找不到怎么关掉设置…你怎么知道
我不是想用 credits 呢". (Roughly: "my account ran out of quota and magpie
switched me to another account by itself; I can't find a setting to turn
that off; how do you know I didn't want to use the credits?")

Cause. At 90% or 98% of a window, smart routing's tier put the account
behind every account that still had room, whether or not it had ChatGPT
credits. Codex's own sign-in (NextLogin / SwitchWhenSpent) moved at the
spent share in the same way. The account's credits were spent only once
every other account was used up, and the switch was a log line. The Use
credits switches that existed (on, and "Only after other accounts" from
699ddf152) were only on the Usage page and the panel. None of them meant
"stay on this account and spend its credits".

Change.
- A fourth credits mode, first: settings.CodexCreditsFirst. on, first,
  last and off are exclusive; one mode replaces another.
- routes.Seat.First: a first seat's tier is 0, so routing keeps it in
  front past its windows while it has credits. The trace records
  Weighed.CreditsFirst.
- NextLogin keeps Codex's own sign-in on such an account (spendsFirst).
- The POST /api/codex-credits handler takes "first". The general
  settings save keeps the stored value.
- The CLI: `magpie quota credits <account> first`.
- GUI. No new page and no new component, only the Use credits row that
  already exists:
  - 供应商 → Codex → 账号 ⋯ → 使用积分 → 「先用完积分再换账号」. The
    Providers ⋯ tools now carry the credits row too, which is where the
    reporter looked.
  - 用量 → Codex 账号卡 → 使用积分 → 「先用完积分再换账号」.
  - The menu-bar panel's folded line reads 「开,先于其他账号」.
  - The "First again once it has room" tag on a moved-off account now
    points to the switch in its title.
  - Strings are in en, zh, zh-TW, ja and de.
- "Only after other accounts" (gokoshiki, 699ddf152) is unchanged.
  Its off title now says what off means.
- Docs: docs/reference.md and docs/subsystems/gateway-routing.md.

Budgets: at this head app.js is 1,312,105 of 1,316,874 bytes, and
TestCoreScriptBudget passes (231 bytes under before the rebase). Comments
were condensed; no budget was raised.

Run on mote, at this tree (rebased on origin/main 9d08993c8; the rebase
moved the settings save into internal/settingsapi, which now carries
CodexCreditsFirst beside CodexCreditsLast):
- go test -count=1 -timeout 45m ./internal/gateway ./internal/provider
  ./internal/routes ./internal/settings ./internal/settingsapi
  ./internal/gui ./internal/cli at 9d08993c8+1: gateway, provider,
  routes, settings and settingsapi ok. Two reds, both filed:
  - internal/gui TestMainWindowCorners/macOS_26_SDK: #3949.
  - internal/cli TestLibraryMCPHub, TempDir cleanup not empty: #4140.
  At the pre-rebase tree (da0005df8+1) internal/gui also had
  TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and TestColdTurnsTaken
  (#4510), red the same at da0005df8; both pass at this head.
- New tests:
  - internal/provider/codex_credits_first_test.go
  - internal/gateway/codex_credits_first_test.go (routing and the trace)
  - internal/gui/codex_credits_first_test.go (POST sequence, sandbox HOME)
  - internal/gui/tests/codex-credits-first.test.cjs: the Usage page and
    Providers ⋯ at 900 and 440px, and the panel at 360px; chromium and
    webkit, en zh zh-TW ja de. It also checks for no select, no stripe,
    the i18n keys, and that a click does not move the page.
- The whole GUI suite (make test-ui), at da0005df8+1 on mote at load
  66 to 213, in two parts (a wiped scratchpad cut the first log; its red
  titles were kept): 59 files with a red. 45 of them are red at
  origin/main da0005df8 too, each under an open issue: #4304 (mote
  umbrella), #4600, #4471, #4120, #4119, #4621, and per file balance-fix
  #4682/#4683, gui-ja #4580, page-width-steady #4541, phone-connect-menu
  #4706/#4707, quota-curve #4768, segs-press-redraw #4566, signin-proxy
  #4643/#1814, zhipu-team #4728, model-copy-id #4621 (red 4 of 4 on main).
- The 14 green at da0005df8 were run again at this tree. One was this
  change's: usage-curve-zoom-back. The Codex card's fourth credits line
  (366px, was 344) held the DeepSeek card beside it to 261px, so the
  "card grows" check at 1100px had no room. Its fixture now turns the
  Codex account's credits off, since the count of credits lines isn't
  what it tests; 20 of 20 pass.
- At this head (9d08993c8+1), on mote at load 75 to 84: codex-credits-first,
  codex-credits-last, codex-credits, routing-codex-credits-again,
  panel-options-fold, usage-curve-zoom-back, i18n-keys and the 13 files
  above: 232 tests, 227 pass. Each red has an open issue:
  - models-fold webkit en/zh, "ebody holds" after the click: #4071; red
    the same at 9d08993c8 (run there).
  - account-weight webkit, same "ebody holds": #4644 (red at
    da0005df8+1, green in this run).
  - routing-many-keys chromium de "2 keys in sight at the foot": #4082
    (under load; red again alone here, green at 9d08993c8 in one run).
  - signin-closes-sheet chromium en/zh: #2628 (green alone at this head
    in a second run).
  - signin-again and signin-port-blocked, red once at da0005df8+1 under
    load, pass at this head and at 9d08993c8.

- Rebased last onto 94f6f6092 (three commits; c0477aa72 changes the
  Codex Providers row): go test -run 'Budget|CodexCredits|SettingsSave'
  ./internal/gui ok, and codex-credits-first, codex-credits,
  codex-credits-last, providers-reset-use, i18n-keys and
  usage-curve-zoom-back: 92 of 92 pass.

Broken by hand, each red, then restored:
- spendsFirst forced false: the provider test is red.
- The gateway's l.first forced false: both gateway tests are red.
- codex-credits-first.test.cjs against origin/main's assets: red
  (TimeoutError on the switch).

Not tried:
- No real ChatGPT account with credits went past its window. The routing
  order and NextLogin are tested on fakes only.
- The Linux and Windows apps were not run.

go vet -tags nogui ./... with GOOS darwin, linux and windows on mote:
clean (cgo enum warnings only). gofmt -l on the changed Go files: clean.

Claude has no equivalent: magpie reads no extra_usage and has no Use
credits modes for Claude. Filed as #4662 (see #4241).
2026-11-01 21:19:22 +08:00

235 lines
15 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Run with Node's test runner and Playwright on the module path; see README.md.
// jojonas_xyz on X: a Codex account's allowance ran out and magpie moved to
// another account by itself, with no setting to be found to keep spending
// the first one's credits. Under Use credits, while it is on, a line says
// "Before moving to another account" with its switch: off until turned on,
// it posts settings/codex-credits with first for that account, says so,
// and turns; it and "Only after every other account, key and fallback"
// are never on together. The same row is under the account's ⋯ on
// Providers, where its other settings are, and the account magpie moved
// off says, on its tag, where the setting is. The panel's folded line says
// it. At narrow widths nothing is cut off or wider than its card, a click
// moves nothing, no native select, no left-border accent. Every language,
// Chromium and WebKit; no backend, the API is faked here.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const assets = path.resolve(__dirname, "../assets");
const later = new Date(Date.now() + 3 * 864e5).toISOString();
const now = new Date();
const quotas = [
{ provider: "codex", name: "Codex", icon: "codex-color", user: "Me@example.com", plan: "Plus", lastServedAt: now.toISOString(),
windows: [{ name: "5 hours", used: 100, resetsAt: later }, { name: "7 days", used: 40, resetsAt: later }],
balance: "1.2K credits" },
];
// magpie moved Codex off Me@example.com (returns) to work@example.com
const logins = [
{ user: "work@example.com", plan: "PLUS", active: true, on: true },
{ user: "Me@example.com", plan: "PLUS", on: true, returns: true },
];
const codex = {
id: "codex", name: "Codex", icon: "codex-color", chat: "", responses: "", anthropic: "", catalog: "", routing: "smart",
models: [{ id: "gpt-6", name: "GPT-6", on: true }], agents: [], fallback: [], headers: {}, keyList: [],
account: { agent: "codex", agentName: "Codex", agentIcon: "codex-color", user: "work@example.com", plan: "PLUS", logins },
};
function serve(lang, posts) {
let off = [], first = [], last = [];
const settings = () => ({ theme: "light", lang, tray: "panel", quotaLeft: false, currency: "usd", trayUsages: ["codex"], trayUsageEvery: 3,
codexNoCredits: off, codexCreditsFirst: first, codexCreditsLast: last });
return async (route) => {
const req = route.request(), url = new URL(req.url());
const json = (data) => route.fulfill({ json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:false};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ agents: [{ id: "codex", name: "Codex", path: "/test/config.toml", fields: [] }], profiles: [], settings: settings() });
if (url.pathname === "/api/settings") return json(settings());
if (url.pathname === "/api/settings/codex-credits") {
// as the server: one of first and last at most; off clears both,
// on alone keeps either
const body = req.postDataJSON();
posts.push(body);
const who = body.user.toLowerCase();
const was = first.includes(who) ? "first" : last.includes(who) ? "last" : "";
off = off.filter((u) => u !== who);
first = first.filter((u) => u !== who);
last = last.filter((u) => u !== who);
if (!body.on) off.push(who);
else if (body.last) last.push(who);
else if (body.first) first.push(who);
else if (body.last === undefined && body.first === undefined && was) (was === "first" ? first : last).push(who);
return json(settings());
}
if (url.pathname === "/api/usage/quotas") return json(quotas);
if (url.pathname === "/api/gateway/trace") {
if (url.searchParams.get("wait")) await new Promise((r) => setTimeout(r, 20e3));
return json({ mine: true, now: now.toISOString(), seq: 1, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] });
}
if (url.pathname === "/api/providers") return json({ providers: [codex], presets: [], excluded: [], gateway: { running: true, window: true } });
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname.startsWith("/api/")) return json({});
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
await route.fulfill({ body: await fs.readFile(file), contentType });
};
}
const words = {
en: { line: "Before moving to another account", on: (who) => `${who} spends its credits before moving to another account`, brief: "Use credits: On, before another account" },
zh: { line: "先用完积分再换账号", on: (who) => `${who} 将先用完积分再换账号`, brief: "使用积分: 开,先于其他账号" },
"zh-TW": { line: "先用完積分再換帳號", on: (who) => `${who} 將先用完積分再換帳號`, brief: null },
ja: { line: "別のアカウントに移る前に使う", on: (who) => `${who} は別のアカウントに移る前にクレジットを使います`, brief: null },
de: { line: "Bevor ein anderes Konto drankommt", on: (who) => `${who} verbraucht Credits, bevor ein anderes Konto drankommt`, brief: null },
};
const keys = [
"Before moving to another account",
"On: past its windows, it keeps its place and Codex's sign-in while it holds credits. Click to turn it off.",
"Off: nearly used up, it gives way to an account with room, Codex's sign-in too. Click to turn it on.",
"Off: past its windows, it answers on its credits when Routing comes to it.",
"{who} spends its credits before moving to another account",
"On, before another account",
"To spend its credits first: ⋯ › Use credits › Before moving to another account.",
];
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of Object.keys(words)) {
const w = words[lang];
test(`${engine} ${lang}: a Codex account's credits spent before moving to another account`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const errors = [];
const open = async (url, viewport, posts) => {
const page = await (await browser.newContext({ viewport, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang, posts));
await page.goto(url);
return page;
};
const wait = async (posts, n) => { for (let i = 0; i < 60 && posts.length < n; i++) await new Promise((r) => setTimeout(r, 50)); };
const text = (loc) => loc.evaluate((e) => e.textContent.replace(/\s+/g, " ").trim());
// a click: it posts, turns, says so, and moves nothing
const flip = async (page, row, posts, sel, want, body, said) => {
const b = page.locator(row + " " + sel);
const spot = () => b.evaluate((e) => [e.getBoundingClientRect().top, document.scrollingElement.scrollTop, ...[...document.querySelectorAll(".view")].map((v) => v.scrollTop)]);
const was = await spot();
const n = posts.length;
await b.click();
await wait(posts, n + 1);
assert.deepEqual(posts.at(-1), body);
await page.locator(row + " " + sel + `[aria-checked="${want}"]`).waitFor();
assert.equal(await page.locator("#status").textContent(), said);
await page.waitForTimeout(200);
assert.deepEqual(await spot(), was, "the click moved the page");
};
// both lines fit their card, their switches whole and at their
// line's end, and nothing cut off
const fits = (page, row, card) => page.evaluate(([row, card]) => {
const r = document.querySelector(row);
const c = r.closest(card).getBoundingClientRect(), b = r.getBoundingClientRect();
if (b.right > c.right + 0.5) return "row";
for (const [line, sw] of [[".ar-credits-first", ".credits-first"], [".ar-credits-last", ".credits-last"]]) {
const l = r.querySelector(line), s = l.querySelector(sw).getBoundingClientRect(), words = l.querySelector(".ar-case-say");
if (s.right > c.right + 0.5 || s.width < 27 || s.height < 15) return sw;
if (words.scrollWidth > words.clientWidth + 1) return line + " cut off";
}
return "";
}, [row, card]);
const noStripe = (page, sel) => page.evaluate((sel) => [...document.querySelectorAll(sel + ", " + sel + " *")].map((e) => getComputedStyle(e).borderLeftWidth).filter((b) => parseFloat(b) > 1), sel);
// the Usage page's card
for (const width of [900, 440]) {
const posts = [];
const page = await open("http://magpie.test/?view=usage", { width, height: 760 }, posts);
const row = '.quota-credits[data-user="Me@example.com"]';
await page.locator(row + " .ar-credits-first").waitFor();
assert.equal(await text(page.locator(row + " .ar-credits-first")), w.line);
const sw = page.locator(row + " .credits-first");
assert.equal(await sw.getAttribute("role"), "switch");
assert.equal(await sw.getAttribute("aria-checked"), "false", "off until set");
assert(await sw.getAttribute("title"));
assert.equal(await fits(page, row, ".subscription-card"), "", `the lines fit the card at ${width}px`);
await flip(page, row, posts, ".credits-first", true, { user: "Me@example.com", on: true, first: true }, w.on("Me@example.com"));
assert.equal(await page.locator(row + " .ar-credits-first.on").count(), 1);
assert.equal(await fits(page, row, ".subscription-card"), "", `the lines, on, fit the card at ${width}px`);
// last takes its place: one of the two at most
await page.locator(row + " .credits-last").click();
await wait(posts, 2);
assert.deepEqual(posts.at(-1), { user: "Me@example.com", on: true, last: true });
await page.locator(row + ' .credits-last[aria-checked="true"]').waitFor();
assert.equal(await page.locator(row + " .credits-first").getAttribute("aria-checked"), "false");
const back = await page.evaluate(() => t("{who} spends its credits when its windows run out", { who: "Me@example.com" }));
await flip(page, row, posts, ".credits-first", true, { user: "Me@example.com", on: true, first: true }, w.on("Me@example.com"));
assert.equal(await page.locator(row + " .credits-last").getAttribute("aria-checked"), "false");
await flip(page, row, posts, ".credits-first", false, { user: "Me@example.com", on: true, first: false }, back);
// Use credits off: no lines, as nothing is spent at all
await page.locator(row + " .use-credits").click();
await wait(posts, 5);
assert.deepEqual(posts.at(-1), { user: "Me@example.com", on: false });
await page.locator(row + ' .use-credits[aria-checked="false"]').waitFor();
assert.equal(await page.locator(row + " .ar-credits-first").count(), 0);
assert.deepEqual(await noStripe(page, ".quota-credits"), [], "no left-border accent");
await page.context().close();
}
// Providers: the account's ⋯, where its other settings are, and the
// account magpie moved off says where it is
for (const width of [900, 440]) {
const posts = [];
const page = await open("http://magpie.test/?view=providers", { width, height: 760 }, posts);
await page.locator(".row.provider", { hasText: "Codex" }).first().click();
const acc = page.locator(".editor .acc", { hasText: "Me@example.com" });
await acc.waitFor();
const tag = acc.locator(".acc-line .using").first();
assert(String(await tag.getAttribute("title")).includes(w.line), "the moved-off account's tag names the setting");
await acc.hover();
await acc.locator(".acc-more").click();
const row = '.editor .acc .acc-credits[data-user="Me@example.com"]';
await page.locator(row + " .ar-credits-first").waitFor();
assert.equal(await text(page.locator(row + " .ar-credits-first")), w.line);
assert.equal(await fits(page, row, ".acc"), "", `the lines fit the account at ${width}px`);
await flip(page, row, posts, ".credits-first", true, { user: "Me@example.com", on: true, first: true }, w.on("Me@example.com"));
assert.equal(await page.locator(row).count(), 1, "the ⋯ stays open");
assert.equal(await fits(page, row, ".acc"), "", `the lines, on, fit the account at ${width}px`);
// the account Codex is signed in to has its own
assert.equal(await page.locator('.editor .acc .acc-credits[data-user="work@example.com"]').count(), 1);
assert.equal(await page.locator("select").count(), 0, "no native select");
assert.deepEqual(await noStripe(page, ".acc-credits"), [], "no left-border accent");
await page.context().close();
}
// the menu bar panel's folded line says it
{
const posts = [];
const panel = await open("http://magpie.test/?mode=panel", { width: 360, height: 640 }, posts);
const row = '.pq-credits[data-user="Me@example.com"]';
await panel.locator('#ptabs [data-ptab="usage"]').click();
await panel.locator(row + " .ar-credits-first").waitFor();
await panel.waitForFunction(() => !quotasLoading);
assert.equal(await fits(panel, row, ".pq-card"), "", "the lines fit the panel's card at 360px");
await flip(panel, row, posts, ".credits-first", true, { user: "Me@example.com", on: true, first: true }, w.on("Me@example.com"));
const id = await panel.locator(row).evaluate((r) => r.closest(".pq-card").dataset.card);
const card = `#panelQuota .pq-card[data-card="${id}"]`;
await panel.locator(card + " .pq-opts-fold").click();
const brief = panel.locator(card + " .pq-opts-brief .ar-say");
await brief.waitFor();
const said = await text(brief);
const want = w.brief || (await panel.evaluate(() => t("Use credits:") + " " + t("On, before another account")));
assert(said.endsWith(want), said);
if (lang !== "en") {
const missing = await panel.evaluate(([keys, lang]) => keys.filter((k) => !I18N[lang][k]), [keys, lang]);
assert.deepEqual(missing, [], `every string has its ${lang}`);
}
await panel.context().close();
}
assert.deepEqual(errors, []);
});
}
}