usage: a priced cost without "≈", at least two decimals; cache hit rate to two

shangyuan0818 on X: Usage → Requests showed every cost as "≈$…", and
the cache hit rate with one decimal.

- A cost from known prices is what magpie counted, so "≈" is gone from
  every priced cost: Requests' Cost card and tiles, the agent, model and
  account rows, the quick panel's Usage, Routing's live rows. An estimate
  keeps it (a window's whole on an account card, a session file's times).
- fmtCost gives at least two decimals ($1.00, $100.00, $2500.50), three
  under $1 as before, and a sub-mill amount to its first two digits
  ($0.00040, $0.000012) instead of $0.000.
- Requests' Cache hit rate card has two decimals (93.97%); hitPct still
  never rounds up to 100% or down to 0%.
- A whole-window estimate from $100 up stays whole ($1235): its cents
  would claim a precision it hasn't (wholeCost, moved to page.js to keep
  app.js inside its budget).

Run, at 2d106b5c1 + this change, on mote (rebased onto fc41381d6,
whose three commits touch nothing under internal/gui):
- usage-exact-cost.test.cjs (new): red on 2d106b5c1, green 12/12.
- The 91 GUI files that read a cost or a hit rate, both engines, every
  language. Reds beside this change's own (fixed: mobile-web,
  panel-currency-provider, ledger-cache-unknown, usage-ledger-chart) are
  red alike on a 2d106b5c1 checkout, each filed: grip-inset #6293,
  key-balance-card de #6414, usage-cards-hide #6294,
  usage-hidden-way-back #6295, quota-curve #6789, old-webkit #6030,
  tray-cell-click #5215, usage-ledger return-to-live #4078, usage-upload
  #6743, zero-priced-free #5262.
- After the test fixes: mobile-web, panel-currency-provider,
  ledger-cache-unknown, usage-ledger-chart, usage-exact-cost, quota-holds,
  usage-unpriced-sum, currency, i18n-keys: 112 pass. The 14 reds are red
  alike on a 2d106b5c1 checkout: usage-ledger-chart's "metric is
  remembered" (filed in #6790) and mobile-web's "desktop matches
  origin/main", which needs git in the copy (mote-run has none; #5013).
- go test -run Budget ./internal/gui: ok (app.js inside appScriptBudget)

