usage: what is hidden from the Overview can be found again (yuu003348 on Discord)

yuu003348 on Discord: "观测/用量/概览 从概览中隐藏 后 无法取消隐藏". The way
back was there: a "{n} hidden" line under the cards (#quotaHid), each row with
Unhide, Show all from two. But it was drawn in --faint (#b9b9c2 on #f4f4f6,
1.77:1, 11.5px), so it couldn't be found; the Agents list's line (ikunbots on
X) is the same class.

- app.css: .us-hid .us-hidline is --muted (3:1 or more in light; ~5:1 in
  dark by the tokens), for both lines.
- plugins/usage/page.js: while any are hidden, a card's menu and an Agents
  row's menu end with "Show {n} Hidden". It opens the line under its list,
  puts the keyboard on it and brings it into sight on the menu's click
  (openHidden, scrollOnPurpose). hiddenQuotas() is the one count both the
  line and the menu read.
- i18n: "Show {n} Hidden" in zh, zh-TW, ja, de.
- docs/subsystems/gui-shell.md says both.
- usage-cards-hide / usage-agents-hide now expect the new item when
  something is hidden already.

Run (mote, node --test):
- usage-hidden-way-back.test.cjs (new): chromium and webkit, en/zh/zh-TW/ja/
  de, 1200, 560 and 390 (touch long-press): 2 of 2 ok (32 cases).
- 130 Usage/menu/tray GUI files: the only reds the change made were
  usage-cards-hide and usage-agents-hide's exact menu lists, now updated.
  Every other red there is red at origin/main fdfce4d98 too, run alone side
  by side (216 tests at base, 248 at head, the same 72 fail by name):
  balance-fix (#4683), menu-input-scroll (#3402), tray-cell-click and
  usage-fold "most on one screen" (#4790, #3415), usage-ledger "newest
  live route" (#3104, #4078), usage-agents-hide "unhiding a row leaves the
  hidden line where it was" (#2276, #3414; it fails after the menu checks).
  usage-cards-hide is ok at head.
- go test ./internal/gui: ok but TestMainWindowCorners/macOS_26_SDK (#3949).
  No Go changed, so no gofmt or vet.

Broken by hand: on the old assets the new test is red on contrast
("#quotaHid .us-hidline reads rgb(185, 185, 194) on rgb(244, 244, 246):
1.77:1"); with the new CSS and the old page.js it is red on the menu (no
"Show 1 Hidden").

Not tried: the real app or a real account; dark mode's contrast is from
the tokens, not measured in a test; Windows and Linux webviews; the whole
GUI suite (the change is a menu item and a colour, no new API call or
layout).
This commit is contained in:
yetone
2026-11-02 10:29:13 +08:00
parent d39358f1bb
commit dee1afa400
7 changed files with 225 additions and 20 deletions
+2 -2
View File
@@ -502,8 +502,8 @@ covers it in both engines, every language and a narrow window.
- There are no native `<select>` elements and no colored left-border stripes. State is shown with a dot or a swatch. A dot never says good or failed by colour alone: a failed state's dot is the same box drawn as an x (`--x-mark`, a mask over its red, scaled 1.5 so it reads as heavy as the round dot), since red and green dots read as one colour to a red-green colour-blind reader (coolmantou on Discord). That holds for Test models (`.tdot`), an agent's status line (`.ag-dot`), the check-in (`.ci-dot`), the request ledger (`.led .st .dot`), Routing's tries, steps and preview (`.rt-req`/`.rt-probe`, `.rt-steps`, `.ps-dst`) and a Library server's health (`.lib-health.err`); see `status-dot-shape.test.cjs`.
- What the window shows can be selected and copied, its controls can't, as in a Mac app (Outvi V on Discord: nothing could be copied into a bug report). The page is `user-select: none`, and two `:where()` rules after `body` in `app.css` make text content selectable (paragraphs, `pre` and `code`, a detail's values, hints and notes, every error class, a conversation, a request's story on Routing) and keep every control unselectable with what is in it (buttons, labels, tabs, menus, the navigation, grips). Both have no specificity, so a view's own rule still decides, as a list being sorted does; a field stays selectable. See `user-select.test.cjs`.
- The Usage page's cards and the tray panel's Allowances tab share one order, `settings.UsageOrder` (`byUsageOrder`). In the panel a balance-only card stands where that order puts it, and balances next to each other share one *Balances* grid (`panelBalances`, #1510); none is gathered after the plans. The panel's *Arrange* (`panelArrange`) moves rows in it and hides subscriptions from that tab alone (`settings.PanelUsageHidden`); both save through `POST /api/usage/arrange`, which changes only the field it is sent, and the Settings save keeps both. Hiding is display only: a menu bar cell's card shows though hidden (`panelPeek`). See `TestUsageArrangePanelHidden`, `panel-arrange.test.cjs` and `panel-balance-order.test.cjs`.
- An allowance card can be hidden from Usage › Overview (whqtian_07012 on Discord: StepFun's plan wanted, its balance not). Right-click a card, or press it long on a touch screen (`quotaCardMenus` in `plugins/usage/page.js`), and the app menu offers *Hide from Overview*; 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, the Accounts list, the tray panel (which has its own *Arrange*) and the menu bar cells never hear of it; a cell clicked for a hidden card shows it until the page is left (`usagePeek`). A quiet "{n} hidden" line under the cards (`#quotaHid`, `renderQuotaHid`) opens them, each with *Unhide*, and *Show all* from two. See `TestUsageArrangeCardsHidden` and `usage-cards-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 quiet "{n} hidden" line under the list opens them, each with *Unhide* (`hideUsageAgent`). See `TestUsageArrangeAgentsHidden` and `usage-agents-hide.test.cjs`.
- An allowance card can be hidden from Usage › Overview (whqtian_07012 on Discord: StepFun's plan wanted, its balance not). Right-click a card, or press it long on a touch screen (`quotaCardMenus` in `plugins/usage/page.js`), and the app menu offers *Hide from Overview*; 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, the Accounts list, the tray panel (which has its own *Arrange*) and the menu bar cells never hear of it; a cell clicked for a hidden card shows it until the page is left (`usagePeek`). 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` and `usage-hidden-way-back.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`.
- 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 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 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`.
- 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`.
+1 -1
View File
@@ -1283,7 +1283,7 @@ body.masked :hover > .acct-eye, body.masked .pq-card:hover .acct-eye, body.maske
.us-hid[hidden] { display: none; }
/* a list folded under its heading (#2378) */
#usagePane .list.folded, #usagePane .us-hid.folded { display: none; }
.us-hid .us-hidline { align-self: flex-start; display: inline-flex; align-items: center; gap: 4px; margin: 4px 0 0 2px; font-size: 11.5px; color: var(--faint); }
.us-hid .us-hidline { align-self: flex-start; display: inline-flex; align-items: center; gap: 4px; margin: 4px 0 0 2px; font-size: 11.5px; color: var(--muted); }
.us-hid .us-hidline:hover { color: var(--fg-2); }
.us-hid .us-hidline svg { transition: transform .15s; }
.us-hid .us-hidline[aria-expanded="true"] svg { transform: rotate(180deg); }
@@ -2,6 +2,7 @@
// kernel adds them to i18n.js's (magpie.strings).
magpie.strings({
zh: {
"Show {n} Hidden": "显示已隐藏的 {n} 个",
"Hide from Overview": "从概览中隐藏",
"Hide this account from Overview": "从概览中隐藏这个账号",
"Hide its balance from Overview": "从概览中隐藏它的余额",
@@ -240,6 +241,7 @@ magpie.strings({
"Sent upstream as {to}, as the agent spoke it": "以 {to} 协议发往上游,与 agent 所用协议相同",
},
"zh-TW": {
"Show {n} Hidden": "顯示已隱藏的 {n} 個",
"Hide from Overview": "從概覽中隱藏",
"Hide this account from Overview": "從概覽中隱藏這個帳號",
"Hide its balance from Overview": "從概覽中隱藏它的餘額",
@@ -478,6 +480,7 @@ magpie.strings({
"Sent upstream as {to}, as the agent spoke it": "以 {to} 協議發往上游,與 agent 所用協議相同",
},
ja: {
"Show {n} Hidden": "非表示の {n} 件を表示",
"Hide from Overview": "概要から隠す",
"Hide this account from Overview": "このアカウントを概要から隠す",
"Hide its balance from Overview": "残高を概要から隠す",
@@ -716,6 +719,7 @@ magpie.strings({
"Sent upstream as {to}, as the agent spoke it": "エージェントと同じ {to} で上流へ送信",
},
de: {
"Show {n} Hidden": "{n} ausgeblendete anzeigen",
"Hide from Overview": "In der Übersicht ausblenden",
"Hide this account from Overview": "Dieses Konto in der Übersicht ausblenden",
"Hide its balance from Overview": "Sein Guthaben in der Übersicht ausblenden",
+22 -2
View File
@@ -751,6 +751,7 @@ function renderUsage() {
...(countable(g.id) ? [{ name: "Count as an agent…", icon: COUNT_AS, run: () => pickCountAs(b, g) }] : []),
...counted.map((c) => ({ name: t("Count {client} on its own", { client: c }), icon: OUT, run: () => countClientAs(c, "") })),
{ name: "Hide from this list", icon: EYE_OFF, sep: countable(g.id) || counted.length > 0, run: () => hideUsageAgent(g.id, true) },
...(hidden.length ? [{ name: t("Show {n} Hidden", { n: hidden.length }), literal: true, icon: EYE, sep: true, run: (e) => openHidden(e, "usageAgentsHid", () => { usageHidOpen = true; renderUsage(); }) }] : []),
]);
};
if (counted.length) {
@@ -862,6 +863,18 @@ async function countClientAs(client, as) {
}
}
// openHidden opens a list's hidden ones from a row's menu (yuu003348 on
// Discord: 从概览中隐藏 后 无法取消隐藏): the line under the list, opened, with
// the keyboard on it, brought into sight when the menu's click asks
function openHidden(e, id, open) {
open();
const line = $("#" + id + " .us-hidline");
if (!line || line.closest("[hidden]")) return;
line.focus({ preventScroll: true });
const box = $("#" + id), v = $("#view-usage"), r = box.getBoundingClientRect(), b = v.getBoundingClientRect();
if ((r.top < b.top || r.bottom > b.bottom) && scrollOnPurpose(e, 400)) box.scrollIntoView({ block: "nearest" });
}
// hideUsageAgent takes a client out of the Usage page's Agents list, or
// puts it back: drawn at once, put back if the save fails. Its calls stay
// in the ledger and in every total.
@@ -954,18 +967,25 @@ function quotaCardMenu(target, card, subs) {
closeAgentMenu();
if (again) return;
const one = of.length === 1 && of[0];
const others = hiddenQuotas().length;
openRowMenu(anchor, [
{ name: who && subs.length > 1 ? "Hide this account from Overview" : "Hide from Overview", icon: EYE_OFF, run: () => hideQuotaCards(of.flatMap(cardHideKeys), true) },
// a plan's card showing its key's balance: the balance alone
...(one?.balanceCard ? [{ name: "Hide its balance from Overview", icon: EYE_OFF, run: () => hideQuotaCards([one.balanceCard + "|balance"], true) }] : []),
// the ones hidden already, from the menu that hid them
...(others ? [{ name: t("Show {n} Hidden", { n: others }), literal: true, icon: EYE, sep: true, run: (e) => openHidden(e, "quotaHid", () => { quotaHidOpen = true; renderQuotaHid(); }) }] : []),
]);
}
// hiddenQuotas: the cards the Overview leaves out, those the line lists
function hiddenQuotas() {
const hid = hiddenCards();
return quotas && hid.size ? sharedBalances(quotas).filter((q) => hid.has(cardHideKey(q)) && !cardPeeked(q)) : [];
}
// renderQuotaHid: the line under the cards saying how many are hidden,
// opening them, each with Unhide, and Show all
function renderQuotaHid() {
const hb = $("#quotaHid");
const hid = hiddenCards();
const hidden = quotas && hid.size ? sharedBalances(quotas).filter((q) => hid.has(cardHideKey(q)) && !cardPeeked(q)) : [];
const hidden = hiddenQuotas();
hb.hidden = !hidden.length;
if (!hidden.length) { quotaHidOpen = false; return; }
const line = hb.querySelector(".us-hidline"), hl = hb.querySelector(".list");
@@ -67,11 +67,11 @@ function server(lang, web, saved, posts) {
}
const L = {
en: { hide: "Hide from this list", n: (n) => `${n} hidden`, unhide: "Unhide" },
zh: { hide: "从列表中隐藏", n: (n) => `已隐藏 ${n} 个`, unhide: "取消隐藏" },
"zh-TW": { hide: "從列表中隱藏", n: (n) => `已隱藏 ${n} 個`, unhide: "取消隱藏" },
ja: { hide: "この一覧から隠す", n: (n) => `${n} 件非表示`, unhide: "再表示" },
de: { hide: "In dieser Liste ausblenden", n: (n) => `${n} ausgeblendet`, unhide: "Einblenden" },
en: { more: (n) => `Show ${n} Hidden`, hide: "Hide from this list", n: (n) => `${n} hidden`, unhide: "Unhide" },
zh: { more: (n) => `显示已隐藏的 ${n} 个`, hide: "从列表中隐藏", n: (n) => `已隐藏 ${n} 个`, unhide: "取消隐藏" },
"zh-TW": { more: (n) => `顯示已隱藏的 ${n} 個`, hide: "從列表中隱藏", n: (n) => `已隱藏 ${n} 個`, unhide: "取消隱藏" },
ja: { more: (n) => `非表示の ${n} 件を表示`, hide: "この一覧から隠す", n: (n) => `${n} 件非表示`, unhide: "再表示" },
de: { more: (n) => `${n} ausgeblendete anzeigen`, hide: "In dieser Liste ausblenden", n: (n) => `${n} ausgeblendet`, unhide: "Einblenden" },
};
const SIZES = [{ width: 1200, web: false }, { width: 560, web: false }, { width: 390, web: true }];
@@ -123,8 +123,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
let at = await top(p);
await more.click();
const item = p.locator(".row-menu .rm-item");
assert.deepEqual(await item.allTextContents(), [w.hide]);
await item.click();
assert.deepEqual(await item.allTextContents(), [w.hide, w.more(1)], "with one hidden, the menu offers the way back too");
await item.filter({ hasText: w.hide }).click();
await p.waitForFunction(() => !document.querySelector('#usageAgents .row.stat[data-id="curl"]'));
assert.deepEqual(posts.at(-1), { agentsHidden: ["python-httpx", "curl"] });
assert.equal((await line.textContent()).trim(), w.n(2));
+8 -8
View File
@@ -60,11 +60,11 @@ function server(lang, web, saved, posts) {
}
const L = {
en: { hide: "Hide from Overview", bal: "Hide its balance from Overview", n: (n) => `${n} hidden`, unhide: "Unhide", all: "Show all", balance: "Balance" },
zh: { hide: "从概览中隐藏", bal: "从概览中隐藏它的余额", n: (n) => `已隐藏 ${n} 个`, unhide: "取消隐藏", all: "全部显示", balance: "余额" },
"zh-TW": { hide: "從概覽中隱藏", bal: "從概覽中隱藏它的餘額", n: (n) => `已隱藏 ${n} 個`, unhide: "取消隱藏", all: "全部顯示", balance: "餘額" },
ja: { hide: "概要から隠す", bal: "残高を概要から隠す", n: (n) => `${n} 件非表示`, unhide: "再表示", all: "すべて表示", balance: "残高" },
de: { hide: "In der Übersicht ausblenden", bal: "Sein Guthaben in der Übersicht ausblenden", n: (n) => `${n} ausgeblendet`, unhide: "Einblenden", all: "Alle anzeigen", balance: "Guthaben" },
en: { more: (n) => `Show ${n} Hidden`, hide: "Hide from Overview", bal: "Hide its balance from Overview", n: (n) => `${n} hidden`, unhide: "Unhide", all: "Show all", balance: "Balance" },
zh: { more: (n) => `显示已隐藏的 ${n} 个`, hide: "从概览中隐藏", bal: "从概览中隐藏它的余额", n: (n) => `已隐藏 ${n} 个`, unhide: "取消隐藏", all: "全部显示", balance: "余额" },
"zh-TW": { more: (n) => `顯示已隱藏的 ${n} 個`, hide: "從概覽中隱藏", bal: "從概覽中隱藏它的餘額", n: (n) => `已隱藏 ${n} 個`, unhide: "取消隱藏", all: "全部顯示", balance: "餘額" },
ja: { more: (n) => `非表示の ${n} 件を表示`, hide: "概要から隠す", bal: "残高を概要から隠す", n: (n) => `${n} 件非表示`, unhide: "再表示", all: "すべて表示", balance: "残高" },
de: { more: (n) => `${n} ausgeblendete anzeigen`, hide: "In der Übersicht ausblenden", bal: "Sein Guthaben in der Übersicht ausblenden", n: (n) => `${n} ausgeblendet`, unhide: "Einblenden", all: "Alle anzeigen", balance: "Guthaben" },
};
const SIZES = [{ width: 1200, web: false }, { width: 560, web: false }, { width: 390, web: true }];
@@ -133,7 +133,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
await reader.inView(p, card(p, "stepfun"));
at = await top(p);
await card(p, "stepfun").locator(".subscription-head").click({ button: "right" });
assert.deepEqual(await items(p), [w.hide, w.bal]);
assert.deepEqual(await items(p), [w.hide, w.bal, w.more(1)], "with one hidden, the menu offers the way back too");
await p.locator(".row-menu .rm-item", { hasText: w.bal }).click();
await p.waitForFunction(() => !/42\.00/.test(document.querySelector('#subscriptionUsage > [data-provider="stepfun"]').textContent));
await savedAs(["stepfun-2|balance", "stepfun|balance"]);
@@ -185,8 +185,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
// a whole card hidden too, then Show all has every card back
await reader.inView(p, card(p, "claude"));
await card(p, "claude").locator(".subscription-head").click({ button: "right" });
assert.deepEqual(await items(p), [w.hide]);
await p.locator(".row-menu .rm-item").click();
assert.deepEqual(await items(p), [w.hide, w.more(1)]);
await p.locator(".row-menu .rm-item", { hasText: w.hide }).click();
await p.waitForFunction(() => !document.querySelector('#subscriptionUsage > [data-provider="claude"]'));
await savedAs(["stepfun|balance", "claude|plan"]);
await reader.click(p, p.locator("#quotaHid .us-hidline"));
@@ -0,0 +1,181 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// What was hidden on Usage → Overview has a way back that can be found
// (yuu003348 on Discord: 观测/用量/概览 从概览中隐藏 后 无法取消隐藏). The
// menu that hid a card, or an agent, offers "Show {n} Hidden" while some
// are, which opens the line under the list with the keyboard on it, each
// with Unhide; and the line itself is legible, not the page's faintest
// grey. Every language, both engines, 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 { isDeepStrictEqual } = require("node:util");
const { chromium, webkit } = require("playwright");
const reader = require("./reader.cjs");
const assets = path.resolve(__dirname, "../assets");
const win = (name, used) => ({ name, used, resetSecs: 3 * 3600 });
const QUOTAS = [
{ provider: "claude", name: "Claude", icon: "claude-color", plan: "max", windows: [win("5h", 70)] },
{ provider: "stepfun", name: "StepFun", icon: "stepfun-color", plan: "Step Plan", windows: [win("5h", 30)] },
{ provider: "stepfun-2", name: "StepFun Work", icon: "stepfun-color", windows: [], balance: "¥7.50" },
];
const G = (id, name, tokens, icon) => ({ id, name, icon: icon || "generic", calls: 10, input: tokens - 100, output: 100, cache_read: 0, cache_write: 0, cost: 0 });
const AGENTS = [G("pi", "Pi", 900000, "pi"), G("curl", "curl", 40000)];
const USAGE = {
calls: 20, errors: 0, input: 939800, output: 200, reasoning: 0, cache_read: 0, cache_write: 0, unpriced: 0, cost: 0, bucket: "day",
series: [], path: "~/.config/magpie/usage.jsonl", agents: AGENTS, models: [{ ...G("m", "glm-5", 940000), model: "glm-5" }],
};
function server(lang, web, saved) {
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", usageCardsHidden: saved.cards, usageAgentsHidden: saved.agents });
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: [{ id: "pi", name: "Pi", icon: "pi" }, { id: "curl", name: "curl", icon: "curl" }], profiles: [], settings: settings(), fx: { rate: 7.2, at: new Date().toISOString() } });
if (url.pathname === "/api/usage/arrange") {
const body = JSON.parse(req.postData() || "{}");
if (body.cardsHidden) saved.cards = body.cardsHidden;
if (body.agentsHidden) saved.agents = body.agentsHidden;
return json(settings());
}
if (url.pathname === "/api/settings") return json(settings());
if (url.pathname === "/api/usage/quotas") return json(QUOTAS);
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)];
const body = await fs.readFile(file).catch(() => null);
await (body ? route.fulfill({ body, contentType }) : route.fulfill({ status: 404, body: "" }));
};
}
const L = {
en: { hide: "Hide from Overview", agentHide: "Hide from this list", more: (n) => `Show ${n} Hidden`, show: "Show in Overview", n: (n) => `${n} hidden`, unhide: "Unhide" },
zh: { hide: "从概览中隐藏", agentHide: "从列表中隐藏", more: (n) => `显示已隐藏的 ${n} 个`, show: "在概览中显示", n: (n) => `已隐藏 ${n} 个`, unhide: "取消隐藏" },
"zh-TW": { hide: "從概覽中隱藏", agentHide: "從列表中隱藏", more: (n) => `顯示已隱藏的 ${n} 個`, show: "在概覽中顯示", n: (n) => `已隱藏 ${n} 個`, unhide: "取消隱藏" },
ja: { hide: "概要から隠す", agentHide: "この一覧から隠す", more: (n) => `非表示の ${n} 件を表示`, show: "概要に表示", n: (n) => `${n} 件非表示`, unhide: "再表示" },
de: { hide: "In der Übersicht ausblenden", agentHide: "In dieser Liste ausblenden", more: (n) => `${n} ausgeblendete anzeigen`, show: "In der Übersicht einblenden", n: (n) => `${n} ausgeblendet`, unhide: "Einblenden" },
};
const SIZES = [{ width: 1200, web: false }, { width: 560, web: false }, { width: 390, web: true }];
// WCAG's contrast of two "rgb(r, g, b)" colours
function contrast(a, b) {
const lum = (c) => {
const [r, g, bl] = c.match(/[\d.]+/g).slice(0, 3).map((x) => { const v = x / 255; return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4; });
return 0.2126 * r + 0.7152 * g + 0.0722 * bl;
};
const [x, y] = [lum(a), lum(b)].sort((m, n) => n - m);
return (x + 0.05) / (y + 0.05);
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": what is hidden from the Overview has a way back from the menu that hid it", 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 saved = { cards: ["stepfun-2|balance"], agents: ["curl"] };
const ctx = await browser.newContext({ viewport: { width, height: 700 }, reducedMotion: "reduce", hasTouch: web, isMobile: web && engine === "chromium" });
const open = async () => {
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, saved));
await p.goto("http://magpie.test/?view=usage");
// the first load of the whole app, on a busy machine
await p.locator("#subscriptionUsage .subscription-card").first().waitFor({ timeout: 20000 });
await p.locator("#usageAgents .row.stat").first().waitFor({ timeout: 20000 });
return p;
};
const cards = (p) => p.locator("#subscriptionUsage > .subscription-card").evaluateAll((cs) => cs.map((c) => c.dataset.provider));
const card = (p, id) => p.locator(`#subscriptionUsage > .subscription-card[data-provider="${id}"]`);
const items = (p) => p.locator(".row-menu .rm-item").evaluateAll((bs) => bs.map((b) => b.textContent.trim()));
const longPress = (loc) => loc.evaluate((c) => new Promise((done) => {
const box = c.querySelector(".subscription-head").getBoundingClientRect();
const at = { pointerType: "touch", isPrimary: true, pointerId: 7, bubbles: true, clientX: box.left + box.width / 2, clientY: box.top + box.height / 2 };
c.querySelector(".subscription-head b").dispatchEvent(new PointerEvent("pointerdown", at));
setTimeout(() => { c.querySelector(".subscription-head b").dispatchEvent(new PointerEvent("pointerup", at)); done(); }, 700);
}));
const cardMenu = async (p, id) => {
await reader.inView(p, card(p, id));
if (web) await longPress(card(p, id));
else await card(p, id).locator(".subscription-head").click({ button: "right" });
await p.locator(".row-menu").waitFor();
};
const until = async (f, want) => {
for (const end = Date.now() + 5000; !isDeepStrictEqual(f(), want) && Date.now() < end;) await new Promise((ok) => setTimeout(ok, 20));
assert.deepEqual(f(), want);
};
const inSight = (p, sel) => p.locator(sel).evaluate((e) => {
const r = e.getBoundingClientRect(), v = document.querySelector("#view-usage").getBoundingClientRect();
return r.top >= v.top - 1 && r.bottom <= v.bottom + 1;
});
const p = await open();
assert.deepEqual(await cards(p), ["claude", "stepfun"]);
// the line is legible: not the page's faintest grey
const line = p.locator("#quotaHid .us-hidline");
assert.equal((await line.textContent()).trim(), w.n(1));
for (const sel of ["#quotaHid .us-hidline", "#usageAgentsHid .us-hidline"]) {
const [fg, bg] = await p.locator(sel).evaluate((e) => {
let b = e, c = "rgba(0, 0, 0, 0)";
while (b && /rgba\(0, 0, 0, 0\)|transparent/.test(c)) { c = getComputedStyle(b).backgroundColor; b = b.parentElement; }
return [getComputedStyle(e).color, c];
});
assert(contrast(fg, bg) >= 3, `${sel} reads ${fg} on ${bg}: ${contrast(fg, bg).toFixed(2)}:1`);
}
// the menu that hides a card shows the hidden ones
await cardMenu(p, "claude");
assert.deepEqual(await items(p), [w.hide, w.more(1)]);
await p.locator(".row-menu .rm-item", { hasText: w.more(1) }).click();
await p.waitForFunction(() => document.querySelector("#quotaHid .us-hidline").getAttribute("aria-expanded") === "true");
assert.equal(await p.evaluate(() => document.activeElement?.matches("#quotaHid .us-hidline")), true, "the keyboard is on the line");
assert.deepEqual(await p.locator("#quotaHid .row.stat").evaluateAll((rs) => rs.map((r) => r.dataset.id)), ["stepfun-2|balance"]);
assert.equal(await inSight(p, "#quotaHid"), true, "the opened list is in sight");
await reader.click(p, p.locator("#quotaHid .us-unhide"));
await until(() => saved.cards, []);
await p.waitForFunction(() => !!document.querySelector('#subscriptionUsage > [data-provider="stepfun-2"]'));
assert.equal(await p.locator("#quotaHid").isHidden(), true);
// nothing hidden, nothing to show
await cardMenu(p, "claude");
assert.deepEqual(await items(p), [w.hide]);
await p.keyboard.press("Escape");
// the Agents list's menu, the same
const more = p.locator('#usageAgents .row.stat[data-id="pi"] .us-more');
await reader.click(p, more);
await p.locator(".row-menu").waitFor();
assert.deepEqual(await items(p), [w.agentHide, w.more(1)]);
await p.locator(".row-menu .rm-item", { hasText: w.more(1) }).click();
await p.waitForFunction(() => document.querySelector("#usageAgentsHid .us-hidline").getAttribute("aria-expanded") === "true");
assert.equal(await p.evaluate(() => document.activeElement?.matches("#usageAgentsHid .us-hidline")), true);
assert.equal(await inSight(p, "#usageAgentsHid"), true);
await reader.click(p, p.locator("#usageAgentsHid .us-unhide"));
await until(() => saved.agents, []);
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);
assert.deepEqual(errors, []);
await ctx.close();
});
}
}
});
}