usage: the tray panel's and Requests' costs follow each provider's currency

onkashiko on X: with Currency set to By provider, the menu bar panel
still showed every cost in one currency; providers and models were not
each in their own. drawLedColumns and drawLedRank (shared by the tray
panel and the window's Requests tab) formatted every value with no
provider, so fmtCost fell back to the Totals in currency.

- usageapi.Ledger echoes the provider a page is filtered to
  (`provider`, omitempty).
- app.js: ledProv(l, split, id) names the provider of a value: the
  ledger's filter, the row's provider (provider split), the provider
  part of a modelAt id, or for a model split the provider(s) that served
  it when they all share a currency. ledFormat/ledFormatLong take it,
  so the rank's values and sub-lines, the tooltip's rows and the axis
  (when one provider is picked) are in that provider's currency. Sums
  (the panel total, the tooltip total, a model served in two currencies)
  stay in the Totals in currency.
- page.js: the Requests head and the cost head use the filter's
  provider; the heatmap tip too. Other fmtCost calls are sums or
  sessions with no provider and are unchanged.
- core script budget +491 (1,269,040 -> 1,269,531): drawLedColumns and
  drawLedRank are drawn by the panel, so there is no lazy page to move
  this to; packed to the shortest form.
- docs/subsystems/gui-shell.md says how By provider reaches the panel.

Run:
- At 065fb6a8b (rebased on 7d5475769), mote: gofmt clean;
  TestCoreScriptBudget and TestLedgerSaysItsOneProvider ok;
  panel-currency-provider.test.cjs 20/20 (chromium + webkit x en, zh,
  zh-TW, ja, de; panel 440/320px, window 1100/420px, no sideways
  scroll, no page errors).
- At ff3ab573d (same change on 90932ed1f), mica, under suite.lock:
  go vet darwin, linux nogui, windows ok; builds for all three ok;
  go test -tags nogui -count=1 -timeout 45m ./... : 99 packages ok,
  exit 0. mote: go test usageapi, gui, usage ok.
- GUI suite, the 155 files the change can reach, mote: 2581 tests, 105
  failures in 13 files; the same 13 files give 104 at 90932ed1f. The
  one extra is tray-cell-click webkit en, flaky on both trees run
  alone (head green twice, base red once). Filed: grip-inset,
  key-balance-card, panel-fold, tray-cell-click, usage-* (#6293,
  #6294, #6295, #6499, #6003, #5872, #6414, #5869, #5796, #5215,
  #4790); panel-shortcut's 20 reds newly filed as #6606.

Broken by hand:
- panel-currency-provider on the old assets (MAGPIE_ASSETS): 20/20 red,
  with the reporter's symptom (DeepSeek $1.00, SiliconFlow $0.500
  under By provider).
- TestLedgerSaysItsOneProvider red with `out.Provider = f.Provider`
  removed.

Not tried: the real app's tray panel with real yuan and dollar
providers.
This commit is contained in:
yetone
2026-11-14 12:42:46 +08:00
parent 7d5475769b
commit 27c998aba0
7 changed files with 284 additions and 15 deletions
+1 -1
View File
@@ -672,7 +672,7 @@ covers it in both engines, every language and a narrow window.
- The requests magpie makes by itself (a routing classifier's, a web search's, an image description's) are told apart from the agents' on the Usage page (#1839): magpie's row among the agents and its rows in the ledger carry a "magpie's own" mark (`ownBadge`), an account's, key's or model's row adds "{n} by magpie itself" from the summary's `own`, and an account's card says how many of the period's requests were magpie's own (`ownLine`, drawn again once the summary comes after the allowances). See `own-requests.test.cjs` and `TestSummaryCountsMagpiesOwnCallsApart`.
- The Usage page's Allowances head ends in a Settings › link (`#usageToSet`, wired in `plugins/usage/page.js`) to Settings › Allowances, where how the allowances show and their alerts are set (the scattered settings audit after netube99 on X); it lights the Allowance display row (`#quotaLeftRow`).
- Opening the allowances is asking to see them (#1588, `quotasOpened` in `app.js`): the Usage page from the nav or its Overview tab picked, the window brought back to the front on the Overview, the tray panel's Allowances tab picked or the panel brought up on it, and a menu bar cell clicked each load `usage/quotas?asked=1`, as Refresh now does. An asked read makes the backend read every account again (`AskClaudeUsage`), so an opening within 30s (`QUOTAS_OPEN_GAP`) of the last asked read sends an ordinary read instead, which joins one on its way; Refresh now always asks, with `&all=1` (`loadQuotas("all")`, `AskEveryClaudeUsage`), so saved Claude accounts are read again too, as their cards' refresh reads them (#5380); an opening's asked read on its way doesn't take its place. A panel page loaded while it is put away (hidden, or without focus) doesn't ask. The timed refresh is unchanged and never asks. See `allowance-open-read.test.cjs`.
- The menu bar can show magpie's own totals beside the allowances (#1984): `usage:today` and `usage:7d` in `settings.TrayUsages`, offered after the cards in the same picker. `trayUsageCards` sums them with `usage.QueryPage(p, Filter{}, 0, 1).Sum` (the Requests tab's and the panel's cached ledger sum, gateway and session-file calls together) and asks no vendor when only totals are picked; `trayTotalCard` makes every token (in, out and cache, as `allTokens`), marked `Σ` so it doesn't read as the input, over the cost in Settings' currency (with *By provider*, `settings.CurrencyByProvider`, in the currency picked for totals, `TotalCostIn`: a sum of every provider has no one currency of its own; Settings › Usage › Advanced › *Menu bar currency*, `settings.TrayCurrency`, per computer through `KeepOwn`, sets the menu bar's and its tooltip's apart, `TrayCostIn`, while Bark's daily message stays in the totals'; the currency rows are drawn by `currencyprefs.js`, imported when Settings draws its usage prefs), `+` when some calls had no price, the cost row left out when none had one. The Mac draws them as plain cells, the bird beside them saying whose. A click opens the Requests tab at the period (`quotaView`, `?tab=requests&period=`) or the panel's Usage tab (`panelUseFocus`). No 3-day total: the Usage page has no such window. See `TestTrayTotals` and `tray-totals.test.cjs`. Settings › *Menu bar cost* (`settings.TrayNoCost`, on by default, on every OS, per computer through `KeepOwn`) turned off leaves the money out (BussanQ on Discord): `trayMoney` drops the total's cost and its count of unpriced calls before `trayTotalCard` and the no-card tooltip `trayIdleTip` see it, so the cards, their tooltip and the idle tooltip say the tokens and requests alone. A relay's or subscription's balance card is money itself and stays. See `TestTrayNoCost` and `tray-cost.test.cjs`.
- The menu bar can show magpie's own totals beside the allowances (#1984): `usage:today` and `usage:7d` in `settings.TrayUsages`, offered after the cards in the same picker. `trayUsageCards` sums them with `usage.QueryPage(p, Filter{}, 0, 1).Sum` (the Requests tab's and the panel's cached ledger sum, gateway and session-file calls together) and asks no vendor when only totals are picked; `trayTotalCard` makes every token (in, out and cache, as `allTokens`), marked `Σ` so it doesn't read as the input, over the cost in Settings' currency (with *By provider*, `settings.CurrencyByProvider`, in the currency picked for totals, `TotalCostIn`: a sum of every provider has no one currency of its own; Settings › Usage › Advanced › *Menu bar currency*, `settings.TrayCurrency`, per computer through `KeepOwn`, sets the menu bar's and its tooltip's apart, `TrayCostIn`, while Bark's daily message stays in the totals'; the currency rows are drawn by `currencyprefs.js`, imported when Settings draws its usage prefs), `+` when some calls had no price, the cost row left out when none had one. The Mac draws them as plain cells, the bird beside them saying whose. A click opens the Requests tab at the period (`quotaView`, `?tab=requests&period=`) or the panel's Usage tab (`panelUseFocus`). No 3-day total: the Usage page has no such window. See `TestTrayTotals` and `tray-totals.test.cjs`. With *By provider*, the tray panel's Usage tab and the Requests tab show each cost that is one provider's in that provider's currency (`ledProv` in app.js): a ranking row and its line in the chart's tooltip, a model every provider of which sells in one currency (from `by.modelAt`), and the whole page while it is filtered to one provider (`Ledger.provider`, `usageapi.LedgerPage`); a sum, the chart's axis and a model served in both currencies are in the totals' (onkashiko on X; `TestLedgerSaysItsOneProvider`, `panel-currency-provider.test.cjs`). Settings › *Menu bar cost* (`settings.TrayNoCost`, on by default, on every OS, per computer through `KeepOwn`) turned off leaves the money out (BussanQ on Discord): `trayMoney` drops the total's cost and its count of unpriced calls before `trayTotalCard` and the no-card tooltip `trayIdleTip` see it, so the cards, their tooltip and the idle tooltip say the tokens and requests alone. A relay's or subscription's balance card is money itself and stays. See `TestTrayNoCost` and `tray-cost.test.cjs`.
- The tray's icon is the bird alone where the bar's other icons are glyphs: the Mac's menu bar takes `tray.png` as a template image, and a Linux bar (StatusNotifierItem `IconPixmap`) gets the same silhouette in one colour on transparency (`trayIconFor`, `linuxTrayIcon` in [`trayglyph.go`](../../internal/gui/trayglyph.go)), so a bar that tints its icons by their alpha tints the bird, not a tile (ylorn on Discord). A bar that doesn't tint shows it light, or dark when the portal's `org.freedesktop.appearance` `color-scheme` prefers light (`traySchemeLight`), and it is drawn again when that changes (`watchTrayScheme`). No `IconName` is set: a host that found a `-symbolic` name and drew it untinted would show a black bird on a dark bar, with no pixmap to fall back on. Windows' tray keeps the app's coloured icon, unless a card is in the menu bar: Windows' notification area shows no text beside an icon, so the icon itself is the first card's figure (Benjaminliang_1 on X; `trayIconFigure`, `trayNumberIcon` in [`traynumber.go`](../../internal/gui/traynumber.go)). It is the first row of the first card whose first row is a percentage, used or left as Allowance display has it, through *Menu bar windows*' pick, its digits alone, drawn in Segoe UI Semibold (Go's bold where the font can't be read) at `SM_CXSMICON`, white on a dark taskbar and near black on a light one, as tall as fits with a pixel above and below, centred by its ink, and three digits narrowed into the square. A balance or magpie's totals are skipped for the next card; with none the icon is the bird. It is drawn again when the figure, the icon size or the taskbar's theme changes (`SystemThemeChanged` wakes the loop); the tooltip still says every card. Settings › *Tray icon number* (`settings.TrayNoNumber`, Windows' alone, on by default) keeps the bird when off. One icon is set for the current theme, not a light and a dark one: Wails' Windows tray shares one handle between them. Linux keeps its label and tooltip; the Mac its cells. See `TestTrayIconFigure`, `TestTrayNumberIcon` and `tray-windows.test.cjs`. With no cards in the menu bar the tooltip is magpie over today's total (`trayIdleTip`: every token, split into input, output and cache as the today card's tooltip is, then the cost and the requests), brought up to date with the cards' refresh; the tray's menu stays Open, the version and Quit. Wails sets the tooltip only on Windows: on Linux `setTrayTip` sets the StatusNotifierItem's `ToolTip` and sends `NewToolTip` ([`traytip_linux.go`](../../internal/gui/traytip_linux.go)), and on the Mac it is the status item's button's `toolTip` (`trayTipNative` in [`trayimage_darwin.go`](../../internal/gui/trayimage_darwin.go); NextCommit on Discord: no hover there showed anything). See `TestTrayIconPerOS`, `TestTrayIdleTip` and `TestMacTrayTipIsSet`. Every tooltip, the idle one, magpie's totals' and each card's (its use or what is left, the pace, when it resets, "as of …"), is in magpie's language, as the tray menu is: `watchTrayUsage` passes `trayLang(settings.Lang, systemLang)` to `trayCardsView`, `trayUsageCards` and `trayIdleTip`, whose words are in `trayWords` beside the menu's, and a change of language in Settings refreshes it at once (`onTrayUsage`). A window's name and an error are the card's own (yi_time on Discord: English on a Windows magpie set to Chinese; `TestTrayTooltipFollowsMagpiesLanguage`).
- A window's Pace is a number on its card's reset line (fflake33 on Discord): the share used less the share of the window gone by, in points, "Pace +12%" over an even pace and "−8%" under it, turned with the meter when it shows what is left, amber while more is used than an even pace would have (`quotaPace`, `paceLine`). The window's start is the gateway's, `startsAt` from `provider.WithWindowStarts` (its reset less its span, `QuotaWindow.Bounds`); a window whose span isn't known, with no limit, or a past cycle has none. Settings › *Menu bar pace* (`settings.TrayPace`, off by default, hidden on Windows, whose tray shows no text but the first card's figure as its icon) puts the same number beside each figure in the menu bar and in its tooltip (`trayPace`, `QuotaWindow.Pace`). See `TestWindowPace`, `TestTrayUsagePace` and `quota-pace.test.cjs`.
- Settings › *Menu bar windows* (`settings.TrayWindows`, StrikingRaw on X) picks which of a subscription's windows its menu bar card shows, keyed by provider id (every account of it, the in-use `|*` card too) and by window kind, not position: `trayWindowKind` names a window by its span ("5h", "1d", "7d", "month", "15m"), by `name:` its name when the span isn't known. Unset shows every window, as before; a pick none of whose kinds the card still has shows every window again (`trayShownKinds`), never an empty card. Only the bar's rows, the Linux label and Windows' icon figure are filtered; the tooltip still says every window. One row draws in the menu bar's own font (13pt regular), two stacked rows in 10pt regular, both with digits of one width (`mpRowFont`, `TestTrayRowFont`; qingnianxiaozhe on X found the old 9.5pt semibold and 11pt medium heavier than Surge's and iStat Menus' figures beside them). The GUI learns the kinds from `trayKind` on `/api/usage/quotas` (`withTrayKinds`; model and aside windows get none). The row lists a pill per ticked subscription with two or more kinds, opening the app's menu (All windows, then each kind), shown on Windows too, where the first card's pick decides the tray icon's figure; its code is in `traywindows.js`, imported when Settings draws ticked cards. Per computer through `KeepOwn`. See `TestTrayWindowsPicked`, `TestTrayWindowsKept` and `tray-windows.test.cjs`.
+19 -10
View File
@@ -17561,7 +17561,7 @@ function renderPanelUse() {
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) }) : ""), "", "", 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);
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("Cache hit rate", hitRate === null ? "—" : hitPct(hitRate), cacheLeftOut(l) || t("of the prompt"));
@@ -18929,8 +18929,17 @@ const ledRankValue = (m, x) => m === "speed" ? ledGroupSpeed(x)?.v || 0 : ledVal
const ledPart = (m, x) => m === "speed" ? ledSpeed(x) : m === "traffic" ? ledBytes(x) : m === "cost" ? +x.cost || 0 : m === "calls" ? +x.calls || 0 : +x.tokens || 0;
// a metric as its axis and its values say it: bytes as "2.5 MB", an
// axis's round "4 MB" without its ".0"
const ledFormat = (m, v) => m === "cost" ? ledMoney(v) : m === "traffic" ? fmtBytes(Math.round(v)).replace(/\.0 /, " ") : (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 }) || "—") : m === "traffic" ? fmtBytes(Math.round(v)) : ledNum(Math.round(v));
const ledFormat = (m, v, p) => m === "cost" ? ledMoney(v, p) : m === "traffic" ? fmtBytes(Math.round(v)).replace(/\.0 /, " ") : (m === "speed" ? ledNum : fmtN)(Math.round(v));
const ledFormatLong = (m, v, p) => m === "speed" ? (v > 0 ? t("{n} tok/s", { n: ledNum(Math.round(v)) }) : "—") : m === "cost" ? (fmtCost({ cost: v, unpriced: 0 }, p) || "—") : m === "traffic" ? fmtBytes(Math.round(v)) : ledNum(Math.round(v));
// ledProv is the provider whose currency a cost of share id (by split) of
// l shows in: the one provider l is filtered to, the share's own (a
// provider, or a model at one), or a model's when every provider that
// served it sells in one currency; "" (a sum: Totals in) otherwise
function ledProv(l, s, id) {
const at = (x) => x.split("/")[0], ps = s == "model" ? ((l.chartBy || l.by)?.modelAt || []).filter((x) => x.id.slice(at(x.id).length + 1) == id).map((x) => at(x.id)) : [s == "provider" ? id : s == "modelAt" && at(id)];
return l.provider || (id?.[0] > "\0" && ps[0] && ps.every((p) => costInYuan(p) == costInYuan(ps[0])) ? ps[0] : "");
}
// an axis's top with four steps under it: round numbers, the top at least the largest value
function ledAxis(max) {
@@ -19002,7 +19011,7 @@ function drawLedColumns(box, l, split, metric, compact, chooseDay, focusDay) {
plot.append(g);
const labs = [0, 1, 2, 3, 4].map((i) => {
const lab = sv("text", { "text-anchor": "end", class: "axis" });
lab.textContent = ledFormat(metric, topV * (1 - i / 4));
lab.textContent = ledFormat(metric, topV * (1 - i / 4), l.provider);
g.append(lab);
return lab;
});
@@ -19078,7 +19087,7 @@ function drawLedColumns(box, l, split, metric, compact, chooseDay, focusDay) {
plot.append(g, tip);
const name = (c) => t(c.name || c.id || "—");
// counts short, as the axis says them (skyhuang1994)
const val = (v) => speed || metric === "cost" || metric === "traffic" ? ledFormatLong(metric, v) : ledFormat(metric, v);
const val = (v, id) => speed || metric === "cost" || metric === "traffic" ? ledFormatLong(metric, v, ledProv(l, split, id)) : ledFormat(metric, v);
const at = (e) => {
const r = g.getBoundingClientRect();
const i = Math.max(0, Math.min(n - 1, Math.floor(((e.clientX - r.left) / r.width * W - M.l) / slot)));
@@ -19090,13 +19099,13 @@ function drawLedColumns(box, l, split, metric, compact, chooseDay, focusDay) {
// first token each in a column of their own (#2343)
tip.classList.toggle("speed", speed);
const by = p.by?.[split] || {};
const rows = [...top, ...(speed ? ledOthers(by, top, list) : [])].map((c) => [name(c), c.color, ledPart(metric, by[c.id] || {}), by[c.id]]);
const rows = [...top, ...(speed ? ledOthers(by, top, list) : [])].map((c) => [name(c), c.color, ledPart(metric, by[c.id] || {}), by[c.id], c.id]);
if (!speed) rows.push([t("Other"), "var(--faint)", Math.max(0, totals[i] - rows.reduce((a, x) => a + x[2], 0))]);
for (const [nm, color, v, part] of rows.filter((x) => x[2] > 0).sort((a, b) => b[2] - a[2])) {
for (const [nm, color, v, part, id] of rows.filter((x) => x[2] > 0).sort((a, b) => b[2] - a[2])) {
const row = el("div");
const sw = el("i");
sw.style.background = color;
row.append(sw, el("span", "", nm), el("em", "", val(v)));
row.append(sw, el("span", "", nm), el("em", "", val(v, id)));
if (speed) row.append(el("em", "ttft", ledTTFT(part) ? t("TTFT {ms}", { ms: ledTook(ledTTFT(part)) }) : ""));
tip.append(row);
}
@@ -19164,7 +19173,7 @@ 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 long = ledFormatLong(metric, v), val = el("span", "rk-val", metric == "speed" ? gs?.text || "—" : metric == "cost" || metric == "traffic" ? long : ledFormat(metric, v));
const prov = ledProv(l, split, x.id), long = ledFormatLong(metric, v, prov), val = el("span", "rk-val", metric == "speed" ? gs?.text || "—" : metric == "cost" || metric == "traffic" ? long : ledFormat(metric, v));
val.title = metric == "speed" ? gs?.title || "" : long;
l1.append(nm, val);
const bar = el("div", "rk-bar"), fill = el("i");
@@ -19175,7 +19184,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));
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 }));
+4 -3
View File
@@ -2514,7 +2514,7 @@ function renderLedgerDash(l) {
}
// and how fast it flows now, while requests are in flight (ledFlow)
strip.lastChild.append(ledFlowLine());
const c = fmtCost(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) : "");
@@ -2794,7 +2794,8 @@ function ledHeatTip(x) {
return tip;
}
const parts = [t("{n} tokens", { n: fmtN(x.tokens) }), t(x.calls === 1 ? "{n} request" : "{n} requests", { n: ledNum(x.calls) })];
const c = fmtCost(x);
// 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);
const order = { tokens: 0, calls: 1, cost: 2 }[ledHeatMetric];
if (order && parts[order]) parts.unshift(...parts.splice(order, 1)); // the metric shown first
@@ -3259,7 +3260,7 @@ function renderLedger() {
renderPeriod();
renderArchive();
costHead(fmtCost(l), l.unpriced ? unpricedCalls(l.unpriced) : "", unpricedCallsWhy(l.unpriced));
costHead(fmtCost(l, l.provider), l.unpriced ? unpricedCalls(l.unpriced) : "", unpricedCallsWhy(l.unpriced));
// the filters: choices seen in the period, and failures alone
sessPick($("#ledPurpose"), "All purposes", ledPurpose, purposeOptions(l.purposes || [], ledPurpose), "Purpose", (v) => { ledPurpose = v; ledOwn("purpose"); ledOffset = 0; loadLedger().catch((e) => status(e.message, "err")); });
+1 -1
View File
@@ -18,7 +18,7 @@ import (
// `git log -L` of this file.
const (
appScriptBudget = 1_086_267 // app.js: 1,080,614 at 8016205e3, with the 5,653 of room it had
coreScriptBudget = 1_269_040 // every core script at 8016205e3, the old measure 682 over its cap there (#5918); +367 for the model test on a chosen account (tmr11235), no page left to move it to; +151 for the provider menu's "Only on this device" item and its four translations; +458 for Settings › About's Report a problem row and its translations; +113 for withScheme, the one rule every typed address goes through (eachg0 on X), cut to the shortest form that keeps it whole; +10 for the kept whole's tooltip (Musikrv77852 on X), the past-cycle line reused for it, no page left to move it to; +1,112 for Codex's Open button and its Open Codex with menu (Yink88564391 on X), packed to the shortest form, no page left to move them to; +168 for Discover's long lists drawn in part (the owner, 11-13), after the rest of its hook moved into plugingrid.js, imported when Plugins first draws; +296 for the cap toggle and Smart sentences that say what they do and the Sign in on another computer row (Wing8Aqua on X), packed to the shortest form, no page left to move them to; +333 for In turn's figure in a provider's editor and its words naming the message that goes round (Wing8Aqua on X), the figure itself in rotfig.js, imported when In turn is first shown, the hook packed to the shortest form; +236 for a lone capped Codex account's row saying its turns go to the fallbacks when Codex is connected (not_4O4 on X), the two helpers inlined, no page left to move it to; +717 for omp's advisor (Awad_Yoo on X, #6408): its three rows moved into ompadvisor.js, imported when an omp's settings show, and what is left is the import, the role's " · off" and the Settings line's name, packed to the shortest form; +468 for a plugin's own file import (auth.import) in the import sheet, in the plugin's words (marchen_cc on X), packed to one statement; importSay is read as the Providers rows draw, so it has no lazy page to go to, and nothing else was moved out; +180 for Claude Magpie's own Claude Code folder (xMopf7RF on X, #6459): its Advanced fold in claudemagpie.js, imported when it first shows, and what is left is the import and the fold's place in the Separate app line, 216 bytes packed to the shortest form, less the 36 of room there was; +81 for the Use Claude Magpie button on Claude Desktop's row (xMopf7RF on X), drawn by claudemagpie.js too, what is left the one line that places it (#2710); +225 for the Hermes row's Other profiles lines (Norethcy on X), which 1d60b165c took out while each profile had a row and c96f33d65 left with no place at all, packed to the shortest form; the dead hermes# Default note went with it, and the Agents rows draw it, so there is no page to move it to; +397 for a key's own price rate (tnt12231 on X): its lines, check and placeholder in keyrates.js, imported when a provider with two or more keys opens, and what is left is the import, the draft's copy, Advanced opening for it, the save's one line and proxyLines drawing another kind of line; +316 for an image or video model's chip saying what it makes from its right-click (iceloon on X): the chat chip's Makes… now shared with it, and the media chip's Copy model ID left out, packed to the shortest form; the provider's editor draws it, so there is no page to move it to; +67 for the Claude Code · Claude Magpie row saying it is on magpie through Claude Magpie (xMopf7RF on X), one line in connectLine with the shortest words that say it; the Agents rows draw it, so there is no page to move it to; +12 for AIGoCode's logo in pngIcons (MindfulReturn on X), the list every drawn icon is looked up in
coreScriptBudget = 1_269_531 // every core script at 8016205e3, the old measure 682 over its cap there (#5918); +367 for the model test on a chosen account (tmr11235), no page left to move it to; +151 for the provider menu's "Only on this device" item and its four translations; +458 for Settings › About's Report a problem row and its translations; +113 for withScheme, the one rule every typed address goes through (eachg0 on X), cut to the shortest form that keeps it whole; +10 for the kept whole's tooltip (Musikrv77852 on X), the past-cycle line reused for it, no page left to move it to; +1,112 for Codex's Open button and its Open Codex with menu (Yink88564391 on X), packed to the shortest form, no page left to move them to; +168 for Discover's long lists drawn in part (the owner, 11-13), after the rest of its hook moved into plugingrid.js, imported when Plugins first draws; +296 for the cap toggle and Smart sentences that say what they do and the Sign in on another computer row (Wing8Aqua on X), packed to the shortest form, no page left to move them to; +333 for In turn's figure in a provider's editor and its words naming the message that goes round (Wing8Aqua on X), the figure itself in rotfig.js, imported when In turn is first shown, the hook packed to the shortest form; +236 for a lone capped Codex account's row saying its turns go to the fallbacks when Codex is connected (not_4O4 on X), the two helpers inlined, no page left to move it to; +717 for omp's advisor (Awad_Yoo on X, #6408): its three rows moved into ompadvisor.js, imported when an omp's settings show, and what is left is the import, the role's " · off" and the Settings line's name, packed to the shortest form; +468 for a plugin's own file import (auth.import) in the import sheet, in the plugin's words (marchen_cc on X), packed to one statement; importSay is read as the Providers rows draw, so it has no lazy page to go to, and nothing else was moved out; +180 for Claude Magpie's own Claude Code folder (xMopf7RF on X, #6459): its Advanced fold in claudemagpie.js, imported when it first shows, and what is left is the import and the fold's place in the Separate app line, 216 bytes packed to the shortest form, less the 36 of room there was; +81 for the Use Claude Magpie button on Claude Desktop's row (xMopf7RF on X), drawn by claudemagpie.js too, what is left the one line that places it (#2710); +225 for the Hermes row's Other profiles lines (Norethcy on X), which 1d60b165c took out while each profile had a row and c96f33d65 left with no place at all, packed to the shortest form; the dead hermes# Default note went with it, and the Agents rows draw it, so there is no page to move it to; +397 for a key's own price rate (tnt12231 on X): its lines, check and placeholder in keyrates.js, imported when a provider with two or more keys opens, and what is left is the import, the draft's copy, Advanced opening for it, the save's one line and proxyLines drawing another kind of line; +316 for an image or video model's chip saying what it makes from its right-click (iceloon on X): the chat chip's Makes… now shared with it, and the media chip's Copy model ID left out, packed to the shortest form; the provider's editor draws it, so there is no page to move it to; +67 for the Claude Code · Claude Magpie row saying it is on magpie through Claude Magpie (xMopf7RF on X), one line in connectLine with the shortest words that say it; the Agents rows draw it, so there is no page to move it to; +12 for AIGoCode's logo in pngIcons (MindfulReturn on X), the list every drawn icon is looked up in; +491 for each cost in the tray panel's and Requests' chart and ranking in its own provider's currency (onkashiko on X): ledProv and the provider passed through, packed to the shortest form; drawLedColumns and drawLedRank are shared by the panel, so there is no page to move it to
)
// codeBytes is how many bytes of b are code: its blank lines, its lines
@@ -0,0 +1,205 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// Currency "By provider" in the tray panel's Usage tab and the window's
// Requests tab (onkashiko on X: "在菜单栏迷你窗中还是只会显示为一种货币").
// The ranking's rows and their tooltips are one provider's costs, in what it
// sells in: DeepSeek's and SiliconFlow's in yuan, OpenAI's in dollars; a
// model in that provider's (deepseek-v4 at DeepSeek and SiliconFlow, both
// yuan), a model served in both currencies, the "Other" row, the chart's axis
// and the total in the "Totals in" currency, never added up as one. With one
// provider picked the whole page is its calls: the total and the axis in its
// currency. Every language, a 440px and a 320px panel, a 1100px and a 420px
// window; no backend, the API is faked as the Go side answers it
// (usageapi.Ledger's provider, fx.yuan). MAGPIE_ASSETS runs it on other assets.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const assets = process.env.MAGPIE_ASSETS || path.resolve(__dirname, "../assets");
const midnight = new Date();
midnight.setHours(0, 0, 0, 0);
// what each provider's calls of each model cost, in dollars as stored
const COST = { deepseek: { "deepseek-v4": 1 }, siliconflow: { "deepseek-v4": 0.25, "kimi-k3": 0.25 }, openai: { "kimi-k3": 0.5, "gpt-5": 1.5 } };
const NAMES = { deepseek: "DeepSeek", siliconflow: "SiliconFlow", openai: "OpenAI" };
const share = (id, name, cost, icon) => ({ id, name, icon, calls: 2, errors: 0, input: cost * 1e5, output: cost * 5e4, cache_read: 0, cache_write: 0, cost });
const sum = (xs) => xs.reduce((a, b) => a + b, 0);
function ledger(q) {
const only = q.get("provider");
const who = Object.entries(COST).filter(([id]) => !only || id === only);
const models = {};
for (const [, ms] of who) for (const [m, c] of Object.entries(ms)) models[m] = (models[m] || 0) + c;
const total = sum(Object.values(models));
const byModel = Object.entries(models).map(([m, c]) => share(m, m, c)).sort((a, b) => b.cost - a.cost);
const byProvider = Object.entries(COST).map(([id, ms]) => share(id, NAMES[id], sum(Object.values(ms)), "generic")).sort((a, b) => b.cost - a.cost);
const modelAt = Object.entries(COST).flatMap(([id, ms]) => Object.entries(ms).map(([m, c]) => share(id + "/" + m, m + " · " + NAMES[id], c, "generic")));
const by = { provider: {}, model: {}, modelAt: {} };
for (const [id, ms] of who) {
by.provider[id] = { calls: 2, tokens: 1000, cost: sum(Object.values(ms)) };
for (const [m, c] of Object.entries(ms)) by.modelAt[id + "/" + m] = { calls: 1, tokens: 500, cost: c };
}
for (const [m, c] of Object.entries(models)) by.model[m] = { calls: 1, tokens: 500, cost: c };
const series = Array.from({ length: 24 }, (_, i) => {
const on = i === 10;
return { label: String(i), time: new Date(midnight.getTime() + i * 3600e3).toISOString(), calls: on ? 6 : 0, errors: 0, input: on ? 1000 : 0, output: on ? 500 : 0, cache_read: 0, cache_write: 0, cost: on ? total : 0, by: on ? by : { provider: {}, model: {}, modelAt: {} } };
});
return {
period: q.get("period") || "today", rows: [], offset: 0, total: 1, calls: 6, errors: 0, input: total * 1e5, output: total * 5e4, cache_read: 0, cache_write: 0, reasoning: 0, cost: total, unpriced: 0,
...(only ? { provider: only } : {}),
bucket: "hour", series, by: { provider: byProvider, agent: [], model: byModel, modelAt },
agents: [], providers: Object.entries(NAMES).map(([id, name]) => ({ id, name, icon: "generic" })),
};
}
const fx = { rate: 7.2, at: new Date().toISOString(), stale: false, yuan: ["deepseek", "siliconflow"] };
function serve(lang, asked, totalCurrency) {
const settings = { lang, theme: "light", currency: "provider", totalCurrency };
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:false};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings, fx });
if (url.pathname === "/api/settings") return json({ ...settings, fx });
if (url.pathname === "/api/usage/requests") { asked.push(url.searchParams); return json(ledger(url.searchParams)); }
if (url.pathname === "/api/usage/heatmap") return json({ days: [] });
if (url.pathname === "/api/gateway/trace") return json({ mine: true, now: new Date().toISOString(), seq: 0, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] });
if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] });
if (url.pathname === "/api/usage/quotas") return json([]);
if (url.pathname === "/api/usage") return json({ calls: 0, errors: 0, input: 0, output: 0, reasoning: 0, unpriced: 0, cost: 0, bucket: "day", series: [], agents: [], models: [], path: "" });
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], models: [], gateway: { running: true, window: true } });
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 route.fulfill(url.pathname.startsWith("/api/window/") ? { status: 204 } : { 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 LANGS = ["en", "zh", "zh-TW", "ja", "de"];
const BROWSERS = process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"];
// 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 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) {
const g = p.locator(box + " svg").first();
const r = await g.boundingBox();
await p.mouse.move(r.x + r.width - 2, r.y + r.height / 2); // off the busy hour first
const at = await p.locator(box + " rect.col").first().boundingBox();
await p.mouse.move(at.x + at.width / 2, at.y + Math.max(1, at.height / 2));
const tip = p.locator(box + " .tip");
await tip.waitFor();
return tip.evaluate((t) => [...t.querySelectorAll("div")].map((d) => [d.querySelector("span")?.textContent, d.querySelector("em")?.textContent?.split(" · ")[0]]));
}
for (const engine of BROWSERS) {
for (const lang of LANGS) {
test(`${engine} ${lang}: the panel's Usage shows each provider's cost in its own currency`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
for (const width of [440, 320]) {
const ctx = await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" });
const errors = [], asked = [];
const p = await ctx.newPage();
p.setDefaultTimeout(5000);
p.setDefaultNavigationTimeout(60000);
p.on("pageerror", (e) => errors.push(e.message));
await p.addInitScript(() => { try { localStorage.setItem("magpie.panelTab", "stats"); localStorage.setItem("magpie.panelUseSplit", "provider"); localStorage.setItem("magpie.panelUseMetric", "tokens"); } catch {} });
await p.route("**/*", serve(lang, asked, "usd"));
await p.goto("http://magpie.test/?mode=panel");
const box = "#panelUsage";
await p.locator(box + " .pu-card .led-rank .rk").first().waitFor();
// 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");
// 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();
await p.waitForFunction(() => [...document.querySelectorAll("#panelUsage .rk-val")].some((v) => v.textContent.startsWith("¥")));
assert.deepEqual(await rankOf(p, box), { DeepSeek: "¥7.20", OpenAI: "$2.00", SiliconFlow: "¥3.60" });
assert.match(await axisOf(p, box), /^\$/);
const tip = await tipOf(p, box);
assert.deepEqual(tip.slice(0, -1).sort(), [["DeepSeek", "¥7.20"], ["OpenAI", "$2.00"], ["SiliconFlow", "¥3.60"]]);
assert.equal(tip.at(-1)[1], "$3.50", "the hour's total in dollars");
// by model: one served only in yuan is in yuan; one served in yuan and
// dollars is a sum of both, in the totals' dollars
await p.locator(box + " .pu-split .opt").nth(1).click();
await p.waitForFunction(() => document.querySelectorAll("#panelUsage .rk").length === 3 && [...document.querySelectorAll("#panelUsage .rk-nm")].some((n) => n.textContent === "gpt-5"));
assert.deepEqual(await rankOf(p, box), { "deepseek-v4": "¥9.00", "gpt-5": "$1.50", "kimi-k3": "$0.750" });
// one provider picked: every figure is DeepSeek's, the total and axis in yuan
await p.locator(box + " .pu-split .opt").nth(0).click();
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.deepEqual(await rankOf(p, box), { "deepseek-v4": "¥7.20" });
assert.match(await axisOf(p, box), /^¥/);
assert(await p.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1), `no sideways scroll at ${width}px`);
const out = await p.locator(box + " .rk-val").evaluateAll((vs) => vs.filter((v) => { const r = v.getBoundingClientRect(), c = v.closest(".pu-card").getBoundingClientRect(); return r.right > c.right + 0.5; }).length);
assert.equal(out, 0, `every figure inside the card at ${width}px`);
assert.deepEqual(errors, []);
await ctx.close();
}
});
test(`${engine} ${lang}: the window's Requests shows each provider's cost in its own currency`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
for (const width of [1100, 420]) {
const ctx = await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: "reduce" });
const errors = [], asked = [];
const p = await ctx.newPage();
p.setDefaultTimeout(5000);
p.setDefaultNavigationTimeout(60000);
p.on("pageerror", (e) => errors.push(e.message));
await p.addInitScript(() => { try { localStorage.setItem("magpie.ledMetric", "cost"); } catch {} });
// totals in yuan this time: OpenAI's stays in dollars
await p.route("**/*", serve(lang, asked, "cny"));
await p.goto("http://magpie.test/");
await p.locator('[data-view="usage"]').first().click();
await p.locator(":is(#usageTab .opt, .nav-s):visible").nth(1).click();
await p.locator("#ledRank button.rk").first().waitFor();
await p.waitForTimeout(200);
const box = "#ledRank";
// Provider: LED_SPLITS' third
await p.locator("#ledSplit .opt").nth(2).click();
await p.waitForFunction(() => [...document.querySelectorAll("#ledRank .rk-nm")].some((n) => n.textContent === "OpenAI"));
assert.deepEqual(await rankOf(p, box), { DeepSeek: "¥7.20", OpenAI: "$2.00", SiliconFlow: "¥3.60" }, `${width}px`);
assert.match(await axisOf(p, "#ledChart"), /^¥/, "the axis, a sum, in the totals' yuan");
// Model: a model served in both currencies is a sum, in yuan
await p.locator("#ledSplit .opt").nth(0).click();
await p.waitForFunction(() => [...document.querySelectorAll("#ledRank .rk-nm")].some((n) => n.textContent === "gpt-5"));
assert.deepEqual(await rankOf(p, box), { "deepseek-v4": "¥9.00", "gpt-5": "$1.50", "kimi-k3": "¥5.40" });
// Model · provider: each at its own provider
await p.locator("#ledSplit .opt").nth(1).click();
await p.waitForFunction(() => document.querySelectorAll("#ledRank .rk").length >= 5);
const at = await rankOf(p, box);
assert.equal(at["kimi-k3 · OpenAI"], "$0.500");
assert.equal(at["kimi-k3 · SiliconFlow"], "¥1.80");
// 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");
assert.equal(asked.at(-1).get("provider"), "openai");
await p.waitForFunction(() => /^\$/.test(document.querySelector("#ledChart svg text.axis")?.textContent || ""));
assert.deepEqual(errors, []);
await ctx.close();
}
});
}
}
+49
View File
@@ -0,0 +1,49 @@
package usageapi
import (
"encoding/json"
"path/filepath"
"testing"
"time"
"github.com/yetone/magpie/internal/usage"
)
// TestLedgerSaysItsOneProvider: a page filtered to one provider says which,
// so with the currency "by provider" its total and chart are shown in what
// that provider sells in (onkashiko on X); a page of every provider says
// none, and its sums go in the "Totals in" currency.
func TestLedgerSaysItsOneProvider(t *testing.T) {
h := t.TempDir()
t.Setenv("HOME", h)
t.Setenv("USERPROFILE", h)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
now := time.Now()
usage.Append(usage.Record{Time: now.Add(-2 * time.Minute), Agent: "codex", Provider: "deepseek", Model: "deepseek/deepseek-v4", Status: 200, Input: 10, Output: 2})
usage.Append(usage.Record{Time: now.Add(-time.Minute), Agent: "codex", Provider: "openai", Model: "openai/gpt-5", Status: 200, Input: 10, Output: 2})
one := LedgerPage(usage.All, usage.Filter{Provider: "deepseek"}, 0, 100)
if one.Provider != "deepseek" || one.Calls != 1 {
t.Fatalf("filtered page: provider %q calls %d, want deepseek, 1", one.Provider, one.Calls)
}
if top := topLevel(t, one); top["provider"] != "deepseek" {
t.Fatalf("the page reads provider %v, want deepseek", top["provider"])
}
all := LedgerPage(usage.All, usage.Filter{}, 0, 100)
if _, ok := topLevel(t, all)["provider"]; ok || all.Provider != "" {
t.Fatalf("the whole page names a provider %q", all.Provider)
}
}
func topLevel(t *testing.T, l Ledger) map[string]any {
t.Helper()
b, err := json.Marshal(l)
var m map[string]any
if err == nil {
err = json.Unmarshal(b, &m)
}
if err != nil {
t.Fatal(err)
}
return m
}
+5
View File
@@ -279,6 +279,10 @@ type Ledger struct {
By map[string][]Share `json:"by"`
ChartBy map[string][]Share `json:"chartBy,omitempty"`
Day string `json:"day,omitempty"`
// Provider is the one provider the filter keeps, if any: every cost
// of the page is of its calls alone, so a page whose currency is "by
// provider" shows them in what that provider sells in
Provider string `json:"provider,omitempty"`
usage.Totals
// Through and Direct: the rows the gateway served, and the rows read
// from the agents' own session files, which it never saw. Totals is
@@ -412,6 +416,7 @@ func LedgerPage(p usage.Period, f usage.Filter, offset, limit int) Ledger {
out.Purposes = l.Purposes
out.BigWrite = l.Big
out.Day = f.Day
out.Provider = f.Provider
out.CallerKeys = inKeyOrder(callerGroups(usage.Summary{CallerKeys: l.CallerKeys}))
callerLabels := map[string]string{}
for _, g := range out.CallerKeys {