usage: the tray panel and the TUI leave out what the Usage page hides

onkashiko on X: a provider whose allowance card was hidden in the main
window (Usage > Overview, "Hide from Overview") still showed in the menu
bar's panel. The panel's Allowances tab had only its own Arrange list
(panelUsageHidden) and read the full cards.

Now the panel leaves out a card whose cardHideKey is in usageCardsHidden
and the rows in usageWindowsHidden (withoutHiddenRows), as Overview does;
a menu bar cell's card still shows (panelPeek). A subscription whose
every card the page hides counts in the foot's "{n} hidden" and shows as
hidden in Arrange; Show there
also drops its keys from usageCardsHidden, since the panel follows the
page. All of it is panelPageCut in the Usage plugin's page.js, which every
window loads, so the core scripts get no bigger (TestCoreScriptBudget
unchanged). Hiding from the panel alone still leaves the page as it is. The
panel reads settings again each time it is shown (loadBack), so a hide or
unhide in the main window reaches it with no restart.

Siblings: magpie tui's Usage page leaves out the same cards and rows
(usageShown, read at every quota read). The menu bar's cells and tooltip
show only the cards picked in Settings, so they keep a hidden card as
before; routing, caps and counting are unchanged.

Run:
- panel-page-hidden.test.cjs (new): chromium + webkit, en/zh/zh-TW/ja/de,
  10/10 green; red on the old app.js/panelarrange.js (cards still drawn).
- TestUsagePageLeavesOutWhatTheAppHides (new): green; red on the old
  pages.go (balance, account and row still listed).
