Files
magpie/internal/gui/tests/usage-24h.test.cjs
T
yetone 3d49ac069e usage: a 24 hours period, and the period picked is kept
The Usage page's periods were Today, 7 days, 30 days and All. "Today"
starts at midnight, so early in the day it shows almost nothing
(mahiro233 on Discord). A "24 hours" period now sits after Today and
asks the server for its rolling window, last:24h (#2075), with an
hourly chart. Its empty state says "No calls in the last 24 hours."
(en, zh, zh-TW, ja, de). The menu bar's credit days count it as 2.

The period picked from the list is kept in localStorage and the page
opens on it next time. Picked day ranges aren't kept (they go stale),
and neither is a period the URL brings (?period=7d from the menu bar).

Tests: usage-24h.test.cjs (new; Chromium and WebKit, en and zh, 900px):
24 hours sits after Today and asks for last:24h, its empty note, a
reload opens on the kept pick, ?period=7d is not kept. Five usage
tests counted the period list by index and were moved one along.

Run on mote at be2d2db5c + this change: usage-24h, usage-range,
usage-phone-head, usage-ledger, usage-ledger-chart,
usage-ledger-open-settled, usage-refresh-flight, credit-days,
tray-totals, usage-head-steady: pass 148, fail 6. The 6 are
usage-ledger's "newest live route needs no return-to-live button"
(en/zh, both engines), which fail the same 6 on be2d2db5c without
this change (#3104). i18n-keys ok; go test -run "Budget|I18n|Script"
./internal/gui ok. No budget raised.

Broken by hand: none beyond the index shifts the old tests caught.
Not tried: the real app with a day of real calls.

Reported-by: mahiro233 (Discord)
2026-11-10 01:39:27 +08:00

103 lines
5.6 KiB
JavaScript

// Run with Node's test runner and Playwright on the module path; see README.md.
// Usage's "24 hours" (mahiro233 on Discord): the day up to now, asked of the
// backend as the rolling window "last:24h", not since midnight as Today is.
// The reader's pick of a period is kept: the page opens on it again, until a
// way in (the menu bar's total) names another. Picked days are not kept.
// English and Chinese, both engines; 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(process.env.MAGPIE_ASSETS || path.resolve(__dirname, "../assets"));
const dayKey = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
const back = (n) => { const d = new Date(); d.setHours(12, 0, 0, 0); d.setDate(d.getDate() - n); return d; };
function serve(lang, asked) {
const settings = { theme: "light", lang, quotaLeft: false, currency: "usd" };
return 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:"${lang}",theme:"light",web:true};` });
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") {
const p = url.searchParams.get("period");
asked.push(p);
return json({ period: p, calls: 0, errors: 0, input: 0, output: 0, reasoning: 0, unpriced: 0, cost: 0, bucket: "day", series: [], agents: [], models: [], path: "" });
}
if (url.pathname === "/api/usage/quotas") return json([]);
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname === "/api/sessions") return json({ sessions: [], dirs: [] });
if (url.pathname === "/api/sessions/stats") return json({ from: "", to: "", days: [], agents: {} });
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 words = {
en: { day: "24 hours", none: "No calls in the last 24 hours.", week: "7 days" },
zh: { day: "24 小时", none: "最近 24 小时没有调用。", week: "7 天" },
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh"]) {
const w = words[lang];
test(`${engine} ${lang}: Usage over the last 24 hours, kept`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
let page;
t.after(async () => {
if (process.env.ARTIFACT_DIR && page) {
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-usage-24h.png`) });
}
await browser.close();
});
page = await (await browser.newContext({ viewport: { width: 900, height: 760 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
const asked = [];
await page.route("**/*", serve(lang, asked));
const on = () => page.locator("#period .opt.on").textContent();
const settle = () => page.waitForFunction(() => document.querySelector("#period .opt") && !document.querySelector("#period .opt:disabled"));
await page.goto("http://magpie.test/?view=usage");
await settle();
assert.equal(asked[0], "today", "a first visit opens on Today");
const opts = await page.locator("#period .opt:not(.range-opt)").allTextContents();
assert.equal(opts[1].trim(), w.day, "24 hours sits after Today");
await page.locator("#period .opt", { hasText: new RegExp("^" + w.day + "$") }).click();
await page.waitForFunction(() => document.querySelector("#view-usage .none"));
assert.equal(asked.at(-1), "last:24h");
assert.ok((await page.locator("#view-usage .none").textContent()).startsWith(w.none));
// opened again: on the pick
asked.length = 0;
await page.reload();
await settle();
assert.equal(asked[0], "last:24h", "the page opens on the kept pick");
assert.equal((await on()).trim(), w.day);
// the menu bar's total names its own period, which isn't kept
asked.length = 0;
await page.goto("http://magpie.test/?view=usage&period=7d");
await settle();
assert.equal(asked[0], "7d");
asked.length = 0;
await page.goto("http://magpie.test/?view=usage");
await settle();
assert.equal(asked[0], "last:24h", "a way in leaves the pick as it was");
assert.deepEqual(errors, []);
});
}
}