From d6b045a7e7730ee728137cbdb59eea6e1c0916d6 Mon Sep 17 00:00:00 2001 From: yetone Date: Thu, 15 Oct 2026 21:01:26 +0800 Subject: [PATCH] usage: the Overview's lists fold under their headings and stay folded, the token totals can count the cache, and the Requests Tokens card wraps its cache count instead of cutting it (#2378) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The reporter asked for three things on the Usage page: fold Agents, Models and Accounts from their titles and remember it (日常看账号维度 较多,都要拉到最底下); an option to count the cache in the token totals; and the Requests tab's Tokens card cut its cache count off on a wide window ("缓存 879…"). - Folds: each Overview list's heading (Agents, Models, Accounts, and Gateway keys beside them) is a .fold button with its chevron, the Gateway page's pattern. A click keeps the page still (backToReader). What is folded is kept per viewer in localStorage magpie.usageFolded (mountUsageFolds at the plugin's mount, showUsageFolds per render). - Cache: the tokens tile's label is a pop-up (usageTokensPick, the app menu, no ` elements and no colored left-border stripes. State is shown with a dot or a swatch. - 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`. - 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`. +- 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 Requests tab's total already counts every token (`allTokens`). A token line in parts (the Requests strip's Tokens card, the Overview's tokens tile) 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`. - 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`. - 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. 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`. diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index cc83422bd..6007f4385 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -1046,6 +1046,13 @@ body.window .field.solo { grid-column: auto; } .kpi b .u:last-child { margin-right: 0; } .kpi span { font-size: 11px; font-weight: 600; letter-spacing: .05em; text-transform: uppercase; color: var(--muted); margin-top: 3px; } .kpi small { font-size: 11px; color: var(--muted); margin-top: 3px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +/* the Overview's tokens tile names how they are counted, a pop-up of the two + ways (#2378): the label's own look, a small chevron after it */ +.kpi .kpi-pick { align-self: flex-start; display: inline-flex; align-items: center; gap: 3px; max-width: 100%; margin: 2px 0 -1px -4px; padding: 1px 4px; border-radius: 5px; color: var(--muted); transition: background .12s, color .12s; } +.kpi .kpi-pick > span { margin-top: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.kpi .kpi-pick svg { flex: none; } +.kpi .kpi-pick:hover, .kpi .kpi-pick.open { background: var(--pill); color: var(--fg-2); } +.kpi .kpi-pick:hover > span, .kpi .kpi-pick.open > span { color: inherit; } .chart { position: relative; margin-top: 8px; padding: 12px 14px 8px; background: var(--card); border: 1px solid var(--line); border-radius: 12px; flex: none; } .chart .peak { font-size: 10.5px; color: var(--faint); font-variant-numeric: tabular-nums; text-align: right; margin: 0 0 5px; } .chart .bars { display: flex; align-items: flex-end; gap: 3px; height: 72px; border-bottom: 1px solid var(--line-2); } @@ -1085,6 +1092,8 @@ body.window .field.solo { grid-column: auto; } /* the hidden ones: a quiet line under the list, opening them dimmed */ .us-hid { display: flex; flex-direction: column; flex: none; } .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:hover { color: var(--fg-2); } .us-hid .us-hidline svg { transition: transform .15s; } @@ -1128,6 +1137,14 @@ body.window .field.solo { grid-column: auto; } .led-strip .sub.jumps { white-space: normal; overflow: visible; } /* the wait for the first token and its count wrap rather than cut the count off */ .led-strip .sub.ttft { white-space: normal; } +/* a line of counts, as the Tokens card's in, out and cache: each kept whole, + wrapping between them rather than cutting the last off (#2378) */ +/* a line in parts wraps between them, each kept whole; only a part wider + than its card on its own is cut (#2378: "缓存 879…") */ +.led-strip .sub.parts, .kpi small.parts { white-space: normal; } +.led-strip .sub.parts > span, .kpi small.parts > span { display: inline-block; max-width: 100%; vertical-align: bottom; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +/* not the tile's label: .kpi span is its small capitals */ +.kpi small.parts > span { margin-top: 0; font: inherit; letter-spacing: normal; text-transform: none; color: inherit; } .led-strip .led-jump { text-align: start; font: inherit; color: inherit; background: none; border: 0; padding: 0; cursor: pointer; text-decoration: underline dotted; text-underline-offset: 2px; } .led-strip .led-jump.bad { color: var(--red); } .led-strip .led-jump:hover, .led-strip .led-jump.on { text-decoration-style: solid; } diff --git a/internal/gui/assets/plugins/usage/client.js b/internal/gui/assets/plugins/usage/client.js index ff2e7fc6b..ddbd2245f 100644 --- a/internal/gui/assets/plugins/usage/client.js +++ b/internal/gui/assets/plugins/usage/client.js @@ -40,14 +40,14 @@ magpie.plugin("usage", (ctx) => {

Gateway calls only; session-log calls are in Requests. Local rejections are excluded from totals.

-
Agents
+
-
Models
+
- + - +

@@ -126,6 +126,7 @@ magpie.plugin("usage", (ctx) => {

`, + mount() { mountUsageFolds(); }, open() { return loadUsage(true).catch((e) => status(e.message, "err")); }, refresh(again) { // on the Overview, where the allowances are, coming back is opening them (#1588) diff --git a/internal/gui/assets/plugins/usage/i18n.js b/internal/gui/assets/plugins/usage/i18n.js index e9ddb9f67..a61b595a7 100644 --- a/internal/gui/assets/plugins/usage/i18n.js +++ b/internal/gui/assets/plugins/usage/i18n.js @@ -5,6 +5,19 @@ magpie.strings({ "(prompt not recorded)": "(未记录提示词)", "Gateway session": "网关会话", "Seen only through the gateway: the agent kept no session file magpie can read. Turn on Record gateway conversations in Sessions to keep its prompts.": "只经网关看到:agent 没有留下 magpie 能读的会话文件。在「会话」里开启「记录网关对话」可保留它的提示词。", + "Show the agents": "展开 Agent", + "Fold the agents away": "收起 Agent", + "Show the accounts": "展开账号", + "Fold the accounts away": "收起账号", + "Show the gateway keys": "展开网关密钥", + "Fold the gateway keys away": "收起网关密钥", + "tokens with cache": "token(含缓存)", + "Count the cache's tokens in the totals, or leave them out": "选择 token 汇总是否计入缓存", + "Without cache": "不含缓存", + "Input and output": "输入与输出", + "With cache": "含缓存", + "Cache read and written counted too": "同时计入缓存读取与写入", + "Token totals": "token 汇总", "Yesterday": "昨天", "This month": "本月", "Last month": "上个月", @@ -183,6 +196,19 @@ magpie.strings({ "(prompt not recorded)": "(未記錄提示詞)", "Gateway session": "閘道會話", "Seen only through the gateway: the agent kept no session file magpie can read. Turn on Record gateway conversations in Sessions to keep its prompts.": "只經閘道看到:agent 沒有留下 magpie 能讀的會話檔案。在「會話」裡開啟「記錄閘道對話」可保留它的提示詞。", + "Show the agents": "展開 Agent", + "Fold the agents away": "收起 Agent", + "Show the accounts": "展開帳號", + "Fold the accounts away": "收起帳號", + "Show the gateway keys": "展開閘道金鑰", + "Fold the gateway keys away": "收起閘道金鑰", + "tokens with cache": "token(含快取)", + "Count the cache's tokens in the totals, or leave them out": "選擇 token 總計是否計入快取", + "Without cache": "不含快取", + "Input and output": "輸入與輸出", + "With cache": "含快取", + "Cache read and written counted too": "一併計入快取讀取與寫入", + "Token totals": "token 總計", "Yesterday": "昨天", "This month": "本月", "Last month": "上個月", @@ -361,6 +387,19 @@ magpie.strings({ "(prompt not recorded)": "(プロンプト未記録)", "Gateway session": "ゲートウェイのセッション", "Seen only through the gateway: the agent kept no session file magpie can read. Turn on Record gateway conversations in Sessions to keep its prompts.": "ゲートウェイ経由でのみ確認:エージェントは magpie が読めるセッションファイルを残していません。「セッション」で「ゲートウェイの会話を記録」をオンにするとプロンプトが残ります。", + "Show the agents": "エージェントを表示", + "Fold the agents away": "エージェントを折りたたむ", + "Show the accounts": "アカウントを表示", + "Fold the accounts away": "アカウントを折りたたむ", + "Show the gateway keys": "ゲートウェイキーを表示", + "Fold the gateway keys away": "ゲートウェイキーを折りたたむ", + "tokens with cache": "トークン(キャッシュ込み)", + "Count the cache's tokens in the totals, or leave them out": "合計にキャッシュのトークンを含めるかどうか", + "Without cache": "キャッシュなし", + "Input and output": "入力と出力", + "With cache": "キャッシュ込み", + "Cache read and written counted too": "キャッシュの読み取りと書き込みも含める", + "Token totals": "トークンの合計", "Yesterday": "昨日", "This month": "今月", "Last month": "先月", @@ -539,6 +578,19 @@ magpie.strings({ "(prompt not recorded)": "(Prompt nicht aufgezeichnet)", "Gateway session": "Gateway-Sitzung", "Seen only through the gateway: the agent kept no session file magpie can read. Turn on Record gateway conversations in Sessions to keep its prompts.": "Nur über das Gateway gesehen: Der Agent hat keine Sitzungsdatei hinterlassen, die magpie lesen kann. Schalte unter Sitzungen „Gateway-Gespräche aufzeichnen“ ein, um seine Prompts zu behalten.", + "Show the agents": "Agenten anzeigen", + "Fold the agents away": "Agenten einklappen", + "Show the accounts": "Konten anzeigen", + "Fold the accounts away": "Konten einklappen", + "Show the gateway keys": "Gateway-Schlüssel anzeigen", + "Fold the gateway keys away": "Gateway-Schlüssel einklappen", + "tokens with cache": "Token mit Cache", + "Count the cache's tokens in the totals, or leave them out": "Die Token des Caches in den Summen mitzählen oder weglassen", + "Without cache": "Ohne Cache", + "Input and output": "Eingabe und Ausgabe", + "With cache": "Mit Cache", + "Cache read and written counted too": "Cache-Lesen und -Schreiben mitgezählt", + "Token totals": "Token-Summen", "Yesterday": "Gestern", "This month": "Dieser Monat", "Last month": "Letzter Monat", diff --git a/internal/gui/assets/plugins/usage/page.js b/internal/gui/assets/plugins/usage/page.js index 52bed3ab7..e0a9842c1 100644 --- a/internal/gui/assets/plugins/usage/page.js +++ b/internal/gui/assets/plugins/usage/page.js @@ -295,9 +295,84 @@ function fitChartLabels() { } new ResizeObserver(fitChartLabels).observe($("#view-usage")); +// The Overview's lists — Agents, Models, Accounts, Gateway keys — each fold +// away under their heading (#2378: 日常看账号维度较多,都要拉到最底下), and +// stay folded across a reload (magpie.usageFolded, the folded ones' names). +let usageFolded = new Set(); +try { usageFolded = new Set(JSON.parse(localStorage.getItem("magpie.usageFolded") || "[]")); } catch {} +const USAGE_FOLDS = { agents: ["usageAgents", "usageAgentsHid"], models: ["usageModels"], accounts: ["usageAccounts"], keys: ["usageKeys"] }; +const USAGE_FOLD_TITLES = { + agents: ["Show the agents", "Fold the agents away"], + models: ["Show the models", "Fold the models away"], + accounts: ["Show the accounts", "Fold the accounts away"], + keys: ["Show the gateway keys", "Fold the gateway keys away"], +}; +function mountUsageFolds() { + for (const b of $$("#usagePane .row-head .fold[data-fold]")) { + b.prepend(svg(CHEV_R, 11, 1.6)); + b.onclick = () => { + const id = b.dataset.fold; + if (usageFolded.has(id)) usageFolded.delete(id); else usageFolded.add(id); + try { localStorage.setItem("magpie.usageFolded", JSON.stringify([...usageFolded])); } catch {} + showUsageFolds(); + backToReader($("#view-usage")); + }; + } + showUsageFolds(); +} +// a folded list is out of sight by its class, so the page's own hidden +// (no calls, no accounts) is left as it is +function showUsageFolds() { + for (const b of $$("#usagePane .row-head .fold[data-fold]")) { + const id = b.dataset.fold, folded = usageFolded.has(id); + b.setAttribute("aria-expanded", String(!folded)); + b.title = t(USAGE_FOLD_TITLES[id][folded ? 0 : 1]); + for (const box of USAGE_FOLDS[id]) $("#" + box)?.classList.toggle("folded", folded); + } +} + +// usageParts: a line of counts, each kept whole in a span of its own and +// " · " between them, where the line may wrap ("{a} in · {b} out" is two) +function usageParts(texts) { + const out = []; + for (const x of texts.flatMap((s) => s.split(" · "))) out.push(...(out.length ? [" · "] : []), el("span", "", x)); + return out; +} + +// The Overview's token totals count what went in and out; the cache's +// tokens, read and written, can be counted in them too (#2378), as the +// Requests tab's total always has them. Kept as the reader left it +// (magpie.usageWithCache). +let usageWithCache = false; +try { usageWithCache = localStorage.getItem("magpie.usageWithCache") === "1"; } catch {} +const cacheOf = (x) => (x.cache_read || 0) + (x.cache_write || 0); +const usageTokens = (x) => tokensOf(x) + (usageWithCache ? cacheOf(x) : 0); +// the tokens tile's label: a pop-up of the two ways to count +function usageTokensPick() { + const b = el("button", "kpi-pick"); + b.type = "button"; + b.setAttribute("aria-haspopup", "menu"); + b.append(el("span", "", t(usageWithCache ? "tokens with cache" : "tokens")), svg(CHEV, 10, 1.6)); + b.title = t("Count the cache's tokens in the totals, or leave them out"); + b.onclick = (e) => { + e.stopPropagation(); + if (b.classList.contains("open")) return closeProtoMenu(); + openProtoMenu(b, [ + { v: "", name: "Without cache", note: "Input and output" }, + { v: "1", name: "With cache", note: "Cache read and written counted too" }, + ], usageWithCache ? "1" : "", (v) => { + usageWithCache = v === "1"; + try { localStorage.setItem("magpie.usageWithCache", usageWithCache ? "1" : "0"); } catch {} + renderUsage(); + }, "Token totals", "sess-menu"); + }; + return b; +} + function renderUsage() { const u = usage; const view = $("#view-usage"); + showUsageFolds(); view.classList.remove("loading"); view.removeAttribute("aria-busy"); renderPeriod(); @@ -324,11 +399,17 @@ function renderUsage() { const tile = (n, label, sub, title) => { const t = el("div", "kpi"); if (title) t.title = title; - t.append(el("b", "", n), el("span", "", label)); - if (sub) t.append(el("small", "", sub)); + t.append(el("b", "", n), typeof label === "string" ? el("span", "", label) : label); + // a line in parts keeps each whole, wrapping between them rather than + // cutting the last off + if (Array.isArray(sub)) { + const s = el("small", "parts"); + s.append(...usageParts(sub)); + t.append(s); + } else if (sub) t.append(el("small", "", sub)); stats.append(t); }; - tile(fmtN(tokensOf(u)), t("tokens"), t("{a} in · {b} out", { a: fmtN(u.input), b: fmtN(u.output) })); + tile(fmtN(usageTokens(u)), usageTokensPick(), [t("{a} in · {b} out", { a: fmtN(u.input), b: fmtN(u.output) }), ...(usageWithCache && cacheOf(u) ? [t("{a} cache", { a: fmtN(cacheOf(u)) })] : [])]); // cache reads are billed at a fraction of input, so how much of the prompt // came from cache is the number that explains the bill; input here already // excludes the cached tokens, read and written (the gateway subtracts @@ -345,7 +426,7 @@ function renderUsage() { const chart = $("#chart"); chart.replaceChildren(); const bars = el("div", "bars"); - const peak = Math.max(1, ...u.series.map(tokensOf)); + const peak = Math.max(1, ...u.series.map(usageTokens)); const labels = el("div", "labels"); const n = u.series.length; const every = n <= 8 ? 1 : n <= 31 ? Math.ceil(n / 6) : Math.ceil(n / 5); @@ -354,11 +435,12 @@ function renderUsage() { u.series.forEach((p, i) => { const b = el("div", "bar"); const inp = el("i", "in"), out = el("i", "out"); - inp.style.height = (100 * p.input / peak).toFixed(1) + "%"; + // counted with the cache, its tokens are in the prompt's part + inp.style.height = (100 * (usageTokens(p) - p.output) / peak).toFixed(1) + "%"; out.style.height = (100 * p.output / peak).toFixed(1) + "%"; b.append(out, inp); const when = u.bucket === "hour" ? `${p.label}:00` : u.bucket === "week" ? t("week of {label}", { label: dayOf(p) }) : dayOf(p); - b.title = p.calls ? t(p.calls === 1 ? "{when} · {tokens} tokens · {n} call" : "{when} · {tokens} tokens · {n} calls", { when, tokens: fmtN(tokensOf(p)), n: p.calls }) + (fmtCost(p) ? " · ≈" + fmtCost(p) : "") : t("{when} · nothing", { when }); + b.title = p.calls ? t(p.calls === 1 ? "{when} · {tokens} tokens · {n} call" : "{when} · {tokens} tokens · {n} calls", { when, tokens: fmtN(usageTokens(p)), n: p.calls }) + (fmtCost(p) ? " · ≈" + fmtCost(p) : "") : t("{when} · nothing", { when }); bars.append(b); const last = i === n - 1 && (n - 1) % every >= every / 2; labels.append(el("span", "", i % every === 0 || last ? dayOf(p) : "")); @@ -366,7 +448,7 @@ function renderUsage() { chart.append(el("div", "peak", fmtN(peak)), bars, labels); fitChartLabels(); - const total = Math.max(1, tokensOf(u)); + const total = Math.max(1, usageTokens(u)); const list = (id, groups, act) => { const box = typeof id === "string" ? $("#" + id) : id; box.replaceChildren(); @@ -401,16 +483,16 @@ function renderUsage() { r.append(who); const share = el("div", "share"); const fill = el("i"); - fill.style.width = Math.max(1.5, 100 * tokensOf(g) / total).toFixed(1) + "%"; + 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 * tokensOf(g) / total) }); + 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 prompt = g.input + g.cache_read + (g.cache_write || 0); const hit = g.cache_read && prompt ? " · " + t("hit rate {p}", { p: Math.round(100 * g.cache_read / prompt) + "%" }) : ""; - num.append(el("b", "", fmtN(tokensOf(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)); + 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) ? "≈" + fmtCost(g) : "")); if (act) act(r, g); @@ -951,7 +1033,11 @@ function renderLedgerDash(l) { // a line holding a count's button wraps rather than cut the button off // (German's "nach erneutem Versuch beantwortet" runs past a narrow card) const jumps = (...parts) => { const s = line(...parts); s.classList.add("jumps"); return s; }; - block("Tokens", fmtN(total), line(t("{a} in · {b} out", { a: fmtN(l.input), b: fmtN(l.output) }), " · ", t("{a} cache", { a: fmtN(l.cache_read + l.cache_write) })), "", ledNum(total)); + // its parts kept whole, the cache's going under in a card too narrow for + // all three rather than cut (#2378: 缓存 879… in a wide window's five cards) + const tokParts = line(...usageParts([t("{a} in · {b} out", { a: fmtN(l.input), b: fmtN(l.output) }), t("{a} cache", { a: fmtN(l.cache_read + l.cache_write) })])); + tokParts.classList.add("parts"); + block("Tokens", fmtN(total), tokParts, "", ledNum(total)); // a request is counted once, by how it ended: one a later try answered // is not a failure, and is counted beside them as answered on a retry // (小一 on Discord). Each count is a button for its requests in the list. diff --git a/internal/gui/tests/mobile-web.test.cjs b/internal/gui/tests/mobile-web.test.cjs index 49728b033..fba74c979 100644 --- a/internal/gui/tests/mobile-web.test.cjs +++ b/internal/gui/tests/mobile-web.test.cjs @@ -339,6 +339,16 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await current.locator("#view-plugins .lib-tabs .opt").first().evaluate((b) => b.remove()); await current.waitForTimeout(350); } + // Usage's lists fold under their headings and the tokens tile's + // label is a pop-up (#2378): until BASE_REF has them, each is + // put back to the plain label it was, and the rest of the page + // is compared as ever; usage-overview-fold.test.cjs covers them. + if (view === "usage" && !baselineFile("plugins/usage/page.js").toString().includes("function mountUsageFolds")) { + await current.evaluate(() => { + for (const b of document.querySelectorAll("#usagePane .row-head .fold, #stats .kpi-pick")) b.replaceWith(b.querySelector(".label, span")); + }); + await current.waitForTimeout(350); + } const before = PNG.sync.read(await still(original)); const after = PNG.sync.read(await still(current)); const sameSize = before.width === after.width && before.height === after.height; diff --git a/internal/gui/tests/usage-overview-fold.test.cjs b/internal/gui/tests/usage-overview-fold.test.cjs new file mode 100644 index 000000000..0d555fa3e --- /dev/null +++ b/internal/gui/tests/usage-overview-fold.test.cjs @@ -0,0 +1,241 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// #2378 (Usage › Overview): the Agents, Models, Accounts and Gateway keys +// lists each fold away under their heading (日常看账号维度较多,都要拉到最底下), +// by a chevron on the heading, and stay folded across a reload; a click on +// a heading leaves the heading where it is. The tokens tile's label is a +// pop-up (the app's own menu) of how the totals are counted: without the +// cache, as before, or with the cache read and written counted too, in the +// tile, the chart and every row; kept across a reload. And on the Requests +// tab the Tokens card's line (in · out · cache) wraps between its parts +// rather than cutting the cache off in a wide window's five cards (缓存 +// 879…). Every language, 1100 and 420 wide (the Requests card at 1500 too); +// 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"); + +// a row: tokens in and out, and the cache read beside them +const G = (id, name, input, output, cache_read, extra) => ({ id, name, icon: "generic", calls: 10, input, output, cache_read, cache_write: 0, cost: 0, ...extra }); +const AGENTS = [G("codex", "Codex", 5856000, 2217000, 560000000), G("pi", "Pi", 38000, 361, 9216), G("curl", "curl", 17000, 218, 0)]; +const MODELS = [G("gpt-6", "gpt-6", 5856000, 2217000, 560000000, { model: "gpt-6" }), G("glm-5", "glm-5", 55000, 579, 9216, { model: "glm-5" })]; +const ACCOUNTS = [G("acct-a", "a@example.com", 4000000, 1500000, 400000000), G("acct-b", "b@example.com", 1911000, 717579, 160009216)]; +const KEYS = [G("key-1", "laptop", 5911000, 2217579, 560009216)]; +const sum = (k) => AGENTS.reduce((n, g) => n + g[k], 0); +const USAGE = { + calls: 30, errors: 0, input: sum("input"), output: sum("output"), reasoning: 0, cache_read: sum("cache_read"), cache_write: 0, unpriced: 0, cost: 0, bucket: "day", + series: [{ label: "Oct 15", time: new Date().toISOString(), calls: 30, input: sum("input"), output: sum("output"), cache_read: sum("cache_read"), cache_write: 0, cost: 0 }], + path: "~/.config/magpie/usage.jsonl", + agents: AGENTS, models: MODELS, accounts: ACCOUNTS, callerKeys: KEYS, +}; +// the Requests tab's totals, the reporter's: 183.2万 in, 71.1万 out, 8793.3万 cache +const LEDGER = { + period: "today", rows: [], offset: 0, total: 938, calls: 938, errors: 4, retried: 7, + input: 1832000, output: 711000, cache_read: 87933000, cache_write: 0, cost: 12.3, unpriced: 0, + by: {}, bucket: "hour", series: [], agents: [], +}; + +function server(lang) { + return async (route) => { + const url = new URL(route.request().url()); + const json = (data) => route.fulfill({ json: data }); + // zh and zh-TW in 万 and 亿, as the reporter reads them (183.2万 in · 8793.3万 cache) + const settings = { lang, theme: "light", chineseUnits: lang.startsWith("zh") }; + 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: { 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/requests") return json(LEDGER); + 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)]; + try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); } + }; +} + +// the words the reader sees: the headings' titles, the tile's label, the menu +const L = { + en: { foldAcc: "Fold the accounts away", showAcc: "Show the accounts", tokens: "tokens", withCache: "tokens with cache", without: "Without cache", with: "With cache", head: "Token totals" }, + zh: { foldAcc: "收起账号", showAcc: "展开账号", tokens: "token", withCache: "token(含缓存)", without: "不含缓存", with: "含缓存", head: "token 汇总" }, + "zh-TW": { foldAcc: "收起帳號", showAcc: "展開帳號", tokens: "token", withCache: "token(含快取)", without: "不含快取", with: "含快取", head: "token 總計" }, + ja: { foldAcc: "アカウントを折りたたむ", showAcc: "アカウントを表示", tokens: "トークン", withCache: "トークン(キャッシュ込み)", without: "キャッシュなし", with: "キャッシュ込み", head: "トークンの合計" }, + de: { foldAcc: "Konten einklappen", showAcc: "Konten anzeigen", tokens: "Token", withCache: "Token mit Cache", without: "Ohne Cache", with: "Mit Cache", head: "Token-Summen" }, +}; + +const goUsage = async (p) => { + const nav = p.locator('[data-view="usage"]:visible').first(); + if (await nav.count()) await nav.click(); + else await p.evaluate(() => show("usage")); +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": the Overview's lists fold, the totals count the cache on request, the Requests card's cache is whole", 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)) { + const w = L[lang]; + for (const width of [1100, 420]) { + await t.test(`${lang} ${width}: folds and the cache`, async () => { + const errors = []; + const ctx = await browser.newContext({ viewport: { width, height: 700 }, reducedMotion: "reduce" }); + t.after(() => ctx.close()); + const open = async () => { + const p = await ctx.newPage(); + p.setDefaultTimeout(5000); + p.on("pageerror", (e) => errors.push(e.message)); + await p.route("**/*", server(lang)); + await p.goto("http://magpie.test/"); + await goUsage(p); + // drawn, folded or not: a reload may find Accounts folded away + await p.locator("#usageAccounts .row.stat").first().waitFor({ state: "attached" }); + return p; + }; + let p = await open(); + const fold = (id) => p.locator(`#usagePane .row-head .fold[data-fold="${id}"]`); + const shown = (sel) => p.locator(sel).evaluate((e) => !!e.offsetParent); + const top = (loc) => loc.evaluate((e) => e.getBoundingClientRect().top); + + // every list's heading is a fold with its chevron, open at first + for (const id of ["agents", "models", "accounts", "keys"]) { + assert.equal(await fold(id).getAttribute("aria-expanded"), "true", id + " starts open"); + assert.equal(await fold(id).locator("svg").count(), 1, id + " has its chevron"); + } + assert.equal(await fold("accounts").getAttribute("title"), w.foldAcc); + // no coloured stripe on a heading + assert.equal(await fold("accounts").evaluate((e) => getComputedStyle(e).borderLeftWidth), "0px"); + + // Accounts folds where the reader has it, and the heading stays put + await reader.inView(p, fold("accounts")); + const was = await top(fold("accounts")); + await fold("accounts").click(); + await p.waitForTimeout(150); + assert.equal(await fold("accounts").getAttribute("aria-expanded"), "false"); + assert.equal(await fold("accounts").getAttribute("title"), w.showAcc); + assert.equal(await shown("#usageAccounts"), false, "the accounts are folded away"); + assert(Math.abs((await top(fold("accounts"))) - was) <= 1, "folding moved the heading"); + assert.equal(await shown("#usageKeys"), true, "the keys below are still open"); + + // Agents and Models fold too: Accounts' heading comes up the page + await reader.inView(p, fold("agents")); + const at = await top(fold("agents")); + await fold("agents").click(); + await p.waitForTimeout(150); + assert(Math.abs((await top(fold("agents"))) - at) <= 1, "folding Agents moved its heading"); + assert.equal(await shown("#usageAgents"), false); + await reader.inView(p, fold("models")); + await fold("models").click(); + await p.waitForTimeout(150); + assert.equal(await shown("#usageModels"), false); + + // a reload keeps what was folded + await p.close(); + p = await open(); + assert.equal(await fold("agents").getAttribute("aria-expanded"), "false", "Agents stays folded"); + assert.equal(await fold("models").getAttribute("aria-expanded"), "false", "Models stays folded"); + assert.equal(await fold("accounts").getAttribute("aria-expanded"), "false", "Accounts stays folded"); + assert.equal(await shown("#usageAgents"), false); + assert.equal(await shown("#usageAccounts"), false); + assert.equal(await shown("#usageKeys"), true); + // Accounts opened again, the others still folded: it is near the top + await reader.inView(p, fold("accounts")); + await fold("accounts").click(); + await p.waitForTimeout(150); + assert.equal(await shown("#usageAccounts"), true); + assert.equal(await p.locator("#usageAccounts .row.stat").count(), 2); + assert.equal(await shown("#usageAgents"), false); + + // the tokens tile: in and out, as before + const tile = p.locator("#stats .kpi").first(); + const pick = tile.locator(".kpi-pick"); + const fmt = (n) => p.evaluate((n) => fmtN(n), n); + const io = USAGE.input + USAGE.output, all = io + USAGE.cache_read; + assert.equal((await tile.locator("b").textContent()).trim(), await fmt(io)); + assert.equal((await pick.textContent()).trim(), w.tokens); + assert.equal(await p.locator("#usagePane select").count(), 0, "no native select"); + // the pop-up takes the label's room and the line under it reads as + // the next tile's does: not the label's small capitals + const looks = await p.locator("#stats .kpi").evaluateAll((ks) => ks.slice(0, 2).map((k) => { + const s = k.querySelector("small"), part = s.querySelector("span") || s, cs = getComputedStyle(part); + // the label's words: in the pop-up, its span + const label = (k.querySelector(".kpi-pick > span") || k.querySelector(":scope > span")).getBoundingClientRect(); + return { at: Math.round(label.top - k.getBoundingClientRect().top), gap: Math.round(s.getBoundingClientRect().top - label.bottom), case: cs.textTransform, weight: cs.fontWeight, size: cs.fontSize }; + })); + assert.deepEqual(looks[0], looks[1], "the tokens tile's label and line sit and read as the next tile's"); + // the pop-up is the app's own menu + await reader.inView(p, pick); + const vt = await p.locator("#view-usage").evaluate((v) => v.scrollTop); + await pick.click(); + const menu = p.locator(".proto-menu:visible"); + await menu.waitFor(); + assert.equal((await menu.locator(".pm-head").textContent()).trim(), w.head); + assert.deepEqual(await menu.locator(".pm-name").allTextContents(), [w.without, w.with]); + await menu.locator(".pm-item").nth(1).click(); + await p.waitForTimeout(150); + assert.equal(await p.locator("#view-usage").evaluate((v) => v.scrollTop), vt, "the pick moved the page"); + // with the cache: the tile, its label and line, the rows + assert.equal((await tile.locator("b").textContent()).trim(), await fmt(all)); + assert.equal((await tile.locator(".kpi-pick").textContent()).trim(), w.withCache); + assert.equal(await tile.locator("small.parts > span").count(), 3, "in, out and the cache"); + const acct = p.locator('#usageAccounts .row.stat[data-id="acct-a"] .num b'); + assert.equal((await acct.textContent()).trim(), await fmt(4000000 + 1500000 + 400000000)); + // kept across a reload + await p.close(); + p = await open(); + assert.equal((await p.locator("#stats .kpi b").first().textContent()).trim(), await fmt(all), "the choice is kept"); + // back to without + const pick2 = p.locator("#stats .kpi .kpi-pick"); + await reader.inView(p, pick2); + await pick2.click(); + await p.locator(".proto-menu:visible .pm-item").first().click(); + await p.waitForTimeout(150); + assert.equal((await p.locator("#stats .kpi b").first().textContent()).trim(), await fmt(io)); + assert.equal((await p.locator('#usageAccounts .row.stat[data-id="acct-a"] .num b').textContent()).trim(), await fmt(5500000)); + // nothing in a tile cut or spilling out of the window + const spill = await p.locator("#stats .kpi").evaluateAll((ks) => ks.filter((k) => k.scrollWidth > k.clientWidth + 1).map((k) => k.innerText.replace(/\s+/g, " ") + " " + k.scrollWidth + "/" + k.clientWidth)); + assert.deepEqual(spill, [], "a tile spills"); + assert.deepEqual(errors, []); + await p.close(); + }); + } + for (const width of [1500, 1100, 420]) { + await t.test(`${lang} ${width}: the Requests card's cache in full`, async () => { + const errors = []; + const ctx = await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" }); + t.after(() => ctx.close()); + const p = await ctx.newPage(); + p.setDefaultTimeout(5000); + p.on("pageerror", (e) => errors.push(e.message)); + await p.route("**/*", server(lang)); + await p.goto("http://magpie.test/"); + await goUsage(p); + await p.locator(":is(#usageTab .opt, .nav-s):visible").nth(1).click(); + await p.locator("#ledKpi .blk").first().waitFor(); + await p.waitForTimeout(200); + const fit = await p.locator("#ledKpi .blk").first().evaluate((b) => { + const sub = b.querySelector(".sub"); + const box = b.getBoundingClientRect(), pad = parseFloat(getComputedStyle(b).paddingRight); + const parts = [...sub.children].map((s) => ({ text: s.textContent, right: s.getBoundingClientRect().right, w: s.scrollWidth, cw: s.getBoundingClientRect().width })); + return { text: sub.textContent, clipped: sub.scrollWidth > sub.clientWidth + 1, parts: parts.length, out: parts.filter((x) => x.right > box.right - pad + 1).map((x) => x.text) }; + }); + assert.equal(fit.parts, 3, "in, out and the cache: " + fit.text); + assert.equal(fit.clipped, false, "the line is cut: " + fit.text); + assert.deepEqual(fit.out, [], "a part runs past the card"); + assert.match(fit.text, new RegExp((await p.evaluate(() => fmtN(87933000))).replace(/[.]/g, "\\.")), "the cache's whole count is there"); + assert.deepEqual(errors, []); + await p.close(); + }); + } + } + }); +}