- GUI: the 128 files that read the panel, Usage or tray code, chromium +
  webkit, every language, on mote: 17 files red, rerun alone at
  concurrency 1 here 123/449 red and at origin/main 015860f2d 122/449,
  the same tests but tray-cell-click's chromium en, which is red alone on
  main too (#5215); the rest noted on #5475. tray-cell-click + panel-arrange +
  panel-page-hidden together before the last rebase (no GUI file changed
  in it): 21 of 22, the one red tray-cell-click's (#5215). At this head
  (after the move into page.js): panel-page-hidden, panel-arrange,
  panel-balance-order and i18n-keys green; the reds in key-balance-card
  (de), panel-fold, tray-cell-click (zh) and usage-cards-hide are each
  in the origin/main 015860f2d record above.
- Full suite (go test -tags nogui -count=1 -timeout 45m ./...) on mica
  under suite.lock at 734f06b64 (this change before the move into
  page.js): 97 packages ok; internal/gui red only on TestCoreScriptBudget
  (fixed by the move), internal/gateway red from "too many open files in
  system" at mica's load ~65. At this head on mote: internal/gateway,
  internal/gui, internal/tui, internal/settings and internal/redact (the
  one commit rebased over) ok; gofmt -l clean; go vet, GOOS=linux go vet
  -tags nogui and GOOS=windows go vet ./... clean; go build ok.
- Rebased onto origin/main 667ac8bd6 (5faed634d): internal/gui (budget
  included), internal/tui and internal/settings ok on mote;
  panel-page-hidden + panel-arrange 18 of 18.
Not tried: the real tray panel by hand on a live install.
This commit is contained in:
yetone
2026-11-14 14:10:24 +08:00
parent 667ac8bd6f
commit 7ea1e6a4b3
10 changed files with 280 additions and 24 deletions
+5 -1
View File
@@ -3206,7 +3206,11 @@ press *Arrange* at the foot of the panel's tab and move the rows there. The
same *Arrange* hides a subscription from the panel's tab (*Hide*, *Show*
puts it back), and the tab's foot says how many are hidden. Hiding is the
panel's only: routing, caps, the Usage page and the menu bar's own cells
still have it, and a menu bar cell for it still opens its card. Both are
still have it, and a menu bar cell for it still opens its card. A card or
quota row hidden on the Usage page (its card's *Hide from Overview*) is left
out of the panel's tab too, and of `magpie tui`'s Usage page; a
subscription hidden there whole shows as hidden in the panel's *Arrange*,
whose *Show* brings it back on the Usage page too. Both are
kept in magpie's settings (`usageOrder`, `panelUsageHidden`). Which
allowances the menu bar itself shows beside its icon is picked in Settings.
The same list has *Tokens and cost today* and *Tokens and cost, last 7
+3 -3
View File
@@ -662,9 +662,9 @@ 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 tray panel is as tall as the tab showing, from `panelMin` to `panelMax` and the screen's room (`panelFrame` in [`textsize.go`](../../internal/gui/textsize.go)), and shrinks as well as grows: `fit` in [`app.js`](../../internal/gui/assets/app.js) lays every tab out to measure the one showing and asks `/api/window/fit` for its height. A tab picked glides the panel's edge there (`TAB_GLIDE`, 240ms on app.css's `--ease-out`; a jump under reduced motion), which `glidePanel` carries out by the tray icon: on the Mac the system animates the frame with its top edge under the menu bar, elsewhere `stepGlide` sets the size a frame at a time through `sizeOpenPanel` ([`panelrefit.go`](../../internal/gui/panelrefit.go)), which on Linux places the panel by the icon again. On Windows every refit of the open panel (the fit, each glide step, a text size) keeps the place the tray gave it as it opened, its centre and the edge by the taskbar held inside the work area (`panelRefit`, `TestPanelRefitKeepsItsPlace`, `TestOpenPanelRefitsInPlaceOnWindows`): asking the tray for the icon's place again moved it, since an icon in the taskbar's overflow flyout is put flush right as it opens and over the flyout's arrow once the flyout closes (jiangshangmuyun on X). It was held at the tallest tab's height (#124) until a short tab sat over empty room once a tall one had been opened (refeccd on Discord). See `panel-fit-tabs.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). The card's "…" button at its head's end (`quotaCardMore`; jen_celeus on X looked for a way to hide OpenCode Zen's card, which has no usage to show, and found none), a right-click, or a long press on a touch screen (`quotaCardMenus` in `plugins/usage/page.js`) opens the app menu with *Hide from Overview*. The button shows as the card is hovered and lies over the head's end, so the head at rest is laid out as before; where nothing hovers it is always shown with room kept for it, drawn at 22px and taken at 44 on a phone; an account of a card with several says *Hide this account from Overview*, and a plan card carrying its key's balance (`keyCards`) also offers *Hide its balance from Overview*, which keeps the plan. Each is kept by its tray card id and kind (`cardHideKey`: `stepfun|balance`, `kimi|me@x|plan`) in `settings.UsageCardsHidden` through the same `POST /api/usage/arrange` (`cardsHidden`), and kept by the Settings save. `overviewCards` leaves them out before `keyCards`, so routing, caps, the counting, 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`). Such a card's menu offers *Show in Overview*, not Hide again, since the "{n} hidden" line leaves it out while it shows. A "{n} hidden" line under the cards (`#quotaHid`, `renderQuotaHid`) opens them, each with *Unhide*, and *Show all* from two. The line is drawn in `--muted`, not `--faint`, so it can be read and found (3:1 or more), and while any are hidden every card's menu ends with *Show {n} Hidden*, which opens the line with the keyboard on it and brings it into sight on the menu's click (`openHidden`; yuu003348 on Discord found no way back). See `TestUsageArrangeCardsHidden`, `usage-cards-hide.test.cjs`, `usage-card-more.test.cjs` and `usage-hidden-way-back.test.cjs`.
- A card's quota rows can be hidden one group at a time from Overview (wangshaowei39 on X: Antigravity's Claude & GPT rows unwanted). A row's right-click or long press (`quotaRowMenuItems` in `plugins/usage/page.js`) adds *Hide {group} from Overview* to the card's menu, and the card's "…" lists each group. The group is a pool's or model family's name, else the window's (`windowGroup`), so a pool's 5-hour and weekly rows go together. Kept as `provider|group` in `settings.UsageWindowsHidden` through `POST /api/usage/arrange` (`windowsHidden`), every account of the provider alike, and kept by the Settings save. `overviewCards` hands the page a copy without them (`withoutHiddenRows`); caps, routing, counting, the tray panel and the menu bar read the full card. A card is never left with no row: a card with one group offers no Hide, and one whose every group is named shows all. The "{n} hidden" line counts the rows with the cards, each with *Unhide* (`hideQuotaRows`). See `TestUsageArrangeWindowsHidden` and `usage-rows-hide.test.cjs`.
- 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`). The panel also leaves out what Usage › Overview hides (onkashiko on X: a card hidden in the main window still showed in the panel): a card whose `cardHideKey` is in `settings.UsageCardsHidden` and the rows in `settings.UsageWindowsHidden` (`withoutHiddenRows`). A subscription whose every card the page hides counts as hidden in the foot and in *Arrange* (both from `panelPageCut`, in the Usage plugin's page.js, which every window loads), and *Show* there drops its cards from `UsageCardsHidden` too, since the panel follows the page. The panel reads settings again each time it is shown (`loadBack`), so a hide in the main window reaches it with no restart. See `TestUsageArrangePanelHidden`, `panel-arrange.test.cjs`, `panel-page-hidden.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). The card's "…" button at its head's end (`quotaCardMore`; jen_celeus on X looked for a way to hide OpenCode Zen's card, which has no usage to show, and found none), a right-click, or a long press on a touch screen (`quotaCardMenus` in `plugins/usage/page.js`) opens the app menu with *Hide from Overview*. The button shows as the card is hovered and lies over the head's end, so the head at rest is laid out as before; where nothing hovers it is always shown with room kept for it, drawn at 22px and taken at 44 on a phone; an account of a card with several says *Hide this account from Overview*, and a plan card carrying its key's balance (`keyCards`) also offers *Hide its balance from Overview*, which keeps the plan. Each is kept by its tray card id and kind (`cardHideKey`: `stepfun|balance`, `kimi|me@x|plan`) in `settings.UsageCardsHidden` through the same `POST /api/usage/arrange` (`cardsHidden`), and kept by the Settings save. `overviewCards` leaves them out before `keyCards`, so routing, caps, the counting, the Accounts list and the menu bar cells never hear of it; the tray panel's Allowances tab and `magpie tui`'s Usage page leave it out too (above, and `usageShown` in `internal/tui`); a cell clicked for a hidden card shows it until the page is left (`usagePeek`). Such a card's menu offers *Show in Overview*, not Hide again, since the "{n} hidden" line leaves it out while it shows. A "{n} hidden" line under the cards (`#quotaHid`, `renderQuotaHid`) opens them, each with *Unhide*, and *Show all* from two. The line is drawn in `--muted`, not `--faint`, so it can be read and found (3:1 or more), and while any are hidden every card's menu ends with *Show {n} Hidden*, which opens the line with the keyboard on it and brings it into sight on the menu's click (`openHidden`; yuu003348 on Discord found no way back). See `TestUsageArrangeCardsHidden`, `usage-cards-hide.test.cjs`, `usage-card-more.test.cjs` and `usage-hidden-way-back.test.cjs`.
- A card's quota rows can be hidden one group at a time from Overview (wangshaowei39 on X: Antigravity's Claude & GPT rows unwanted). A row's right-click or long press (`quotaRowMenuItems` in `plugins/usage/page.js`) adds *Hide {group} from Overview* to the card's menu, and the card's "…" lists each group. The group is a pool's or model family's name, else the window's (`windowGroup`), so a pool's 5-hour and weekly rows go together. Kept as `provider|group` in `settings.UsageWindowsHidden` through `POST /api/usage/arrange` (`windowsHidden`), every account of the provider alike, and kept by the Settings save. `overviewCards` hands the page a copy without them (`withoutHiddenRows`); caps, routing, counting and the menu bar read the full card; the tray panel and `magpie tui`'s Usage page leave the rows out as the page does. A card is never left with no row: a card with one group offers no Hide, and one whose every group is named shows all. The "{n} hidden" line counts the rows with the cards, each with *Unhide* (`hideQuotaRows`). See `TestUsageArrangeWindowsHidden` and `usage-rows-hide.test.cjs`.
- A client in the Usage page's Agents list can be hidden from that list (ikunbots on X): its row's "…" button or right-click opens the row menu with *Hide from this list*, saved by client id in `settings.UsageAgentsHidden` through the same `POST /api/usage/arrange` (`agentsHidden`), and kept by the Settings save. The ledger, the totals and the chart still count a hidden client. A "{n} hidden" line under the list opens them, each with *Unhide* (`hideUsageAgent`), and while any are hidden the row menu ends with *Show {n} Hidden*, which opens it as the cards' does (`openHidden`). See `TestUsageArrangeAgentsHidden`, `usage-agents-hide.test.cjs` and `usage-hidden-way-back.test.cjs`.
- Usage › Overview's Agents, Models, Accounts and Gateway keys lists each fold under their heading (#2378): the heading is a `.fold` button with its chevron, as on the Gateway page, and the click doesn't move the page (`backToReader`). What is folded is kept per viewer in localStorage `magpie.usageFolded` (`mountUsageFolds`, `showUsageFolds`). The totals leave the cache out, as before, unless the tokens tile's label, a pop-up button (`usageTokensPick`, the app menu), is set to *With cache*: then the tile, the chart and every row's count and share add cache read and written (`usageTokens`), and the tile says the cache's count; kept in localStorage `magpie.usageWithCache`. The Sessions tab counts by the same pick (#2591): its tokens tile carries the same label pop-up and says the cache's count, and the list's rows, the projects and models bars and pickers, the day chart (whose day and week buckets carry the cache's counts), the calendar and the top sessions read `usageTokens` too, the top list ranked again by the count shown (`sessTokens`, `sessSums`, `renderSessChart`, `renderSessTop`); a pick made on that tab refreshes the tab, not the Overview. The per-session median and p90 stay counted in and out (`Stats.Overview`). The account cards' whole-window estimate follows the same pick (Anotiaww on X): with cache, it adds the cache read and written that magpie routed in the window, scaled by the same share used, and says so (`holdsLine`, now in the Usage plugin's `page.js`, redrawn with the cards when the pick changes; `quota-holds.test.cjs`). The Requests tab's total already counts every token (`allTokens`). A token line in parts (the Requests strip's Tokens card, the Overview's and the Sessions tab's tokens tiles) wraps between its counts and keeps each whole (`usageParts`, `.parts`); only a count wider than its card on its own is cut. See `usage-overview-fold.test.cjs` and `sessions-cache-tokens.test.cjs`.
- A click on a row of the Usage page's Requests (or Enter or Space on it) opens that one request on a page of its own, `#ledReqPane` in place of the list, not Routing (geesehowardt7 on X; `ledReqOpen`, `renderLedReq`): Requests ‹ or Escape goes back to the list where it was left and to its row (`ledReqClose`), and leaving the page closes it (`ledLeave`). The page heads with the model and status, then `ledDetail`: time, agent, source IP (`client_ip`; a loopback address is "This computer", a gateway row older than the field "Not recorded"), requested, provider, account, sent, served, effort, then status, error, duration, tokens, cost and the rest; Routing is the *View routing* link in it. A refresh keeps the page as it was opened (`usage-request-page.test.cjs`, `usage-ledger-detail.test.cjs`).
+5 -4
View File
@@ -17659,17 +17659,18 @@ function renderPanelQuota(lazy) {
fit();
return;
}
// what the arranging hid is left out, but for the one a menu bar cell
// what the arranging hid is left out, and what the Usage page hid, its
// cards and their rows (onkashiko on X), but for the one a menu bar cell
// was clicked for
const hidden = new Set(state.settings?.panelUsageHidden || []);
const peek = (q) => !!panelPeek && (trayCardID(q) === panelPeek || q.balanceCard === panelPeek || q.provider === panelPeek);
const away = new Set(subs.filter((q) => hidden.has(q.provider) && !peek(q)).map((q) => q.provider));
const { cards, away } = panelPageCut(subs, peek, hidden);
// a balance, or a vendor's every account, at 0: behind the foot's button
const zero = new Set(subs.filter((q) => quotaAtZero(q) && !peek(q)));
const zero = new Set(cards.filter((q) => quotaAtZero(q) && !peek(q)));
let atZero = 0;
// the sections in order: a vendor's accounts, or a run of balances
const parts = [], groups = new Map();
for (const q of subs) {
for (const q of cards) {
if (away.has(q.provider)) continue;
// a balance with windows (Command Code's credits beside its 5-hour and
// weekly windows) is the windows' card; a balance alone, a figure
+11 -7
View File
@@ -17,10 +17,11 @@ window.panelArrange = function panelArrange(subs) {
const hidden = new Set(state.settings?.panelUsageHidden || []);
const list = el("div", "pq-alist");
const seen = new Set();
const gone = panelPageCut(subs).gone;
for (const q of subs) {
if (seen.has(q.provider)) continue;
seen.add(q.provider);
const off = hidden.has(q.provider);
const page = gone(q.provider), off = page || hidden.has(q.provider);
const row = el("div", "pq-arow" + (off ? " put-away" : ""));
row.dataset.key = q.provider;
const h = el("button", "ag-handle pq-ahandle");
@@ -46,7 +47,7 @@ window.panelArrange = function panelArrange(subs) {
pill.type = "button";
pill.setAttribute("aria-pressed", String(!off));
pill.title = t(off ? "Show {name} in this panel" : "Hide {name} from this panel", { name: q.name });
pill.onclick = () => hidePanelUsage(q.provider, !off);
pill.onclick = () => hidePanelUsage(q.provider, !off, page);
row.append(h, el("span", "pq-aname", q.name), off ? el("span", "pq-hidden", t("Hidden")) : "", pill);
list.append(row);
}
@@ -55,20 +56,23 @@ window.panelArrange = function panelArrange(subs) {
};
// hidePanelUsage hides a subscription from the panel's Allowances tab, or
// shows it again: drawn at once, put back if the save fails.
async function hidePanelUsage(key, hide) {
// shows it again: drawn at once, put back if the save fails. One the Usage
// page hides every card of (page) is shown there again too, as the panel
// leaves out what that page hides (onkashiko on X).
async function hidePanelUsage(key, hide, page) {
const prev = state.settings;
const cur = (prev.panelUsageHidden || []).filter((k) => k !== key);
const panelHidden = hide ? [...cur, key] : cur;
state.settings = { ...prev, panelUsageHidden: panelHidden };
const cardsHidden = !hide && page ? cardsShownFor(key) : void 0;
state.settings = { ...prev, panelUsageHidden: panelHidden, ...(cardsHidden && { usageCardsHidden: cardsHidden }) };
const again = () => {
renderPanelQuota();
$(`#panelQuota .pq-arow[data-key="${CSS.escape(key)}"] .pq-show`)?.focus(NO_SCROLL);
};
again();
try {
const s = await api("usage/arrange", { panelHidden });
state.settings = { ...state.settings, panelUsageHidden: s.panelUsageHidden || [] };
const s = await api("usage/arrange", { panelHidden, cardsHidden });
state.settings = { ...state.settings, panelUsageHidden: s.panelUsageHidden || [], usageCardsHidden: s.usageCardsHidden || [] };
} catch (e) {
state.settings = prev;
again();
+25 -4
View File
@@ -1299,10 +1299,10 @@ async function hideUsageAgent(id, hide) {
//
// 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
// card's own menu (quotaCardMenus). Only from what is shown: routing, caps
// and the counting never hear of it, the tray panel's Allowances tab leaves
// it out too (panelPageCut, onkashiko on X), 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.
@@ -5267,3 +5267,24 @@ if (mode === "window" && params.get("view") === "usage") {
for (const k of ["tab", "provider", "agent", "computer", "card", "purpose", "via", "period"]) u.searchParams.delete(k);
history.replaceState(null, "", u);
}
// The tray panel's Allowances tab leaves out what this page hides
// (onkashiko on X): cards are the ones it draws, their hidden rows gone and
// the cards hidden left out but for one peek asks for; gone says whether
// this page hides a vendor's every card, which the panel's Arrange calls
// hidden; away is the vendors the panel leaves out, those and the ones its
// own Arrange hid (hidden). Here, not in the core, as page.js is in every
// window.
function panelPageCut(subs, peek = () => false, hidden = new Set()) {
const all = subs.map(withoutHiddenRows), hid = hiddenCards();
const off = (q) => hid.has(cardHideKey(q));
const gone = (p) => all.every((q) => q.provider !== p || off(q));
const away = new Set(all.filter((q) => (hidden.has(q.provider) || gone(q.provider)) && !peek(q)).map((q) => q.provider));
return { gone, away, cards: all.filter((q) => !off(q) || peek(q)) };
}
// usageCardsHidden with a vendor's every card shown again, for the panel's
// Arrange showing one this page hid
function cardsShownFor(p) {
return (state.settings.usageCardsHidden || []).filter((k) => k.split("|")[0] !== p);
}
@@ -0,0 +1,108 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// What the Usage page hides is left out of the tray panel's Allowances tab
// too (onkashiko on X: a provider hidden in the main window still showed in
// the menu bar's panel): a hidden card, a hidden row, and a subscription
// hidden whole, which Arrange calls hidden and whose Show brings it back on
// the page too. A hide in the main window reaches the panel when it is
// shown again, with no restart. APIs are mocked.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const assets = path.resolve(__dirname, "../assets");
const quotas = [
{ provider: "claude", name: "Claude Code", icon: "claude-color", user: "a@b.c", windows: [{ name: "Weekly", used: 17.6 }, { name: "5-hour", used: 42.2 }] },
{ provider: "codex", name: "Codex", icon: "codex-color", user: "x@y.z", windows: [{ name: "5-hour", used: 8 }] },
{ provider: "codex", name: "Codex", icon: "codex-color", user: "other@例子.test", windows: [{ name: "Weekly", used: 25 }] },
{ provider: "deepseek", name: "DeepSeek", icon: "deepseek-color", windows: [], balance: "¥12.30" },
{ provider: "kimi", name: "Kimi Code", icon: "kimi-color", windows: [{ name: "Weekly", used: 30 }] },
];
function serve(lang, posts, settings) {
return async (route) => {
const url = new URL(route.request().url());
const json = (data) => route.fulfill({ json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:false};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings });
if (url.pathname === "/api/settings") return json(settings);
if (url.pathname === "/api/usage/arrange") {
const body = route.request().postDataJSON();
posts.push(body);
if (body.panelHidden) settings.panelUsageHidden = body.panelHidden;
if (body.cardsHidden) settings.usageCardsHidden = body.cardsHidden;
return json(settings);
}
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } });
if (url.pathname === "/api/usage/quotas") return json(quotas);
if (url.pathname === "/api/usage") return json({ days: [] });
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
if (url.pathname === "/api/plugins") return json({ plugins: [] });
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: "" }); }
};
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
test(`${engine} ${lang}: the panel leaves out what the Usage page hides`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(async () => { await browser.close(); });
const errors = [], posts = [];
const settings = {
theme: "light", lang, tray: "panel", quotaLeft: false, currency: "usd", usageOrder: [], panelUsageHidden: [],
usageCardsHidden: ["deepseek|balance", "codex|x@y.z|plan"], usageWindowsHidden: ["claude|5-hour"],
};
const context = await browser.newContext({ viewport: { width: 440, height: 600 }, reducedMotion: "reduce" });
await context.addInitScript(() => { try { localStorage.setItem("magpie.panelTab", "usage"); } catch {} });
const page = await context.newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang, posts, settings));
await page.goto("http://magpie.test/?mode=panel");
await page.waitForFunction(() => document.querySelectorAll("#panelQuota .pq-card").length >= 2);
const tr = (s, v) => page.evaluate(([s, v]) => t(s, v), [s, v]);
const cards = () => page.evaluate(() => [...document.querySelectorAll("#panelQuota .pq-card")].map((c) => c.dataset.card));
const rings = (card) => page.locator(`#panelQuota .pq-card[data-card="${card}"] .pq-ring`).count();
// the hidden card, the account and the row are left out
assert.deepEqual(await cards(), ["claude|a@b.c", "codex|other@例子.test", "kimi"]);
assert.equal(await rings("claude|a@b.c"), 1, "the row the page hides is left out");
assert.equal(await page.evaluate(() => document.querySelector("#panelQuota .pq-bals")), null, "no balance for the hidden DeepSeek card");
assert.equal(await page.locator("#panelQuota .pq-foot .pq-hidden").textContent(), await tr("{n} hidden", { n: 1 }));
// hidden in the main window while the panel was put away: shown again,
// the panel has it gone, and one shown there comes back
settings.usageCardsHidden = ["deepseek|balance", "kimi|plan"];
settings.usageWindowsHidden = [];
await page.evaluate(() => document.dispatchEvent(new Event("visibilitychange")));
await page.waitForFunction(() => !document.querySelector('#panelQuota .pq-card[data-card="kimi"]'));
assert(!(await cards()).includes("kimi") && (await cards()).includes("claude|a@b.c"));
assert.equal(await rings("claude|a@b.c"), 2, "the row shown in the main window again is back");
assert.equal(await page.locator("#panelQuota .pq-foot .pq-hidden").textContent(), await tr("{n} hidden", { n: 2 }));
// Arrange calls them hidden; Show brings DeepSeek back on the page too
await page.locator("#panelQuota .pq-arrange").click();
await page.waitForSelector("#panelQuota .pq-arow");
for (const key of ["deepseek", "kimi"]) {
assert(await page.locator(`#panelQuota .pq-arow[data-key="${key}"]`).evaluate((r) => r.classList.contains("put-away")), key + " shows as hidden");
assert.equal(await page.locator(`#panelQuota .pq-arow[data-key="${key}"] .pq-show`).textContent(), await tr("Show"));
}
assert.equal(await page.locator('#panelQuota .pq-arow[data-key="claude"] .pq-show').textContent(), await tr("Hide"));
await page.locator('#panelQuota .pq-arow[data-key="deepseek"] .pq-show').click();
await page.waitForFunction(() => !document.querySelector('#panelQuota .pq-arow[data-key="deepseek"]').classList.contains("put-away"));
assert.deepEqual(posts.splice(0), [{ panelHidden: [], cardsHidden: ["kimi|plan"] }]);
// hiding from the panel alone leaves the page's list as it is
await page.locator('#panelQuota .pq-arow[data-key="claude"] .pq-show').click();
await page.waitForFunction(() => document.querySelector('#panelQuota .pq-arow[data-key="claude"]').classList.contains("put-away"));
assert.deepEqual(posts.splice(0), [{ panelHidden: ["claude"] }]);
assert.deepEqual(settings.usageCardsHidden, ["kimi|plan"]);
assert.deepEqual(errors, []);
});
}
}
+7 -4
View File
@@ -1042,7 +1042,8 @@ type Settings struct {
// PanelUsageHidden are the subscriptions, by provider id, that the tray
// panel's Allowances tab leaves out (H20 on Discord). It is what the
// panel shows, nothing more: routing, caps, the Usage page and the menu
// bar's cells still have them. The panel's order is UsageOrder.
// bar's cells still have them. The panel's order is UsageOrder, and it
// leaves out what UsageCardsHidden and UsageWindowsHidden do too.
PanelUsageHidden []string `json:"panelUsageHidden,omitempty"`
// UsageAgentsHidden are the clients, by the id the ledger records them
// under ("curl", "Go-http-client", an agent's id), that the Usage page's
@@ -1053,15 +1054,17 @@ type Settings struct {
// 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.
// stays. Only what is shown: the tray panel's Allowances tab and the
// TUI's Usage page leave them out too (onkashiko on X), while routing,
// caps, counting and the menu bar's cells keep them.
UsageCardsHidden []string `json:"usageCardsHidden,omitempty"`
// UsageWindowsHidden are the quota rows of an allowance card that the
// Overview leaves out (wangshaowei39 on X: Antigravity's Claude & GPT
// rows unwanted), each as the provider id, "|" and the row's group: a
// pool's or a model family's name, else the window's name. Every
// account of the provider alike. A card is never left with none: when
// every row is named, all show. Only what that page shows.
// every row is named, all show. Only what is shown, there, in the tray
// panel and in the TUI's Usage page.
UsageWindowsHidden []string `json:"usageWindowsHidden,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
+1 -1
View File
@@ -879,7 +879,7 @@ var readQuotas = func(asked bool) ([]provider.SubscriptionQuota, bool) {
func quotasCmd(asked bool, gen int) tea.Cmd {
return func() tea.Msg {
qs, reading := readQuotas(asked)
return quotaMsg{qs: qs, reading: reading, gen: gen}
return quotaMsg{qs: usageShown(qs, settings.Load()), reading: reading, gen: gen}
}
}
+50
View File
@@ -0,0 +1,50 @@
package tui
import (
"cmp"
"slices"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
)
// usageShown is the cards the Usage page leaves as the app's Overview does
// (onkashiko on X: a card hidden in the app's window still showed
// elsewhere): a card hidden there (settings.UsageCardsHidden, by its tray
// card id and kind, cardHideKey in the app) is left out, and so are the
// rows hidden there (settings.UsageWindowsHidden, by provider and the row's
// group), unless that would leave a card with none. Only what is shown.
func usageShown(qs []provider.SubscriptionQuota, s settings.Settings) []provider.SubscriptionQuota {
if qs == nil || len(s.UsageCardsHidden)+len(s.UsageWindowsHidden) == 0 {
return qs
}
out := make([]provider.SubscriptionQuota, 0, len(qs))
for _, q := range qs {
if slices.Contains(s.UsageCardsHidden, cardHideKey(q)) {
continue
}
if q.Error == "" && len(q.Windows) > 0 && len(s.UsageWindowsHidden) > 0 {
ws := slices.DeleteFunc(slices.Clone(q.Windows), func(w provider.QuotaWindow) bool {
return slices.Contains(s.UsageWindowsHidden, q.Provider+"|"+cmp.Or(w.Pool, w.Family, w.Name))
})
if len(ws) > 0 {
q.Windows = ws
}
}
out = append(out, q)
}
return out
}
// cardHideKey is how the app keeps a hidden card: its tray card id, then
// "|balance" for a balance alone, else "|plan".
func cardHideKey(q provider.SubscriptionQuota) string {
id := q.Provider
if q.User != "" {
id += "|" + q.User
}
if q.Balance != "" && len(q.Windows) == 0 && q.Plan == "" {
return id + "|balance"
}
return id + "|plan"
}
+65
View File
@@ -0,0 +1,65 @@
package tui
import (
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
)
// What the app's Usage page hides, a card or a card's rows, the TUI's Usage
// page leaves out too (onkashiko on X: a card hidden in the app's window
// still showed elsewhere), read again at every read of the cards, so a
// hide in the app reaches it with no restart. A card is never left with no
// row.
func TestUsagePageLeavesOutWhatTheAppHides(t *testing.T) {
home(t)
readQ := readQuotas
t.Cleanup(func() { readQuotas = readQ })
readQuotas = func(bool) ([]provider.SubscriptionQuota, bool) {
return []provider.SubscriptionQuota{
{Provider: "stepfun", Name: "StepFun", Plan: "Plus", Windows: []provider.QuotaWindow{{Name: "5h", Used: 10}}},
{Provider: "stepfun", Name: "StepFun", Balance: "¥9.00"},
{Provider: "codex", Name: "Codex", User: "a@b.c", Windows: []provider.QuotaWindow{{Name: "5h", Used: 20}}},
{Provider: "codex", Name: "Codex", User: "x@y.z", Windows: []provider.QuotaWindow{{Name: "5h", Used: 30}}},
{Provider: "antigravity", Name: "Antigravity", Windows: []provider.QuotaWindow{
{Name: "Weekly", Used: 40, Pool: "Claude"}, {Name: "Daily", Used: 50, Pool: "Gemini"},
}},
{Provider: "kimi", Name: "Kimi", Windows: []provider.QuotaWindow{{Name: "Weekly", Used: 60}}},
}, false
}
lines := func() string {
t.Helper()
msg := quotasCmd(false, 0)().(quotaMsg)
return strings.Join(quotaLines(msg.qs, true, false, 200, time.Now()), "\n")
}
all := lines()
for _, want := range []string{"¥9.00", "x@y.z", "60% used", "40% used", "50% used"} {
if !strings.Contains(all, want) {
t.Fatalf("nothing hidden: missing %q in\n%s", want, all)
}
}
if err := settings.Save(settings.Settings{
UsageCardsHidden: []string{"stepfun|balance", "codex|x@y.z|plan"},
UsageWindowsHidden: []string{"antigravity|Claude", "kimi|Weekly"},
}); err != nil {
t.Fatal(err)
}
got := lines()
for _, gone := range []string{"¥9.00", "x@y.z", "40% used"} {
if strings.Contains(got, gone) {
t.Errorf("%q is hidden in the app, but shows:\n%s", gone, got)
}
}
// the plan card the balance was hidden from stays, the other account
// stays, a pool not named stays, and Kimi's only row is never taken
for _, want := range []string{"StepFun · Plus", "a@b.c", "50% used", "60% used"} {
if !strings.Contains(got, want) {
t.Errorf("missing %q in\n%s", want, got)
}
}
}