Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
usage: an allowance card can be hidden from the Overview (whqtian_07012 on Discord)
yetone75a7db27b970
diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.mdindex dc44289af..404220d73 100644--- a/docs/subsystems/gui-shell.md+++ b/docs/subsystems/gui-shell.md@@ -420,6 +420,7 @@ 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.- 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`.- 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`.diff --git a/internal/gui/api.go b/internal/gui/api.goindex 18233a9c4..43e8d5787 100644--- a/internal/gui/api.go+++ b/internal/gui/api.go@@ -1388,6 +1388,8 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {in.PanelUsageHidden = cur.PanelUsageHidden// and the clients the Usage page's Agents list leaves out, set therein.UsageAgentsHidden = cur.UsageAgentsHidden+ // and the allowance cards the Usage page's Overview leaves out, set there+ in.UsageCardsHidden = cur.UsageCardsHidden// and the names models' usage is counted under (magpie model alias)in.UsageAliases = cur.UsageAliases// and the clears of usage made on the Usage page@@ -2089,7 +2091,8 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {})// the Usage page's order of its cards, which the tray panel's Allowances// tab follows, what that tab leaves out, the clients the page's Agents- // list leaves out, and a client it counts as one of the agents (Count,+ // list leaves out, the allowance cards its Overview leaves out+ // (CardsHidden), and a client it counts as one of the agents (Count,// #1958; As "" counts it on its own again), in magpie's settings; one// not sent stays as it ismux.HandleFunc("POST /api/usage/arrange", func(rw http.ResponseWriter, r *http.Request) {@@ -2097,6 +2100,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {Order *[]stringPanelHidden *[]stringAgentsHidden *[]string+ CardsHidden *[]stringCount *struct{ Client, As string }}if err := json.NewDecoder(r.Body).Decode(&in); err != nil {@@ -2121,6 +2125,9 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {if in.AgentsHidden != nil {s.UsageAgentsHidden = *in.AgentsHidden}+ if in.CardsHidden != nil {+ s.UsageCardsHidden = *in.CardsHidden+ }if err := settings.Save(s); err != nil {fail(rw, err)returndiff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.cssindex 6116a865e..0288006cc 100644--- a/internal/gui/assets/app.css+++ b/internal/gui/assets/app.css@@ -1216,6 +1216,9 @@ body.masked :hover > .acct-eye, body.masked .pq-card:hover .acct-eye, body.maske.us-hid .us-hidline[aria-expanded="true"] svg { transform: rotate(180deg); }.us-hid .list { margin-top: 4px; }.us-hid .list[hidden] { display: none; }+.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; }.row.stat.hid > :not(.us-unhide) { opacity: .55; }.usage-note { padding: 10px 4px 2px; font-size: 11px; color: var(--faint); user-select: text; -webkit-user-select: text; }.usage-clear { margin: 0; padding: 2px 0 6px; }diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.jsindex 407c2b29b..2b2e927f2 100644--- a/internal/gui/assets/app.js+++ b/internal/gui/assets/app.js@@ -15716,6 +15716,7 @@ function renderQuotas(lazy) {slide(pick, "quotaMode");}renderQuotaTrend();+ renderQuotaHid();if (!quotas) {subscriptions.hidden = false;for (let i = 0; i < 2; i++) {@@ -15728,10 +15729,12 @@ function renderQuotas(lazy) {return;}if (usageArranging) { usageRenderPending = true; restoreRefresh(); return; }- subscriptions.hidden = !quotas.length;+ // less the ones hidden from it (overviewCards, the Usage page's)+ const shown = overviewCards(quotas);+ subscriptions.hidden = !shown.length;// an agent with several accounts is one card, a section per accountconst groups = [];- for (const sub of byUsageOrder(keyCards(quotas))) {+ for (const sub of byUsageOrder(keyCards(shown))) {const g = sub.user && groups.find((x) => x[0].user && x[0].provider === sub.provider);if (g) g.push(sub); else groups.push([sub]);}@@ -15752,6 +15755,7 @@ function renderQuotas(lazy) {if (!first.user && first.alias) head.append(...quotaWho(first));if (!first.user && (first.plan || first.until)) head.append(planSpan(first));card.append(head);+ quotaCardMenus(card, subs); // the card's hide menu (page.js)// a provider's keys, each its balance: past a few, the rest folded// behind a button at the card's foot, and the sum in its head (361 on// Discord: an OpenRouter card listed every key's balance, very long)diff --git a/internal/gui/assets/plugins/usage/client.js b/internal/gui/assets/plugins/usage/client.jsindex b74feaa5a..e128446a9 100644--- a/internal/gui/assets/plugins/usage/client.js+++ b/internal/gui/assets/plugins/usage/client.js@@ -37,6 +37,7 @@ magpie.plugin("usage", (ctx) => {<div class="segs" id="quotaMode" hidden></div></div><section class="subscription-usage" id="subscriptionUsage"></section>+ <div class="us-hid" id="quotaHid" hidden><button class="text us-hidline" type="button" aria-expanded="false"></button><div class="list" hidden></div></div><p class="usage-note" id="usageScope" data-t>Gateway calls only; session-log calls are in Requests. Local rejections are excluded from totals.</p><section class="stats" id="stats"></section><section class="chart" id="chart"></section>diff --git a/internal/gui/assets/plugins/usage/i18n.js b/internal/gui/assets/plugins/usage/i18n.jsindex 8030fd4c1..e7d79ec54 100644--- a/internal/gui/assets/plugins/usage/i18n.js+++ b/internal/gui/assets/plugins/usage/i18n.js@@ -2,6 +2,10 @@// kernel adds them to i18n.js's (magpie.strings).magpie.strings({zh: {+ "Hide from Overview": "从概览中隐藏",+ "Hide this account from Overview": "从概览中隐藏这个账号",+ "Hide its balance from Overview": "从概览中隐藏它的余额",+ "Hidden from the Overview only: they are still used and counted. Click to see them.": "只在概览中隐藏:它们照常使用和计数。点击查看。","Clear usage…": "清除用量…","Clear all usage…": "清除全部用量…","Clear the usage of {model}?": "清除 {model} 的用量?",@@ -233,6 +237,10 @@ magpie.strings({"Sent upstream as {to}, as the agent spoke it": "以 {to} 协议发往上游,与 agent 所用协议相同",},"zh-TW": {+ "Hide from Overview": "從概覽中隱藏",+ "Hide this account from Overview": "從概覽中隱藏這個帳號",+ "Hide its balance from Overview": "從概覽中隱藏它的餘額",+ "Hidden from the Overview only: they are still used and counted. Click to see them.": "只在概覽中隱藏:它們照常使用和計數。點擊查看。","Clear usage…": "清除用量…","Clear all usage…": "清除全部用量…","Clear the usage of {model}?": "清除 {model} 的用量?",@@ -464,6 +472,10 @@ magpie.strings({"Sent upstream as {to}, as the agent spoke it": "以 {to} 協議發往上游,與 agent 所用協議相同",},ja: {+ "Hide from Overview": "概要から隠す",+ "Hide this account from Overview": "このアカウントを概要から隠す",+ "Hide its balance from Overview": "残高を概要から隠す",+ "Hidden from the Overview only: they are still used and counted. Click to see them.": "概要で隠しているだけです。使用もカウントもこれまでどおりです。クリックで表示します。","Clear usage…": "使用量を消去…","Clear all usage…": "すべての使用量を消去…","Clear the usage of {model}?": "{model} の使用量を消去しますか?",@@ -695,6 +707,10 @@ magpie.strings({"Sent upstream as {to}, as the agent spoke it": "エージェントと同じ {to} で上流へ送信",},de: {+ "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",+ "Hidden from the Overview only: they are still used and counted. Click to see them.": "Nur in der Übersicht ausgeblendet: Sie werden weiter genutzt und gezählt. Klicken, um sie zu sehen.","Clear usage…": "Nutzung löschen…","Clear all usage…": "Gesamte Nutzung löschen…","Clear the usage of {model}?": "Nutzung von {model} löschen?",diff --git a/internal/gui/assets/plugins/usage/page.js b/internal/gui/assets/plugins/usage/page.jsindex 2beb038c8..a8771a42e 100644--- a/internal/gui/assets/plugins/usage/page.js+++ b/internal/gui/assets/plugins/usage/page.js@@ -813,6 +813,141 @@ async function hideUsageAgent(id, hide) {}}+// ---------- allowance cards hidden from the Overview ----------+//+// An allowance card can be hidden from the Overview (whqtian_07012 on+// Discord: StepFun's plan card wanted, its balance card not), from the+// card's own menu (quotaCardMenus). Only from this page: routing, caps and+// the counting never hear of it, the tray panel's Allowances tab has its+// own (Arrange), and a menu bar cell asking for a hidden card shows it+// until the page is left. Each is kept by its tray card id and its kind+// (cardHideKey), in magpie's settings (usageCardsHidden), so every window+// and magpie web agree; one line at the section's end says how many, and+// has them back.+let quotaHidOpen = false; // the hidden cards listed under their line+let usagePeek = ""; // a card a menu bar cell asked for, shown though hidden+new MutationObserver(() => { if ($("#view-usage").hidden) usagePeek = ""; }).observe($("#view-usage"), { attributes: true, attributeFilter: ["hidden"] });+const cardHideKind = (q) => q.balance && !q.windows?.length && !q.plan ? "balance" : "plan";+const cardHideKey = (q) => trayCardID(q) + "|" + cardHideKind(q);+// the keys a card as drawn stands for: a plan's card carrying its key's+// balance (keyCards) hides both+const cardHideKeys = (q) => [cardHideKey(q), ...(q.balanceCard ? [q.balanceCard + "|balance"] : [])];+const hiddenCards = () => new Set(state.settings?.usageCardsHidden || []);+const cardPeeked = (q) => !!usagePeek && (trayCardID(q) === usagePeek || q.provider === usagePeek);+// overviewCards: the cards the Overview draws, a provider's keys sharing+// one balance already one card (sharedBalances), the hidden left out+function overviewCards(list) {+ const hid = hiddenCards();+ list = sharedBalances(list);+ return hid.size ? list.filter((q) => !hid.has(cardHideKey(q)) || cardPeeked(q)) : list;+}+// quotaCardMenus gives a card its menu: a right-click, the keyboard's menu+// key on its handle, or on a touch screen a long press (iOS Safari sends+// no contextmenu for one), for the account whose section it was on, or+// the whole card from its head+let quotaPressed = 0; // when a long press last opened a card's menu+// the mouse events a phone makes up once the finger lifts don't close it,+// nor press what the finger was on+const quotaPressing = () => !!agentMenu && performance.now() - quotaPressed < 1000;+for (const k of ["mousedown", "click"]) addEventListener(k, (e) => { if (quotaPressing() && !e.target.closest?.(".row-menu")) { e.stopImmediatePropagation(); e.preventDefault(); } }, true);+function quotaCardMenus(card, subs) {+ let press = null;+ card.oncontextmenu = (e) => {+ if (e.target.closest("input, textarea")) return;+ e.preventDefault();+ // Android sends one after the long press that opened it already+ if (quotaPressing()) return;+ quotaCardMenu(e.target, card, subs);+ };+ const stop = () => { clearTimeout(press?.timer); press = null; };+ card.addEventListener("pointerdown", (e) => {+ stop();+ if (e.pointerType !== "touch" || usageArranging || e.target.closest(".us-handle, input, textarea")) return;+ const at = e.target;+ press = { x: e.clientX, y: e.clientY, timer: setTimeout(() => { press = null; quotaPressed = performance.now(); quotaCardMenu(at, card, subs); }, 550) };+ });+ card.addEventListener("pointermove", (e) => { if (press && Math.hypot(e.clientX - press.x, e.clientY - press.y) > 8) stop(); });+ for (const k of ["pointerup", "pointercancel", "pointerleave"]) card.addEventListener(k, stop);+}+function quotaCardMenu(target, card, subs) {+ let part = [...card.children].find((c) => c.contains(target));+ while (part && !part.classList.contains("subscription-account") && !part.classList.contains("subscription-head")) part = part.previousElementSibling;+ const who = part?.classList.contains("subscription-account") && subs.find((q) => trayCardID(q) === part.dataset.card);+ const of = who ? [who] : subs;+ const anchor = card.querySelector(".us-handle") || card.querySelector(".subscription-head");+ const again = agentMenu?.anchor === anchor;+ closeAgentMenu();+ if (again) return;+ const one = of.length === 1 && of[0];+ 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) }] : []),+ ]);+}+// 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)) : [];+ hb.hidden = !hidden.length;+ if (!hidden.length) { quotaHidOpen = false; return; }+ const line = hb.querySelector(".us-hidline"), hl = hb.querySelector(".list");+ let all = hb.querySelector(".us-showall");+ if (!all) {+ all = el("button", "text us-showall", t("Show all"));+ all.type = "button";+ hb.append(all);+ }+ all.textContent = t("Show all");+ all.hidden = !quotaHidOpen || hidden.length < 2;+ all.onclick = () => hideQuotaCards(hidden.map(cardHideKey), false);+ line.replaceChildren(el("span", "", t("{n} hidden", { n: hidden.length })), svg(CHEV, 11, 1.6));+ line.title = t("Hidden from the Overview only: they are still used and counted. Click to see them.");+ line.setAttribute("aria-expanded", String(quotaHidOpen));+ line.onclick = () => { quotaHidOpen = !quotaHidOpen; renderQuotaHid(); };+ hl.hidden = !quotaHidOpen;+ hl.replaceChildren();+ if (!quotaHidOpen) return;+ for (const q of hidden) {+ const r = el("div", "row stat hid acts");+ r.dataset.id = cardHideKey(q);+ r.append(icon(q.icon));+ const who = el("div", "who");+ who.append(el("div", "name", quotaName(q)), el("div", "sub", [q.alias || q.user, t(cardHideKind(q) === "balance" ? "Balance" : "Plan")].filter(Boolean).join(" · ")));+ const b = el("button", "text us-unhide", t("Unhide"));+ b.type = "button";+ b.onclick = (e) => { e.stopPropagation(); hideQuotaCards([cardHideKey(q)], false); };+ r.append(who, b);+ hl.append(r);+ }+}+// hideQuotaCards hides cards from the Overview, or has them back: drawn at+// once, put back if the save fails+async function hideQuotaCards(keys, hide) {+ const prev = state.settings || {};+ const cur = (prev.usageCardsHidden || []).filter((k) => !keys.includes(k));+ const cardsHidden = hide ? [...cur, ...keys] : cur;+ usagePeek = "";+ state.settings = { ...prev, usageCardsHidden: cardsHidden };+ const again = () => {+ renderQuotas();+ // the keyboard stays near: on the hidden line, or the card put back+ const to = $("#quotaHid .us-hidline");+ (hide && to && !to.closest("[hidden]") ? to : null)?.focus({ preventScroll: true });+ };+ again();+ try {+ const s = await api("usage/arrange", { cardsHidden });+ state.settings = { ...state.settings, usageCardsHidden: s.usageCardsHidden || [] };+ } catch (e) {+ state.settings = prev;+ again();+ status(e.message, "err");+ }+}+// ---------- requests ----------//// The ledger: every request of the period, one row each, newest first —@@ -3846,6 +3981,7 @@ if (mode === "window" && params.get("view") === "usage") {const per = params.get("period");if (PERIODS.some(([id]) => id === per)) period = per;quotaFocus = usageTab === "usage" ? (params.get("card") || params.get("provider") || "") : "";+ usagePeek = quotaFocus;quotaFocusUntil = performance.now() + 5000;ledProvider = params.get("provider") || "";ledAgent = params.get("agent") || "";diff --git a/internal/gui/settings_keep_test.go b/internal/gui/settings_keep_test.goindex 9b417a3db..d284771f8 100644--- a/internal/gui/settings_keep_test.go+++ b/internal/gui/settings_keep_test.go@@ -154,6 +154,7 @@ func TestSettingsSaveKeepsWhatItDoesNotSend(t *testing.T) {UsageOrder: []string{"kimi", "codex"},PanelUsageHidden: []string{"deepseek"},UsageAgentsHidden: []string{"curl"},+ UsageCardsHidden: []string{"stepfun|balance"},ClientAgents: map[string]string{"hermes-codex-thread-bridge": "codex"},PlainNames: true,PlainOwnNames: true,diff --git a/internal/gui/tests/usage-cards-hide.test.cjs b/internal/gui/tests/usage-cards-hide.test.cjsnew file mode 100644index 000000000..23b13ccfa--- /dev/null+++ b/internal/gui/tests/usage-cards-hide.test.cjs@@ -0,0 +1,205 @@+// Run with Node's test runner and Playwright on the module path; see README.md.+// An allowance card on Usage → Overview can be hidden from it+// (whqtian_07012 on Discord: StepFun's plan card wanted, its balance card+// not). A right-click on a card, or a long press on a touch screen, opens+// its menu: Hide from Overview, and on a plan's card showing its key's+// balance, Hide its balance from Overview, which leaves the plan. Each is+// kept by provider, account and kind (POST /api/usage/arrange,+// cardsHidden) and stays hidden when the page is opened again. A quiet+// line under the cards says how many are hidden and opens them, each with+// Unhide, and Show all. No click moves the page. 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 { 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)] },+ // one StepFun key: its Step Plan and its balance, drawn as one card+ { provider: "stepfun", name: "StepFun", icon: "stepfun-color", plan: "Step Plan", windows: [win("5h", 30)] },+ { provider: "stepfun", name: "StepFun", icon: "stepfun-color", windows: [], balance: "¥42.00" },+ // a second StepFun provider with a balance alone: a card of its own+ { provider: "stepfun-2", name: "StepFun Work", icon: "stepfun-color", windows: [], balance: "¥7.50" },+];++function server(lang, web, saved, posts) {+ 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.hidden });+ 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/usage/arrange") {+ const body = JSON.parse(req.postData() || "{}");+ posts.push(body);+ if (body.cardsHidden) saved.hidden = body.cardsHidden;+ 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({ calls: 0, errors: 0, input: 0, output: 0, reasoning: 0, cache_read: 0, cache_write: 0, unpriced: 0, cost: 0, bucket: "day", series: [], path: "~/.config/magpie/usage.jsonl", agents: [], models: [] });+ 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", 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" },+};+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 + ": an allowance card is hidden from the Overview, and brought back", 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 = { hidden: [] }, posts = [];+ 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.on("pageerror", (e) => errors.push(e.message));+ await p.route("**/*", server(lang, web, saved, posts));+ 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 });+ 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 top = (p) => p.locator("#view-usage").evaluate((v) => v.scrollTop);+ const items = (p) => p.locator(".row-menu .rm-item").allTextContents();+ // a long press, as a finger makes it: the pointer down, held, up+ 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);+ }));++ // the save reaches the fake server after the page has drawn it+ const savedAs = async (want) => {+ for (const end = Date.now() + 5000; !isDeepStrictEqual(saved.hidden, want) && Date.now() < end;) await new Promise((ok) => setTimeout(ok, 20));+ assert.deepEqual(saved.hidden, want);+ };++ let p = await open();+ assert.deepEqual(await cards(p), ["claude", "stepfun", "stepfun-2"]);+ assert.match(await card(p, "stepfun").textContent(), /42\.00/, "the plan's card shows its key's balance");+ assert.equal(await p.locator("#quotaHid").isHidden(), true, "nothing hidden, no line");++ // the balance-only card: its menu has Hide from Overview alone+ await reader.inView(p, card(p, "stepfun-2"));+ let at = await top(p);+ if (web) await longPress(card(p, "stepfun-2"));+ else await card(p, "stepfun-2").locator(".subscription-head").click({ button: "right" });+ await p.locator(".row-menu").waitFor();+ assert.deepEqual(await items(p), [w.hide]);+ await p.locator(".row-menu .rm-item").click();+ await p.waitForFunction(() => !document.querySelector('#subscriptionUsage > [data-provider="stepfun-2"]'));+ await savedAs(["stepfun-2|balance"]);+ assert.deepEqual(posts.at(-1), { cardsHidden: ["stepfun-2|balance"] });+ const line = p.locator("#quotaHid .us-hidline");+ assert.equal((await line.textContent()).trim(), w.n(1));+ assert.equal(await top(p), at, "hiding a card doesn't move the page");++ // the plan's card with its balance: the balance alone goes+ 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]);+ 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"]);+ assert.deepEqual(await cards(p), ["claude", "stepfun"], "the plan stays");+ assert.match(await card(p, "stepfun").textContent(), /Step Plan/);+ assert.equal((await line.textContent()).trim(), w.n(2));+ assert.equal(await top(p), at, "hiding a balance doesn't move the page");++ // the line opens them, each named with its kind, and Show all+ await reader.inView(p, line);+ at = await top(p);+ await line.click();+ assert.equal(await line.getAttribute("aria-expanded"), "true");+ const hidIds = () => p.locator("#quotaHid .row.stat").evaluateAll((rs) => rs.map((r) => r.dataset.id));+ assert.deepEqual(await hidIds(), ["stepfun|balance", "stepfun-2|balance"]);+ assert.match(await p.locator("#quotaHid .row.stat").first().textContent(), new RegExp(w.balance));+ assert.deepEqual((await p.locator("#quotaHid .us-unhide").allTextContents()).map((s) => s.trim()), [w.unhide, w.unhide]);+ assert.equal((await p.locator("#quotaHid .us-showall").textContent()).trim(), w.all);+ assert.equal(await top(p), at, "opening the hidden ones doesn't move the page");++ // Unhide puts one card back+ const back = p.locator('#quotaHid .row.stat[data-id="stepfun-2|balance"] .us-unhide');+ await reader.inView(p, back);+ at = await top(p);+ await back.click();+ await p.waitForFunction(() => !!document.querySelector('#subscriptionUsage > [data-provider="stepfun-2"]'));+ await savedAs(["stepfun|balance"]);+ assert.deepEqual(posts.at(-1), { cardsHidden: ["stepfun|balance"] });+ assert.deepEqual(await cards(p), ["claude", "stepfun", "stepfun-2"]);+ assert.equal((await line.textContent()).trim(), w.n(1));+ assert.equal(await p.locator("#quotaHid .us-showall").isHidden(), true, "Show all is for more than one");++ // nothing is wider than the page, every action inside its row+ 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("#quotaHid .row.stat")].filter((r) => {+ const box = r.getBoundingClientRect(), x = r.querySelector(".us-unhide").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 Unhide stays inside its row");++ // opened again, the balance is still hidden+ await p.close();+ p = await open();+ assert.deepEqual(await cards(p), ["claude", "stepfun", "stepfun-2"]);+ assert.doesNotMatch(await card(p, "stepfun").textContent(), /42\.00/);+ assert.equal((await p.locator("#quotaHid .us-hidline").textContent()).trim(), w.n(1));++ // 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();+ await p.waitForFunction(() => !document.querySelector('#subscriptionUsage > [data-provider="claude"]'));+ await savedAs(["stepfun|balance", "claude|plan"]);+ await reader.click(p, p.locator("#quotaHid .us-hidline"));+ const all = p.locator("#quotaHid .us-showall");+ await reader.inView(p, all);+ await all.click();+ await p.waitForFunction(() => document.querySelector("#quotaHid").hidden);+ await savedAs([]);+ assert.deepEqual(await cards(p), ["claude", "stepfun", "stepfun-2"]);+ assert.match(await card(p, "stepfun").textContent(), /42\.00/);+ assert.deepEqual(errors, []);+ await ctx.close();+ });+ }+ }+ });+}diff --git a/internal/gui/usage_arrange_test.go b/internal/gui/usage_arrange_test.goindex 3e7d1a6f7..b6bc054c3 100644--- a/internal/gui/usage_arrange_test.go+++ b/internal/gui/usage_arrange_test.go@@ -89,6 +89,47 @@ func TestUsageArrangeAgentsHidden(t *testing.T) {want(nil, []string{"deepseek"})}+// The allowance cards the Usage page's Overview leaves out+// (whqtian_07012 on Discord: StepFun's balance card, not its plan card)+// are saved on their own, trimmed and once each, leave the other hidden+// lists as they were, and are kept through a save of the Settings page.+func TestUsageArrangeCardsHidden(t *testing.T) {+ h := t.TempDir()+ t.Setenv("HOME", h)+ t.Setenv("USERPROFILE", h)+ t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))+ t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache"))+ t.Setenv("APPDATA", filepath.Join(h, "AppData", "Roaming"))+ t.Setenv("LOCALAPPDATA", filepath.Join(h, "AppData", "Local"))+ post := func(path, body string) {+ t.Helper()+ rec := httptest.NewRecorder()+ Handler(nil, nil).ServeHTTP(rec, httptest.NewRequest("POST", path, strings.NewReader(body)))+ if rec.Code != http.StatusOK {+ t.Fatalf("%s: %d %s", path, rec.Code, rec.Body)+ }+ }+ want := func(cards []string) {+ t.Helper()+ s := settings.Load()+ if !slices.Equal(s.UsageCardsHidden, cards) {+ t.Fatalf("cards hidden %v, want %v", s.UsageCardsHidden, cards)+ }+ if !slices.Equal(s.PanelUsageHidden, []string{"deepseek"}) || !slices.Equal(s.UsageAgentsHidden, []string{"curl"}) {+ t.Fatalf("panel hidden %v agents hidden %v, want them kept", s.PanelUsageHidden, s.UsageAgentsHidden)+ }+ }+ post("/api/usage/arrange", `{"panelHidden":["deepseek"],"agentsHidden":["curl"]}`)+ post("/api/usage/arrange", `{"cardsHidden":["stepfun|balance"," stepfun|balance","kimi|me@x|plan"]}`)+ want([]string{"stepfun|balance", "kimi|me@x|plan"})+ post("/api/settings", `{"theme":"dark"}`)+ want([]string{"stepfun|balance", "kimi|me@x|plan"})+ post("/api/usage/arrange", `{"order":["kimi","stepfun"]}`)+ want([]string{"stepfun|balance", "kimi|me@x|plan"})+ post("/api/usage/arrange", `{"cardsHidden":[]}`)+ want(nil)+}+// A client magpie doesn't know is counted as one of its agents from the// Usage page's Agents list (#1958, NorethSea), saved on its own and kept// through a save of the Settings page; As "" counts it on its own again.diff --git a/internal/settings/settings.go b/internal/settings/settings.goindex 468fda624..499533701 100644--- a/internal/settings/settings.go+++ b/internal/settings/settings.go@@ -645,6 +645,13 @@ type Settings struct {// Agents list leaves out (ikunbots on X). It is that list's only: the// ledger keeps their calls, and the totals and the chart count them.UsageAgentsHidden []string `json:"usageAgentsHidden,omitempty"`+ // UsageCardsHidden are the allowance cards the Usage page's Overview+ // leaves out (whqtian_07012 on Discord), each as its tray card id (the+ // provider id, then "|" and the account when there is one) and "|plan"+ // or "|balance", so StepFun's balance card goes while its plan card+ // stays. Only what that page shows: routing, caps, counting, the tray+ // panel (PanelUsageHidden is its own) and the menu bar's cells keep them.+ UsageCardsHidden []string `json:"usageCardsHidden,omitempty"`// ClientAgents counts a client magpie doesn't know as one of the agents// it does, on the Usage and Sessions pages (#1958, NorethSea): a bridge// that starts Codex's app-server under a name of its own@@ -1702,6 +1709,7 @@ func save(s Settings, recording bool) error {s.UsageOrder = ids(s.UsageOrder)s.PanelUsageHidden = ids(s.PanelUsageHidden)s.UsageAgentsHidden = ids(s.UsageAgentsHidden)+ s.UsageCardsHidden = ids(s.UsageCardsHidden)s.ClientAgents = clientAgents(s.ClientAgents)s.UsageCleared = usageCleared(s.UsageCleared)s.TrayUsages = ids(s.TrayUsages)