tray: pick which of a subscription's windows the menu bar shows (StrikingRaw on X)

Claude Pro's menu bar card drew its 5-hour and 7-day windows as two
small stacked numbers, and the user wanted one of them alone. Settings ›
Usage › Menu bar windows (under Allowances in the menu bar) lists a pill
per ticked subscription with two or more windows ("Claude Code · All
windows"), opening the app's menu: All windows, then each window. The
choice is settings.TrayWindows, by provider id (every account of it, the
in-use "|*" card too) and by window kind from the span ("5h", "1d", "7d",
"month", "15m", "name:<name>" when the span is unknown), so a vendor
reordering windows changes nothing. Unset shows every window as before;
a pick whose windows are all gone shows every window again, never an
empty card. Only the bar's rows and the Linux label are filtered; the
tooltip still says every window. One row draws at mpRowFont's 11pt
single-row size. Hidden on Windows (its tray shows no text). Per
computer through KeepOwn. The GUI learns kinds from trayKind on
/api/usage/quotas (withTrayKinds; model and aside windows get none). The
row's code is a lazily imported traywindows.js, so the core script
budget is not raised (app.js +4 lines for the call and the prefs keep).

Run:
- mote (macOS): go test -run 'TrayWindow|TrayUsage|WithTrayKinds|
  CoreScriptBudget|AppScript|TrayImage' ./internal/gui/ ok;
  ./internal/settings/ ok; davsync TestSync ok. TestTrayImageOneWindow
  draws through AppKit: Claude's card one line ("42%"), both windows two;
  the PNGs were looked at.
- mote: gofmt -l empty; go vet ./..., GOOS=linux go vet -tags nogui
  ./..., GOOS=windows go vet ./... ok; go build, GOOS=linux go build
  -tags nogui, GOOS=windows go build ok.
- magpie-desktop (Linux VM), --test-concurrency=1, BROWSER=chromium and
  webkit: tray-windows (en, zh, zh-TW, ja, de; picking All; hidden on
  Windows / single-window / no cards; 360px narrow), i18n-keys,
  old-webkit, tray-usages, tray-logos, tray-cost, quota-pace: 43/43 each.
After rebasing on ec5571d6f: the focused Go run above, davsync and vet of
the touched packages ok on mote; tray-windows, i18n-keys, old-webkit,
tray-usages 27/27 in chromium and webkit on the Linux VM.
Broken by hand: the row filter in trayCardText off -> TestTrayWindowsPicked
and TestTrayImageOneWindow red; trayWindows out of prefsKeep ->
tray-windows.test.cjs red in every language. Restored, green.
Not run: the full Go suite (owner: ship each verified fix at once; mote
was at load 20-27 under another session's full GUI suite) and the whole
GUI suite. The GUI ran on the Linux VM because mote's browsers crash or
hang under that load (#4125; TestTrayCellClickReleasedPanel is red the
same way on origin/main c84c3e1c0 there).
Not tried: the live app's real menu bar with a signed-in Claude account
(the AppKit drawer was exercised in-process instead); Linux tray label
on a real desktop.
This commit is contained in:
yetone
2026-10-30 23:14:08 +08:00
parent ec5571d6f2
commit 7d4a631480
18 changed files with 569 additions and 18 deletions
+1
View File
@@ -430,6 +430,7 @@ covers it in both engines, every language and a narrow window.
- The menu bar can show magpie's own totals beside the allowances (#1984): `usage:today` and `usage:7d` in `settings.TrayUsages`, offered after the cards in the same picker. `trayUsageCards` sums them with `usage.QueryPage(p, Filter{}, 0, 1).Sum` (the Requests tab's and the panel's cached ledger sum, gateway and session-file calls together) and asks no vendor when only totals are picked; `trayTotalCard` makes every token (in, out and cache, as `allTokens`), marked `Σ` so it doesn't read as the input, over the cost in Settings' currency, `+` when some calls had no price, the cost row left out when none had one. The Mac draws them as plain cells, the bird beside them saying whose. A click opens the Requests tab at the period (`quotaView`, `?tab=requests&period=`) or the panel's Usage tab (`panelUseFocus`). No 3-day total: the Usage page has no such window. See `TestTrayTotals` and `tray-totals.test.cjs`. Settings › *Menu bar cost* (`settings.TrayNoCost`, on by default, on every OS, per computer through `KeepOwn`) turned off leaves the money out (BussanQ on Discord): `trayMoney` drops the total's cost and its count of unpriced calls before `trayTotalCard` and the no-card tooltip `trayIdleTip` see it, so the cards, their tooltip and the idle tooltip say the tokens and requests alone. A relay's or subscription's balance card is money itself and stays. See `TestTrayNoCost` and `tray-cost.test.cjs`.
- The tray's icon is the bird alone where the bar's other icons are glyphs: the Mac's menu bar takes `tray.png` as a template image, and a Linux bar (StatusNotifierItem `IconPixmap`) gets the same silhouette in one colour on transparency (`trayIconFor`, `linuxTrayIcon` in [`trayglyph.go`](../../internal/gui/trayglyph.go)), so a bar that tints its icons by their alpha tints the bird, not a tile (ylorn on Discord). A bar that doesn't tint shows it light, or dark when the portal's `org.freedesktop.appearance` `color-scheme` prefers light (`traySchemeLight`), and it is drawn again when that changes (`watchTrayScheme`). No `IconName` is set: a host that found a `-symbolic` name and drew it untinted would show a black bird on a dark bar, with no pixmap to fall back on. Windows' tray keeps the app's coloured icon. With no cards in the menu bar the tooltip is magpie over today's total (`trayIdleTip`: every token, split into input, output and cache as the today card's tooltip is, then the cost and the requests), brought up to date with the cards' refresh; the tray's menu stays Open, the version and Quit. Wails sets the tooltip only on Windows: on Linux `setTrayTip` sets the StatusNotifierItem's `ToolTip` and sends `NewToolTip` ([`traytip_linux.go`](../../internal/gui/traytip_linux.go)), and on the Mac it is the status item's button's `toolTip` (`trayTipNative` in [`trayimage_darwin.go`](../../internal/gui/trayimage_darwin.go); NextCommit on Discord: no hover there showed anything). See `TestTrayIconPerOS`, `TestTrayIdleTip` and `TestMacTrayTipIsSet`.
- A window's Pace is a number on its card's reset line (fflake33 on Discord): the share used less the share of the window gone by, in points, "Pace +12%" over an even pace and "−8%" under it, turned with the meter when it shows what is left, amber while more is used than an even pace would have (`quotaPace`, `paceLine`). The window's start is the gateway's, `startsAt` from `provider.WithWindowStarts` (its reset less its span, `QuotaWindow.Bounds`); a window whose span isn't known, with no limit, or a past cycle has none. Settings › *Menu bar pace* (`settings.TrayPace`, off by default, hidden on Windows, whose tray shows no text) puts the same number beside each figure in the menu bar and in its tooltip (`trayPace`, `QuotaWindow.Pace`). See `TestWindowPace`, `TestTrayUsagePace` and `quota-pace.test.cjs`.
- Settings › *Menu bar windows* (`settings.TrayWindows`, StrikingRaw on X) picks which of a subscription's windows its menu bar card shows, keyed by provider id (every account of it, the in-use `|*` card too) and by window kind, not position: `trayWindowKind` names a window by its span ("5h", "1d", "7d", "month", "15m"), by `name:` its name when the span isn't known. Unset shows every window, as before; a pick none of whose kinds the card still has shows every window again (`trayShownKinds`), never an empty card. Only the bar's rows and the Linux label are filtered; the tooltip still says every window. One row draws at the 11pt single-row size (`mpRowFont`). The GUI learns the kinds from `trayKind` on `/api/usage/quotas` (`withTrayKinds`; model and aside windows get none). The row lists a pill per ticked subscription with two or more kinds, opening the app's menu (All windows, then each kind), hidden on Windows; its code is in `traywindows.js`, imported when Settings draws ticked cards. Per computer through `KeepOwn`. See `TestTrayWindowsPicked`, `TestTrayWindowsKept` and `tray-windows.test.cjs`.
- In Usage → Allowances, Trends → Cycle offers each account's own recorded cycle menu beside its curve (`quotaCurve`, `quotaRecordedCycles` in [`app.js`](../../internal/gui/assets/app.js)). The longest window (usually weekly) owns the menu; shorter windows are drawn over the selected dates with their own reset breaks. `/api/usage/quotas/history?days=45` supplies all retained readings, including remote cards. Completed cycles come from observed boundaries, not seven-day arithmetic; an early reset ends the previous cycle at the vendor's new start if it fits between readings, otherwise at the first new reading. Each menu option gives its observed duration, so an early reset is not labelled as a full seven days. The selected meters, plot, legend, tooltip and dashed pace use that cycle's last readings, never today's percentages. A window without a reading in the selected interval says so instead of showing a current value. A local account's past cycle asks `/api/usage/quotas/history/holds?provider=&user=&from=&to=` once per selection (`quotaCycleHoldsOf`), which asks no vendor (#2009, NorethSea): `HistoricalWindowHolds` in [`window_holds_history.go`](../../internal/usage/window_holds_history.go) reckons each window's whole at its own last reading in that cycle, from the request log up to that reading, so the 5-hour figure is the cycle's last 5-hour window, never its short windows added up. Its tooltip names that window's start and the reading's time. It shows "Loading…" until the answer comes. A window it can't reckon says "not enough data" with the reason, as a current card does; a reply that comes after another cycle was picked is dropped, and a card's Refresh or an asked read reckons again. Historical meters show the cycle end and sampling time; current account actions, balances and policies are left out until returning to the current view. Accounts are independent, and a selection survives card refreshes in the same page. Trends → 2 days temporarily shows recent readings; Off removes the curves; the tray always shows its current cycle. See `quota-curve.test.cjs` and the [history limits and reset inference](providers-accounts.md#constraints-and-failure-behavior).
- The Usage page's cards are packed into columns, never all stretched to a row's height (`packUsage`, #860): each card in that order goes to the leftmost column that ends highest, on 1px grid rows, so short cards stack beside a tall one. The last card in each column then reaches down to where the tallest column ends (a `min-height`, cleared before the cards are measured again), so cards side by side in one row are as tall as each other and a stack ends with the tall card beside it (ikunbots on X); content stays at each card's top. The page's order (DOM, dragging, Alt+arrows) stays `UsageOrder`. The column count is the most 260px columns that fit, or one fewer when that leaves much less empty room; it is chosen again only when the cards change or the width fits another number of columns, so a card opened or folded stays where it is, even as the scrollbar comes in. See `usage-pack.test.cjs`.
- The Providers page has a search box over its list (#1614, `findProviders` in [`app.js`](../../internal/gui/assets/app.js)): the words typed keep the rows, on and off, whose text or data say them all: name, id, preset, addresses, every model's id and name, the account's user and plan and each login's, account names and key names. The Turned off fold stays open while searching; Escape or clearing the box shows every row and the fold as it was. A row that is on reorders by dragging its logo, Alt+↑/↓, Alt+Shift+↑/↓ (top, bottom) or its right-click menu (`openProviderMenu`: Move to top, Move up, Move down, Move to bottom). While searching, a step or a drop moves it among the rows shown (it takes the place of the row it passes, `stepProvider`, `shownToOn`) and the hidden ones keep their order; Move to top and Move to bottom go to the ends of the whole list. Every move saves the whole order through `POST /api/providers/arrange`. See `provider-find.test.cjs` and `provider-order.test.cjs`.
+2 -2
View File
@@ -191,7 +191,7 @@ func TestSync(t *testing.T) {
a, b := newComputer(t), newComputer(t)
a.use(t)
provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Chat: "https://api.deepseek.com/v1", Key: "k1"})
settings.Save(settings.Settings{Theme: "dark", Proxy: "http://127.0.0.1:7890", Window: []int{900, 700}, TrayUsages: []string{"claude|a@b.c"}, TrayUsageEvery: 5, TrayNoLogos: true, TrayNoBird: true, TrayPace: true, TrayNoCost: true})
settings.Save(settings.Settings{Theme: "dark", Proxy: "http://127.0.0.1:7890", Window: []int{900, 700}, TrayUsages: []string{"claude|a@b.c"}, TrayUsageEvery: 5, TrayNoLogos: true, TrayNoBird: true, TrayPace: true, TrayNoCost: true, TrayWindows: map[string][]string{"claude": {"5h"}}})
profile.Save("work", profile.Profile{Fields: map[string]string{"claude.model": "x"}})
same := cfg
same.Passphrase = cfg.Password
@@ -236,7 +236,7 @@ func TestSync(t *testing.T) {
}
// nor does a's menu bar: what shows beside the icon is b's own (yoooo
// on Discord)
if s := settings.Load(); len(s.TrayUsages) != 0 || s.TrayUsage != "" || s.TrayUsageEvery == 5 || s.TrayNoLogos || s.TrayNoBird || s.TrayPace || s.TrayNoCost {
if s := settings.Load(); len(s.TrayUsages) != 0 || s.TrayUsage != "" || s.TrayUsageEvery == 5 || s.TrayNoLogos || s.TrayNoBird || s.TrayPace || s.TrayNoCost || s.TrayWindows != nil {
t.Fatalf("b's menu bar: %+v", s)
}
if ps, _ := profile.Load(); len(ps) != 1 {
+3 -2
View File
@@ -1498,10 +1498,11 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
}
// the cards the menu bar shows, any of them (TrayUsage is only the first),
// how often, with their logos or not, beside the bird or not, and
// with their Pace numbers or not, with magpie's totals' cost or not
// with their Pace numbers or not, with magpie's totals' cost or not, and
// which of each subscription's windows
if (!slices.Equal(settings.Load().TrayUsages, cur.TrayUsages) || in.TrayUsageEvery != cur.TrayUsageEvery ||
in.TrayNoLogos != cur.TrayNoLogos || in.TrayNoBird != cur.TrayNoBird || in.TrayPace != cur.TrayPace ||
in.TrayNoCost != cur.TrayNoCost) && onTrayUsage != nil {
in.TrayNoCost != cur.TrayNoCost || !maps.EqualFunc(in.TrayWindows, cur.TrayWindows, slices.Equal)) && onTrayUsage != nil {
onTrayUsage()
}
// an alert turned on or moved is looked at now, the Mac asked for its
+3
View File
@@ -2811,6 +2811,9 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; }
.row.pref .proto.pick.open svg { transform: rotate(180deg); }
.row.pref .proto.pick:hover, .row.pref .proto.pick.open { color: var(--fg); background: var(--pill-hover); }
.row.pref .proto.pick.busy { opacity: .6; }
.row.pref .tray-windows { flex: 0 1 auto; display: flex; flex-direction: column; align-items: flex-end; gap: 6px; min-width: 0; max-width: 55%; }
.row.pref .tray-windows .proto.pick { max-width: 100%; margin-left: 0; }
.row.pref .tray-windows .proto.pick > span { overflow: hidden; text-overflow: ellipsis; }
.pop.proto-menu { width: 262px; max-height: min(360px, 70vh); overflow-y: auto; overscroll-behavior: contain; padding: 4px; border: 1px solid var(--line); display: grid; gap: 1px; }
.proto-menu .pm-head { padding: 6px 8px 5px; font-size: 11px; color: var(--muted); }
.proto-menu .pm-item { display: flex; align-items: flex-start; gap: 7px; width: 100%; padding: 6px 8px 7px; border: 0; border-radius: 7px; background: none; color: var(--fg); font: inherit; text-align: left; cursor: default; outline: none; }
+4 -1
View File
@@ -20745,6 +20745,9 @@ function renderTrayUsage(s, keep) {
$("#trayPaceRow").hidden = !ids.length || document.documentElement.classList.contains("win");
$("#trayPaceSegs").replaceChildren(segs([["off", t("Off")], ["on", t("On")]], s.trayPace ? "on" : "off",
(v) => savePrefs({ ...keep, trayPace: v === "on" })));
// which windows a card shows
if (!ids.length) $("#trayWindowsRow").hidden = true;
else import("./traywindows.js").then(() => trayWindowsRow(s, keep, ids, mac), () => {});
// and the cost beside magpie's own totals, in their cards and the
// tooltip, which every OS shows with or without cards (BussanQ)
$("#trayCostSegs").replaceChildren(segs([["off", t("Off")], ["on", t("On")]], s.trayNoCost ? "off" : "on",
@@ -22764,7 +22767,7 @@ function prefsKeep(s) {
codexWarmAts: warmTimes(s.codexWarmAts, s.codexWarmAt), claudeWarmAts: warmTimes(s.claudeWarmAts, s.claudeWarmAt), workbuddyCheckin: !!s.workbuddyCheckin, traeCheckin: !!s.traeCheckin, minimaxCheckin: !!s.minimaxCheckin, qoderCheckin: !!s.qoderCheckin, noStats: !!s.noStats, noUsageStats: !!s.noUsageStats,
memberModel: !!s.memberModel, noLoopGuard: !!s.noLoopGuard, claudeLeanPrompt: !!s.claudeLeanPrompt, refusalRetries: s.refusalRetries ?? null,
noUpdatePill: !!s.noUpdatePill, noAutoUpdate: !!s.noAutoUpdate, updateEvery: s.updateEvery || 360, autoRestart: !!s.autoRestart, noAutoDownload: !!s.noAutoDownload, updateChannel: s.updateChannel || "",
trayUsage: s.trayUsage || "", trayUsageEvery: s.trayUsageEvery || 3, trayNoLogos: !!s.trayNoLogos, trayNoBird: !!s.trayNoBird, trayPace: !!s.trayPace, trayNoCost: !!s.trayNoCost, vision: s.vision || "", visionEffort: s.visionEffort || "", searcherEffort: s.searcherEffort || "", imageGen: s.imageGen || "", imageTimeout: s.imageTimeout || 0, classifyTimeout: s.classifyTimeout || 0, searcher: s.searcher || "", searchFirst: s.searchFirst || "", currency: s.currency || "usd",
trayUsage: s.trayUsage || "", trayUsageEvery: s.trayUsageEvery || 3, trayNoLogos: !!s.trayNoLogos, trayNoBird: !!s.trayNoBird, trayPace: !!s.trayPace, trayNoCost: !!s.trayNoCost, trayWindows: s.trayWindows || {}, vision: s.vision || "", visionEffort: s.visionEffort || "", searcherEffort: s.searcherEffort || "", imageGen: s.imageGen || "", imageTimeout: s.imageTimeout || 0, classifyTimeout: s.classifyTimeout || 0, searcher: s.searcher || "", searchFirst: s.searchFirst || "", currency: s.currency || "usd",
chineseUnits: !!s.chineseUnits, usageAlert: s.usageAlert || 0, balanceAlert: s.balanceAlert || 0, resetReminder: s.resetReminder || 0,
turnDoneAlert: s.turnDoneAlert || 0, maskAlert: !!s.maskAlert };
}
+16
View File
@@ -1032,6 +1032,10 @@ const I18N = {
"Warm up on reset": "窗口重置时预热",
"Daily warm-up": "每日定时预热",
"Allowances in the menu bar": "菜单栏显示额度",
"Menu bar windows": "菜单栏额度窗口",
"Which of a subscription's windows its card shows, such as 5 hours or 7 days alone; every window unless you pick, and every window again when those picked are gone": "订阅的卡片显示哪几个额度窗口,比如只显示 5 小时或只显示 7 天;不选则全部显示,选中的窗口不在了也会全部显示",
"All windows": "全部窗口",
"Shown in the menu bar": "显示在菜单栏",
"Show your subscriptions' allowances, or the tokens and cost of today or the last 7 days, beside magpie's icon in the menu bar, side by side, refreshed every few minutes": "在菜单栏 magpie 图标旁并排显示所选订阅的额度,或今天、最近 7 天的 token 数和费用,每隔几分钟刷新",
"Show your subscriptions' allowances, or the tokens and cost of today or the last 7 days, when pointing at magpie's tray icon, refreshed every few minutes": "鼠标指向托盘里的 magpie 图标时显示所选订阅的额度,或今天、最近 7 天的 token 数和费用,每隔几分钟刷新",
"{n} shown": "已选 {n} 项",
@@ -5228,6 +5232,10 @@ const I18N = {
"Warm up on reset": "時段重置時預熱",
"Daily warm-up": "每日定時預熱",
"Allowances in the menu bar": "選單列顯示額度",
"Menu bar windows": "選單列額度視窗",
"Which of a subscription's windows its card shows, such as 5 hours or 7 days alone; every window unless you pick, and every window again when those picked are gone": "訂閱的卡片顯示哪幾個額度視窗,例如只顯示 5 小時或只顯示 7 天;不選則全部顯示,選中的視窗不在了也會全部顯示",
"All windows": "全部視窗",
"Shown in the menu bar": "顯示在選單列",
"Show your subscriptions' allowances, or the tokens and cost of today or the last 7 days, beside magpie's icon in the menu bar, side by side, refreshed every few minutes": "在選單列 magpie 圖示旁並排顯示所選訂閱的額度,或今天、最近 7 天的 token 數和費用,每隔幾分鐘重新整理",
"Show your subscriptions' allowances, or the tokens and cost of today or the last 7 days, when pointing at magpie's tray icon, refreshed every few minutes": "滑鼠指向托盤裡的 magpie 圖示時顯示所選訂閱的額度,或今天、最近 7 天的 token 數和費用,每隔幾分鐘重新整理",
"{n} shown": "已選 {n} 項",
@@ -9396,6 +9404,10 @@ const I18N = {
"Warm up on reset": "リセット時にウォームアップ",
"Daily warm-up": "毎日のウォームアップ",
"Allowances in the menu bar": "メニューバーに利用枠を表示",
"Menu bar windows": "メニューバーの期間",
"Which of a subscription's windows its card shows, such as 5 hours or 7 days alone; every window unless you pick, and every window again when those picked are gone": "サブスクリプションのカードにどの期間を表示するか(5 時間だけ、7 日だけなど)。選ばなければすべて表示し、選んだ期間がなくなったときもすべて表示します",
"All windows": "すべての期間",
"Shown in the menu bar": "メニューバーに表示",
"Show your subscriptions' allowances, or the tokens and cost of today or the last 7 days, beside magpie's icon in the menu bar, side by side, refreshed every few minutes": "メニューバーの magpie アイコンの横に、サブスクリプションの利用枠、または今日・直近 7 日間のトークン数と費用を並べて表示します(数分ごとに更新)",
"Show your subscriptions' allowances, or the tokens and cost of today or the last 7 days, when pointing at magpie's tray icon, refreshed every few minutes": "トレイの magpie アイコンにポインタを合わせると、サブスクリプションの利用枠、または今日・直近 7 日間のトークン数と費用を表示します(数分ごとに更新)",
"{n} shown": "{n} 件を表示",
@@ -13578,6 +13590,10 @@ const I18N = {
"Warm up on reset": "Beim Reset vorwärmen",
"Daily warm-up": "Tägliches Vorwärmen",
"Allowances in the menu bar": "Kontingente in der Menüleiste",
"Menu bar windows": "Zeitfenster in der Menüleiste",
"Which of a subscription's windows its card shows, such as 5 hours or 7 days alone; every window unless you pick, and every window again when those picked are gone": "Welche Zeitfenster eines Abos seine Karte zeigt, etwa nur 5 Stunden oder nur 7 Tage; ohne Auswahl alle, und wieder alle, wenn die gewählten fehlen",
"All windows": "Alle Zeitfenster",
"Shown in the menu bar": "In der Menüleiste angezeigt",
"Show your subscriptions' allowances, or the tokens and cost of today or the last 7 days, beside magpie's icon in the menu bar, side by side, refreshed every few minutes": "Kontingente Ihrer Abos oder Tokens und Kosten von heute bzw. den letzten 7 Tagen nebeneinander neben dem magpie-Symbol in der Menüleiste anzeigen, alle paar Minuten aktualisiert",
"Show your subscriptions' allowances, or the tokens and cost of today or the last 7 days, when pointing at magpie's tray icon, refreshed every few minutes": "Kontingente Ihrer Abos oder Tokens und Kosten von heute bzw. den letzten 7 Tagen beim Zeigen auf das magpie-Tray-Symbol anzeigen, alle paar Minuten aktualisiert",
"{n} shown": "{n} angezeigt",
+4
View File
@@ -260,6 +260,10 @@
<div class="who"><div class="name" data-t>Allowances in the menu bar</div><div class="sub" id="trayUsageSub"></div></div>
<div id="trayUsagePick"></div>
</div>
<div class="row pref" id="trayWindowsRow" hidden>
<div class="who"><div class="name" data-t>Menu bar windows</div><div class="sub" data-t>Which of a subscription's windows its card shows, such as 5 hours or 7 days alone; every window unless you pick, and every window again when those picked are gone</div></div>
<div id="trayWindowsPick" class="tray-windows"></div>
</div>
<div class="row pref" id="trayEveryRow" hidden>
<div class="who"><div class="name" data-t>Menu bar refresh</div><div class="sub" data-t>How often the allowances beside the icon are asked for again</div></div>
<div id="trayEverySegs"></div>
+32
View File
@@ -0,0 +1,32 @@
// Settings › Menu bar windows. app.js imports this only when the menu bar
// shows a card (renderTrayUsage), so it weighs nothing on the core.
// which of a subscription's windows its menu bar card shows, by kind
// (settings.TrayWindows, StrikingRaw on X): a pill each for those ticked
// with two or more, every window unless some are picked; not on Windows,
// whose tooltip says them all
window.trayWindowsRow = function trayWindowsRow(s, keep, ids, mac) {
const pick = s.trayWindows || {}, box = $("#trayWindowsPick"), subs = [];
for (const pid of new Set(ids.filter((id) => !id.startsWith("usage:")).map((id) => id.split("|")[0]))) {
const ws = [], q = (quotas || []).find((q) => q.provider === pid);
for (const w of q?.windows || []) if (w.trayKind && !ws.some((x) => x.v === w.trayKind)) ws.push({ v: w.trayKind, name: w.name, note: "" });
if (ws.length > 1) subs.push([pid, q.name, ws]);
}
$("#trayWindowsRow").hidden = !subs.length || !mac && document.documentElement.classList.contains("win");
if (!quotas && ids.some((id) => !id.startsWith("usage:"))) loadQuotas().then(() => box.isConnected && trayWindowsRow(s, keep, ids, mac));
box.replaceChildren(...subs.map(([pid, name, ws]) => {
const on = (pick[pid] || []).filter((k) => ws.some((w) => w.v === k)), b = el("button", "proto pick" + (on.length ? " set" : ""));
b.type = "button";
b.append(el("span", "", name + " · " + (on.length ? on.map((k) => t(ws.find((w) => w.v === k).name)).join(" · ") : t("All windows"))), svg(CHEV, 11, 1.6));
b.onclick = (e) => {
e.stopPropagation();
if (b.classList.contains("open")) return closeProtoMenu();
openProtoMenu(b, [{ v: "", name: "All windows", note: "" }, ...ws], on, (v) => {
const next = { ...pick };
if (v.length && v.length < ws.length) next[pid] = v; else delete next[pid];
savePrefs({ ...keep, trayWindows: next });
}, "Shown in the menu bar");
};
return b;
}));
};
+3 -3
View File
@@ -144,9 +144,9 @@ test("compat.js is the first of the page's own scripts", async () => {
// webfonts.js is imported by app.js in a browser tab only, cfgblocked.js
// when magpie can't write its folder, signsheets.js when a sign-in asks a
// value first, ruleedit.js on a masking rule's Edit, ratewindows.js when
// a provider editor draws its rate windows; the checks above still read
// them
for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html");
// a provider editor draws its rate windows, traywindows.js when the menu
// bar shows a card; the checks above still read them
for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html");
});
test("the styles hold up in Safari 15.0", async () => {
+164
View File
@@ -0,0 +1,164 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// Settings → Menu bar windows (settings.TrayWindows, StrikingRaw on X): for
// each ticked subscription with two or more windows the menu bar can show,
// a pill picks which of them its card shows, by kind ("5h", "7d"), every
// window unless some are picked. The pick is saved by provider, kept when
// another setting is saved, and All windows takes it back. Hidden on
// Windows, whose tray shows the tooltip alone, and with no card of two
// windows. Every language; narrow too. No backend, the API is faked here.
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 { openPart } = require("./reader.cjs");
const assets = path.resolve(__dirname, "../assets");
const quotas = [
{ provider: "claude", name: "Claude Code", icon: "claude-color", user: "a@b.c", plan: "Pro",
windows: [{ name: "5 hours", used: 42, trayKind: "5h" }, { name: "7 days", used: 18, trayKind: "7d" }, { name: "Opus", used: 90 }] },
{ provider: "copilot", name: "Copilot", icon: "githubcopilot", windows: [{ name: "Premium", used: 63, trayKind: "month" }] },
];
function server(lang, posts, over) {
let cur = {
theme: "light", lang, tray: "panel", quotaLeft: false, currency: "usd", dock: false, dockWindow: false, proxy: "",
trayUsage: "claude|*", trayUsages: ["claude|*", "copilot", "usage:today"], trayUsageEvery: 3,
version: "0.1.400", dir: "~/.config/magpie", gateway: "http://127.0.0.1:3425", proxyNow: "none", proxySource: "none",
fx: { rate: 7.2, at: new Date().toISOString(), stale: false }, ...over,
};
return async (route) => {
const req = route.request(), url = new URL(req.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: { lang, theme: "light" }, fx: cur.fx });
if (url.pathname === "/api/settings") {
if (req.method() === "POST") { posts.push(req.postDataJSON()); cur = { ...cur, ...req.postDataJSON() }; }
return json(cur);
}
if (url.pathname === "/api/usage/quotas") return json(quotas);
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)];
await route.fulfill({ body: await fs.readFile(file), contentType });
};
}
async function open(browser, lang, posts, { platform = "MacIntel", width = 900, over = {} } = {}) {
const context = await browser.newContext({ viewport: { width, height: 560 }, reducedMotion: "reduce" });
await context.addInitScript((p) => Object.defineProperty(Navigator.prototype, "platform", { get: () => p }), platform);
const page = await context.newPage();
page.setDefaultTimeout(5000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", server(lang, posts, over));
await page.goto("http://magpie.test/?view=usage");
await page.locator("#prefs").click();
await openPart(page, "usage");
await page.locator("#trayUsagePick button").waitFor();
return { context, page, errors };
}
const LANGS = [
["en", "Menu bar windows", "All windows", "5 hours", "7 days"],
["zh", "菜单栏额度窗口", "全部窗口", "5 小时", "7 天"],
["zh-TW", "選單列額度視窗", "全部視窗", "5 小時", "7 天"],
["ja", "メニューバーの期間", "すべての期間", "5 時間", "7 日"],
["de", "Zeitfenster in der Menüleiste", "Alle Zeitfenster", "5 Stunden", "7 Tage"],
];
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": which windows a menu bar card shows", 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, name, all, five, seven] of LANGS) {
await t.test(lang, async () => {
const posts = [];
const { context, page, errors } = await open(browser, lang, posts);
const row = page.locator("#trayWindowsRow");
await row.waitFor();
assert.equal(await row.locator(".name").textContent(), name);
// one pill: Claude's, the card with two windows the menu bar can
// show (Opus counts one model's use); Copilot has one, totals none
const pills = row.locator("#trayWindowsPick button");
await page.waitForFunction(() => document.querySelectorAll("#trayWindowsPick button").length === 1);
assert.equal((await pills.first().textContent()).trim(), "Claude Code · " + all);
assert.equal(await pills.first().evaluate((b) => getComputedStyle(b).borderLeftWidth), "0px");
// the app's menu: All windows, then each window by its name
await pills.first().click();
const menu = page.locator(".proto-menu");
await menu.waitFor();
assert.equal(await page.locator("select").count(), 0);
const items = menu.locator(".pm-item");
assert.deepEqual((await items.locator(".pm-name").allTextContents()).map((s) => s.trim()), [all, five, seven]);
assert.deepEqual(await items.evaluateAll((bs) => bs.map((b) => b.getAttribute("aria-checked"))), ["true", "false", "false"]);
await items.nth(1).click();
assert.equal(posts.length, 0, "nothing is saved till the menu closes");
await page.keyboard.press("Escape");
await page.waitForFunction((s) => document.querySelector("#trayWindowsPick button")?.textContent.trim() === s, "Claude Code · " + five);
assert.equal(posts.length, 1);
assert.deepEqual(posts[0].trayWindows, { claude: ["5h"] });
assert.deepEqual(posts[0].trayUsages, ["claude|*", "copilot", "usage:today"], "the cards are kept");
// another setting saved keeps the pick
await page.locator("#trayPaceSegs button").nth(1).click();
for (let i = 0; i < 100 && posts.length < 2; i++) await page.waitForTimeout(20);
assert.equal(posts.length, 2);
assert.equal(posts[1].trayPace, true);
assert.deepEqual(posts.at(-1).trayWindows, { claude: ["5h"] });
// both ticked is every window: nothing kept for it
await page.locator("#trayWindowsPick button").click();
await menu.waitFor();
await menu.locator(".pm-item").nth(2).click();
await page.keyboard.press("Escape");
await page.waitForFunction((s) => document.querySelector("#trayWindowsPick button")?.textContent.trim() === s, "Claude Code · " + all);
assert.deepEqual(posts.at(-1).trayWindows, {});
assert.deepEqual(errors, []);
await context.close();
});
}
await t.test("All windows takes a pick back", async () => {
const posts = [];
const { context, page } = await open(browser, "en", posts, { over: { trayWindows: { claude: ["7d"], codex: ["5h"] } } });
const pill = page.locator("#trayWindowsPick button");
await page.waitForFunction(() => document.querySelector("#trayWindowsPick button")?.textContent.trim() === "Claude Code · 7 days");
await pill.click();
await page.locator(".proto-menu .pm-item").first().click();
await page.waitForFunction(() => document.querySelector("#trayWindowsPick button")?.textContent.trim() === "Claude Code · All windows");
// another subscription's pick, not ticked now, is left as it was
assert.deepEqual(posts.at(-1).trayWindows, { codex: ["5h"] });
await context.close();
});
await t.test("hidden where it changes nothing", async () => {
for (const opt of [{ platform: "Win32" }, { over: { trayUsages: ["copilot", "usage:today"], trayUsage: "copilot" } }, { over: { trayUsages: [], trayUsage: "" } }]) {
const { context, page } = await open(browser, "en", [], opt);
await page.waitForTimeout(300);
assert.equal(await page.locator("#trayWindowsRow").isVisible(), false, JSON.stringify(opt));
await context.close();
}
});
await t.test("narrow", async () => {
for (const [lang] of LANGS) {
const { context, page } = await open(browser, lang, [], { width: 360, over: { trayWindows: { claude: ["5h", "7d"] } } });
const row = page.locator("#trayWindowsRow");
await row.waitFor();
const pill = row.locator("#trayWindowsPick button");
await pill.waitFor();
const [r, p] = [await row.boundingBox(), await pill.boundingBox()];
assert(p.x >= r.x && p.x + p.width <= r.x + r.width + 0.5, `${lang}: the pill stays in its row: ${JSON.stringify([r, p])}`);
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true, lang + ": no sideways scroll");
await context.close();
}
});
});
}
+77 -8
View File
@@ -61,11 +61,70 @@ func trayWindows(q provider.SubscriptionQuota) []provider.QuotaWindow {
return ws
}
// trayUsageText is the menu bar's text for a card and the tooltip that
// trayWindowKind names a window by how long it runs, as
// settings.TrayWindows keeps a choice of them: "5h", "1d", "7d", "month",
// which stay when the vendor renames or reorders its windows; where the
// span isn't known, the vendor's name for it after "name:".
func trayWindowKind(w provider.QuotaWindow) string {
d := w.Span
if d >= 28*24*time.Hour && d <= 31*24*time.Hour {
return "month"
}
if h := int64(d.Round(time.Hour) / time.Hour); h >= 24 && h%24 == 0 {
return fmt.Sprintf("%dd", h/24)
} else if h >= 1 {
return fmt.Sprintf("%dh", h)
}
if d > 0 {
return fmt.Sprintf("%dm", max(1, int64(d.Round(time.Minute)/time.Minute)))
}
return "name:" + strings.ToLower(strings.TrimSpace(w.Name))
}
// trayShownKinds are the kinds of ws a card's rows show, as chosen in
// Settings (settings.TrayWindows): nil, every window, when none was chosen
// or none chosen is among ws now, so a card is never left empty.
func trayShownKinds(ws []provider.QuotaWindow, kinds []string) []string {
for _, w := range ws {
if slices.Contains(kinds, trayWindowKind(w)) {
return kinds
}
}
return nil
}
// withTrayKinds is qs with each window the menu bar can show named by its
// kind (TrayKind), for Settings to offer them; qs and its windows, which
// the caches share, are left as they were.
func withTrayKinds(qs []provider.SubscriptionQuota) []provider.SubscriptionQuota {
out := make([]provider.SubscriptionQuota, len(qs))
for i, q := range qs {
if len(q.Windows) > 0 {
ws := slices.Clone(q.Windows)
for j := range ws {
if !ws[j].Aside && ws[j].Model == "" {
ws[j].TrayKind = trayWindowKind(ws[j])
}
}
q.Windows = ws
}
out[i] = q
}
return out
}
// trayUsageText is trayCardText with every window shown.
func trayUsageText(q provider.SubscriptionQuota, now time.Time, left, pace bool) (label, tip string) {
return trayCardText(q, now, left, pace, nil)
}
// trayCardText is the menu bar's text for a card and the tooltip that
// spells it out: each window's use, or what is left of it (left), and when
// it starts again. With pace (settings.TrayPace) each window's Pace number
// follows its figure, in both, as the Usage page's cards show it.
func trayUsageText(q provider.SubscriptionQuota, now time.Time, left, pace bool) (label, tip string) {
// follows its figure, in both, as the Usage page's cards show it. The text
// has the windows of the kinds given alone (trayShownKinds); the tooltip
// has them all.
func trayCardText(q provider.SubscriptionQuota, now time.Time, left, pace bool, kinds []string) (label, tip string) {
if strings.HasPrefix(q.Provider, trayTotal) {
return q.Balance, q.Name // trayTotalCard's: its rows, and its tooltip
}
@@ -84,6 +143,7 @@ func trayUsageText(q provider.SubscriptionQuota, now time.Time, left, pace bool)
if q.ReadAt != nil && !q.ReadAt.After(now) {
readAt = *q.ReadAt
}
kinds = trayShownKinds(ws, kinds)
var short, long []string
for _, w := range ws {
used := math.Max(0, math.Min(100, w.Used))
@@ -99,7 +159,9 @@ func trayUsageText(q provider.SubscriptionQuota, now time.Time, left, pace bool)
row = pct + " " + trayPace(p, left)
paceNote = " · pace " + trayPace(p, left)
}
short = append(short, row)
if kinds == nil || slices.Contains(kinds, trayWindowKind(w)) {
short = append(short, row)
}
tipPct := pct
if used != math.Trunc(used) {
tipPct = fmt.Sprintf("%.1f%%", used)
@@ -436,13 +498,20 @@ func trayPlain(cells []trayCell) []trayCell {
return out
}
// trayUsageView is what the tray shows for the cards: a cell for each
// that has a label, with its stable identity for clicks; labels joined by
// " | " for a tray that shows text; and a tooltip spelling each out.
// trayUsageView is trayCardsView with every window shown.
func trayUsageView(cards []provider.SubscriptionQuota, now time.Time, left, pace bool) (cells []trayCell, label, tip string) {
return trayCardsView(cards, now, left, pace, nil)
}
// trayCardsView is what the tray shows for the cards: a cell for each
// that has a label, with its stable identity for clicks; labels joined by
// " | " for a tray that shows text; and a tooltip spelling each out. A
// card's rows are the windows its provider's kinds in pick name
// (settings.TrayWindows), all when it names none.
func trayCardsView(cards []provider.SubscriptionQuota, now time.Time, left, pace bool, pick map[string][]string) (cells []trayCell, label, tip string) {
var labels, tips []string
for _, q := range cards {
l, t := trayUsageText(q, now, left, pace)
l, t := trayCardText(q, now, left, pace, pick[q.Provider])
if t != "" {
tips = append(tips, t)
}
+105
View File
@@ -0,0 +1,105 @@
package gui
import (
"slices"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
// A subscription's card shows the windows Settings picked for it
// (settings.TrayWindows, StrikingRaw on X: Claude's 5 hours alone, not two
// small numbers squeezed together), named by how long they run, so a
// vendor's order doesn't matter; the tooltip still spells out every one,
// one picked that is gone shows every window rather than none, and a card
// of another provider is left as it was.
func TestTrayWindowsPicked(t *testing.T) {
now := time.Date(2026, 10, 30, 12, 0, 0, 0, time.UTC)
claude := provider.SubscriptionQuota{Provider: "claude", Name: "Claude", User: "a@b.c", Windows: []provider.QuotaWindow{
{Name: "7 days", Used: 70, Span: 7 * 24 * time.Hour}, // the vendor's order, longest first
{Name: "5 hours", Used: 42, Span: 5 * time.Hour},
{Name: "Opus", Used: 90, Span: 7 * 24 * time.Hour, Model: "opus"},
}}
codex := provider.SubscriptionQuota{Provider: "codex", Name: "Codex", User: "x@y.z", Windows: []provider.QuotaWindow{
{Name: "5 hours", Used: 10, Span: 5 * time.Hour},
{Name: "Weekly", Used: 20, Span: 7 * 24 * time.Hour},
}}
cards := []provider.SubscriptionQuota{claude, codex}
rows := func(pick map[string][]string) ([][]string, string) {
cells, _, tip := trayCardsView(cards, now, false, false, pick)
var out [][]string
for _, c := range cells {
out = append(out, c.Rows)
}
return out, tip
}
same := func(got, want [][]string) bool { return slices.EqualFunc(got, want, slices.Equal) }
all, allTip := rows(nil)
if !same(all, [][]string{{"42%", "70%"}, {"10%", "20%"}}) {
t.Fatalf("none picked: %q", all)
}
got, tip := rows(map[string][]string{"claude": {"5h"}})
if !same(got, [][]string{{"42%"}, {"10%", "20%"}}) {
t.Fatalf("5h alone: %q", got)
}
if tip != allTip {
t.Errorf("the tooltip lost a window:\n%s\nwant\n%s", tip, allTip)
}
if got, _ = rows(map[string][]string{"claude": {"7d"}, "codex": {"7d"}}); !same(got, [][]string{{"70%"}, {"20%"}}) {
t.Fatalf("7d alone: %q", got)
}
// a picked window gone (the vendor dropped it): every window, not an
// empty card
if got, _ = rows(map[string][]string{"claude": {"month"}}); !same(got, all) {
t.Fatalf("gone: %q", got)
}
// the Linux tray's text follows it too
if _, label, _ := trayCardsView(cards, now, true, false, map[string][]string{"claude": {"5h"}}); label != "58% | 90% · 80%" {
t.Fatalf("text: %q", label)
}
}
// Windows are named by how long they run; one whose span isn't known by
// the vendor's name for it.
func TestTrayWindowKind(t *testing.T) {
for _, c := range []struct {
w provider.QuotaWindow
want string
}{
{provider.QuotaWindow{Span: 5 * time.Hour}, "5h"},
{provider.QuotaWindow{Span: 5*time.Hour + 3*time.Second}, "5h"},
{provider.QuotaWindow{Span: 24 * time.Hour}, "1d"},
{provider.QuotaWindow{Span: 7 * 24 * time.Hour}, "7d"},
{provider.QuotaWindow{Span: 30 * 24 * time.Hour}, "month"},
{provider.QuotaWindow{Span: 31 * 24 * time.Hour}, "month"},
{provider.QuotaWindow{Span: 15 * time.Minute}, "15m"},
{provider.QuotaWindow{Name: " Credits "}, "name:credits"},
} {
if got := trayWindowKind(c.w); got != c.want {
t.Errorf("%+v: %q, want %q", c.w, got, c.want)
}
}
}
// Settings is told each window the menu bar can show by its kind, and only
// those: not one a single model's use counts, nor money aside; the cards
// the cache keeps are left as they were.
func TestWithTrayKinds(t *testing.T) {
qs := []provider.SubscriptionQuota{{Provider: "claude", Windows: []provider.QuotaWindow{
{Name: "5 hours", Span: 5 * time.Hour},
{Name: "Opus", Span: 7 * 24 * time.Hour, Model: "opus"},
{Name: "Extra", Span: 30 * 24 * time.Hour, Aside: true},
}}, {Provider: "deepseek", Balance: "¥5"}}
out := withTrayKinds(qs)
if ws := out[0].Windows; ws[0].TrayKind != "5h" || ws[1].TrayKind != "" || ws[2].TrayKind != "" {
t.Fatalf("kinds: %+v", ws)
}
if qs[0].Windows[0].TrayKind != "" {
t.Fatal("the cache's window was written")
}
if out[1].Balance != "¥5" {
t.Fatalf("balance card: %+v", out[1])
}
}
+1 -1
View File
@@ -41,7 +41,7 @@ func (h *host) watchTrayUsage() {
for {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
s := settings.Load()
cells, label, tip := trayUsageView(trayUsageCards(ctx, s.TrayUsages), time.Now(), s.QuotaLeft, s.TrayPace)
cells, label, tip := trayCardsView(trayUsageCards(ctx, s.TrayUsages), time.Now(), s.QuotaLeft, s.TrayPace, s.TrayWindows)
cancel()
if s.TrayNoLogos {
cells = trayPlain(cells)
+73
View File
@@ -0,0 +1,73 @@
package gui
import (
"bytes"
"image"
"image/png"
"os"
"path/filepath"
"testing"
"time"
)
// TestTrayImageOneWindow draws, through AppKit, Claude's card with its
// 5-hour window alone (settings.TrayWindows, StrikingRaw on X): one line
// at the bar's own size, not two small stacked numbers, in a cell not much
// wider than both took.
func TestTrayImageOneWindow(t *testing.T) {
bird, err := os.ReadFile("tray.png")
if err != nil {
t.Fatal(err)
}
cards := trayCards()[:2]
both, _, _ := trayCardsView(cards, time.Now(), false, false, nil)
one, _, _ := trayCardsView(cards, time.Now(), false, false, map[string][]string{"claude": {"5h"}})
if len(both[0].Rows) != 2 || len(one[0].Rows) != 1 || one[0].Rows[0] != "42%" || len(one[1].Rows) != 2 {
t.Fatalf("both %q %q, one %q %q", both[0].Rows, both[1].Rows, one[0].Rows, one[1].Rows)
}
out := os.Getenv("MAGPIE_TRAY_PREVIEW")
for _, dark := range []bool{false, true} {
_, w0, _ := trayImagePNG(nil, bird, 22, 2, dark, false)
lines := map[string]int{}
for name, cs := range map[string][]trayCell{"both": both[:1], "one": one[:1]} {
b, w, h := trayImagePNG(cs, bird, 22, 2, dark, false)
img, err := png.Decode(bytes.NewReader(b))
if err != nil || h != 44 || img.Bounds().Dx() != w {
t.Fatalf("dark %v %s: %v, %dx%d", dark, name, err, w, h)
}
// the right half of Claude's cell, past its logo: its digits
lines[name] = inkBands(img, image.Rect(w0+(w-w0)/2, 0, w, h), dark)
}
if lines["both"] != 2 || lines["one"] != 1 {
t.Errorf("dark %v: both windows draw %d lines, one %d", dark, lines["both"], lines["one"])
}
_, wb, _ := trayImagePNG(both, bird, 22, 2, dark, false)
_, wo, _ := trayImagePNG(one, bird, 22, 2, dark, false)
if wo > wb+12 {
t.Errorf("dark %v: one window is %d px wide, both %d", dark, wo, wb)
}
if out != "" {
for name, cs := range map[string][]trayCell{"both": both, "one": one} {
bg, _, _ := trayImagePNG(cs, bird, 22, 2, dark, true)
f := filepath.Join(out, "tray-windows-"+name+map[bool]string{false: "-light.png", true: "-dark.png"}[dark])
if err := os.WriteFile(f, bg, 0o644); err != nil {
t.Fatal(err)
}
}
}
}
}
// inkBands counts the runs of pixel rows in r that hold ink: the lines of
// text drawn there.
func inkBands(img image.Image, r image.Rectangle, dark bool) int {
n, in := 0, false
for y := r.Min.Y; y < r.Max.Y; y++ {
on := inkIn(img, image.Rect(r.Min.X, y, r.Max.X, y+1), dark) > 0
if on && !in {
n++
}
in = on
}
return n
}
+4 -1
View File
@@ -270,6 +270,9 @@ func usageRoutes(mux *http.ServeMux, w Windows) {
qs = usage.WithWindowHolds(qs, usage.Clock())
// and when each began, for its Pace number (fflake33)
qs = provider.WithWindowStarts(qs, usage.Clock())
// and which the menu bar can show, by kind, for Settings to pick
// among (settings.TrayWindows)
qs = withTrayKinds(qs)
// an account's card may be the stale copy a read under way will
// replace: the page asks again until it has landed (#959)
if provider.SubscriptionUsageReading() {
@@ -289,7 +292,7 @@ func usageRoutes(mux *http.ServeMux, w Windows) {
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
provider.RefreshUsage(ctx, id, r.URL.Query().Get("user"))
writeJSON(rw, provider.WithWindowStarts(usage.WithWindowHolds(provider.InProviderOrder(provider.WithCheckins(provider.Quotas(ctx))), usage.Clock()), usage.Clock()))
writeJSON(rw, withTrayKinds(provider.WithWindowStarts(usage.WithWindowHolds(provider.InProviderOrder(provider.WithCheckins(provider.Quotas(ctx))), usage.Clock()), usage.Clock())))
})
// WorkBuddy's daily check-in pressed now, from the Usage card, for
// each account not in yet today, as `magpie accounts checkin` does; the
+4
View File
@@ -111,6 +111,10 @@ type QuotaWindow struct {
// (WithWindowStarts): with ResetsAt it places an even pace through the
// window, which the card's Pace number is measured from (fflake33).
StartsAt *time.Time `json:"startsAt,omitempty"`
// TrayKind is, for the GUI only, how Settings names the window among
// those the menu bar can show (gui.withTrayKinds): "5h", "7d",
// "month"; empty on one the menu bar leaves out.
TrayKind string `json:"trayKind,omitempty"`
// matches further scopes pools whose membership isn't one model word.
matches func(string) bool
// partial is set on the windows of a reading that may leave some out:
+25
View File
@@ -477,6 +477,14 @@ type Settings struct {
// no cards say the tokens alone (BussanQ on Discord); off by default,
// the cost shown.
TrayNoCost bool `json:"trayNoCost,omitempty"`
// TrayWindows are, by subscription or plan (a provider's id, every
// account of it alike), the windows its menu bar card shows, each by
// how long it runs ("5h", "7d", "month": gui.trayWindowKind), so a
// vendor reordering or renaming them changes nothing (StrikingRaw on
// X: Claude's 5h alone, not two small numbers). A provider not named
// shows every window, as before; one whose named windows are all gone
// shows every window too, never an empty card.
TrayWindows map[string][]string `json:"trayWindows,omitempty"`
// Lightweight lets the webview of a window closed — the tray panel or
// the main window — go once it has stayed closed a while, and makes it
// again when it is opened (#580): less memory, a moment's wait. This
@@ -1200,6 +1208,7 @@ func (s *Settings) KeepOwn(cur Settings) {
s.WindowMaximised, s.KeepAwake, s.KeepAwakeDisplay = cur.WindowMaximised, cur.KeepAwake, cur.KeepAwakeDisplay
s.WindowAt = cur.WindowAt
s.TrayUsages, s.TrayUsage, s.TrayUsageEvery, s.TrayNoLogos, s.TrayNoBird, s.TrayPace, s.TrayNoCost = cur.TrayUsages, cur.TrayUsage, cur.TrayUsageEvery, cur.TrayNoLogos, cur.TrayNoBird, cur.TrayPace, cur.TrayNoCost
s.TrayWindows = cur.TrayWindows
s.GatewayMode = cur.GatewayMode
s.NoWSLAgents = cur.NoWSLAgents
s.QuotaReads = cur.QuotaReads
@@ -1829,6 +1838,7 @@ func saveOwn(s Settings, recording, reads bool) error {
s.ClientAgents = clientAgents(s.ClientAgents)
s.UsageCleared = usageCleared(s.UsageCleared)
s.TrayUsages = ids(s.TrayUsages)
s.TrayWindows = trayWindows(s.TrayWindows)
for i, u := range s.CodexAutoReset {
s.CodexAutoReset[i] = strings.ToLower(u)
}
@@ -2032,6 +2042,21 @@ func ids(in []string) []string {
return out
}
// trayWindows is TrayWindows as kept: each provider's kinds trimmed, once
// each, and a provider with none left out, as it shows every window.
func trayWindows(m map[string][]string) map[string][]string {
out := map[string][]string{}
for p, kinds := range m {
if p, kinds = strings.TrimSpace(p), ids(kinds); p != "" && len(kinds) > 0 {
out[p] = kinds
}
}
if len(out) == 0 {
return nil
}
return out
}
// clientAgents is ClientAgents as kept: the clients' names lower-cased and
// trimmed, an empty name or agent left out.
func clientAgents(m map[string]string) map[string]string {
+48
View File
@@ -0,0 +1,48 @@
package settings
import (
"maps"
"os"
"slices"
"testing"
)
// Which of a subscription's windows its menu bar card shows (TrayWindows,
// StrikingRaw on X): kept by provider and kind as the user picked them,
// each kind once, and a provider with none picked left out, as it shows
// every window; a file without the field shows every window, as before.
func TestTrayWindowsKept(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
if err := os.MkdirAll(Dir(), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(Path(), []byte(`{"trayUsages":["claude|a@b.c"]}`), 0o644); err != nil {
t.Fatal(err)
}
s := Load()
if s.TrayWindows != nil {
t.Fatalf("a file from before: %v", s.TrayWindows)
}
s.TrayWindows = map[string][]string{"claude": {" 5h", "5h"}, "codex": {"7d", "5h"}, "kimi": {}, " ": {"5h"}}
if err := Save(s); err != nil {
t.Fatal(err)
}
want := map[string][]string{"claude": {"5h"}, "codex": {"7d", "5h"}}
if s = Load(); !maps.EqualFunc(s.TrayWindows, want, slices.Equal) {
t.Fatalf("saved: %v", s.TrayWindows)
}
// every one taken back: none kept
s.TrayWindows = map[string][]string{"claude": nil}
if err := Save(s); err != nil {
t.Fatal(err)
}
if s = Load(); s.TrayWindows != nil {
t.Fatalf("taken back: %v", s.TrayWindows)
}
// and it is this computer's, as the rest of the menu bar is
in := Settings{TrayWindows: map[string][]string{"claude": {"7d"}}}
in.KeepOwn(Settings{TrayWindows: want})
if !maps.EqualFunc(in.TrayWindows, want, slices.Equal) {
t.Fatalf("KeepOwn: %v", in.TrayWindows)
}
}