Files
magpie/internal/gui/tests/usage-open-light.test.cjs
T
yetone d17a0b3ca0 usage: opening the Usage page no longer stutters (_hii11 on Discord)
_hii11 (Discord #general): switching sidebar pages stutters a little,
most of all on Usage. The click that opened Usage built every allowance
card and curve twice, the first time inside the click:

- renderUsageLoading drew the cards again although the read of the
  allowances that goes with every load (loadQuotas) draws them once it
  answers. Cards already drawn now stay until then.
- every card's draw parsed each history line's readings (up to 6000 a
  window, 45 days) three times. quotaPoints parses a line once for each
  read of the history (loadQuotaHist puts a new quotaHist), and the
  recorded cycles are found once for those points.

The UI is the same; nothing new moves.

Measured on mote, headless Chromium, 1280x820, a busy user's data (10
accounts, 45 days of history, 30 days of usage), Usage clicked 4 times,
frames dropped in the 900ms after the click:
- CPU x1: before 4/4/1/1 (worst gap 50ms), after 1/1/0/1 (33ms)
- CPU x4: before 43/37/33/32, after 32/17/20/19; the click's own task
  ~250ms before, ~70-85ms after; click handling in the trace 303ms -> 89ms.
Agents and Providers switches were 0-1 dropped before and after.

Run (mote):
- usage-open-light.test.cjs (new), Chromium and WebKit, en/zh/zh-TW/ja/de:
  green. Red on the old assets: 17292 dates parsed again per redraw; with
  only page.js put back by hand, the cards are rebuilt inside the click.
- the 195 GUI files that touch the Usage page or its cards, both engines:
  3243 of 3295 pass. Each red file was then run alone on this change and
  on origin/main 4a9cfb52e: the same reds on main, all filed already:
  tray-cell-click #5215, usage-agents-hide #2276, usage-fold #3415,
  context-map #3488, codex-auto-reset (webkit de) #4790, usage-ledger
  Requests #5048. account-eye's '' for 'none' is #5052 (on main too;
  4 of 4 green here alone). plugin-checkin passed alone on both.
- quota-curve.test.cjs both engines green; TestCoreScriptBudget passes.

Not tried: the real app at 60fps (ffmpeg), WebKitGTK on Linux, Windows
WebView2, the reporter's own data.
2026-11-05 00:41:16 +08:00

102 lines
6.4 KiB
JavaScript

// Run with Node's test runner and Playwright on the module path; see README.md.
// Opening Usage again does no heavy drawing inside the click (_hii11 on
// Discord: the page switch stuttered, Usage most of all). The allowance cards
// already drawn stay as they are until the read that goes with every open
// answers, so each card and curve is built once per open, not twice and the
// first time in the click. And a curve's readings are parsed once for each
// read of the history: drawing the cards again parses none of them.
// 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 = process.env.MAGPIE_OPEN_ASSETS || path.resolve(__dirname, "../assets");
const H = 3600e3;
const iso = (ms) => new Date(ms).toISOString();
function fixtures(now) {
const quotas = ["a@x.com", "b@x.com"].map((user) => ({ provider: "codex", name: "Codex", icon: "openai", plan: "Pro", user, readAt: iso(now), windows: [
{ name: "5 hours", used: 40, resetsAt: iso(now + 2 * H) },
{ name: "Weekly", used: 30, resetsAt: iso(now + 72 * H) },
] }));
// ten days of readings every 15 minutes: 960 a line
const line = (name, span) => ({ name, points: Array.from({ length: 960 }, (_, k) => {
const at = now - 240 * H + k * 15 * 60e3, s = Math.floor((at - now) / span);
return { at: iso(at), left: 90 - (k % 20), start: iso(now + s * span), resetsAt: iso(now + (s + 1) * span) };
}) });
const history = quotas.map((q) => ({ provider: q.provider, user: q.user, lines: [line("5 hours", 5 * H), line("Weekly", 168 * H)] }));
return { quotas, history };
}
function serve(lang, data, gate) {
const settings = { theme: "light", lang, tray: "panel", currency: "usd" };
return async (route) => {
const url = new URL(route.request().url());
const json = (body) => route.fulfill({ json: body });
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: [], profiles: [], settings });
if (url.pathname === "/api/settings") return json(settings);
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } });
if (url.pathname === "/api/usage/quotas") { await gate.held; return json(data.quotas); }
if (url.pathname === "/api/usage/quotas/history/holds") return json([]);
if (url.pathname === "/api/usage/quotas/history") { await gate.held; return json(data.history); }
if (url.pathname === "/api/usage") return json({ calls: 0, input: 0, output: 0, cost: 0, agents: [], accounts: [], models: [], series: [], days: [] });
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)];
try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }
};
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(`${engine}: opening Usage draws its cards once, after the click`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) await t.test(lang, async () => {
const context = await browser.newContext({ viewport: { width: 1280, height: 820 }, reducedMotion: "reduce" });
const page = await context.newPage();
page.setDefaultTimeout(10000);
page.setDefaultNavigationTimeout(60000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
const gate = { held: Promise.resolve() };
await page.route("**/*", serve(lang, fixtures(Date.now()), gate));
await page.goto("http://magpie.test/");
await page.locator('#nav button[data-view="usage"]').click();
await page.locator(".subscription-card .quota-curve").first().waitFor();
// both accounts share Codex's card, the second's curve behind its More
const cards = await page.locator(".subscription-card").count();
const curves = await page.locator(".subscription-card .quota-curve").count();
assert.ok(cards >= 1 && curves >= 1);
// drawn again from the same read of the history: no reading parsed again
const parsed = await page.evaluate(() => {
const parse = Date.parse; let n = 0;
Date.parse = (s) => { n++; return parse(s); };
try { renderQuotas(true); } finally { Date.parse = parse; }
return n;
});
assert.ok(parsed < 100, `drawing the cards again parsed ${parsed} dates; the 3840 readings were parsed already`);
// away and back, with the reads that go with the open held
await page.locator('#nav button[data-view="agents"]').click();
let release;
gate.held = new Promise((r) => { release = r; });
await page.evaluate(() => { for (const c of document.querySelectorAll(".subscription-card")) c.dataset.drawnBefore = "1"; });
await page.locator('#nav button[data-view="usage"]').click();
await page.locator("#view-usage").waitFor();
assert.equal(await page.locator('.subscription-card[data-drawn-before="1"]').count(), cards, "the cards drawn before stay until the read answers");
release();
await page.waitForFunction((n) => document.querySelectorAll(".subscription-card").length === n && !document.querySelector('.subscription-card[data-drawn-before="1"]'), cards);
assert.equal(await page.locator(".subscription-card .quota-curve").count(), curves, "the answer draws them again, curves and all");
assert.deepEqual(errors, []);
await context.close();
});
});
}