Not tried: Windows (WebView2), the reporter's own data, a real account.
This commit is contained in:
yetone
2026-11-16 04:38:36 +08:00
parent fc41381d60
commit d597b4d010
18 changed files with 191 additions and 86 deletions
+5 -3
View File
@@ -16125,7 +16125,9 @@ function fmtCost(t, prov) {
if (typeof t.cost !== "number" || (!t.cost && t.unpriced)) return "";
let c = t.cost, sign = "$";
if (costInYuan(prov)) { c = c * fx.rate; sign = "¥"; }
const s = c >= 100 ? c.toFixed(0) : c >= 1 ? c.toFixed(2) : c.toFixed(3);
// at least two decimals (shangyuan0818 on X), a sub-mill amount to its
// first two digits rather than $0.000
const s = c.toFixed(c >= 1 ? 2 : c > 0 && c < 1e-3 ? 1 - Math.floor(Math.log10(c)) : 3);
return sign + s + (t.unpriced ? "+" : "");
}
const tokensOf = (t) => t.input + t.output;
@@ -17536,7 +17538,7 @@ function renderPanelUse() {
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, l.provider);
const u = l.unpriced, one = u === 1;
blk("Cost", c ? "≈" + c : "—", u ? t(one ? "{n} call unpriced" : "{n} calls unpriced", { n: u }) : t("effective prices"), c ? "cost" : "", "", u ? t(one ? "{n} call had no known price and is not counted" : "{n} calls had no known price and are not counted", { n: u }) : "");
blk("Cost", c || "—", u ? t(one ? "{n} call unpriced" : "{n} calls unpriced", { n: u }) : t("effective prices"), c ? "cost" : "", "", u ? t(one ? "{n} call had no known price and is not counted" : "{n} calls had no known price and are not counted", { n: u }) : "");
blk("Cache hit rate", hitRate === null ? "—" : hitPct(hitRate), cacheLeftOut(l) || t("of the prompt"));
const card = el("div", "pu-card");
const head = el("div", "led-bar");
@@ -19162,7 +19164,7 @@ function drawLedRank(box, l, split, metric, picked, choose, compact) {
if (metric === "traffic") more.push("↑ " + fmtBytes(x.up_bytes || 0) + " · ↓ " + fmtBytes(x.down_bytes || 0));
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, prov));
if (metric !== "cost" && x.cost) more.push(fmtCost(x, prov));
if (x.credited) more.push(ledCredits(x));
// how fast its replies came, beside what they cost (#860)
if (metric !== "speed" && gs) more.push(Object.assign(el("span", "rk-speed", gs.text), { title: gs.title }));
@@ -4253,7 +4253,7 @@ function routingPage(part) {
function routeCost(r) {
const credits = routeCredits([r]);
if (!r.priced) return credits || "—";
return "≈" + fmtCost({ cost: r.cost || 0, unpriced: 0 }, routeProvider(r)) + (r.unpriced ? "+" : "") + (credits ? " · " + credits : "");
return fmtCost({ cost: r.cost || 0, unpriced: 0 }, routeProvider(r)) + (r.unpriced ? "+" : "") + (credits ? " · " + credits : "");
}
// byKey: grouped by the gateway key each came with, one sent with none
// (from this computer, or kept before routes named their key) a group of
@@ -4349,7 +4349,7 @@ function routingPage(part) {
const metaSig = JSON.stringify([bits, tokenHelp, meta.map((e) => [e.textContent, e.title])]);
if (x.meta.dataset.sig !== metaSig) { x.meta.replaceChildren(...meta); x.meta.dataset.sig = metaSig; }
const credits = routeCredits(g.rows);
setText(x.cost, [total.priced ? "≈" + fmtCost({ cost: total.cost, unpriced: 0 }) + (total.unpriced ? "+" : "") : "", credits].filter(Boolean).join(" · "));
setText(x.cost, [total.priced ? fmtCost({ cost: total.cost, unpriced: 0 }) + (total.unpriced ? "+" : "") : "", credits].filter(Boolean).join(" · "));
x.cost.hidden = !visibleMetrics.includes("cost") || !total.priced && !credits;
x.cost.title = [total.priced ? costNote() : "", credits ? t("What {n} of these requests cost in their plan's credits, as the replies said", { n: g.rows.filter((r) => routeCredits([r])).length }) : ""].filter(Boolean).join("\n");
x.b.setAttribute("aria-expanded", String(open));
+20 -17
View File
@@ -566,7 +566,7 @@ function costHead(c, note, title) {
cost.replaceChildren();
cost.title = "";
if (!c && !note) return;
if (c) cost.append(el("b", "", "≈" + c));
if (c) cost.append(el("b", "", c));
cost.append(el("span", note ? "unpriced" : "", note || t("effective prices")));
cost.title = title;
}
@@ -848,12 +848,15 @@ function usageTokensPick() {
// holdsLine: a window's whole (WindowHolds), how in its tooltip. With a
// baseCost (#5861, no long-context premium) its figure switches every card.
let holdsBase = kept("holdsBase", false);
// an estimate's cost, whole from 100 up: its cents would claim a precision
// the estimate hasn't
const wholeCost = (c, prov) => fmtCost({ cost: c }, prov).replace(/\d{3,}\.\d+/, (n) => Math.round(n));
function holdsCostText(h, prov) {
const c = fmtCost({ cost: holdsBase ? h.baseCost : h.cost }, prov);
const c = wholeCost(holdsBase ? h.baseCost : h.cost, prov);
return holdsBase ? t("≈ {cost} base", { cost: c }) : t("≈ {cost} API", { cost: c });
}
function holdsLine(h, prov) {
const cost = (c) => fmtCost({ cost: c }, prov);
const cost = (c) => wholeCost(c, prov);
const line = el("span", "quota-holds");
const r = h.routed || {};
// with the tokens tiles' "with cache" pick, the cache's tokens, read and
@@ -1019,7 +1022,7 @@ function renderUsage() {
out.style.height = (100 * p.output / peak).toFixed(1) + "%";
b.append(out, inp);
const when = u.bucket === "hour" ? `${p.label}:00` : u.bucket === "week" ? t("week of {label}", { label: dayOf(p) }) : dayOf(p);
b.title = p.calls ? t(p.calls === 1 ? "{when} · {tokens} tokens · {n} call" : "{when} · {tokens} tokens · {n} calls", { when, tokens: fmtN(usageTokens(p)), n: p.calls }) + (fmtCost(p) ? " · ≈" + fmtCost(p) : "") : t("{when} · nothing", { when });
b.title = p.calls ? t(p.calls === 1 ? "{when} · {tokens} tokens · {n} call" : "{when} · {tokens} tokens · {n} calls", { when, tokens: fmtN(usageTokens(p)), n: p.calls }) + (fmtCost(p) ? " · " + fmtCost(p) : "") : t("{when} · nothing", { when });
bars.append(b);
const last = i === n - 1 && (n - 1) % every >= every / 2;
labels.append(el("span", "", i % every === 0 || last ? dayOf(p) : ""));
@@ -1085,7 +1088,7 @@ function renderUsage() {
const hit = g.cache_read && hitRate !== null ? " · " + t("hit rate {p}", { p: hitPct(hitRate) }) : "";
num.append(el("b", "", fmtN(usageTokens(g))), el("small", "", t("{a} in · {b} out", { a: fmtN(g.input), b: fmtN(g.output) }) + (g.cache_read ? " · " + t("{n} cached", { n: fmtN(g.cache_read) }) : "") + hit));
r.append(num);
r.append(el("div", "cost", fmtCost(g, g.provider) ? "≈" + fmtCost(g, g.provider) : ""));
r.append(el("div", "cost", fmtCost(g, g.provider) || ""));
if (act) act(r, g);
return r;
};
@@ -2143,7 +2146,7 @@ function ledDetail(r) {
if (r.in || r.out || r.cache_read || r.cache_write || !ledFailed_(r)) {
add("Tokens", t("{i} in · {o} out · {r} cache read · {w} cache creation", { i: ledNum(r.in || 0), o: ledNum(r.out || 0), r: ledNum(r.cache_read || 0), w: ledNum(r.cache_write || 0) }) + cacheTTLs(r, ledNum) + (r.cache_unknown ? " · " + t("The vendor doesn't count the cache") : ""), "led-tokens");
}
if (r.priced) add("Cost", "≈" + fmtCost({ cost: r.cost, unpriced: 0 }, r.provider));
if (r.priced) add("Cost", fmtCost({ cost: r.cost, unpriced: 0 }, r.provider));
if (r.credits != null) add("Credits", ledCredits({ credits: r.credits, credited: 1 }).textContent);
if (ledRowSpeed(r)) add("Speed", t("{n} tok/s", { n: ledNum(Math.round(ledRowSpeed(r))) }));
else if (ledFloorSpeed(r)) add("Speed", "≥" + t("{n} tok/s", { n: ledNum(Math.round(ledFloorSpeed(r))) }));
@@ -2601,8 +2604,8 @@ function renderLedgerDash(l) {
const c = fmtCost(l, l.provider);
// the count in the words the quick panel uses too, the whole sentence on
// hover (tenacious_eagle on Discord)
block("Cost", c ? "≈" + c : "—", line(l.unpriced ? unpricedCalls(l.unpriced) : t("effective prices")), c ? "cost" : "", l.unpriced ? unpricedCallsWhy(l.unpriced) : "");
const hit = block("Cache hit rate", rate === null ? "—" : hitPct(rate, 1), cacheLeftOut(l) ? line(cacheLeftOut(l)) : null, "", t("The share of the prompt read from the cache"));
block("Cost", c || "—", line(l.unpriced ? unpricedCalls(l.unpriced) : t("effective prices")), c ? "cost" : "", l.unpriced ? unpricedCallsWhy(l.unpriced) : "");
const hit = block("Cache hit rate", rate === null ? "—" : hitPct(rate, 2), cacheLeftOut(l) ? line(cacheLeftOut(l)) : null, "", t("The share of the prompt read from the cache"));
const meter = el("div", "meter"), fill = el("i");
fill.style.width = (100 * (rate || 0)).toFixed(1) + "%";
meter.append(fill);
@@ -2880,7 +2883,7 @@ function ledHeatTip(x) {
const parts = [t("{n} tokens", { n: fmtN(x.tokens) }), t(x.calls === 1 ? "{n} request" : "{n} requests", { n: ledNum(x.calls) })];
// of one provider's calls, while the filters keep only its
const c = fmtCost(x, new URLSearchParams(ledHeat?.want).get("provider") || "");
if (c) parts.push("≈" + c);
if (c) parts.push(c);
const order = { tokens: 0, calls: 1, cost: 2 }[ledHeatMetric];
if (order && parts[order]) parts.unshift(...parts.splice(order, 1)); // the metric shown first
tip.append(el("span", "", parts.join(" · ")));
@@ -3621,7 +3624,7 @@ function renderLedger() {
// (jiabubu on Discord): in place of the dash a plan's model has for a
// price, or under the price; a reply that said none says nothing
const credits = r.credits != null ? ledCredits({ credits: r.credits, credited: 1 }).textContent : "";
const cost = td(r.priced ? "≈" + fmtCost({ cost: r.cost, unpriced: 0 }, r.provider) : credits || "—", "n cost" + (r.priced || credits ? "" : " faint"), r.priced ? (r.pricing_model ? t("API price reference") + ": " + r.pricing_model : "") : credits ? t("What it cost in its plan's credits, as the reply said") : t("No known price for this model"));
const cost = td(r.priced ? fmtCost({ cost: r.cost, unpriced: 0 }, r.provider) : credits || "—", "n cost" + (r.priced || credits ? "" : " faint"), r.priced ? (r.pricing_model ? t("API price reference") + ": " + r.pricing_model : "") : credits ? t("What it cost in its plan's credits, as the reply said") : t("No known price for this model"));
if (r.priced && r.pricing_model) {
const reference = el("div", "price-reference", t("Price reference: {model}", { model: r.pricing_model }));
reference.title = t("Model used for the API price estimate; this is not an observed model forwarding event.");
@@ -3810,7 +3813,7 @@ function sessUsageDetail(d, s, line) {
for (const x of s.models) {
m.append(el("span", "model", x.model || t("a model with no name")),
el("span", "n", t("{a} in · {b} out", { a: fmtN(x.input), b: fmtN(x.output) }) + (x.cache_read ? " · " + t("{n} cached", { n: fmtN(x.cache_read) }) : "") + (x.cache_write ? " · " + t("{n} written", { n: fmtN(x.cache_write) }) : "")),
el("span", "c" + (x.priced ? "" : " none"), x.priced ? "≈" + fmtCost({ cost: x.cost }) : "—"));
el("span", "c" + (x.priced ? "" : " none"), x.priced ? fmtCost({ cost: x.cost }) : "—"));
}
d.append(m);
}
@@ -4250,7 +4253,7 @@ const sessTokens = (s) => usageTokens(s);
// a session's cost: "—" when none of its models has a known price
function sessCost(s) {
if (!s.models.some((m) => m.priced && (m.input || m.output || m.cache_read || m.cache_write))) return "—";
return "≈" + fmtCost({ cost: s.cost, unpriced: s.unpriced });
return fmtCost({ cost: s.cost, unpriced: s.unpriced });
}
// the range picker, in the page's head where the Overview's period is
function renderSessRange(loading) {
@@ -4419,7 +4422,7 @@ function renderSessions() {
t("Tokens in and out per session: the middle session's, and what nine in ten stay under"), stale ? "stale" : "");
// counted as the Overview's tokens tile is, by the same pick (#2591)
tile(fmtN(usageTokens(tot)), usageTokensPick(), [t("{a} in · {b} out", { a: fmtN(tot.input), b: fmtN(tot.output) }), ...(usageWithCache && cacheOf(tot) ? [t("{a} cache", { a: fmtN(cacheOf(tot)) })] : [])]);
tile(c ? "≈" + c : "—", t("cost"), unpricedModels || t("at effective prices"), unpricedNote);
tile(c || "—", t("cost"), unpricedModels || t("at effective prices"), unpricedNote);
// input leaves out what was read from the cache and written to it
const prompt = tot.input + tot.cache_read + tot.cache_write;
tile(fmtN(tot.cache_read), t("cache read"), tot.cache_read && prompt ? t("hit rate {p}", { p: hitPct(tot.cache_read / prompt) }) : "", tot.cache_write ? t("{n} written", { n: fmtN(tot.cache_write) }) : "");
@@ -4563,9 +4566,9 @@ function renderSessChart(chart, st, used, ov, acts) {
const metric = off[sessMetric] ? "tokens" : sessMetric;
const value = (x) => metric === "cost" ? x.cost : metric === "sessions" ? x.sessions : metric === "messages" ? x.messages :
metric === "active" ? x.active : metric === "output" ? x.output : usageTokens(x);
const show = (v) => metric === "cost" ? "≈" + fmtCost({ cost: v }) : metric === "active" ? fmtDur(v) : fmtN(v);
const show = (v) => metric === "cost" ? fmtCost({ cost: v }) : metric === "active" ? fmtDur(v) : fmtN(v);
const tip = (x, when) => {
const parts = [usageTokens(x) ? t("{n} tokens", { n: fmtN(usageTokens(x)) }) : "", x.cost && fmtCost(x) ? "≈" + fmtCost(x) : "",
const parts = [usageTokens(x) ? t("{n} tokens", { n: fmtN(usageTokens(x)) }) : "", x.cost && fmtCost(x) || "",
x.messages ? t(x.messages === 1 ? "{n} message" : "{n} messages", { n: fmtN(x.messages) }) : "",
x.sessions ? t(x.sessions === 1 ? "{n} session" : "{n} sessions", { n: x.sessions }) : "", x.active ? t("{d} active", { d: fmtDur(x.active) }) : ""].filter(Boolean);
return parts.length ? when + " · " + parts.join(" · ") : t("{when} · nothing", { when });
@@ -4838,7 +4841,7 @@ function renderSessTop() {
who.append(sub);
r.append(who);
const fc = fmtCost({ cost: s.cost, unpriced: !s.priced });
const v = sessTopBy === "cost" ? (fc ? "≈" + fc : "—") : sessTopBy === "active" ? fmtDur(s.active) : fmtN(usageTokens(s));
const v = sessTopBy === "cost" ? (fc || "—") : sessTopBy === "active" ? fmtDur(s.active) : fmtN(usageTokens(s));
r.append(el("div", "v", v));
r.onclick = () => {
if (window.getSelection()?.toString()) return;
@@ -5084,7 +5087,7 @@ function sessBars(box, title, items, cur, choose, name, menu) {
fill.style.width = Math.max(1.5, 100 * x.n / peak).toFixed(1) + "%";
track.append(fill);
const fc = x.cost ? fmtCost(x) : "";
r.append(el("span", "n", name(x.v)), track, el("span", "v", fmtN(x.n)), el("span", "c", fc ? "≈" + fc : ""));
r.append(el("span", "n", name(x.v)), track, el("span", "v", fmtN(x.n)), el("span", "c", fc || ""));
r.onclick = () => choose(x.v === cur ? "" : x.v);
// a model's bar: its price, on a right-click
if (menu) r.oncontextmenu = (e) => { e.preventDefault(); menu(r, x.v); };
+1 -1
View File
@@ -133,7 +133,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
await page.locator("#usageKeys .row").first().waitFor();
assert.deepEqual(await page.locator("#usageKeys .name").allTextContents(), ["Server", "Laptop"]);
assert.deepEqual(await page.locator("#usageKeys .num b").allTextContents(), ["2.2K", "1.1K"]);
assert.deepEqual(await page.locator("#usageKeys .cost").allTextContents(), ["≈$0.400", "≈$0.200"]);
assert.deepEqual(await page.locator("#usageKeys .cost").allTextContents(), ["$0.400", "$0.200"]);
assert(!/Workspace|Personal/.test(await page.locator("#usageKeys").textContent()));
await page.locator(":is(#usageTab .opt, .nav-s):visible").nth(1).click();
await page.locator(".led tbody tr").first().waitFor();
+15 -15
View File
@@ -119,9 +119,9 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
// dollars everywhere by default
await page.goto("http://magpie.test/?view=usage");
await page.locator("#usageModels .row").first().waitFor();
assert.equal(await totalCost(page), "≈$3.00");
assert.equal(await modelCost(page, "deepseek-chat"), "≈$1.00");
assert.equal(await modelCost(page, "gpt-5"), "≈$2.00");
assert.equal(await totalCost(page), "$3.00");
assert.equal(await modelCost(page, "deepseek-chat"), "$1.00");
assert.equal(await modelCost(page, "gpt-5"), "$2.00");
// Settings: the third choice, and no "Totals in" row until it is picked
await toSettings(page);
@@ -145,9 +145,9 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
// Usage: DeepSeek in yuan (1 × 7.2), OpenAI and the total in dollars
await toUsage(page);
assert.equal(await modelCost(page, "deepseek-chat"), "≈¥7.20");
assert.equal(await modelCost(page, "gpt-5"), "≈$2.00");
assert.equal(await totalCost(page), "≈$3.00");
assert.equal(await modelCost(page, "deepseek-chat"), "¥7.20");
assert.equal(await modelCost(page, "gpt-5"), "$2.00");
assert.equal(await totalCost(page), "$3.00");
// totals in yuan: the sum goes ¥, each provider keeps its own
await toSettings(page);
@@ -157,9 +157,9 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.equal(saved.at(-1).totalCurrency, "cny");
assert.equal(saved.at(-1).currency, "provider", "picking the totals' currency keeps By provider");
await toUsage(page);
assert.equal(await totalCost(page), "≈¥21.60");
assert.equal(await modelCost(page, "deepseek-chat"), "≈¥7.20");
assert.equal(await modelCost(page, "gpt-5"), "≈$2.00");
assert.equal(await totalCost(page), "¥21.60");
assert.equal(await modelCost(page, "deepseek-chat"), "¥7.20");
assert.equal(await modelCost(page, "gpt-5"), "$2.00");
// the menu bar's currency, set apart from the totals' (onkashiko's
// second ask): folded under Advanced, closed while unset
@@ -183,15 +183,15 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.equal(saved.at(-1).totalCurrency, "cny", "the menu bar's pick leaves the totals'");
assert.equal(saved.at(-1).currency, "provider");
await toUsage(page);
assert.equal(await totalCost(page), "≈¥21.60", "the menu bar's pick leaves the Usage page's totals");
assert.equal(await totalCost(page), "¥21.60", "the menu bar's pick leaves the Usage page's totals");
// after a restart, straight onto Usage: the same
await page.reload();
await page.locator("#usageModels .row").first().waitFor();
await page.waitForTimeout(200);
assert.equal(await totalCost(page), "≈¥21.60");
assert.equal(await modelCost(page, "deepseek-chat"), "≈¥7.20");
assert.equal(await modelCost(page, "gpt-5"), "≈$2.00");
assert.equal(await totalCost(page), "¥21.60");
assert.equal(await modelCost(page, "deepseek-chat"), "¥7.20");
assert.equal(await modelCost(page, "gpt-5"), "$2.00");
// a set menu bar currency opens Advanced, so it is seen
await toSettings(page);
@@ -203,8 +203,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
await page.locator("#currencySegs .opt").nth(0).click();
await page.locator("#totalCurrencyRow").waitFor({ state: "hidden" });
await toUsage(page);
assert.equal(await modelCost(page, "deepseek-chat"), "≈$1.00");
assert.equal(await totalCost(page), "≈$3.00");
assert.equal(await modelCost(page, "deepseek-chat"), "$1.00");
assert.equal(await totalCost(page), "$3.00");
assert.deepEqual(errors, []);
await context.close();
+4 -4
View File
@@ -92,7 +92,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
// the Usage page shows $ by default
await page.goto("http://magpie.test/?view=usage");
await page.locator("#usageCost b").waitFor();
assert.equal((await page.locator("#usageCost b").textContent()).trim(), "≈$12.34", "usd is the default");
assert.equal((await page.locator("#usageCost b").textContent()).trim(), "$12.34", "usd is the default");
// Settings: the currency row, its rate in the tooltip
await page.locator("#prefs").click();
@@ -138,7 +138,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
// the Usage page now shows ¥, at the fixed rate (12.34 * 7.2)
await page.locator('[data-view="usage"]').click();
await page.waitForTimeout(200);
assert.equal((await page.locator("#usageCost b").textContent()).trim(), "≈¥88.85");
assert.equal((await page.locator("#usageCost b").textContent()).trim(), "¥88.85");
// and back to Settings, ¥ CNY is still picked after a reload
await page.reload();
@@ -189,7 +189,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
// no visit to Settings first: the Usage page at start is in ¥
await page.goto("http://magpie.test/?view=usage");
await page.locator("#usageCost b").waitFor();
assert.equal((await page.locator("#usageCost b").textContent()).trim(), "≈¥88.85", "cny at the rate state gave");
assert.equal((await page.locator("#usageCost b").textContent()).trim(), "¥88.85", "cny at the rate state gave");
// Settings agrees
await page.locator("#prefs").click();
@@ -200,7 +200,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
// and back on Usage, still ¥
await page.locator('[data-view="usage"]').click();
await page.waitForTimeout(200);
assert.equal((await page.locator("#usageCost b").textContent()).trim(), "≈¥88.85");
assert.equal((await page.locator("#usageCost b").textContent()).trim(), "¥88.85");
assert.deepEqual(errors, []);
await context.close();
@@ -109,7 +109,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
const tiles = await p.locator(".kpi").allTextContents();
assert(tiles.some((x) => x.includes(r90)), tiles.join(" | "));
// the requests: 90.0% with one left out, and the Kiro call's cache
// the requests: 90.00% with one left out, and the Kiro call's cache
// cells say nothing counted rather than 0
await p.locator(":is(#usageTab .opt, .nav-s):visible").nth(1).click();
const rows = p.locator(".led tbody tr.led-row");
@@ -119,7 +119,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
return b && { v: b.querySelector(".v").textContent, sub: b.querySelector(".sub")?.textContent || "" };
}, await say("Cache hit rate"));
assert(card, "a Cache hit rate card");
assert.equal(card.v, "90.0%");
assert.equal(card.v, "90.00%");
assert.equal(card.sub, leftOut);
const cells = await p.locator(".led").evaluate((tb, [w, r]) => {
const heads = [...tb.tHead.rows[0].cells].map((c) => c.textContent);
+1 -1
View File
@@ -252,7 +252,7 @@ async function usageFits(page) {
return bad;
});
assert.deepEqual(bad, []);
for (const selector of ["#usageAgents .cost", "#usageModels .cost"]) assert.match(await page.locator(selector).first().textContent(), /≈\$12\.34/);
for (const selector of ["#usageAgents .cost", "#usageModels .cost"]) assert.match(await page.locator(selector).first().textContent(), /^\$12\.34$/);
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
@@ -87,7 +87,7 @@ const BROWSERS = process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "web
// each ranked row's name and value
const rankOf = (p, box) => p.locator(box + " button.rk").evaluateAll((rs) => Object.fromEntries(rs.map((r) => [r.querySelector(".rk-nm").textContent, r.querySelector(".rk-val").textContent])));
// each ranked row's name and the cost in its second line (by tokens)
const subOf = (p, box) => p.locator(box + " button.rk").evaluateAll((rs) => Object.fromEntries(rs.map((r) => [r.querySelector(".rk-nm").textContent, (r.querySelector(".rk-b").textContent.match(/≈([$¥][\d.]+)/) || [])[1]])));
const subOf = (p, box) => p.locator(box + " button.rk").evaluateAll((rs) => Object.fromEntries(rs.map((r) => [r.querySelector(".rk-nm").textContent, (r.querySelector(".rk-b").textContent.match(/([$¥][\d.]+)/) || [])[1]])));
const axisOf = (p, box) => p.locator(box + " svg text.axis").first().textContent();
// the chart's tooltip over the one busy hour: each row's name and value, the total's last
async function tipOf(p, box) {
@@ -122,7 +122,7 @@ for (const engine of BROWSERS) {
// by tokens: each provider's cost under it, in what it sells in
assert.deepEqual(await subOf(p, box), { DeepSeek: "¥7.20", OpenAI: "$2.00", SiliconFlow: "¥3.60" }, `${width}px`);
// the total across them in the Totals in currency, dollars
assert.equal(await p.locator(box + " .pu-tot .v.cost").textContent(), "≈$3.50");
assert.equal(await p.locator(box + " .pu-tot .v.cost").textContent(), "$3.50");
// by cost: the ranking's figures too; the axis is a sum, in dollars
await p.locator(box + " .pu-card .led-bar .segs:not(.pu-split) .opt").nth(1).click();
@@ -144,7 +144,7 @@ for (const engine of BROWSERS) {
await p.locator(box + " .led-rank .rk", { hasText: "DeepSeek" }).click();
await p.waitForFunction(() => document.querySelector("#panelUsage .rk-nm")?.textContent === "deepseek-v4" && !document.querySelector("#panelUsage.pu-loading"));
assert.equal(asked.at(-1).get("provider"), "deepseek");
assert.equal(await p.locator(box + " .pu-tot .v.cost").textContent(), "≈¥7.20");
assert.equal(await p.locator(box + " .pu-tot .v.cost").textContent(), "¥7.20");
assert.deepEqual(await rankOf(p, box), { "deepseek-v4": "¥7.20" });
assert.match(await axisOf(p, box), /^¥/);
@@ -194,7 +194,7 @@ for (const engine of BROWSERS) {
// OpenAI picked: the whole page is its calls, in dollars
await p.locator("#ledSplit .opt").nth(2).click();
await p.locator(box + " button.rk", { hasText: "OpenAI" }).click();
await p.waitForFunction(() => document.querySelector("#usageCost b")?.textContent === "≈$2.00");
await p.waitForFunction(() => document.querySelector("#usageCost b")?.textContent === "$2.00");
assert.equal(asked.at(-1).get("provider"), "openai");
await p.waitForFunction(() => /^\$/.test(document.querySelector("#ledChart svg text.axis")?.textContent || ""));
assert.deepEqual(errors, []);
+10 -10
View File
@@ -1,7 +1,7 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// The tray panel follows Settings' units (blrbrzkj on Discord, two
// screenshots: Settings said ¥ 人民币 and 中文(万 / 亿), the panel's Usage
// tab still ≈$7.18 and 16M). The panel is open on its Usage tab while
// tab still $7.18 and 16M). The panel is open on its Usage tab while
// Settings, in the window, picks another currency and number units; when
// the panel is shown again it reads the settings again, and its cost, its
// counts and its chart's axis say what was picked, not what was picked
@@ -105,14 +105,14 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
await p.locator("#panelUsage .pu-card .led-chart svg").waitFor();
let s = await shown(p);
assert.equal(s.tokens, "1.54B", lang + ": K/M/B at first");
assert.equal(s.cost, "≈$26.40", lang + ": $ at first");
assert.equal(s.cost, "$26.40", lang + ": $ at first");
// Settings, in the window, picks ¥ and 万 / 亿
store.cur = { ...store.cur, currency: "cny", chineseUnits: true };
await hideAndShow(p, store);
await p.waitForFunction(() => /¥/.test(document.querySelectorAll("#panelUsage .pu-tot .blk .v")[2]?.textContent || ""), null, { timeout: 3000 }).catch(() => {});
s = await shown(p);
assert.equal(s.cost, "≈¥185", lang + ": the cost in yuan once Settings picks ¥, got " + s.cost);
assert.equal(s.cost, "¥184.80", lang + ": the cost in yuan once Settings picks ¥, got " + s.cost);
if (chinese) {
assert.equal(s.tokens, "15.4 " + (lang === "zh" ? "亿" : "億"), lang + ": the tokens in 万/亿, got " + s.tokens);
assert(s.axis.some((x) => /万|萬/.test(x)), lang + ": the chart's axis in 万, got " + s.axis);
@@ -125,7 +125,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
await hideAndShow(p, store);
await p.waitForFunction(() => /\$/.test(document.querySelectorAll("#panelUsage .pu-tot .blk .v")[2]?.textContent || ""), null, { timeout: 3000 }).catch(() => {});
s = await shown(p);
assert.equal(s.cost, "≈$26.40", lang + ": back in dollars, got " + s.cost);
assert.equal(s.cost, "$26.40", lang + ": back in dollars, got " + s.cost);
assert.equal(s.tokens, "1.54B", lang + ": back in K/M/B, got " + s.tokens);
assert(!s.axis.some((x) => /万|萬|亿|億/.test(x)), lang + ": the axis back in K/M/B, got " + s.axis);
assert.deepEqual(errors, []);
@@ -136,7 +136,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
}
// The currency alone (dLdgKyRd on Discord, v0.1.3025: the panel's Usage tab
// ≈$12.36 while the Usage page said ≈¥82.61). The test above picks ¥ and
// $12.36 while the Usage page said ¥82.61). The test above picks ¥ and
// 万 / 亿 together, and the units' change redrew the panel while the
// currency's alone didn't; nor was a panel drawn before the state came
// ever redrawn. Each way the panel gets its currency: its first open, with
@@ -180,7 +180,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
await o.p.locator("#panelUsage .pu-card .led-chart svg").waitFor();
for (let i = 0; i < 100 && store.stateReads === 0; i++) await o.p.waitForTimeout(20);
await o.p.waitForTimeout(500); // the state is in
await costBecomes(o.p, "≈¥185", lang + ": first open, the state after the usage");
await costBecomes(o.p, "¥184.80", lang + ": first open, the state after the usage");
assert.deepEqual(o.errors, []);
await o.ctx.close();
@@ -188,15 +188,15 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
store = { cur: { ...units, currency: "usd" }, stateReads: 0 };
o = await openPanel(browser, lang, store, width, "stats");
await o.p.locator("#panelUsage .pu-card .led-chart svg").waitFor();
await costBecomes(o.p, "≈$26.40", lang + ": $ at first");
await costBecomes(o.p, "$26.40", lang + ": $ at first");
store.cur = { ...store.cur, currency: "cny" };
await hideAndShow(o.p, store);
await costBecomes(o.p, "≈¥185", lang + ": reopened after ¥ was picked alone");
await costBecomes(o.p, "¥184.80", lang + ": reopened after ¥ was picked alone");
store.cur = { ...store.cur, currency: "usd" };
const before = store.stateReads;
await o.p.evaluate(() => window.dispatchEvent(new Event("focus")));
for (let i = 0; i < 100 && store.stateReads === before; i++) await o.p.waitForTimeout(20);
await costBecomes(o.p, "≈$26.40", lang + ": focused after $ was picked again");
await costBecomes(o.p, "$26.40", lang + ": focused after $ was picked again");
assert.deepEqual(o.errors, []);
await o.ctx.close();
@@ -209,7 +209,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
await o.p.waitForTimeout(100);
await o.p.locator('[data-ptab="stats"]').click();
await o.p.locator("#panelUsage .pu-card .led-chart svg").waitFor();
await costBecomes(o.p, "≈¥185", lang + ": its Usage tab picked after ¥");
await costBecomes(o.p, "¥184.80", lang + ": its Usage tab picked after ¥");
assert.deepEqual(o.errors, []);
await o.ctx.close();
});
+2 -2
View File
@@ -81,7 +81,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
// newest first: none said, priced and said, then the two credited alone
const cost = (i) => rows.nth(i).locator(".cost-metric");
assert.equal(await cost(0).count(), 0, "a reply that said no credits and has no price shows no cost, as before");
assert.equal(await cost(1).locator(".v").textContent(), `≈$0.010 · ${w.n(num(lang, 2))}`);
assert.equal(await cost(1).locator(".v").textContent(), `$0.010 · ${w.n(num(lang, 2))}`);
assert.equal(await cost(2).locator(".v").textContent(), w.n(num(lang, 0.25)), "no known price: the credits alone, never a dash");
assert.equal(await cost(3).locator(".v").textContent(), w.n(num(lang, 1.5)));
assert.match(await cost(3).getAttribute("title"), w.one);
@@ -96,7 +96,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.equal(await sum.isVisible(), true, "a session of credits alone shows them");
assert.equal(await sum.textContent(), w.n(num(lang, 1.75)));
assert.match(await sum.getAttribute("title"), w.some);
assert.equal(await group("s-priced").locator(".cost").textContent(), `≈$0.010 · ${w.n(num(lang, 2))}`);
assert.equal(await group("s-priced").locator(".cost").textContent(), `$0.010 · ${w.n(num(lang, 2))}`);
assert.equal(await group("s-none").locator(".cost").isVisible(), false, "a session that said none reads as before");
const fit = await page.evaluate(() => ({ client: document.documentElement.clientWidth, scroll: document.documentElement.scrollWidth }));
@@ -86,7 +86,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.match(await rows.nth(0).locator(".speed .v").textContent(), lang === "zh" ? /^100 token\/秒$/ : /^100 tok\/s$/);
assert.match(await rows.nth(1).locator(".cache-hit .v").textContent(), /0%$/);
assert.match(await rows.nth(2).locator(".cache-hit .v").textContent(), /100%$/);
assert.equal(await rows.nth(1).locator(".cost").textContent(), "≈$0.000", "known zero cost remains visible");
assert.equal(await rows.nth(1).locator(".cost").textContent(), "$0.000", "known zero cost remains visible");
assert.equal(await rows.nth(3).locator(".cache-hit").count(), 0, "legacy totals cannot establish a cache rate");
assert.equal(await rows.nth(4).locator(".cache-hit").count(), 0, "output is not part of the prompt");
for (const i of [5, 9, 10, 11]) assert.equal(await rows.nth(i).locator(".speed").count(), 0, `row ${i} has no output speed`);
+17 -17
View File
@@ -72,8 +72,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
const group = page.locator("button.rt-session").filter({ hasText: "Codex · conversation-a" });
assert.equal(await page.locator(".rt-session").count(), 4, "identical IDs from different agents must not merge");
assert.match(await group.locator(".summary").textContent(), lang === "zh" ? /3 个请求.*6.0k/ : /3 requests.*6.0k/);
assert.equal(await group.locator(".cost").textContent(), "≈$0.030+", "partial totals must be marked");
assert.equal(await page.locator("button.rt-session").filter({ hasText: "Claude Code" }).locator(".cost").textContent(), "≈$0.000", "zero price is known");
assert.equal(await group.locator(".cost").textContent(), "$0.030+", "partial totals must be marked");
assert.equal(await page.locator("button.rt-session").filter({ hasText: "Claude Code" }).locator(".cost").textContent(), "$0.000", "zero price is known");
assert.equal(await page.locator(".rt-session", { hasText: lang === "zh" ? "未提供会话标识" : "No session ID" }).locator(".cost").isVisible(), false, "unknown cost is omitted for legacy requests");
assert.equal(await page.locator(".rt-req").count(), 6);
@@ -86,13 +86,13 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
for (let i = 0; i < 50 && !feed.next; i++) await page.waitForTimeout(20);
assert(feed.next, "long poll started");
feed.next([req(7, "codex", "conversation-a", 0.01)]);
await page.waitForFunction(() => [...document.querySelectorAll("button.rt-session")].some((e) => e.textContent.includes("≈$0.040+")));
await page.waitForFunction(() => [...document.querySelectorAll("button.rt-session")].some((e) => e.textContent.includes("$0.040+")));
assert.equal(await group.getAttribute("aria-expanded"), "false");
assert(await group.evaluate((e, previous) => e === previous, handle), "live update replaced the heading");
// Currency changes redraw routing costs using the existing formatter.
await page.evaluate(() => { currency = "cny"; fx = { rate: 7, at: null, stale: false }; renderCosts(); });
assert.equal(await group.locator(".cost").textContent(), "≈¥0.280+");
assert.equal(await group.locator(".cost").textContent(), "¥0.280+");
await group.click();
assert.equal(await page.locator(".rt-req").count(), 7);
await page.locator(".rt-group-by button").first().click();
@@ -155,7 +155,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
const memoryName = lang === "zh" ? "后台记忆整理" : "Background memory task";
assert.equal(await group("memory-a").locator(".nm").textContent(), `Codex · ${memoryName}`);
assert.equal(await group("memory-b").locator(".nm").textContent(), `Codex · ${memoryName}`);
assert.equal(await group("memory-a").locator(".cost").textContent(), "≈$0.070");
assert.equal(await group("memory-a").locator(".cost").textContent(), "$0.070");
assert.match(await group("memory-a").locator(".summary").textContent(), lang === "zh" ? /2 个请求/ : /2 requests/);
assert.match(await group("memory-a").locator(".nm").getAttribute("title"), lang === "zh" ? /回答结束后.*继续/ : /continue after a chat finishes/);
assert.equal(await group("chat").locator(".nm").textContent(), "Codex · Chat title");
@@ -170,7 +170,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
for (let i = 0; i < 50 && !feed.next; i++) await page.waitForTimeout(20);
assert(feed.next, "long poll started");
feed.next([{ ...req(11, "codex", "memory-a", 0.01), kind: "memory_consolidation" }]);
await page.waitForFunction(() => [...document.querySelectorAll("button.rt-session .cost")].some((e) => e.textContent === "≈$0.080"));
await page.waitForFunction(() => [...document.querySelectorAll("button.rt-session .cost")].some((e) => e.textContent === "$0.080"));
assert.equal(await memory.getAttribute("aria-expanded"), "false");
assert(await memory.evaluate((e, previous) => e === previous, handle), "labeling must preserve the heading through live updates");
assert.equal(await group("memory-b").getAttribute("aria-expanded"), "true");
@@ -237,7 +237,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.match(tooltip, lang === "zh" ? /后台.*提示词建议.*安全检查/ : /suggested prompts.*in the background.*checked them for safety/);
assert(tooltip.endsWith((lang === "zh" ? "会话 ID" : "Session id") + ": " + id), "tooltip retains the group's own session ID");
}
assert.equal(await group("suggestions-a").locator(".cost").textContent(), "≈$0.030");
assert.equal(await group("suggestions-a").locator(".cost").textContent(), "$0.030");
assert.equal(await group("named-suggestions").locator(".nm").textContent(), "Codex · Named suggestions");
assert.equal(await group("mixed").locator(".nm").textContent(), "Codex · mixed");
assert.equal(await group("named-chat").locator(".nm").textContent(), "Codex · Chat title");
@@ -267,7 +267,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
await group.waitFor();
assert.equal(await page.locator(".rt-session").count(), 3);
assert.match(await group.locator(".summary").textContent(), /2 个请求/);
assert.equal(await group.locator(".cost").textContent(), "≈$0.042");
assert.equal(await group.locator(".cost").textContent(), "$0.042");
assert.equal(await page.locator(".rt-req .kind").filter({ hasText: "标题" }).count(), 2);
await group.click();
assert.equal(await page.locator(".rt-req").count(), 2, "only this parent and its title fold together");
@@ -280,7 +280,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.equal(await named.getAttribute("aria-expanded"), "false", "late title must not reset folding");
assert(await named.evaluate((e, previous) => e === previous, handle));
assert.match(await named.locator(".nm").getAttribute("title"), /main-a/);
assert.equal(await named.locator(".cost").textContent(), "≈$0.042");
assert.equal(await named.locator(".cost").textContent(), "$0.042");
assert.equal(await page.locator("button.rt-session").filter({ hasText: "main-b" }).count(), 1, "unknown names retain ID");
await page.waitForTimeout(50);
for (let i = 0; i < 50 && !feed.next; i++) await page.waitForTimeout(20);
@@ -345,17 +345,17 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
t.after(async () => { feed.next?.([]); await browser.close(); });
await page.goto("http://magpie.test/?view=routing");
await page.locator(".rt-req").nth(3).waitFor();
assert.equal(await page.locator(".rt-req").filter({ hasText: "model-a" }).locator(".cost").textContent(), "≈$0.000+", "a zero-priced attempt plus an unknown attempt retains its amount");
assert.equal(await page.locator(".rt-req").filter({ hasText: "model-a" }).locator(".cost").textContent(), "$0.000+", "a zero-priced attempt plus an unknown attempt retains its amount");
await page.locator(".rt-group-by button").nth(1).click();
const group = (name) => page.locator("button.rt-session").filter({ hasText: name });
assert.equal(await group("Codex · partial").locator(".cost").textContent(), "≈$0.000+");
assert.equal(await group("Codex · partial").locator(".cost").textContent(), "$0.000+");
assert.match(await group("Codex · partial").locator(".summary").textContent(), lang === "zh" ? /^1 个请求/ : /^1 request ·/);
assert.equal(await group("Codex · mixed").locator(".cost").textContent(), "≈$0.000+", "a free request plus an unknown request is a partial zero estimate");
assert.equal(await group("Codex · mixed").locator(".cost").textContent(), "$0.000+", "a free request plus an unknown request is a partial zero estimate");
assert.match(await group("Codex · mixed").locator(".summary").textContent(), lang === "zh" ? /^2 个请求/ : /^2 requests ·/);
assert.equal(await group("Claude Code · unknown").locator(".cost").isVisible(), false, "all unknown costs are omitted");
await page.evaluate(() => { currency = "cny"; fx = { rate: 7, at: null, stale: false }; renderCosts(); });
assert.equal(await group("Codex · mixed").locator(".cost").textContent(), "≈¥0.000+");
assert.equal(await page.locator(".rt-req").filter({ hasText: "model-a" }).locator(".cost").textContent(), "≈¥0.000+");
assert.equal(await group("Codex · mixed").locator(".cost").textContent(), "¥0.000+");
assert.equal(await page.locator(".rt-req").filter({ hasText: "model-a" }).locator(".cost").textContent(), "¥0.000+");
});
}
}
@@ -401,7 +401,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.equal(await group(title.session).count(), 0);
assert.equal(await parent.locator(".nm").textContent(), "Codex · 完成标题关联测试");
if (main.priced && title.priced) {
const cost = await page.evaluate((amount) => "≈" + fmtCost({ cost: amount, unpriced: 0 }), main.cost + title.cost);
const cost = await page.evaluate((amount) => fmtCost({ cost: amount, unpriced: 0 }), main.cost + title.cost);
assert.equal(await parent.locator(".cost").textContent(), cost, "helper cost joins the original chat total");
}
assert.match(await parent.locator(".summary").textContent(), lang === "zh" ? /2 个请求/ : /2 requests/);
@@ -482,7 +482,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.equal(await (await scrolledTo(mixed ? "chat-801" : "chat-1")).locator(".nm").textContent(), `Codex · Applied chat-${mixed ? 801 : 1}`);
await page.evaluate(() => { document.querySelector(".rt-reqs").scrollTop = 0; });
await page.waitForFunction(() => [...document.querySelectorAll(".rt-session .nm")].some((e) => e.textContent === "Codex · Applied opened-chat"));
assert.equal(await group("opened-chat").locator(".cost").textContent(), "≈$0.010");
assert.equal(await group("opened-chat").locator(".cost").textContent(), "$0.010");
const batches = titleRequests.filter((input) => input.day === day);
assert(batches.length > 0, "history refresh never ran");
assert(batches.every((input) => input.ids.length <= 2000 && input.routeIds.length <= 2000), "API batch exceeded the ID limit");
@@ -522,7 +522,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
for (let i = 0; i < 50 && !feed.next; i++) await page.waitForTimeout(20);
assert(feed.next, "long poll started");
feed.next([...fixture, req(4, "claude", uuid, 0.02)]);
await page.waitForFunction(() => [...document.querySelectorAll("button.rt-session")].some((e) => e.textContent.includes("≈$0.030")));
await page.waitForFunction(() => [...document.querySelectorAll("button.rt-session")].some((e) => e.textContent.includes("$0.030")));
assert.equal(await named.count(), 1, "a live update keeps the name");
assert.deepEqual(errors, []);
});
+1 -1
View File
@@ -88,7 +88,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.equal((await page.locator("#usageAccountsHead .label").textContent()).trim(), w.head);
assert.deepEqual(await page.locator("#usageAccounts .name").allTextContents(), ["a@example.com", "b@example.com", w.none, "a@example.com"]);
assert.deepEqual(await page.locator("#usageAccounts .sub").evaluateAll((s) => s.map((x) => x.textContent.split(" · ")[0])), ["Codex", "Codex", "Codex", "Claude"]);
assert.deepEqual(await page.locator("#usageAccounts .cost").allTextContents(), ["≈$3.75", "≈$2.50", "≈$2.50", "≈$1.25"]);
assert.deepEqual(await page.locator("#usageAccounts .cost").allTextContents(), ["$3.75", "$2.50", "$2.50", "$1.25"]);
// no coloured stripe down a row's side
assert(await page.locator("#usageAccounts .row").evaluateAll((rs) => rs.every((r) => parseFloat(getComputedStyle(r).borderLeftWidth) === 0)));
@@ -0,0 +1,100 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// shangyuan0818 on X: the Usage page's request costs all read "≈" with three
// decimals at most and none above $100, and the cache hit rate one decimal.
// A cost worked out from known prices is said as it is: no "≈", at least
// two decimals at any size ($123.46, not $123), a sub-cent one to its first
// two digits ($0.00042, not $0.000). The Requests head's cache hit rate has
// two decimals (87.65%). A sum missing some prices still ends in "+". In
// Chromium and WebKit, in every language; 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 reader = require("./reader.cjs");
const { chromium, webkit } = require("playwright");
const assets = path.resolve(__dirname, "../assets");
const now = Date.now();
const usage = { calls: 3, errors: 0, input: 1235, output: 57, cache_read: 8765, cache_write: 0, reasoning: 0, cost: 123.47, unpriced: 0, path: "/test/usage.jsonl", bucket: "day", agents: [], models: [], series: [] };
const req = (i, x) => ({
t: new Date(now - (i + 1) * 60e3).toISOString(), agent: "claude", agentName: "Claude Code", icon: "claudecode-color",
provider: "anthropic", providerName: "Anthropic", providerAccount: "a@example.com", req: "sonnet", model: "sonnet", served: "sonnet",
ms: 3000, status: 200, rid: "r-" + i, ep: "/v1/messages", priced: true, out: 19, in: 400, cache_read: 3000, cache_write: 0, ...x,
});
const ROWS = [req(0, { cost: 123.456 }), req(1, { cost: 0.00042 }), req(2, { cost: 0.0123 })];
const WANT = ["$123.46", "$0.00042", "$0.012"];
// 8765 of a 10000 prompt read: 87.65%
const page = (q) => ({ period: q.get("period"), rows: ROWS, offset: 0, total: ROWS.length, calls: 3, errors: 0, input: 1235, output: 57, cache_read: 8765, cache_write: 0, reasoning: 0, cost: 123.46842, unpriced: 0,
bucket: "day", series: [], by: { provider: [], agent: [], model: [] }, agents: [{ id: "claude", name: "Claude Code", icon: "claudecode-color" }] });
function serve(lang) {
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: [{ id: "codex", name: "Codex", path: "/test/config.toml", fields: [] }], profiles: [], settings: { lang, theme: "light" } });
if (url.pathname === "/api/gateway/trace") {
if (url.searchParams.get("wait")) await new Promise((r) => setTimeout(r, 20e3));
return json({ mine: true, now: new Date(now).toISOString(), seq: 1, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] });
}
if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] });
if (url.pathname === "/api/groups") return json({ groups: [], pools: [], models: [] });
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, calls: [], groups: [] } });
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname === "/api/usage/requests") return json(page(url.searchParams));
if (url.pathname === "/api/usage/requests/content") return json({ found: false, why: "read" });
if (url.pathname === "/api/usage/quotas") return json([]);
if (url.pathname === "/api/usage") return json(usage);
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/window/")) return route.fulfill({ status: 204 });
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 }); }
};
}
const LANGS = ["en", "zh", "zh-TW", "ja", "de"];
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(`${engine}: a priced request's cost is said as it is, two decimals at least`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
for (const lang of LANGS) {
await t.test(lang, async () => {
const context = await browser.newContext({ viewport: { width: 1600, height: 900 }, reducedMotion: "reduce" });
const errors = [];
try {
const p = await context.newPage();
p.setDefaultTimeout(5000);
p.setDefaultNavigationTimeout(60000);
p.on("pageerror", (e) => errors.push(e.message));
await p.route("**/*", serve(lang));
await p.goto("http://magpie.test/?view=usage&tab=requests");
const say = (s) => p.evaluate((s) => t(s), s);
const rows = p.locator(".led tbody tr.led-row");
await rows.nth(ROWS.length - 1).waitFor({ timeout: 15000 });
assert.deepEqual(await p.locator(".led tbody tr.led-row td.cost").allTextContents(), WANT);
// the head: the sum, and the hit rate to two decimals
const blk = (label) => p.locator("#ledKpi .blk").filter({ has: p.locator(".k", { hasText: label }) }).locator(".v");
assert.equal(await blk(await say("Cost")).textContent(), "$123.47");
assert.equal(await blk(await say("Cache hit rate")).textContent(), "87.65%");
// and the request's own page
const dt = (await reader.openRequest(p, rows.nth(0))).locator("dt", { hasText: await say("Cost") });
assert.equal(await dt.evaluate((d) => d.nextElementSibling.textContent), "$123.46");
await reader.closeRequest(p);
// the formatter at the edges: none is rounded away or to a bare dollar
assert.deepEqual(await p.evaluate(() => [0, 0.0004, 0.000012345, 0.5, 1, 99.999, 100, 2500.5].map((cost) => fmtCost({ cost }))),
["$0.000", "$0.00040", "$0.000012", "$0.500", "$1.00", "$100.00", "$100.00", "$2500.50"]);
assert.equal(await p.evaluate(() => wholeCost(1234.56)), "$1235", "an estimate stays whole");
assert.deepEqual(errors, []);
} finally {
await context.close();
}
});
}
});
}
@@ -158,7 +158,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.deepEqual(await p.locator("#ledKpi .k").allTextContents(), w.strip);
assert.equal(await p.locator("#ledKpi .blk").nth(0).getAttribute("title"), Math.round(allTokens).toLocaleString(lang === "zh" ? "zh-CN" : "en"));
const rate = TOTALS.cache_read / (TOTALS.input + TOTALS.cache_write + TOTALS.cache_read);
assert.equal(await p.locator("#ledKpi .blk").nth(3).locator(".v").textContent(), (100 * rate).toFixed(1) + "%");
assert.equal(await p.locator("#ledKpi .blk").nth(3).locator(".v").textContent(), (100 * rate).toFixed(2) + "%");
assert.equal(parseFloat(await p.locator("#ledKpi .blk").nth(3).locator(".meter i").evaluate((i) => i.style.width)), parseFloat((100 * rate).toFixed(1)));
assert.equal(await p.locator("#ledKpi .blk").nth(1).locator(".v").textContent(), String(TOTALS.calls));
+2 -2
View File
@@ -2,7 +2,7 @@
// Usage's sum at the head's right is never cut (#1599, sean908): in the
// window, between 640px and the width the tabs, the periods with Custom
// named and the refresh need, the sum was the one thing to give way, and
// ≈$0.001 read "≈$0.". At every width from a phone's to a wide window the
// $0.001 read "$0.". At every width from a phone's to a wide window the
// sum is whole and on the page, and the page never scrolls sideways.
// English, Chinese, Japanese and German, Chromium and WebKit; no backend,
// the API is faked here.
@@ -73,7 +73,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
if (!b) return JSON.stringify({ text: cost.textContent }); // redrawn: not a sum yet
const c = cost.getBoundingClientRect(), s = b.getBoundingClientRect();
const got = { head: cost.parentElement.className, text: b.textContent, sum: [s.left, s.right], box: [c.left, c.right], wide: document.documentElement.scrollWidth, inner: innerWidth };
const whole = got.text === "≈$0.001" && got.sum[1] <= got.box[1] + 0.5 && got.sum[0] >= got.box[0] - 0.5 && got.sum[1] <= got.inner && got.wide <= got.inner;
const whole = got.text === "$0.001" && got.sum[1] <= got.box[1] + 0.5 && got.sum[0] >= got.box[0] - 0.5 && got.sum[1] <= got.inner && got.wide <= got.inner;
return whole ? "" : JSON.stringify(got);
};
// the head is fitted a frame or two after a resize: given a few
@@ -128,7 +128,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.match(await page.locator("#usageCost").getAttribute("title"), /2/, "the tooltip says how many");
const tile = await page.locator("#stats .tile, #stats > *").evaluateAll((ts, n) => ts.some((x) => x.textContent.includes(n)), w.tile);
assert(tile, `the calls tile says "${w.tile}"`);
await sweep(page, "≈$0.001+", w.calls);
await sweep(page, "$0.001+", w.calls);
if (process.env.ARTIFACT_DIR) await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-unpriced-overview.png`) });
// nothing priced: no sum, and the count alone rather than nothing
@@ -138,7 +138,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
// Requests: the same count beside its sum; and with nothing priced
page = await open("requests", true);
await page.waitForFunction(() => document.querySelector("#usageCost b")?.textContent.includes("0.001"));
await sweep(page, "≈$0.001+", w.calls);
await sweep(page, "$0.001+", w.calls);
page = await open("requests", false);
await sweep(page, null, w.calls);
@@ -146,7 +146,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
page = await open("sessions", true);
await page.locator("#sessList .row.sess").first().waitFor();
await page.waitForFunction(() => document.querySelector("#usageCost b"));
await sweep(page, "≈$0.020+", w.models);
await sweep(page, "$0.020+", w.models);
assert.deepEqual(errors, []);
});
}