usage: small, idle clients fold into one Other row

WJaunita45604 on X: test runs leave dozens of randomly named clients of
~10K tokens each in the Usage page's Agents list, and the page crawls.
renderUsage draws every Agents row again at each refresh whose summary
changed, at ~0.1ms of DOM and layout a row: with 400 clients a redraw
took 30-54ms in Chromium and 45-66ms in WebKit, with 2000 136-178ms and
224-246ms (probe at 1200px, Bun/SiYuan/translate-web and N clients).

A client not hidden folds when it is past the 5 with the most tokens,
under 1% of the period's tokens, and either made no call in the last 3
days (the agent group's new `last`) or is past the top 20; two or more
fold, or none do. No setting. Other sits at the list's foot with the
folded groups' sums (usageSum), so totals stay exact, and opens with a
click, Enter or Space; open, it draws the folded rows with their own
actions 100 at a time (Show {n} more). Closed they aren't drawn at all:
with 400 or 2000 clients a redraw now fits one frame (~13-20ms in both
engines), as with none.

Run at 442964d70 + this change, on mote (then rebased clean onto
9afec644c, which touches sync/library/update only; go test -run
'Budget|Size|I18n|Css' ./internal/gui ./internal/usage ok there):
gofmt -l clean; go vet ./internal/usage ./internal/usageapi
./internal/gui on darwin, linux (-tags nogui) and windows: ok;
go test ./internal/usage (58s), ./internal/usageapi, ./internal/gui
(137s): ok.
GUI, both engines: usage-*, i18n-*, mobile-web, own-requests and
ledger-cache-unknown files: 1740 tests, 1663 pass, 77 fail. The reds:
usage-agents-hide #6003/#3414, mobile-web #3952, usage-cards-hide
#6294, usage-range-times #6499, usage-hidden-way-back #6295,
usage-fold #3415, usage-speed-all-models #5834 fail the same way at
base 442964d70 (those 7 files there: 152 pass, 70 fail, the same
usage-agents-hide error "536.7 -> 586.98"); usage-ledger's "newest
live route needs no return-to-live button" is #5048/#6003 (the
Requests tab, which this doesn't touch); usage-chart-dates (chromium)
timed out launching the browser (180s) under load.
The new usage-agents-other.test.cjs: 33/33 (chromium + webkit, en zh
zh-TW ja de, three widths).
Perf probe at 1200px, one redraw: 400 clients 30–54ms (Chromium) and
45–66ms (WebKit) before, 2000 clients 136–178ms and 224–246ms; after,
both fit one frame (~13–20ms), the same as no clients.
Broken by hand: USAGE_FOLD_TOP=0 turns the rule test red; dropping the
100-row cap turns the page test red ("151 !== 100").
Not run: the full GUI suite (mote and mica were both running other
sessions' suites).
This commit is contained in:
yetone
2026-11-15 02:51:18 +08:00
parent d50ae6fcb1
commit 93762f968a
5 changed files with 388 additions and 52 deletions
+1
View File
@@ -681,6 +681,7 @@ covers it in both engines, every language and a narrow window.
- An allowance card can be hidden from Usage › Overview (whqtian_07012 on Discord: StepFun's plan wanted, its balance not). The card's "…" button at its head's end (`quotaCardMore`; jen_celeus on X looked for a way to hide OpenCode Zen's card, which has no usage to show, and found none), a right-click, or a long press on a touch screen (`quotaCardMenus` in `plugins/usage/page.js`) opens the app menu with *Hide from Overview*. The button shows as the card is hovered, at the head's end, with room kept for it either way (drawn over the end, it hid "Show the other accounts in brief", normalcoder_ on X; `usage-card-menu-room.test.cjs`); where nothing hovers it is always shown, drawn at 22px and taken at 44 on a phone; an account of a card with several says *Hide this account from Overview*, and a plan card carrying its key's balance (`keyCards`) also offers *Hide its balance from Overview*, which keeps the plan. Each is kept by its tray card id and kind (`cardHideKey`: `stepfun|balance`, `kimi|me@x|plan`) in `settings.UsageCardsHidden` through the same `POST /api/usage/arrange` (`cardsHidden`), and kept by the Settings save. `overviewCards` leaves them out before `keyCards`, so routing, caps, the counting and the Accounts list never hear of it; the tray panel's Allowances tab, the menu bar's cells, tooltip and Windows' tray figure (`trayShown`), and `magpie tui`'s Usage page leave it out too (above, and `provider.ShownQuotas`). A cell naming an account takes its card the Overview still shows (its balance with its plan hidden); a cell following the account in use is left empty while that account's card is hidden, rather than moving to another. `settings.TrayUsages` keeps the cell, so it comes back with the card, and `POST /api/usage/arrange` wakes the menu bar (`onTrayUsage`) when `cardsHidden` or `windowsHidden` is sent, with no restart. See `TestTrayLeavesOutWhatTheOverviewHides` and `TestUsageArrangeWakesTheMenuBar`. Such a card's menu offers *Show in Overview*, not Hide again, since the "{n} hidden" line leaves it out while it shows. A "{n} hidden" line under the cards (`#quotaHid`, `renderQuotaHid`) opens them, each with *Unhide*, and *Show all* from two. The line is drawn in `--muted`, not `--faint`, so it can be read and found (3:1 or more), and while any are hidden every card's menu ends with *Show {n} Hidden*, which opens the line with the keyboard on it and brings it into sight on the menu's click (`openHidden`; yuu003348 on Discord found no way back). See `TestUsageArrangeCardsHidden`, `usage-cards-hide.test.cjs`, `usage-card-more.test.cjs` and `usage-hidden-way-back.test.cjs`.
- A card's quota rows can be hidden one group at a time from Overview (wangshaowei39 on X: Antigravity's Claude & GPT rows unwanted). A row's right-click or long press (`quotaRowMenuItems` in `plugins/usage/page.js`) adds *Hide {group} from Overview* to the card's menu, and the card's "…" lists each group. The group is a pool's or model family's name, else the window's (`windowGroup`), so a pool's 5-hour and weekly rows go together. Kept as `provider|group` in `settings.UsageWindowsHidden` through `POST /api/usage/arrange` (`windowsHidden`), every account of the provider alike, and kept by the Settings save. `overviewCards` hands the page a copy without them (`withoutHiddenRows`); caps, routing and counting read the full card; the tray panel, the menu bar and `magpie tui`'s Usage page leave the rows out as the page does. A card is never left with no row: a card with one group offers no Hide, and one whose every group is named shows all. The "{n} hidden" line counts the rows with the cards, each with *Unhide* (`hideQuotaRows`). See `TestUsageArrangeWindowsHidden` and `usage-rows-hide.test.cjs`.
- A client in the Usage page's Agents list can be hidden from that list (ikunbots on X): its row's "…" button or right-click opens the row menu with *Hide from this list*, saved by client id in `settings.UsageAgentsHidden` through the same `POST /api/usage/arrange` (`agentsHidden`), and kept by the Settings save. The ledger, the totals and the chart still count a hidden client. A "{n} hidden" line under the list opens them, each with *Unhide* (`hideUsageAgent`), and while any are hidden the row menu ends with *Show {n} Hidden*, which opens it as the cards' does (`openHidden`). See `TestUsageArrangeAgentsHidden`, `usage-agents-hide.test.cjs` and `usage-hidden-way-back.test.cjs`.
- The Agents list folds the clients that are small and idle into one *Other* row at its foot, with no setting (WJaunita45604 on X: dozens of randomly named test clients of ~10K tokens each, every one a row laid out again at each refresh, made the page crawl). A client not hidden folds when it is past the 5 with the most tokens, under 1% of the period's tokens, and either made no call in the last 3 days or is past the top 20 (`usageFoldAgents` in `plugins/usage/page.js`); two or more fold, or none do. The last call is the agent group's `last` (`usage.Group.Last`, set by `summaryCounts.add` and `direct`); a group without one is not idle. Other's numbers are the folded groups' sum (`usageSum`), so every total stays exact. It opens with a click, Enter or Space (`aria-expanded`), the page left where it is, and draws the folded rows, each with its own actions, 100 at a time with *Show {n} more*; closed, they are not drawn at all. With 400 clients a redraw took ~30–54ms in Chromium and ~45–66ms in WebKit; with them folded, one frame (~13–20ms), as with none (`usage-fold` probe, N=400 and 2000). See `TestSummaryAgentsSayTheirLastCall`, `TestLoggedSummaryAgentsLastCallMovesOn` and `usage-agents-other.test.cjs`.
- Usage › Overview's Agents, Models, Accounts and Gateway keys lists each fold under their heading (#2378): the heading is a `.fold` button with its chevron, as on the Gateway page, and the click doesn't move the page (`backToReader`). What is folded is kept per viewer in localStorage `magpie.usageFolded` (`mountUsageFolds`, `showUsageFolds`). The totals leave the cache out, as before, unless the tokens tile's label, a pop-up button (`usageTokensPick`, the app menu), is set to *With cache*: then the tile, the chart and every row's count and share add cache read and written (`usageTokens`), and the tile says the cache's count; kept in localStorage `magpie.usageWithCache`. The Sessions tab counts by the same pick (#2591): its tokens tile carries the same label pop-up and says the cache's count, and the list's rows, the projects and models bars and pickers, the day chart (whose day and week buckets carry the cache's counts), the calendar and the top sessions read `usageTokens` too, the top list ranked again by the count shown (`sessTokens`, `sessSums`, `renderSessChart`, `renderSessTop`); a pick made on that tab refreshes the tab, not the Overview. The per-session median and p90 stay counted in and out (`Stats.Overview`). The account cards' whole-window estimate follows the same pick (Anotiaww on X): with cache, it adds the cache read and written that magpie routed in the window, scaled by the same share used, and says so (`holdsLine`, now in the Usage plugin's `page.js`, redrawn with the cards when the pick changes; `quota-holds.test.cjs`). The Requests tab's total already counts every token (`allTokens`). A token line in parts (the Requests strip's Tokens card, the Overview's and the Sessions tab's tokens tiles) wraps between its counts and keeps each whole (`usageParts`, `.parts`); only a count wider than its card on its own is cut. See `usage-overview-fold.test.cjs` and `sessions-cache-tokens.test.cjs`.
- A click on a row of the Usage page's Requests (or Enter or Space on it) opens that one request on a page of its own, `#ledReqPane` in place of the list, not Routing (geesehowardt7 on X; `ledReqOpen`, `renderLedReq`): Requests ‹ or Escape goes back to the list where it was left and to its row (`ledReqClose`), and leaving the page closes it (`ledLeave`). The page heads with the model and status, then `ledDetail`: time, agent, source IP (`client_ip`; a loopback address is "This computer", a gateway row older than the field "Not recorded"), requested, provider, account, sent, served, effort, then status, error, duration, tokens, cost and the rest; Routing is the *View routing* link in it. A refresh keeps the page as it was opened (`usage-request-page.test.cjs`, `usage-ledger-detail.test.cjs`).
- A request's details in the Usage ledger say its tokens at every width (#1839, `ledDetail`): "{i} in · {o} out · {r} cache read · {w} cache creation", 0 said as 0, with how much was written for 5 minutes and for an hour when it says so. A failure that spent nothing has no Tokens row. See `ledger-cache-tokens.test.cjs` and `usage-ledger-detail.test.cjs`.
+9
View File
@@ -1442,6 +1442,15 @@ body.masked :hover > .acct-eye, body.masked .pq-card:hover .acct-eye, body.maske
.us-hid .us-showall { align-self: flex-start; margin: 4px 0 0 2px; font-size: 11.5px; }
.us-hid .us-showall[hidden] { display: none; }
#quotaHid .row.stat .who { flex: 1 1 auto; min-width: 0; }
/* the Agents list's small, idle clients, folded into one Other row */
.row.stat.us-other { cursor: default; }
.row.stat.us-other .us-other-chev { display: inline-flex; flex: none; align-items: center; justify-content: center; width: 16px; height: 16px; color: var(--muted); }
.row.stat.us-other .us-other-chev svg { transition: transform .15s cubic-bezier(.23, 1, .32, 1); }
.row.stat.us-other[aria-expanded="true"] .us-other-chev svg { transform: rotate(90deg); }
.row.stat.us-other .who .name { color: var(--fg-2); }
.us-folded { display: flex; flex-direction: column; margin-left: 12px; border-top: 1px solid var(--line-2); }
.us-folded .us-folded-more { align-self: flex-start; margin: 4px 0 0 2px; font-size: 11.5px; }
@media (prefers-reduced-motion: reduce) { .row.stat.us-other .us-other-chev svg { transition: none; } }
/* the switched-off providers' check-ins (wxkwxk666 on X) */
#quotaOff .row.stat .who { flex: 1 1 auto; min-width: 0; }
#quotaOff .wb-checkin { margin-top: 3px; }
+12
View File
@@ -2,6 +2,9 @@
// kernel adds them to i18n.js's (magpie.strings).
magpie.strings({
zh: {
"{n} client": "{n} 个客户端",
"{n} clients": "{n} 个客户端",
"Clients under 1% of the tokens, idle for 3 days or past the top 20. Their calls still count in every total.": "token 不到总量 1%、3 天未使用或排在前 20 名之后的客户端。它们的调用仍计入每一项总计。",
"What the bytes sent upstream were made of": "发往上游的字节由什么组成",
"≈ {size} a request": "每个请求约 {size}",
"Each request sends the whole conversation again, with the system prompt and the tools' definitions, so a request's bytes grow with its context.": "每个请求都会把整段对话连同系统提示词和工具定义重新发送一遍,所以一个请求的字节数随上下文增长。",
@@ -291,6 +294,9 @@ magpie.strings({
"Sent upstream as {to}, as the agent spoke it": "以 {to} 协议发往上游,与 agent 所用协议相同",
},
"zh-TW": {
"{n} client": "{n} 個用戶端",
"{n} clients": "{n} 個用戶端",
"Clients under 1% of the tokens, idle for 3 days or past the top 20. Their calls still count in every total.": "token 不到總量 1%、3 天未使用或排在前 20 名之後的用戶端。它們的呼叫仍計入每一項總計。",
"What the bytes sent upstream were made of": "傳往上游的位元組由什麼組成",
"≈ {size} a request": "每個請求約 {size}",
"Each request sends the whole conversation again, with the system prompt and the tools' definitions, so a request's bytes grow with its context.": "每個請求都會把整段對話連同系統提示詞和工具定義重新傳送一遍,所以一個請求的位元組數隨上下文增長。",
@@ -580,6 +586,9 @@ magpie.strings({
"Sent upstream as {to}, as the agent spoke it": "以 {to} 協議發往上游,與 agent 所用協議相同",
},
ja: {
"{n} client": "{n} 個のクライアント",
"{n} clients": "{n} 個のクライアント",
"Clients under 1% of the tokens, idle for 3 days or past the top 20. Their calls still count in every total.": "トークンが 1% 未満で、3 日間使われていないか上位 20 位より下のクライアント。その呼び出しはすべての合計に含まれます。",
"What the bytes sent upstream were made of": "上流へ送ったバイトの内訳",
"≈ {size} a request": "1 リクエストあたり約 {size}",
"Each request sends the whole conversation again, with the system prompt and the tools' definitions, so a request's bytes grow with its context.": "各リクエストは会話全体をシステムプロンプトとツール定義ごと送り直すため、リクエストのバイト数はコンテキストとともに増えます。",
@@ -869,6 +878,9 @@ magpie.strings({
"Sent upstream as {to}, as the agent spoke it": "エージェントと同じ {to} で上流へ送信",
},
de: {
"{n} client": "{n} Client",
"{n} clients": "{n} Clients",
"Clients under 1% of the tokens, idle for 3 days or past the top 20. Their calls still count in every total.": "Clients unter 1 % der Tokens, seit 3 Tagen ungenutzt oder nach den ersten 20. Ihre Aufrufe zählen weiter in jeder Summe mit.",
"What the bytes sent upstream were made of": "Woraus die an den Upstream gesendeten Bytes bestehen",
"≈ {size} a request": "≈ {size} pro Anfrage",
"Each request sends the whole conversation again, with the system prompt and the tools' definitions, so a request's bytes grow with its context.": "Jede Anfrage sendet die ganze Unterhaltung erneut, samt Systemprompt und Tool-Definitionen, daher wachsen die Bytes einer Anfrage mit ihrem Kontext.",
+134 -52
View File
@@ -909,6 +909,42 @@ function holdsUnknownLine(why) {
return line;
}
// The Agents list folds the clients that are small and idle into one
// Other row (WJaunita45604 on X: dozens of randomly named test clients of
// ~10K tokens each, every one a row laid out again at each refresh, slowed
// the page down). A client folds when it is past the 5 with the most
// tokens, under 1% of the period's tokens, and either has made no call in
// the last 3 days or is past the top 20; two or more fold, or none do.
// Their sum is the Other row's, so every total stays exact.
const USAGE_FOLD_TOP = 5, USAGE_FOLD_LONG = 20, USAGE_FOLD_SHARE = 0.01, USAGE_FOLD_IDLE = 3 * 864e5;
const USAGE_OTHER_PAGE = 100;
let usageOtherOpen = false, usageOtherShown = USAGE_OTHER_PAGE;
function usageFoldAgents(groups, total, now = Date.now()) {
const rank = new Map([...groups].sort((a, b) => usageTokens(b) - usageTokens(a)).map((g, i) => [g, i]));
const idle = (g) => {
const at = Date.parse(g.last || "");
return at > 0 && now - at >= USAGE_FOLD_IDLE;
};
const folds = (g) => {
const i = rank.get(g);
return i >= USAGE_FOLD_TOP && usageTokens(g) < USAGE_FOLD_SHARE * total && (i >= USAGE_FOLD_LONG || idle(g));
};
const folded = groups.filter(folds);
if (folded.length < 2) return { kept: groups, folded: [] };
return { kept: groups.filter((g) => !folds(g)), folded };
}
// usageSum adds groups' counts up, as one group
function usageSum(groups) {
const add = (s, g) => {
for (const [k, v] of Object.entries(g)) {
if (typeof v === "number") s[k] = (s[k] || 0) + v;
else if (k === "own" && v) s.own = add(s.own || {}, v);
}
return s;
};
return groups.reduce(add, {});
}
function renderUsage() {
const u = usage;
const view = $("#view-usage");
@@ -992,61 +1028,66 @@ function renderUsage() {
fitChartLabels();
const total = Math.max(1, usageTokens(u));
const list = (id, groups, act) => {
// list draws a list's rows anew; more adds what follows them while the
// logos drawn before are still kept
const list = (id, groups, act, more) => {
const box = typeof id === "string" ? $("#" + id) : id;
keepIcons(box); // a logo made again blinks (keepIcons)
box.replaceChildren();
for (const g of groups) {
const r = el("div", "row stat");
r.dataset.id = g.id || "";
r.append(icon(g.icon || "generic"));
const who = el("div", "who");
who.append(el("div", "name" + (g.name ? "" : " faint"), g.name || t("account not recorded")));
const sub = [];
if (g.sub) sub.push(g.sub);
sub.push(t(g.calls === 1 ? "{n} call" : "{n} calls", { n: g.calls }));
// what the calls cost in their plan's credits, as the replies said
// (WorkBuddy's 积分): an account's, a model's, an agent's (lcyksp
// on Discord), not only their tokens
if (g.credited) sub.push(ledCredits(g).textContent);
// magpie's own calls apart from the agents' (#1839): magpie's row
// says it is, and a model's, a key's or an account's how many of
// its calls were
if (id === "usageAgents" && g.id === "magpie") who.firstChild.append(ownBadge());
else if (g.own?.calls) sub.push(ownCalls(g.own.calls));
if (g.errors) sub.push(t("{n} failed", { n: g.errors }));
// of those, the replies magpie ended stuck in a loop (#1858)
if (g.loops) sub.push(t("{n} looped", { n: g.loops }));
if (g.retried) sub.push(t("{n} answered on a retry", { n: g.retried }));
// how long the streamed replies took to begin, and how fast they
// wrote after (#196)
if (g.timed) {
sub.push(t("TTFT {ms}", { ms: ledTook(Math.round(g.ttft_ms / g.timed)) }));
}
const gs = ledGroupSpeed(g);
if (gs) sub.push(gs.text);
const subLine = el("div", "sub", sub.join(" · "));
if (g.own?.calls) subLine.title = ownWhy();
who.append(subLine);
r.append(who);
const share = el("div", "share");
const fill = el("i");
fill.style.width = Math.max(1.5, 100 * usageTokens(g) / total).toFixed(1) + "%";
share.append(fill);
share.title = t("{n}% of tokens", { n: Math.round(100 * usageTokens(g) / total) });
r.append(share);
const num = el("div", "num");
// how much of its prompt came from the cache, counted as the cache
// read tile counts it (#925)
const hitRate = cacheHitOf(g);
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) : ""));
if (act) act(r, g);
box.append(r);
}
for (const g of groups) box.append(row(id, g, act));
if (more) more(box);
keptIcons = null;
return box;
};
const row = (id, g, act) => {
const r = el("div", "row stat");
r.dataset.id = g.id || "";
r.append(icon(g.icon || "generic"));
const who = el("div", "who");
who.append(el("div", "name" + (g.name ? "" : " faint"), g.name || t("account not recorded")));
const sub = [];
if (g.sub) sub.push(g.sub);
sub.push(t(g.calls === 1 ? "{n} call" : "{n} calls", { n: g.calls }));
// what the calls cost in their plan's credits, as the replies said
// (WorkBuddy's 积分): an account's, a model's, an agent's (lcyksp
// on Discord), not only their tokens
if (g.credited) sub.push(ledCredits(g).textContent);
// magpie's own calls apart from the agents' (#1839): magpie's row
// says it is, and a model's, a key's or an account's how many of
// its calls were
if (id === "usageAgents" && g.id === "magpie") who.firstChild.append(ownBadge());
else if (g.own?.calls) sub.push(ownCalls(g.own.calls));
if (g.errors) sub.push(t("{n} failed", { n: g.errors }));
// of those, the replies magpie ended stuck in a loop (#1858)
if (g.loops) sub.push(t("{n} looped", { n: g.loops }));
if (g.retried) sub.push(t("{n} answered on a retry", { n: g.retried }));
// how long the streamed replies took to begin, and how fast they
// wrote after (#196)
if (g.timed) {
sub.push(t("TTFT {ms}", { ms: ledTook(Math.round(g.ttft_ms / g.timed)) }));
}
const gs = ledGroupSpeed(g);
if (gs) sub.push(gs.text);
const subLine = el("div", "sub", sub.join(" · "));
if (g.own?.calls) subLine.title = ownWhy();
who.append(subLine);
r.append(who);
const share = el("div", "share");
const fill = el("i");
fill.style.width = Math.max(1.5, 100 * usageTokens(g) / total).toFixed(1) + "%";
share.append(fill);
share.title = t("{n}% of tokens", { n: Math.round(100 * usageTokens(g) / total) });
r.append(share);
const num = el("div", "num");
// how much of its prompt came from the cache, counted as the cache
// read tile counts it (#925)
const hitRate = cacheHitOf(g);
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) : ""));
if (act) act(r, g);
return r;
};
// a client hidden from the Agents list (ikunbots on X: curl,
// Go-http-client, python-httpx beside the agents in use) is left out of
@@ -1055,7 +1096,7 @@ function renderUsage() {
const hid = new Set(state.settings?.usageAgentsHidden || []);
const agents = usageSorted(u.agents, "agents");
const hidden = agents.filter((g) => hid.has(g.id));
list("usageAgents", agents.filter((g) => !hid.has(g.id)), (r, g) => {
const agentAct = (r, g) => {
r.classList.add("acts");
const b = el("button", "icon us-more");
b.type = "button";
@@ -1084,6 +1125,47 @@ function renderUsage() {
b.onclick = (e) => { e.stopPropagation(); menu(); };
r.oncontextmenu = (e) => { e.preventDefault(); menu(); };
r.querySelector(".share").after(b);
};
// the small clients idle for days fold into one Other row at the
// list's foot (usageFoldAgents), drawn only while it is open
const { kept, folded } = usageFoldAgents(agents.filter((g) => !hid.has(g.id)), total);
if (!folded.length) usageOtherOpen = false;
list("usageAgents", kept, agentAct, (box) => {
if (!folded.length) return;
// a page at a time: every row drawn is laid out again at each refresh.
// The folded rows are made before the Other row, so their logos are
// the ones kept from the last draw
let inner = null;
if (usageOtherOpen) {
const shown = folded.slice(0, usageOtherShown);
inner = el("div", "us-folded");
for (const g of shown) inner.append(row("usageAgents", g, agentAct));
if (folded.length > shown.length) {
const more = el("button", "text us-folded-more", t("Show {n} more", { n: folded.length - shown.length }));
more.type = "button";
more.onclick = (e) => { e.stopPropagation(); usageOtherShown += USAGE_OTHER_PAGE; renderUsage(); };
inner.append(more);
}
}
const other = row("usageAgents", { ...usageSum(folded), id: "", name: t("Other"), sub: t(folded.length === 1 ? "{n} client" : "{n} clients", { n: folded.length }), icon: "generic" });
other.classList.add("us-other");
const chev = el("span", "us-other-chev");
chev.append(svg(CHEV_R, 11, 1.6));
other.firstChild.replaceWith(chev);
other.tabIndex = 0;
other.setAttribute("role", "button");
other.setAttribute("aria-expanded", String(usageOtherOpen));
other.title = t("Clients under 1% of the tokens, idle for 3 days or past the top 20. Their calls still count in every total.");
const flip = () => {
usageOtherOpen = !usageOtherOpen;
usageOtherShown = USAGE_OTHER_PAGE;
renderUsage();
$("#usageAgents .us-other")?.focus({ preventScroll: true });
};
other.onclick = flip;
other.onkeydown = (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); flip(); } };
box.append(other);
if (inner) box.append(inner);
});
const hb = $("#usageAgentsHid");
hb.hidden = !hidden.length;
@@ -0,0 +1,232 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// The Usage page's Agents list folds the clients that are small and idle
// into one Other row at its foot (WJaunita45604 on X: dozens of randomly
// named test clients of ~10K tokens each made the page crawl). A client
// folds when it is past the 5 with the most tokens, under 1% of the
// tokens, and either made no call in the last 3 days or is past the top
// 20. The top clients always show; a small client used today stays in
// sight. The Other row's numbers are the folded ones' sum, so the totals
// are exact. It opens and closes with a click or Enter, the page left
// where it is, and shows its rows 100 at a time. Every language, a wide
// window, a narrow one and magpie web on a phone; no backend, the API is
// faked.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const reader = require("./reader.cjs");
const assets = path.resolve(__dirname, "../assets");
const now = Date.now();
const ago = (ms) => new Date(now - ms).toISOString();
const H = 3600e3, D = 24 * H;
const G = (id, name, tokens, last, icon) => ({ id, name, icon: icon || "generic", calls: 10, input: tokens - 100, output: 100, cache_read: 0, cache_write: 0, cost: 0.01, ...(last ? { last } : {}) });
// the clients kept in sight, in token order
const KEPT = [
G("bun", "Bun", 5e6, ago(H)),
G("siyuan", "SiYuan", 2e6, ago(H)),
G("translate-web", "translate-web", 1e6, ago(H)),
G("busy", "busy", 300000, ago(10 * D)), // idle, but over 1%: kept
G("mid", "mid", 200000, ago(H)),
G("today", "today", 15000, ago(H)), // small, used an hour ago, in the top 20
G("unknown", "unknown", 11000), // no last call said: not called idle
];
// the folded ones: 150 test clients idle for 5 days, and one used today
// past the top 20
const FOLDED = [];
for (let i = 0; i < 150; i++) FOLDED.push(G("t" + (1000 + i) + "q", (1000 + i) + "q", 10000 - i, ago(5 * D)));
FOLDED.push(G("late", "late", 5000, ago(H)));
const AGENTS = [...KEPT, ...FOLDED];
const TOTAL = AGENTS.reduce((n, g) => n + g.input + g.output, 0);
const USAGE = {
calls: 10 * AGENTS.length, errors: 0, input: TOTAL - 1000, output: 1000, reasoning: 0, cache_read: 0, cache_write: 0, unpriced: 0, cost: 0.01 * AGENTS.length, bucket: "day",
series: [],
path: "~/.config/magpie/usage.jsonl",
agents: AGENTS,
models: [{ ...G("m", "glm-5", TOTAL), model: "glm-5" }],
};
function server(lang, web) {
return async (route) => {
const req = route.request();
const url = new URL(req.url());
const json = (data) => route.fulfill({ json: data });
const settings = () => ({ lang, theme: "light" });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:${web}};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ agents: [], clients: [], profiles: [], settings: settings(), fx: { rate: 7.2, at: new Date().toISOString() } });
if (url.pathname === "/api/settings") return json(settings());
if (url.pathname === "/api/usage/quotas") return json([]);
if (url.pathname === "/api/usage") return json(USAGE);
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], models: [], gateway: { running: false } });
if (url.pathname === "/api/sessions") return json({ sessions: [], dirs: [] });
if (url.pathname === "/api/sessions/stats") return json({ from: "", to: "", days: [], agents: {} });
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
if (url.pathname.startsWith("/api/")) return json({});
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
await route.fulfill({ body: await fs.readFile(file), contentType });
};
}
const L = {
en: { other: "Other", clients: (n) => `${n} clients`, more: (n) => `Show ${n} more` },
zh: { other: "其他", clients: (n) => `${n} 个客户端`, more: (n) => `显示其余 ${n} 个` },
"zh-TW": { other: "其他", clients: (n) => `${n} 個用戶端`, more: (n) => `顯示其餘 ${n} 個` },
ja: { other: null, clients: (n) => `${n} 個のクライアント`, more: null },
de: { other: null, clients: (n) => `${n} Clients`, more: null },
};
// bring wheels the view as a reader does, in steps as long as the way to
// the control, till it is in sight: 100 rows are far for 20px steps
async function bring(p, loc) {
await loc.waitFor({ state: "visible" });
const view = p.locator("#view-usage");
const v = await view.boundingBox();
await p.mouse.move(v.x + v.width / 2, v.y + v.height / 2);
for (let i = 0; i < 60; i++) {
const b = await loc.boundingBox();
if (b.y >= v.y && b.y + b.height <= v.y + v.height) { await p.waitForTimeout(150); return; }
const d = b.y < v.y ? b.y - v.y - 40 : b.y + b.height - (v.y + v.height) + 40;
const was = await view.evaluate((e) => e.scrollTop);
await p.mouse.wheel(0, Math.max(-600, Math.min(600, d)));
await p.waitForFunction(([was]) => document.querySelector("#view-usage").scrollTop !== was, [was], { timeout: 2000 }).catch(() => {});
}
throw new Error("not in sight: " + JSON.stringify({ view: v, target: await loc.boundingBox() }));
}
const SIZES = [{ width: 1200, web: false }, { width: 560, web: false }, { width: 390, web: true }];
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": the Usage page folds small, idle clients into Other", async (t) => {
assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
for (const lang of Object.keys(L)) {
for (const { width, web } of SIZES) {
const w = L[lang];
await t.test(`${lang} ${width}${web ? " web" : ""}`, async () => {
const errors = [];
const ctx = await browser.newContext({ viewport: { width, height: 700 }, reducedMotion: "reduce", hasTouch: web, isMobile: web && engine === "chromium" });
const p = await ctx.newPage();
p.setDefaultTimeout(5000);
p.setDefaultNavigationTimeout(60000);
p.on("pageerror", (e) => errors.push(e.message));
await p.route("**/*", server(lang, web));
await p.goto("http://magpie.test/");
const nav = p.locator('[data-view="usage"]:visible').first();
if (await nav.count()) await nav.click();
else await p.evaluate(() => show("usage"));
await p.locator("#usageAgents .row.stat").first().waitFor();
const ids = (sel) => p.locator(sel).evaluateAll((rs) => rs.map((r) => r.dataset.id));
const top = () => p.locator("#view-usage").evaluate((v) => v.scrollTop);
const fmt = (n) => p.evaluate((n) => fmtN(n), n);
// the top clients and the small one used today stay; the rest is
// one row at the foot
assert.deepEqual(await ids("#usageAgents > .row.stat"), [...KEPT.map((g) => g.id), ""]);
const other = p.locator("#usageAgents > .row.stat.us-other");
assert.equal(await other.count(), 1);
if (w.other) assert.equal((await other.locator(".who .name").textContent()).trim(), w.other);
const sub = (await other.locator(".who .sub").textContent()).trim();
assert(sub.startsWith(w.clients(FOLDED.length)), `the Other row says how many it holds: ${sub}`);
assert.equal(await other.locator(".us-more").count(), 0, "Other has no actions of its own");
assert.equal(await other.getAttribute("aria-expanded"), "false");
assert.equal(await p.locator("#usageAgents .us-folded").count(), 0, "the folded rows aren't drawn while closed");
assert.equal(await p.locator("#usageAgents .row.stat").count(), KEPT.length + 1);
// its numbers are the folded ones' sum: every row adds up to the total
const foldedTokens = FOLDED.reduce((n, g) => n + g.input + g.output, 0);
assert.equal((await other.locator(".num b").textContent()).trim(), await fmt(foldedTokens));
const shown = await p.evaluate(() => {
const u = usage;
const { kept, folded } = usageFoldAgents(u.agents, usageTokens(u));
return [kept.reduce((n, g) => n + usageTokens(g), 0) + usageTokens(usageSum(folded)), usageTokens(u), usageSum(folded).calls, usageSum(folded).cost];
});
assert.equal(shown[0], shown[1], "kept and folded add up to the page's tokens");
assert.equal(shown[2], 10 * FOLDED.length, "and to its calls");
assert(Math.abs(shown[3] - 0.01 * FOLDED.length) < 1e-9, "and to its cost");
// a click opens it, the page left where it is; 100 rows at a time
await reader.inView(p, other);
let at = await top();
await other.click();
assert.equal(await other.getAttribute("aria-expanded"), "true");
const folded = "#usageAgents .us-folded > .row.stat";
assert.equal(await p.locator(folded).count(), 100);
assert.deepEqual((await ids(folded)).slice(0, 3), FOLDED.slice(0, 3).map((g) => g.id));
assert.equal(await top(), at, "opening Other doesn't move the page");
assert.equal(await p.locator(folded + " .us-more").count(), 100, "a folded row keeps its actions");
const moreBtn = p.locator("#usageAgents .us-folded-more");
if (w.more) assert.equal((await moreBtn.textContent()).trim(), w.more(FOLDED.length - 100));
await bring(p, moreBtn);
at = await top();
await moreBtn.click();
await p.waitForFunction((n) => document.querySelectorAll("#usageAgents .us-folded > .row.stat").length === n, FOLDED.length);
assert.equal(await moreBtn.count(), 0);
assert.equal(await top(), at, "showing more doesn't move the page");
assert.equal((await ids(folded)).at(-1), "late");
// nothing is wider than the page, and every row's action stays in it
const wide = await p.evaluate(() => { const v = document.querySelector("#view-usage"); return [v.scrollWidth, v.clientWidth, document.documentElement.scrollWidth, window.innerWidth]; });
assert(wide[0] <= wide[1] + 1 && wide[2] <= wide[3] + 1, "no sideways scroll: " + wide);
const out = await p.evaluate(() => [...document.querySelectorAll("#usageAgents .row.stat")].filter((r) => {
const box = r.getBoundingClientRect();
return [...r.querySelectorAll(".us-more")].some((b) => { const x = b.getBoundingClientRect(); return x.right > box.right + 0.5 || x.left < box.left - 0.5; });
}).map((r) => r.dataset.id));
assert.deepEqual(out, [], "every row's action stays inside its row");
// Enter closes it, the focus kept on the row
await bring(p, other);
const rowAt = () => other.evaluate((e) => e.getBoundingClientRect().top);
const was = await rowAt();
await other.focus();
await p.keyboard.press("Enter");
assert.equal(await other.getAttribute("aria-expanded"), "false");
assert.equal(await p.locator("#usageAgents .us-folded").count(), 0);
assert.equal(await p.evaluate(() => document.activeElement?.classList.contains("us-other")), true);
// the row stays where it was on the screen, unless the page is
// now too short to be scrolled that far: then it is at its end
const end = await p.locator("#view-usage").evaluate((v) => v.scrollTop + v.clientHeight >= v.scrollHeight - 1);
const now = await rowAt();
assert(Math.abs(now - was) < 1.5 || (end && now > was), `closing Other leaves its row where it was: ${was} → ${now}`);
// and Space opens it again, 100 at a time once more
await p.keyboard.press(" ");
assert.equal(await p.locator(folded).count(), 100);
assert.deepEqual(errors, []);
await ctx.close();
});
}
}
});
}
// The rule itself, apart from the page: two or more fold or none do, a
// client with no last call is not idle, and rank comes from tokens.
test("the fold rule", async (t) => {
const browser = await chromium.launch({ channel: "chromium" });
t.after(() => browser.close());
const ctx = await browser.newContext();
const p = await ctx.newPage();
await p.route("**/*", server("en", false));
await p.goto("http://magpie.test/");
await p.waitForFunction(() => typeof usageFoldAgents === "function");
const fold = (groups) => p.evaluate(([groups, now]) => {
const total = groups.reduce((n, g) => n + usageTokens(g), 0);
return usageFoldAgents(groups, total, now).folded.map((g) => g.id);
}, [groups, now]);
const top5 = [G("a", "a", 1e6), G("b", "b", 1e6), G("c", "c", 1e6), G("d", "d", 1e6), G("e", "e", 1e6)];
// one idle small client alone stays a row
assert.deepEqual(await fold([...top5, G("x", "x", 100, ago(5 * D))]), []);
// two do fold
assert.deepEqual(await fold([...top5, G("x", "x", 100, ago(5 * D)), G("y", "y", 100, ago(4 * D))]), ["x", "y"]);
// under 3 days is not idle; no last is not idle
assert.deepEqual(await fold([...top5, G("x", "x", 100, ago(2 * D)), G("y", "y", 100)]), []);
// the top 5 never fold, small and idle as they are
assert.deepEqual(await fold([G("a", "a", 100, ago(9 * D)), G("b", "b", 100, ago(9 * D)), G("c", "c", 1e6)]), []);
// the order given doesn't decide the rank
assert.deepEqual(await fold([G("x", "x", 100, ago(5 * D)), G("y", "y", 100, ago(4 * D)), ...top5]), ["x", "y"]);
await ctx.close();
});