Files
magpie/internal/gui/tests/quota-holds.test.cjs
T
yetone 95a61a5d18 usage: a card's captions read at 4.5:1 on the card (Jiabubu)
Jiabubu (Discord, #feedback) found the Usage Overview cards' captions,
"重置于 …", "本周期" and a curve's dates, small and hard to read in
both themes. They were --faint: 1.95:1 on a light card, 2.16:1 on a
dark one, under WCAG AA's 4.5:1.

Every caption on a card is --muted now: a window's reset line, the
curve's range and axis dates, "Last reading", a balance curve's pace,
a credit day's note, the all-accounts head and its unknown, a card's
error line, and on the tray panel's allowance card .pq-sub, .pq-rn,
"until …" and an auto-reset's used line. Light's --muted is 3.66:1 on
white, so a card (and its tinted all-accounts box) takes --ctl-fg,
the token documented as a control's quiet text at 4.5:1 on every
surface; dark keeps its --muted. The reset line's "held" reason lost
its 0.75 opacity (it read under 4.5:1); it keeps the caption colour. Sizes are unchanged; the figures keep --fg-2 at 600.

Measured in the page (Chromium and WebKit, same numbers):
  Usage card, light: captions 1.95 -> 5.95:1; figures 8.64:1
  Usage card, dark:  captions 2.16 -> 4.64:1; figures 8.03:1
  Panel card, light: .pq-sub 2.79 -> 5.95:1
  Panel card, dark:  .pq-sub 3.66 -> 5.54:1 (computed from the tokens)

quota-caption-contrast.test.cjs checks every caption on a Usage card
at 4.5:1 or better, each below the card's figure by 1.5 or more, and
the panel card's captions at 4.5:1, in Chromium and WebKit, light and
dark, en/zh/zh-TW/ja/de, at 900 and 420 wide.

Broken by hand: with origin/main's app.css it fails at "light en 900:
.quota-reset reads at 1.95:1"; with only .pq-sub put back on --faint
it fails at "light en panel: .pq-sub reads at 2.79:1".

Run on mote at this tree (on origin/main 8abdf53a8), with mote at load
164-191 from other sessions: the new test 2 of 2 ok; the GUI files this
can reach (360 files, every one naming a usage card, the panel card, the
routing page, app.css, i18n or a budget; both engines, every language,
narrow widths), 5573 of 5668 ok. The 22 red files were run again alone at
this head and at 8abdf53a8: three were this change (routing-save-blank
and routing-save-keeps-the-row wheeled until Save was in sight, which it
now is at once, so they wheel to the editor's foot; quota-holds took a
faded "not enough data" as muted, now the reset line's caption colour),
fixed here and green at concurrency 2. The rest are red at 8abdf53a8 too
(account-eye #4244, routing-rule-* #4585, tray-cell-click and usage-fold
#4790, numbers on #4932). The whole suite was started once and stopped at
316 tests after an hour at that load; it was not run to the end.

Rebased on origin/main 1851ead1a (app.css and the usage page changed),
then run again at the pushed head: go test -run 'Budget|CSS' ./internal/gui
ok, and quota-caption-contrast, group-editor-selected, quota-holds,
routing-save-blank, routing-save-keeps-the-row, plan-credits and
balance-fix, 154 of 154 ok in both engines.

Not tried: the real app's window (the GUI suite's pages only), and
the menu bar cells, which have their own colours.

Reported by Jiabubu on Discord (#feedback).
2026-11-03 05:50:10 +08:00

140 lines
9.6 KiB
JavaScript

// Run with Node's test runner and Playwright on the module path; see README.md.
// Chiao on Discord: an account card's window says what the whole window
// holds, reckoned from what magpie routed through the account in it over
// the share used — "≈ N tokens · ≈ $X" under its reset, in every language,
// at a phone's width too, and in its tooltip how it was reckoned and that
// it reads low if the account is used elsewhere. A window the server didn't
// reckon says "not enough data", muted, with why in its tooltip (#2045),
// one it gives no reason for says nothing, and one with no API price says
// no cost.
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 soon = (h) => new Date(Date.now() + h * 3600e3).toISOString();
const holds = (tokens, cost, used, priced = true) => ({ tokens, cost, priced, used, since: new Date().toISOString(), routed: { calls: 41, tokens: Math.round(tokens * used / 100), cacheRead: 52345678, cost: cost * used / 100 } });
const quotas = [
{ provider: "claude", name: "Claude Code", icon: "claude-color", plan: "max", user: "dee@example.com", windows: [
{ name: "5 hours", used: 20, resetsAt: soon(2), holds: holds(12345678, 85.4321, 20) },
{ name: "7 days", used: 40, resetsAt: soon(70), holds: holds(234567890, 1234.5, 40) },
{ name: "7 days · Fable", used: 3, resetsAt: soon(70), holdsWhy: "low" },
{ name: "7 days · Sonnet", used: 30, resetsAt: soon(70), holdsWhy: "credits" },
{ name: "7 days · Haiku", used: 30, resetsAt: soon(70), holdsWhy: "some reason this GUI doesn't know" },
] },
{ provider: "kiro", name: "Kiro", icon: "kiro-color", plan: "Pro", user: "kay@example.com", windows: [
{ name: "Weekly", used: 25, holds: holds(40000, 0, 25, false) },
{ name: "Credits", used: 30, holdsWhy: "clock" },
] },
];
function serve(lang) {
const settings = { lang, theme: "light", currency: "usd", chineseUnits: lang.startsWith("zh") };
const state = { agents: [], profiles: [], settings };
return async (r) => {
const url = new URL(r.request().url());
const json = (data) => r.fulfill({ json: data });
if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json(state);
if (url.pathname === "/api/settings") return json(settings);
if (url.pathname === "/api/gateway/trace") return url.searchParams.get("wait") ? new Promise(() => {}) : json({ mine: true, now: new Date().toISOString(), seq: 0, totals: {}, routes: [] });
if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] });
if (url.pathname === "/api/groups") return json({ models: [], groups: [], pools: [] });
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } });
if (url.pathname === "/api/usage/quotas") return json(quotas);
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)];
try { await r.fulfill({ body: await fs.readFile(file), contentType }); } catch { await r.fulfill({ status: 404, body: "" }); }
};
}
const want = {
en: { line: "Whole ≈ 12M tokens", low: "reads low", none: "Whole: not enough data", under: "Under 5%", credits: "credits", clock: "reset time" },
zh: { line: "整窗 ≈ 1234.6 万 tokens", low: "偏低", none: "整窗:数据不足", under: "不到 5%", credits: "积分", clock: "重置时间" },
"zh-TW": { line: "整窗 ≈ 1234.6 萬 tokens", low: "偏低", none: "整窗:資料不足", under: "不到 5%", credits: "積分", clock: "重置時間" },
ja: { line: "枠全体 ≈ 12M トークン", low: "低め", none: "枠全体:データ不足", under: "5% 未満", credits: "クレジット", clock: "リセット時刻" },
de: { line: "Gesamt ≈ 12M Tokens", low: "zu niedrig", none: "Gesamt: zu wenig Daten", under: "Weniger als 5 %", credits: "Guthaben", clock: "Rücksetzzeit" },
};
for (const [name, engine] of [["webkit", webkit], ["chromium", chromium]]) {
test(`${name}: a window's whole, or not enough data and why, under its reset, whole at 360 to 1100px in every language`, async () => {
const browser = await engine.launch();
try {
for (const lang of Object.keys(want)) {
for (const width of [360, 420, 440, 1000, 1100]) {
const page = await (await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
await page.route("**/*", serve(lang));
await page.goto("http://magpie.test/?view=usage");
await page.locator(".subscription-card .quota-holds").nth(2).waitFor();
const got = await page.evaluate(() => {
const lines = [...document.querySelectorAll(".quota-holds")];
return {
count: document.querySelectorAll(".quota").length,
lines: lines.map((l) => {
const card = l.closest(".subscription-card").getBoundingClientRect(), b = l.getBoundingClientRect();
return {
text: l.textContent, title: l.title,
window: l.closest(".quota").querySelector(".quota-labels > span").textContent,
inReset: !!l.closest(".quota-reset"),
cut: [...l.children].some((s) => s.scrollWidth > s.clientWidth + 1 || s.getBoundingClientRect().right > card.right + 1),
inCard: b.left >= card.left - 1 && b.right <= card.right + 1,
};
}),
unknown: [...document.querySelectorAll(".quota-holds-why")].map((l) => {
const card = l.closest(".subscription-card").getBoundingClientRect(), b = l.getBoundingClientRect(), cs = getComputedStyle(l);
return {
text: l.textContent, title: l.title, window: l.closest(".quota").querySelector(".quota-labels > span").textContent,
inReset: !!l.closest(".quota-reset"), cut: l.scrollWidth > l.clientWidth + 1, inCard: b.left >= card.left - 1 && b.right <= card.right + 1,
// muted as the reset line is: its caption colour, not faded below it
// (a card's captions read at 4.5:1, Jiabubu)
muted: cs.color === getComputedStyle(l.closest(".quota-reset")).color && cs.color !== getComputedStyle(l.closest(".quota")).color,
};
}),
pageScroll: document.documentElement.scrollWidth > document.documentElement.clientWidth + 1,
};
});
const at = `${lang} ${width}px`;
assert.equal(got.count, 7, at);
assert.equal(got.lines.length, 3, `${at}: only the windows reckoned tell a whole: ${JSON.stringify(got.lines)}`);
// the ones not reckoned say so, and why; one with a reason this
// GUI doesn't know says nothing
assert.deepEqual(got.unknown.map((l) => l.text), [want[lang].none, want[lang].none, want[lang].none], `${at}: ${JSON.stringify(got.unknown)}`);
const [fable, sonnet, credits] = got.unknown;
assert.ok(fable.title.includes(want[lang].under), `${at}: ${fable.title}`);
assert.ok(sonnet.title.includes(want[lang].credits), `${at}: ${sonnet.title}`);
assert.ok(credits.title.includes(want[lang].clock), `${at}: ${credits.title}`);
for (const l of got.unknown) {
assert.ok(l.inReset && !l.cut && l.inCard && l.muted, `${at}: ${JSON.stringify(l)}`);
assert.equal(l.title.split("\n").length, 2, at);
}
const [five, week, kiro] = got.lines;
assert.equal(five.text, want[lang].line + " · ≈ $85.43", at);
assert.match(week.text, /≈ \$1235$/, at);
assert.doesNotMatch(kiro.text, /\$/, `${at}: no API price, no cost`);
for (const l of got.lines) {
assert.ok(l.inReset, `${at}: ${l.text} isn't on the reset's line`);
assert.ok(!l.cut && l.inCard, `${at}: "${l.text}" is cut or past its card`);
assert.ok(l.title.includes(want[lang].low), `${at}: the tooltip doesn't say it reads low: ${l.title}`);
assert.ok(l.title.includes("41") && l.title.split("\n").length === 4, `${at}: ${l.title}`);
}
assert.ok(five.title.includes("$85.43") && five.title.includes("20%"), at);
assert.ok(!kiro.title.includes("$"), at);
assert.equal(got.pageScroll, false, `${at}: the page scrolls sideways`);
// a click on it moves nothing
const before = await page.evaluate(() => [scrollY, document.querySelector("#view-usage")?.scrollTop]);
await page.locator(".quota-holds").first().click();
await page.waitForTimeout(100);
assert.deepEqual(await page.evaluate(() => [scrollY, document.querySelector("#view-usage")?.scrollTop]), before, at);
await page.close();
}
}
} finally { await browser.close(); }
});
}