usage, routing: counts are said short (K/M, 万/亿), the exact number on hover (skyhuang1994)
skyhuang1994 on Discord: long token and request counts on Usage and
Routing are hard to read at a glance. They now go through fmtN (K/M/B,
in Chinese 万/亿), with the exact grouped number (ledNum) as the title,
so hovering shows it. A count that fmtN already writes in full gets no
title.
- Usage (plugins/usage/page.js): the Requests table's input, output and
cache cells (output keeps its reasoning line, cache write its TTLs
under the exact number), the Requests block, retried, the sources
tile and the ledger's sum line. sameRead moves here from app.js,
beside loadSessions, its only reader.
- app.js: the Tokens and Requests blocks (blk takes a title), the
ledger's call count, the rank's values and "{n} requests".
- Routing (plugins/routing/client.js): the day menu's note, the "more
days" name, the day rows and the stats.
Core scripts: 22 bytes smaller than their base (1533979 at this head;
TestCoreScriptBudget stays red on #5139 as on main, not worse).
Tests: usage-compact-counts.test.cjs is new (Usage and Routing, every
language, chromium and webkit, 420 and 1100px). panel-usage's rank
value expects "900K" with title "900,000"; ledger-cache-unknown's
counted cells expect fmtN text with ledNum as the title.
Run (mote-run):
- at ded9e4a62 (on c03dee7e3): TestCoreScriptBudget 1533979 (red, #5139),
usage-compact-counts, ledger-cache-unknown, panel-usage, i18n-keys:
50/50.
- at c533a569d (on 69eb93e0a): 136 GUI files (usage-*, ledger-*,
panel-usage, i18n-keys, routing day/stats files) 1868/1917. The reds,
rest-try-now (#5035, #2564), usage-agents-hide (#2276), usage-fold
(#3415), usage-ledger (#5048), ledger-swipe (#5223), usage-computers
(#5224), are red the same or worse on origin/main 0a5dc40ab in a
4-file run under the same load; c533a569d's 4-file run had a subset.
- at 56fff616a (on d5d48f4f9): 206 GUI files; besides the above,
tray-cell-click (#5215) red the same on origin/main 009076a2a.
Broken by hand: page.js, client.js and app.js put back to main's ->
usage-compact-counts and ledger-cache-unknown 0 pass / 42 fail;
restored.
Not tried: the real app with real usage data, the Linux WebKitGTK app,
Windows.
This commit is contained in:
@@ -127,7 +127,6 @@ const readsSame = (path) => /^sessions(\?|$)|^sessions\/stats\?/.test(path);
|
||||
// each such answer's tag: two answers with tags are the same only when they
|
||||
// are one object, so the Sessions tab needn't compare ~8 MB to know
|
||||
const readTags = new WeakMap();
|
||||
const sameRead = (a, b) => a === b || !(readTags.has(a) && readTags.has(b)) && JSON.stringify(a) === JSON.stringify(b);
|
||||
|
||||
// heads, when given, is shown the answer's headers (loadQuotas' X-Magpie-Reading);
|
||||
// signal, when given, cancels the request (a read the reader moved on from)
|
||||
@@ -17197,8 +17196,9 @@ function renderPanelUse() {
|
||||
} else {
|
||||
const hitRate = cacheHitOf(l);
|
||||
const tot = el("div", "pu-tot");
|
||||
const blk = (label, value, sub, cls, subCls) => {
|
||||
const blk = (label, value, sub, cls, subCls, full) => {
|
||||
const b = el("div", "blk");
|
||||
if (full) b.title = full;
|
||||
// a value in parts (an array) keeps each whole, wrapping between them
|
||||
const v = el("span", "v" + (cls ? " " + cls : "") + (Array.isArray(value) ? " parts" : ""), Array.isArray(value) ? undefined : value);
|
||||
// (a space between two stays out of them: one leading a part is dropped)
|
||||
@@ -17209,8 +17209,8 @@ function renderPanelUse() {
|
||||
};
|
||||
// the total counts the cache's tokens too, so they're named beside in and out
|
||||
const cached = l.cache_read + l.cache_write;
|
||||
blk("Tokens", fmtN(allTokens(l)), t("{a} in · {b} out", { a: fmtN(l.input), b: fmtN(l.output) }) + (cached ? " · " + t("{n} cached", { n: fmtN(cached) }) : ""));
|
||||
blk("Requests", ledNum(l.calls), [l.errors ? t("{n} failed", { n: ledNum(l.errors) }) : t("none failed"), l.retried ? t("{n} answered on a retry", { n: ledNum(l.retried) }) : ""].filter(Boolean).join(" · "), "", l.errors ? "bad" : "");
|
||||
blk("Tokens", fmtN(allTokens(l)), t("{a} in · {b} out", { a: fmtN(l.input), b: fmtN(l.output) }) + (cached ? " · " + t("{n} cached", { n: fmtN(cached) }) : ""), "", "", ledNum(allTokens(l)));
|
||||
blk("Requests", fmtN(l.calls), [l.errors ? t("{n} failed", { n: fmtN(l.errors) }) : t("none failed"), l.retried ? t("{n} answered on a retry", { n: fmtN(l.retried) }) : ""].filter(Boolean).join(" · "), "", l.errors ? "bad" : "", ledNum(l.calls));
|
||||
const c = fmtCost(l);
|
||||
blk("Cost", c ? "≈" + c : "—", l.unpriced ? t("{n} unpriced", { n: l.unpriced }) : t("effective prices"), c ? "cost" : "");
|
||||
blk("Cache hit rate", hitRate === null ? "—" : Math.round(100 * hitRate) + "%", cacheLeftOut(l) || t("of the prompt"));
|
||||
@@ -18658,7 +18658,7 @@ const ledRankValue = (m, x) => m === "speed" ? ledGroupSpeed(x)?.v || 0 : ledVal
|
||||
// of a point's part, which has its calls, tokens, cost and speed
|
||||
const ledPart = (m, x) => m === "speed" ? ledSpeed(x) : m === "cost" ? +x.cost || 0 : m === "calls" ? +x.calls || 0 : +x.tokens || 0;
|
||||
// a metric as its axis and its values say it
|
||||
const ledFormat = (m, v) => m === "cost" ? ledMoney(v) : m === "calls" || m === "speed" ? ledNum(Math.round(v)) : fmtN(Math.round(v));
|
||||
const ledFormat = (m, v) => m === "cost" ? ledMoney(v) : (m === "speed" ? ledNum : fmtN)(Math.round(v));
|
||||
const ledFormatLong = (m, v) => m === "speed" ? (v > 0 ? t("{n} tok/s", { n: ledNum(Math.round(v)) }) : "—") : m === "cost" ? (fmtCost({ cost: v, unpriced: 0 }) || "—") : ledNum(Math.round(v));
|
||||
|
||||
// an axis's top with four steps under it: round numbers, the top at least the largest value
|
||||
@@ -18888,15 +18888,15 @@ function drawLedRank(box, l, split, metric, picked, choose, compact) {
|
||||
if (x.icon && split !== "model") l1.append(icon(x.icon));
|
||||
const nm = el("span", "rk-nm", t(x.name || x.id || "—"));
|
||||
nm.title = t(x.name || x.id || "");
|
||||
const val = el("span", "rk-val", metric === "speed" ? gs?.text || "—" : ledFormatLong(metric, v));
|
||||
if (metric === "speed" && gs?.title) val.title = gs.title;
|
||||
const long = ledFormatLong(metric, v), val = el("span", "rk-val", metric == "speed" ? gs?.text || "—" : metric == "cost" ? long : ledFormat(metric, v));
|
||||
val.title = metric == "speed" ? gs?.title || "" : long;
|
||||
l1.append(nm, val);
|
||||
const bar = el("div", "rk-bar"), fill = el("i");
|
||||
fill.style.width = Math.max(1.5, (100 * v) / leader).toFixed(1) + "%";
|
||||
fill.style.background = color;
|
||||
bar.append(fill);
|
||||
const more = [];
|
||||
if (metric !== "calls") more.push(t(x.calls === 1 ? "{n} request" : "{n} requests", { n: ledNum(x.calls) }));
|
||||
if (metric !== "calls") more.push(t(x.calls === 1 ? "{n} request" : "{n} requests", { n: fmtN(x.calls) }));
|
||||
if (metric !== "tokens") more.push(t("{n} tokens", { n: fmtN(allTokens(x)) }));
|
||||
if (metric !== "cost" && x.cost) more.push("≈" + fmtCost(x));
|
||||
if (x.credited) more.push(ledCredits(x));
|
||||
|
||||
@@ -150,7 +150,7 @@ function routingPage(part) {
|
||||
moreDays.onclick = (e) => {
|
||||
e.stopPropagation();
|
||||
if (moreDays.classList.contains("open")) return closeProtoMenu();
|
||||
openProtoMenu(moreDays, unseenDays.map((d) => ({ v: d.day, name: dayName(d.day), literalName: true, note: String(d.requests) })),
|
||||
openProtoMenu(moreDays, unseenDays.map((d) => ({ v: d.day, name: dayName(d.day), literalName: true, note: fmtN(d.requests) })),
|
||||
day, (v) => { if (v !== day) lookAt(v); }, "Earlier days", "rt-days-menu");
|
||||
};
|
||||
function nameMoreDays() {
|
||||
@@ -158,7 +158,7 @@ function routingPage(part) {
|
||||
moreDays.classList.toggle("on", !!picked);
|
||||
moreDays.setAttribute("aria-pressed", String(!!picked));
|
||||
moreDays.replaceChildren(el("span", "", picked ? dayName(picked.day) : t("Earlier days")),
|
||||
...(picked ? [el("small", "", String(picked.requests))] : []), svg(CHEV, 10, 1.6));
|
||||
...(picked ? [count(picked.requests)] : []), svg(CHEV, 10, 1.6));
|
||||
}
|
||||
function fitDays() {
|
||||
if (!dayBar.clientWidth) return; // out of sight: fitted when it shows
|
||||
@@ -523,6 +523,10 @@ function routingPage(part) {
|
||||
if (prompt) s += " · " + t("request cache hit rate {p}", { p: pct(100 * read / prompt) });
|
||||
return s;
|
||||
}
|
||||
// a count short (fmtN: 12.3K, 1.2 万), exact on hover when they differ
|
||||
// (skyhuang1994 on Discord: "看这么长串的数字有点懵逼")
|
||||
const exactN = (n) => fmtN(n) == String(n) ? "" : ledNum(n);
|
||||
const count = (n) => Object.assign(el("small", "", fmtN(n)), { title: exactN(n) });
|
||||
const tokens = (n) => n >= 1e6 ? (n / 1e6).toFixed(1) + "M" : n >= 1e3 ? (n / 1e3).toFixed(1) + "k" : String(Math.round(n));
|
||||
const pct = (n) => Math.round(n) + "%";
|
||||
// an account's window as Settings' allowance display has it, how much is
|
||||
@@ -3541,7 +3545,7 @@ function routingPage(part) {
|
||||
rerouted: done.reduce((n, r) => n + r.tries.filter((tr, i) => tr.rest && i < r.tries.length - 1).length, 0),
|
||||
errors: done.filter(failedRoute).length,
|
||||
} : traceTotals;
|
||||
[counts.requests, counts.rerouted, counts.errors].forEach((n, i) => setText(statB[i], String(n)));
|
||||
[counts.requests, counts.rerouted, counts.errors].forEach((n, i) => { setText(statB[i], fmtN(n)); setAttr(statB[i], "title", exactN(n)); });
|
||||
setAttr(stats, "title", t(scoped ? "Counts for the requests in this list" : "Counts since the gateway started"));
|
||||
const failed = rs.some(failedRoute), btn = statB[2].parentElement;
|
||||
setAttr(btn, "aria-disabled", String(!failed));
|
||||
@@ -3588,7 +3592,7 @@ function routingPage(part) {
|
||||
function renderDays() {
|
||||
const b = (d, label, n) => {
|
||||
const x = el("button", "rt-day" + (d === day ? " on" : ""));
|
||||
x.append(el("span", "", label), ...(n != null ? [el("small", "", String(n))] : []));
|
||||
x.append(el("span", "", label), ...(n != null ? [count(n)] : []));
|
||||
x.setAttribute("aria-pressed", String(d === day));
|
||||
x.onclick = () => { if (d !== day) lookAt(d); };
|
||||
return x;
|
||||
|
||||
@@ -1536,6 +1536,11 @@ const LED_TREND = [...LED_METRICS, ["speed", "Speed"]];
|
||||
// the gateway key that made it, "none" for calls with none, offered while
|
||||
// the period has a key's calls (#2521)
|
||||
const LED_SPLITS = [["model", "Model"], ["modelAt", "Model · provider"], ["provider", "Provider"], ["agent", "Agent"], ["callerKey", "Gateway key"]];
|
||||
// a count said short (fmtN: 1.2M, 35K, 12.3 万) with its exact value for a
|
||||
// tooltip, nothing when the two read the same (skyhuang1994 on Discord:
|
||||
// "看这么长串的数字有点懵逼")
|
||||
const exactN = (n) => fmtN(n ||= 0) == String(n) ? "" : ledNum(n);
|
||||
const tipOf = (...lines) => lines.filter(Boolean).join("\n");
|
||||
// cacheTTLs: a call's cache writes split by how long they are kept, where
|
||||
// some were for an hour (Anthropic bills those at 2× input, 5 minutes'
|
||||
// at 1.25×); nothing when none were
|
||||
@@ -1618,10 +1623,10 @@ function renderLedgerDash(l) {
|
||||
b.onclick = () => ledShowStatus(ledStatusOf() === to ? "" : to);
|
||||
return b;
|
||||
};
|
||||
block("Requests", ledNum(l.calls), l.errors
|
||||
? jumps(jump(t("{n} failed", { n: ledNum(l.errors) }), "failed", t("Show only the failed requests")), " · " + t("{p} succeeded", { p: (100 * (1 - l.errors / l.calls)).toFixed(1) + "%" }))
|
||||
: line(t("none failed")));
|
||||
if (l.retried) strip.lastChild.append(jumps(jump(t("{n} answered on a retry", { n: ledNum(l.retried) }), "retried", t("Show only the requests answered on a retry"))));
|
||||
block("Requests", fmtN(l.calls), l.errors
|
||||
? jumps(jump(t("{n} failed", { n: fmtN(l.errors) }), "failed", t("Show only the failed requests")), " · " + t("{p} succeeded", { p: (100 * (1 - l.errors / l.calls)).toFixed(1) + "%" }))
|
||||
: line(t("none failed")), "", exactN(l.calls));
|
||||
if (l.retried) strip.lastChild.append(jumps(jump(t("{n} answered on a retry", { n: fmtN(l.retried) }), "retried", t("Show only the requests answered on a retry"))));
|
||||
const c = fmtCost(l);
|
||||
block("Cost", c ? "≈" + c : "—", line(l.unpriced ? t(l.unpriced === 1 ? "{n} call had no known price and is not counted" : "{n} calls had no known price and are not counted", { n: l.unpriced }) : t("effective prices")), c ? "cost" : "");
|
||||
const hit = block("Cache hit rate", rate === null ? "—" : (100 * rate).toFixed(1) + "%", cacheLeftOut(l) ? line(cacheLeftOut(l)) : null, "", t("The share of the prompt read from the cache"));
|
||||
@@ -2328,13 +2333,17 @@ function renderLedger() {
|
||||
slide(seg, "ledStatus");
|
||||
$("#ledExport").disabled = !l.total;
|
||||
|
||||
const sum = [t(l.total === 1 ? "{n} request" : "{n} requests", { n: ledNum(l.total) })];
|
||||
// each count short, and exact in the line's tooltip
|
||||
const sum = [], exact = [];
|
||||
const say = (k, n) => { sum.push(t(k, { n: fmtN(n || 0) })); exact.push(t(k, { n: ledNum(n) })); };
|
||||
say(l.total === 1 ? "{n} request" : "{n} requests", l.total);
|
||||
if (l.total) {
|
||||
sum.push(t("{n} in", { n: fmtN(l.input) }), t("{n} out", { n: fmtN(l.output) }), t("{n} cache write", { n: fmtN(l.cache_write) }), t("{n} cache read", { n: fmtN(l.cache_read) }));
|
||||
if (l.errors) sum.push(t("{n} failed", { n: l.errors }));
|
||||
if (l.retried) sum.push(t("{n} answered on a retry", { n: l.retried }));
|
||||
say("{n} in", l.input); say("{n} out", l.output); say("{n} cache write", l.cache_write); say("{n} cache read", l.cache_read);
|
||||
if (l.errors) say("{n} failed", l.errors);
|
||||
if (l.retried) say("{n} answered on a retry", l.retried);
|
||||
}
|
||||
$("#ledSum").textContent = sum.join(" · ");
|
||||
$("#ledSum").title = sum.join() == exact.join() ? "" : exact.join(" · ");
|
||||
// the two sources and their total, in the same block of cells as the totals
|
||||
// above them: what magpie carried, what it only read about in the agents'
|
||||
// own session files, and the two together. Each is a filter: picking one
|
||||
@@ -2357,7 +2366,8 @@ function renderLedger() {
|
||||
b.type = "button";
|
||||
b.setAttribute("aria-pressed", on ? "true" : "false");
|
||||
b.title = pick ? t("Show only these requests") : t("Show every request again");
|
||||
const v = el("span", "v", ledNum(calls));
|
||||
const v = el("span", "v", fmtN(calls));
|
||||
if (exactN(calls)) v.title = exactN(calls);
|
||||
// the unit, so a bare number isn't read as the tokens below it
|
||||
v.append(el("em", "", t(calls === 1 ? "request" : "requests")));
|
||||
b.replaceChildren(el("span", "k", t(label)), v,
|
||||
@@ -2542,13 +2552,13 @@ function renderLedger() {
|
||||
td(r.model || "—", "model " + (r.model ? "model-value" : "faint"), r.source === "log" && r.model ? t("Model recorded in the local session log; the outbound HTTP request was not captured.") : r.model);
|
||||
td(ledServed(r), "model");
|
||||
td(r.effort || "—", r.effort ? "" : "faint");
|
||||
td(ledNum(r.in), "n");
|
||||
td(ledNum(r.out), "n", r.reasoning ? t("{n} reasoning, inside output", { n: ledNum(r.reasoning) }) : "");
|
||||
td(fmtN(r.in || 0), "n", exactN(r.in));
|
||||
td(fmtN(r.out || 0), "n", tipOf(exactN(r.out), r.reasoning ? t("{n} reasoning, inside output", { n: ledNum(r.reasoning) }) : ""));
|
||||
// a vendor that counts no cache wrote and read none we know of, not 0 (#3464)
|
||||
if (r.cache_unknown) for (let i = 0; i < 2; i++) td("—", "n faint", t("The vendor doesn't count the cache"));
|
||||
else {
|
||||
td(ledNum(r.cache_write), "n" + (r.cache_write ? "" : " faint"), cacheTTLs(r, ledNum).replace(/^ · /, ""));
|
||||
td(ledNum(r.cache_read), "n" + (r.cache_read ? "" : " faint"));
|
||||
td(fmtN(r.cache_write || 0), "n" + (r.cache_write ? "" : " faint"), tipOf(exactN(r.cache_write), cacheTTLs(r, ledNum).replace(/^ · /, "")));
|
||||
td(fmtN(r.cache_read || 0), "n" + (r.cache_read ? "" : " faint"), exactN(r.cache_read));
|
||||
}
|
||||
// what the reply said it cost in its plan's credits (WorkBuddy's
|
||||
// usage.credit, #2512), on its own row as on the ranking's line
|
||||
@@ -2843,6 +2853,9 @@ function renderUsageTab() {
|
||||
}
|
||||
|
||||
const sessDays = () => SESS_RANGES.find(([id]) => id === sessRange)[2];
|
||||
// two answers are the same: with the tags api read them under (readTags in
|
||||
// app.js), only when they are one object
|
||||
const sameRead = (a, b) => a === b || !(readTags.has(a) && readTags.has(b)) && JSON.stringify(a) === JSON.stringify(b);
|
||||
async function loadSessions() {
|
||||
const first = !sessions || !sessStats;
|
||||
if (first) renderSessionsLoading();
|
||||
|
||||
@@ -125,7 +125,9 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
const at = [heads.indexOf(w), heads.indexOf(r)];
|
||||
return [...tb.tBodies[0].rows].filter((x) => x.classList.contains("led-row")).map((x) => at.map((i) => ({ text: x.cells[i].textContent, title: x.cells[i].title })));
|
||||
}, [await say("Cache write"), await say("Cache read")]);
|
||||
assert.deepEqual(cells[0].map((c) => c.text), [await p.evaluate(() => ledNum(500)), await p.evaluate(() => ledNum(9000))]);
|
||||
// said short, the exact count on hover
|
||||
assert.deepEqual(cells[0].map((c) => c.text), [await p.evaluate(() => fmtN(500)), await p.evaluate(() => fmtN(9000))]);
|
||||
assert.equal(cells[0][1].title, await p.evaluate(() => ledNum(9000)));
|
||||
assert.deepEqual(cells[1], [{ text: "—", title: notCounted }, { text: "—", title: notCounted }]);
|
||||
// its details say so beside its tokens
|
||||
await rows.nth(1).click();
|
||||
|
||||
@@ -247,7 +247,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
await p.locator("#panelUsage:not(.pu-loading)").waitFor();
|
||||
const selectedDay = asked.at(-1).get("day");
|
||||
assert.equal(await p.locator('#panelUsage .led-day[aria-pressed="true"]').getAttribute("aria-label"), label);
|
||||
assert.equal(await p.locator("#panelUsage .led-rank .rk").first().locator(".rk-val").textContent(), "900,000");
|
||||
assert.equal(await p.locator("#panelUsage .led-rank .rk").first().locator(".rk-val").textContent(), "900K");
|
||||
assert.equal(await p.locator("#panelUsage .led-rank .rk").first().locator(".rk-val").getAttribute("title"), "900,000");
|
||||
assert.deepEqual(await p.locator("#panelUsage rect.col").evaluateAll((rs) => rs.map((r) => [r.dataset.day, r.dataset.k, r.getAttribute("height"), r.dataset.color])), original, "the chart keeps its heights and colors");
|
||||
const dimmed = () => p.locator("#panelUsage rect.col").evaluateAll((rs, day) => rs.every((r) => r.dataset.day === day ? r.style.opacity === "" && r.style.fill === r.dataset.color : r.style.opacity === "0.22" && r.style.fill === "var(--faint)"), selectedDay);
|
||||
assert(await dimmed(), "the other days are gray");
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// skyhuang1994 on Discord: "用量的这个数据展示 可以遵循 数字单位的展示逻辑吗
|
||||
// 看这么长串的数字有点懵逼". The Usage page's request rows said their tokens
|
||||
// in full (52,345,678), and the Requests total, the line over the list, the
|
||||
// ranking and the Routing page's counts said requests in full. Each says
|
||||
// fmtN's short form now (52M, 123K, or 5234.6 万 with Settings' 万 / 亿), and
|
||||
// its exact value on hover. In every language, both engines, at 1100 and
|
||||
// 420 wide; the API is faked.
|
||||
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 now = Date.now();
|
||||
const IN = 1234567, OUT = 98765, READ = 52345678, WRITE = 400, CALLS = 123456;
|
||||
const ALL = IN + OUT + READ + WRITE;
|
||||
const ROWS = [{
|
||||
t: new Date(now - 60e3).toISOString(), agent: "claude", agentName: "Claude Code", icon: "claudecode-color",
|
||||
provider: "claude", providerName: "Claude", providerAccount: "a@example.com", req: "claude-opus-5", model: "claude-opus-5", served: "claude-opus-5",
|
||||
ms: 3000, status: 200, rid: "r-0", ep: "/v1/messages", cost: 0.01, priced: true, in: IN, out: OUT, cache_read: READ, cache_write: WRITE,
|
||||
}];
|
||||
const tot = { calls: CALLS, errors: 0, input: IN, output: OUT, cache_read: READ, cache_write: WRITE, reasoning: 0, cost: 2, unpriced: 0 };
|
||||
const ledger = {
|
||||
period: "today", rows: ROWS, offset: 0, total: CALLS, ...tot, bucket: "hour", series: [],
|
||||
by: { provider: [{ id: "claude", name: "Claude", icon: "claude-color", ...tot }], agent: [{ id: "claude", name: "Claude Code", icon: "claudecode-color", ...tot }], model: [{ id: "claude-opus-5", name: "claude-opus-5", ...tot }] },
|
||||
agents: [{ id: "claude", name: "Claude Code", icon: "claudecode-color" }], providers: [{ id: "claude", name: "Claude", icon: "claude-color" }],
|
||||
};
|
||||
|
||||
function serve(lang, units) {
|
||||
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: { lang, theme: "light", chineseUnits: units } });
|
||||
if (url.pathname === "/api/settings") return json({ lang, theme: "light", chineseUnits: units });
|
||||
if (url.pathname === "/api/gateway/trace") {
|
||||
if (url.searchParams.get("wait")) return new Promise(() => {});
|
||||
return json({ mine: true, now: new Date(now).toISOString(), seq: 1, totals: { requests: CALLS, rerouted: 1234, errors: 7 }, routes: [] });
|
||||
}
|
||||
if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [{ day: "2026-11-03", requests: 23456 }], routes: [] });
|
||||
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
|
||||
if (url.pathname === "/api/providers") return json({ providers: [], excluded: [], gateway: { running: true, window: true } });
|
||||
if (url.pathname === "/api/plugins") return json({ plugins: [] });
|
||||
if (url.pathname === "/api/usage/requests") return json(ledger);
|
||||
if (url.pathname === "/api/usage/quotas") return json([]);
|
||||
if (url.pathname === "/api/usage") return json({ ...tot, bucket: "day", series: [], agents: [], models: [] });
|
||||
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)];
|
||||
await route.fulfill({ body: await fs.readFile(file), contentType });
|
||||
};
|
||||
}
|
||||
|
||||
const LOCALE = { en: "en", zh: "zh-CN", "zh-TW": "zh-TW", ja: "ja-JP", de: "de-DE" };
|
||||
// the short forms: K / M by default, 万 / 亿 in Chinese with Settings' units
|
||||
const KMB = { [IN]: "1.2M", [OUT]: "98.8K", [READ]: "52M", [CALLS]: "123K", [ALL]: "54M", 1234: "1.2K", 23456: "23.5K" };
|
||||
const WAN = { [IN]: "123.5 万", [OUT]: "9.9 万", [READ]: "5234.6 万", [CALLS]: "12.3 万", [ALL]: "5367.9 万", 1234: "1234", 23456: "2.3 万" };
|
||||
const CASES = [...Object.keys(LOCALE).map((lang) => [lang, false]), ["zh", true], ["zh-TW", true]];
|
||||
const short = (lang, units, n) => units ? WAN[n].replace("万", lang === "zh-TW" ? "萬" : "万") : KMB[n];
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
test(`${engine}: the Usage and Routing pages say counts short, exact on hover`, async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
for (const [lang, units] of CASES) {
|
||||
for (const width of [1100, 420]) {
|
||||
await t.test(`${lang}${units ? " 万" : ""} at ${width}px`, async () => {
|
||||
const ctx = await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" });
|
||||
try {
|
||||
const page = await ctx.newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
page.setDefaultNavigationTimeout(60000);
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", serve(lang, units));
|
||||
const s = (n) => short(lang, units, n), x = (n) => n.toLocaleString(LOCALE[lang]);
|
||||
const at = `${lang}${units ? " 万" : ""} ${width}`;
|
||||
|
||||
// the Usage page's requests: its row, its totals, the line over the list, the ranking
|
||||
await page.goto("http://magpie.test/?view=usage");
|
||||
await page.locator(":is(#usageTab .opt, .nav-s):visible").nth(1).click();
|
||||
await page.locator(".led tbody tr.led-row").first().waitFor({ timeout: 15000 });
|
||||
const cells = await page.locator(".led tbody tr.led-row").first().locator("td.n").evaluateAll((ts) => ts.map((c) => [c.textContent, c.title]));
|
||||
for (const n of [IN, OUT, READ]) {
|
||||
assert.ok(cells.some(([text, title]) => text === s(n) && title.split("\n")[0].split(" · ")[0] === x(n)), `${at}: no cell says ${s(n)} with ${x(n)} on hover: ${JSON.stringify(cells)}`);
|
||||
}
|
||||
const blocks = await page.locator("#ledKpi .blk").evaluateAll((bs) => bs.map((b) => [b.querySelector(".v").textContent, b.title]));
|
||||
assert.ok(blocks.some(([v, title]) => v === s(CALLS) && title === x(CALLS)), `${at}: no total says ${s(CALLS)} requests: ${JSON.stringify(blocks)}`);
|
||||
const sum = page.locator("#ledSum");
|
||||
const sumText = await sum.textContent();
|
||||
assert.ok(sumText.includes(s(CALLS)) && !sumText.includes(x(CALLS)), `${at}: the line says "${sumText}"`);
|
||||
assert.ok((await sum.getAttribute("title")).includes(x(CALLS)), `${at}: the line's tooltip lacks ${x(CALLS)}`);
|
||||
const rank = page.locator("#ledRank .rk").first();
|
||||
await rank.waitFor();
|
||||
const val = rank.locator(".rk-val");
|
||||
assert.equal((await val.textContent()).trim(), s(ALL), `${at}: the ranking's tokens`);
|
||||
assert.equal(await val.getAttribute("title"), x(ALL), `${at}: the ranking's tooltip`);
|
||||
assert.ok(!(await rank.textContent()).includes(x(CALLS)), `${at}: the ranking says requests in full`);
|
||||
let over = await page.evaluate(() => document.documentElement.scrollWidth - innerWidth);
|
||||
assert.ok(over <= 1, `${at}: the Usage page is ${over}px past`);
|
||||
|
||||
// the Routing page's counts and a day's requests
|
||||
await page.goto("http://magpie.test/?view=routing");
|
||||
const stat = page.locator(".rt-stats b").first();
|
||||
await page.waitForFunction((want) => document.querySelector(".rt-stats b")?.textContent === want, s(CALLS), { timeout: 5000 }).catch(() => {});
|
||||
assert.equal(await stat.textContent(), s(CALLS), `${at}: Routing's requests`);
|
||||
assert.equal(await stat.getAttribute("title"), x(CALLS), `${at}: Routing's requests on hover`);
|
||||
assert.equal(await page.locator(".rt-stats b").nth(1).textContent(), s(1234), `${at}: Routing's rerouted`);
|
||||
const day = page.locator(".rt-day small").first();
|
||||
await day.waitFor({ state: "attached" });
|
||||
assert.equal(await day.textContent(), s(23456), `${at}: a day's requests`);
|
||||
assert.equal(await day.getAttribute("title"), x(23456), `${at}: a day's requests on hover`);
|
||||
over = await page.evaluate(() => document.documentElement.scrollWidth - innerWidth);
|
||||
assert.ok(over <= 1, `${at}: the Routing page is ${over}px past`);
|
||||
assert.deepEqual(errors, []);
|
||||
} finally {
|
||||
await ctx.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user