tray: the menu bar and panel leave out what Usage's Overview hides (onkashiko on X)
onkashiko on X: a quota hidden in the main window still showed from the menu bar.7ea1e6a4bmade the tray panel and the TUI leave out Overview-hidden cards and rows, but two gaps were left: - The menu bar's cells, its tooltip and Windows' tray figure still showed a hidden card and its hidden rows. trayUsageCards now goes through trayShown: a cell naming an account takes the card the Overview still shows (its balance with its plan hidden), a cell following the account in use (`|*`) picks that account among every card as before and is left empty while its card is hidden, never moved to another account. Hidden rows are left out, a card never left with none. settings.TrayUsages is untouched, so the cell comes back with the card. - POST /api/usage/arrange now wakes the menu bar (onTrayUsage) when cardsHidden or windowsHidden is sent, so a hide or unhide reaches it at once rather than at the next tick (3 minutes by default). - The panel hid a card after keyCards had put a key's balance on its plan's card, so "Hide its balance from Overview" left the balance on the panel's plan card, and a hidden plan took its unhidden balance with it. panelPageCut now takes the quotas as read and leaves the hidden out before keyCards, as overviewCards does; gone counts a merged card hidden only when its plan and balance both are. The Go hide rule (cardHideKey/usageShown) moved from internal/tui to internal/provider (ShownQuotas, QuotaCardHidden, QuotaRowsShown, QuotaHideKey), shared by the TUI and the menu bar. Not changed: Bark's daily push still warns about a near-limit hidden card (an alert, not a display). Docs: settings.go comments, docs/subsystems/gui-shell.md. Run on mica (mote at load 117 on 18 cores), at baseee6352b63: - go test -count=1 -timeout 45m ./internal/gui ./internal/tui ./internal/provider ./internal/settings: all ok. - go vet of those packages; GOOS=linux go vet -tags nogui and GOOS=windows go vet of internal/gui, internal/tui, internal/provider: clean. gofmt -l clean. - GUI (Chromium + WebKit, en/zh/zh-TW/ja/de): panel-hidden-balance (new), panel-page-hidden, panel-arrange: 28/28. panel-balance-order, usage-rows-hide pass. usage-cards-hide and usage-hidden-way-back are red at "de 560" (no sideways scroll), the same 8 on an origin/mainee6352b63copy (#6294, #6295). tray-cell-click "chromium zh/en" is red 1 run in 3 on origin/main as on this tree (#5215). Broken by hand: panel-hidden-balance is red on origin/main's assets (the plan card carries the hidden balance, MiniMax's balance gone); TestTrayLeavesOutWhatTheOverviewHides is red with trayShown returning trayPick, TestUsageArrangeWakesTheMenuBar red with the onTrayUsage call removed. At the pushed head (rebased on534b1a334, which adds installdir_windows.go): GOOS=windows go vet ./internal/gui ./internal/update and go test -run "TestTray|TestUsageArrange|TestCoreScriptBudget" ./internal/gui: ok. Not tried: the real menu bar on a Mac or Windows with a real account; no full go test ./... (a full suite was running on mica).
This commit is contained in:
@@ -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`). 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`.
|
||||
- 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`, left out before `keyCards` puts a key's balance on its plan's card as on the Overview (a balance hidden leaves the plan's card without it, a plan hidden leaves its balance on its own), 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`, `panel-hidden-balance.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 and the Accounts list never hear of it; the tray panel's Allowances tab, the menu bar's cells, tooltip and Windows' tray figure (`trayShown`), and `magpie tui`'s Usage page leave it out too (above, and `provider.ShownQuotas`). A cell naming an account takes its card the Overview still shows (its balance with its plan hidden); a cell following the account in use is left empty while that account's card is hidden, rather than moving to another. `settings.TrayUsages` keeps the cell, so it comes back with the card, and `POST /api/usage/arrange` wakes the menu bar (`onTrayUsage`) when `cardsHidden` or `windowsHidden` is sent, with no restart. See `TestTrayLeavesOutWhatTheOverviewHides` and `TestUsageArrangeWakesTheMenuBar`. Such a card's menu offers *Show in Overview*, not Hide again, since the "{n} hidden" line leaves it out while it shows. A "{n} hidden" line under the cards (`#quotaHid`, `renderQuotaHid`) opens them, each with *Unhide*, and *Show all* from two. The line is drawn in `--muted`, not `--faint`, so it can be read and found (3:1 or more), and while any are hidden every card's menu ends with *Show {n} Hidden*, which opens the line with the keyboard on it and brings it into sight on the menu's click (`openHidden`; yuu003348 on Discord found no way back). See `TestUsageArrangeCardsHidden`, `usage-cards-hide.test.cjs`, `usage-card-more.test.cjs` and `usage-hidden-way-back.test.cjs`.
|
||||
- A card's quota rows can be hidden one group at a time from Overview (wangshaowei39 on X: Antigravity's Claude & GPT rows unwanted). A row's right-click or long press (`quotaRowMenuItems` in `plugins/usage/page.js`) adds *Hide {group} from Overview* to the card's menu, and the card's "…" lists each group. The group is a pool's or model family's name, else the window's (`windowGroup`), so a pool's 5-hour and weekly rows go together. Kept as `provider|group` in `settings.UsageWindowsHidden` through `POST /api/usage/arrange` (`windowsHidden`), every account of the provider alike, and kept by the Settings save. `overviewCards` hands the page a copy without them (`withoutHiddenRows`); caps, routing and counting read the full card; the tray panel, the menu bar and `magpie tui`'s Usage page leave the rows out as the page does. A card is never left with no row: a card with one group offers no Hide, and one whose every group is named shows all. The "{n} hidden" line counts the rows with the cards, each with *Unhide* (`hideQuotaRows`). See `TestUsageArrangeWindowsHidden` and `usage-rows-hide.test.cjs`.
|
||||
- A client in the Usage page's Agents list can be hidden from that list (ikunbots on X): its row's "…" button or right-click opens the row menu with *Hide from this list*, saved by client id in `settings.UsageAgentsHidden` through the same `POST /api/usage/arrange` (`agentsHidden`), and kept by the Settings save. The ledger, the totals and the chart still count a hidden client. A "{n} hidden" line under the list opens them, each with *Unhide* (`hideUsageAgent`), and while any are hidden the row menu ends with *Show {n} Hidden*, which opens it as the cards' does (`openHidden`). See `TestUsageArrangeAgentsHidden`, `usage-agents-hide.test.cjs` and `usage-hidden-way-back.test.cjs`.
|
||||
- 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`).
|
||||
|
||||
@@ -2731,6 +2731,11 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
// the menu bar leaves out what the Overview hides (trayShown): it
|
||||
// follows a card hidden or shown again at once
|
||||
if (in.CardsHidden != nil || in.WindowsHidden != nil) && onTrayUsage != nil {
|
||||
onTrayUsage()
|
||||
}
|
||||
writeJSON(rw, settingsState())
|
||||
})
|
||||
mux.HandleFunc("POST /api/settings/login", func(rw http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -17672,7 +17672,7 @@ function renderPanelQuota(lazy) {
|
||||
// was clicked for
|
||||
const hidden = new Set(state.settings?.panelUsageHidden || []);
|
||||
const peek = (q) => !!panelPeek && (trayCardID(q) === panelPeek || q.balanceCard === panelPeek || q.provider === panelPeek);
|
||||
const { cards, away } = panelPageCut(subs, peek, hidden);
|
||||
const { cards, away } = panelPageCut(quotas, peek, hidden);
|
||||
// a balance, or a vendor's every account, at 0: behind the foot's button
|
||||
const zero = new Set(cards.filter((q) => quotaAtZero(q) && !peek(q)));
|
||||
let atZero = 0;
|
||||
|
||||
@@ -1300,9 +1300,9 @@ 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 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
|
||||
// and the counting never hear of it; the tray panel's Allowances tab
|
||||
// (panelPageCut) and the menu bar (trayShown, onkashiko on X) leave it out
|
||||
// too. 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.
|
||||
@@ -5269,18 +5269,25 @@ if (mode === "window" && params.get("view") === "usage") {
|
||||
}
|
||||
|
||||
// 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
|
||||
// (onkashiko on X): cards are the ones it draws from list (the quotas as
|
||||
// read), in this page's order, the cards hidden left out before a key's
|
||||
// balance is put on its plan's card (keyCards), as the Overview has it, so
|
||||
// a plan hidden leaves its balance and a balance hidden leaves its plan's
|
||||
// card without it, and their hidden rows gone, but for what peek asks for;
|
||||
// gone says whether this page hides a vendor's every card, which the
|
||||
// panel's Arrange calls hidden, for list as read or as keyCards puts it;
|
||||
// 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)) };
|
||||
function panelPageCut(list, peek = () => false, hidden = new Set()) {
|
||||
const hid = hiddenCards();
|
||||
list = sharedBalances(list || []).filter((q) => q.balance || q.error || q.windows?.length);
|
||||
const gone = (p) => list.every((q) => q.provider !== p || cardHideKeys(q).every((k) => hid.has(k)));
|
||||
const kept = list.filter((q) => !hid.has(cardHideKey(q)) || peek(q));
|
||||
const cards = byUsageOrder(keyCards(kept)).map(withoutHiddenRows);
|
||||
const peeked = (p) => list.some((q) => q.provider === p && peek(q));
|
||||
const away = new Set(list.map((q) => q.provider).filter((p) => (hidden.has(p) || gone(p)) && !peeked(p)));
|
||||
return { gone, away, cards };
|
||||
}
|
||||
|
||||
// usageCardsHidden with a vendor's every card shown again, for the panel's
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// A key's balance drawn on its plan's card (keyCards) is hidden from the
|
||||
// tray panel as the Usage page's Overview hides it (onkashiko on X: hidden
|
||||
// in the main window, still in the menu bar's panel): a balance hidden
|
||||
// leaves its plan's card without it, and a plan hidden leaves its balance
|
||||
// on its own. 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: "stepfun", name: "StepFun", icon: "stepfun-color", user: "s@x.y", plan: "Plus", windows: [{ name: "5-hour", used: 12 }] },
|
||||
{ provider: "stepfun", name: "StepFun", icon: "stepfun-color", user: "s@x.y", windows: [], balance: "¥9.00" },
|
||||
{ provider: "minimax", name: "MiniMax", icon: "minimax-color", user: "m@x.y", plan: "Max", windows: [{ name: "5-hour", used: 30 }] },
|
||||
{ provider: "minimax", name: "MiniMax", icon: "minimax-color", user: "m@x.y", windows: [], balance: "¥4.20" },
|
||||
];
|
||||
|
||||
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 hides a plan's balance, or its plan, as the Usage page does`, 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: ["stepfun|s@x.y|balance", "minimax|m@x.y|plan"], usageWindowsHidden: [],
|
||||
};
|
||||
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.waitForSelector("#panelQuota .pq-foot .pq-arrange");
|
||||
const drawn = () => page.evaluate(() => [...document.querySelectorAll("#panelQuota .pq-card")].map((c) =>
|
||||
(c.classList.contains("bal") ? "bal " : "plan ") + c.dataset.card + (c.querySelector(".quota-balance") ? " +balance" : "")));
|
||||
|
||||
// StepFun's balance hidden: its plan's card without it; MiniMax's
|
||||
// plan hidden: its balance on its own, among the balances
|
||||
assert.deepEqual(await drawn(), ["plan stepfun|s@x.y", "bal minimax|m@x.y"]);
|
||||
assert.equal(await page.locator("#panelQuota .pq-bals .pq-amt").textContent(), "¥4.20");
|
||||
assert.equal(await page.locator("#panelQuota .pq-foot .pq-hidden").count(), 0, "neither vendor is hidden whole");
|
||||
|
||||
// shown again in the main window, and MiniMax's balance hidden too,
|
||||
// while the panel was put away: shown again, the panel follows
|
||||
settings.usageCardsHidden = ["minimax|m@x.y|plan", "minimax|m@x.y|balance"];
|
||||
await page.evaluate(() => document.dispatchEvent(new Event("visibilitychange")));
|
||||
await page.waitForFunction(() => !document.querySelector('#panelQuota .pq-card[data-card="minimax|m@x.y"]'));
|
||||
assert.deepEqual(await drawn(), ["plan stepfun|s@x.y +balance"]);
|
||||
assert.equal(await page.locator("#panelQuota .pq-foot .pq-hidden").textContent(), await page.evaluate(() => t("{n} hidden", { n: 1 })));
|
||||
assert.deepEqual(posts, []);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -388,8 +388,9 @@ func until(lang string, d time.Duration) string {
|
||||
|
||||
// trayUsageCards are the cards settings.TrayUsages names, in its order,
|
||||
// among the Usage page's (cached as there), and magpie's own totals it
|
||||
// names (trayTotal); one gone is left out. The vendors aren't asked when
|
||||
// only totals are named.
|
||||
// names (trayTotal); one gone is left out, and so is one the Usage page's
|
||||
// Overview hides, as are the rows it hides (trayShown). The vendors aren't
|
||||
// asked when only totals are named.
|
||||
func trayUsageCards(ctx context.Context, lang string, ids []string) []provider.SubscriptionQuota {
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
@@ -412,7 +413,36 @@ func trayUsageCards(ctx context.Context, lang string, ids []string) []provider.S
|
||||
}
|
||||
cards = append(cards, trayTotalCard(lang, id, trayMoney(trayTotalSum(p), noCost), currency, rate))
|
||||
}
|
||||
return trayPick(cards, ids, time.Now())
|
||||
return trayShown(cards, ids, time.Now(), settings.Shared())
|
||||
}
|
||||
|
||||
// trayShown is trayPick less what the Usage page's Overview hides
|
||||
// (settings.UsageCardsHidden, UsageWindowsHidden): a card hidden there
|
||||
// showed on in the menu bar, its tooltip and Windows' tray figure, though
|
||||
// the Overview and the tray panel left it out (onkashiko on X). The cells
|
||||
// ticked are kept, so a card shown again comes back to its cell. A named
|
||||
// cell takes the account's card the Overview still shows (its balance,
|
||||
// say, with its plan hidden); a cell following the account in use picks
|
||||
// that account among them all, as before, and is left empty when its card
|
||||
// is hidden, rather than moving to another account.
|
||||
func trayShown(cards []provider.SubscriptionQuota, ids []string, now time.Time, s settings.Settings) []provider.SubscriptionQuota {
|
||||
if len(s.UsageCardsHidden)+len(s.UsageWindowsHidden) == 0 {
|
||||
return trayPick(cards, ids, now)
|
||||
}
|
||||
shown := provider.ShownQuotas(cards, s)
|
||||
var out []provider.SubscriptionQuota
|
||||
for _, id := range ids {
|
||||
if !strings.HasSuffix(id, trayInUse) {
|
||||
out = append(out, trayPick(shown, []string{id}, now)...)
|
||||
continue
|
||||
}
|
||||
for _, q := range trayPick(cards, []string{id}, now) {
|
||||
if !provider.QuotaCardHidden(q, s) {
|
||||
out = append(out, provider.QuotaRowsShown(q, s))
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// trayTotal starts the id of a card of magpie's own count instead of a
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// onkashiko on X: a card hidden from the Usage page's Overview showed on in
|
||||
// the menu bar. Its cell, the tooltip and Windows' tray figure leave it out
|
||||
// as the Overview and the tray panel do, and the rows hidden there too;
|
||||
// the cells ticked are kept for when it is shown again.
|
||||
func TestTrayLeavesOutWhatTheOverviewHides(t *testing.T) {
|
||||
was := trayInUseAccount
|
||||
trayInUseAccount = func(string) string { return "b@x.y" }
|
||||
t.Cleanup(func() { trayInUseAccount = was })
|
||||
cards := []provider.SubscriptionQuota{
|
||||
{Provider: "claude", Name: "Claude Code", User: "a@x.y", Windows: []provider.QuotaWindow{{Name: "5-hour", Used: 10}, {Name: "Weekly", Used: 20}}},
|
||||
{Provider: "claude", Name: "Claude Code", User: "b@x.y", Windows: []provider.QuotaWindow{{Name: "5-hour", Used: 70}, {Name: "Weekly", Used: 30}}},
|
||||
{Provider: "stepfun", Name: "StepFun", User: "s", Plan: "Plus", Windows: []provider.QuotaWindow{{Name: "5-hour", Used: 5}}},
|
||||
{Provider: "stepfun", Name: "StepFun", User: "s", Balance: "¥9.00"},
|
||||
{Provider: "deepseek", Name: "DeepSeek", Balance: "¥1.00"},
|
||||
{Provider: "kimi", Name: "Kimi", Windows: []provider.QuotaWindow{{Name: "Weekly", Used: 1}}},
|
||||
}
|
||||
ids := []string{"claude|*", "claude|a@x.y", "stepfun|s", "deepseek", "kimi"}
|
||||
now := time.Now()
|
||||
if got := trayShown(cards, ids, now, settings.Settings{}); len(got) != 5 {
|
||||
t.Fatalf("nothing hidden: %d cards, want 5", len(got))
|
||||
}
|
||||
s := settings.Settings{
|
||||
UsageCardsHidden: []string{"claude|b@x.y|plan", "deepseek|balance", "stepfun|s|plan"},
|
||||
UsageWindowsHidden: []string{"claude|Weekly"},
|
||||
}
|
||||
got := trayShown(cards, ids, now, s)
|
||||
var names []string
|
||||
for _, q := range got {
|
||||
names = append(names, trayCardID(q)+":"+q.Balance+":"+strconv.Itoa(len(q.Windows)))
|
||||
}
|
||||
// the account in use (b) is hidden: its cell is empty, not moved to a;
|
||||
// a's card loses its weekly row; StepFun's plan hidden, its balance
|
||||
// shows; DeepSeek's balance hidden; Kimi's one row stays, a card never
|
||||
// left with none
|
||||
want := "claude|a@x.y::1 stepfun|s:¥9.00:0 kimi::1"
|
||||
if strings.Join(names, " ") != want {
|
||||
t.Fatalf("got %q, want %q", strings.Join(names, " "), want)
|
||||
}
|
||||
if cards[0].Windows[1].Name != "Weekly" || len(cards[0].Windows) != 2 {
|
||||
t.Fatal("the cached cards were changed")
|
||||
}
|
||||
}
|
||||
|
||||
// A card hidden or shown again from the Usage page reaches the menu bar at
|
||||
// once, not at its next tick.
|
||||
func TestUsageArrangeWakesTheMenuBar(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"))
|
||||
woke := 0
|
||||
was := onTrayUsage
|
||||
onTrayUsage = func() { woke++ }
|
||||
t.Cleanup(func() { onTrayUsage = was })
|
||||
for _, c := range []struct {
|
||||
body string
|
||||
want int
|
||||
}{
|
||||
{`{"order":["kimi"]}`, 0},
|
||||
{`{"cardsHidden":["deepseek|balance"]}`, 1},
|
||||
{`{"windowsHidden":["claude|Weekly"]}`, 2},
|
||||
{`{"cardsHidden":[]}`, 3},
|
||||
} {
|
||||
rec := httptest.NewRecorder()
|
||||
Handler(nil, nil).ServeHTTP(rec, httptest.NewRequest("POST", "/api/usage/arrange", strings.NewReader(c.body)))
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: %d %s", c.body, rec.Code, rec.Body)
|
||||
}
|
||||
if woke != c.want {
|
||||
t.Fatalf("after %s the menu bar was woken %d times, want %d", c.body, woke, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"slices"
|
||||
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// What the app's Usage page hides from its Overview (onkashiko on X) is
|
||||
// left out wherever an allowance is shown: the tray panel (page.js's
|
||||
// panelPageCut), the menu bar's cells, tooltip and Windows' tray figure,
|
||||
// and the TUI's Usage page. Only what is shown: routing, caps and counting
|
||||
// keep every card.
|
||||
|
||||
// ShownQuotas is qs less the cards hidden (s.UsageCardsHidden) and the rows
|
||||
// hidden (s.UsageWindowsHidden), as the Overview draws them.
|
||||
func ShownQuotas(qs []SubscriptionQuota, s settings.Settings) []SubscriptionQuota {
|
||||
if qs == nil || len(s.UsageCardsHidden)+len(s.UsageWindowsHidden) == 0 {
|
||||
return qs
|
||||
}
|
||||
out := make([]SubscriptionQuota, 0, len(qs))
|
||||
for _, q := range qs {
|
||||
if QuotaCardHidden(q, s) {
|
||||
continue
|
||||
}
|
||||
out = append(out, QuotaRowsShown(q, s))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// QuotaCardHidden is whether the Overview hides q's card.
|
||||
func QuotaCardHidden(q SubscriptionQuota, s settings.Settings) bool {
|
||||
return len(s.UsageCardsHidden) > 0 && slices.Contains(s.UsageCardsHidden, QuotaHideKey(q))
|
||||
}
|
||||
|
||||
// QuotaRowsShown is q less the rows the Overview hides, by provider and the
|
||||
// row's group (a pool's or family's name, else the window's), unless that
|
||||
// would leave it with none.
|
||||
func QuotaRowsShown(q SubscriptionQuota, s settings.Settings) SubscriptionQuota {
|
||||
if q.Error != "" || len(q.Windows) == 0 || len(s.UsageWindowsHidden) == 0 {
|
||||
return q
|
||||
}
|
||||
ws := slices.DeleteFunc(slices.Clone(q.Windows), func(w QuotaWindow) bool {
|
||||
return slices.Contains(s.UsageWindowsHidden, q.Provider+"|"+cmp.Or(w.Pool, w.Family, w.Name))
|
||||
})
|
||||
if len(ws) > 0 {
|
||||
q.Windows = ws
|
||||
}
|
||||
return q
|
||||
}
|
||||
|
||||
// QuotaHideKey is how the app keeps a hidden card (cardHideKey in
|
||||
// page.js): its tray card id, then "|balance" for a balance alone, else
|
||||
// "|plan".
|
||||
func QuotaHideKey(q 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"
|
||||
}
|
||||
@@ -1054,9 +1054,11 @@ 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 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.
|
||||
// stays. Only what is shown: the tray panel's Allowances tab, the menu
|
||||
// bar's cells, tooltip and Windows' tray figure, and the TUI's Usage
|
||||
// page leave them out too (onkashiko on X; provider.ShownQuotas), while
|
||||
// routing, caps and counting keep them. TrayUsages keeps a hidden
|
||||
// card's cell, which shows again with the card.
|
||||
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
|
||||
@@ -1064,7 +1066,7 @@ type Settings struct {
|
||||
// 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 is shown, there, in the tray
|
||||
// panel and in the TUI's Usage page.
|
||||
// panel, the menu bar and 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,50 +1,13 @@
|
||||
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.
|
||||
// elsewhere), provider.ShownQuotas. 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"
|
||||
return provider.ShownQuotas(qs, s)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user