usage: a window's Pace as a number on its card, and in the menu bar when asked (fflake33)
fflake33 on Discord asked for the pace as a figure, "+12%" or "−8%"
against an even pace through the window, on the Usage cards and in the
menu bar.
- provider: QuotaWindow.Pace(readAt, now) is the share used (0-100) less
the share of the window gone by, from Bounds (reset less span; a
month's window a calendar month); none for an unlimited window, one
whose span or reset isn't known, or outside it. WithWindowStarts sets
startsAt on copies of the cards for the GUI (the caches' cards are
left alone); /api/usage/quotas and its refresh send it.
- Usage page: "Pace +20%" on the reset line after the wait (quotaPace,
paceLine), its sign turned with the meter in Left mode, amber while
more is used than an even pace would have, what it means in its
tooltip. Past cycles and windows with no known start show none.
- Menu bar: Settings > Menu bar pace (settings.TrayPace, off by default;
hidden on Windows, whose tray shows no text) puts " +12%" beside each
figure ("42% −14%", at most 10 runes, trayRowMax) and "pace −14%" in
the tooltip. KeepOwn keeps it device-local like the other tray
settings; the Settings save keeps it (prefsKeep).
- Strings in en, zh, zh-TW, ja, de. gui-shell.md says it.
Run:
- go test -tags nogui ./internal/provider ./internal/gui ./internal/settings
./internal/usage: ok; ./internal/davsync: ok (now covers TrayPace;
red with TrayPace taken out of KeepOwn). go test ./internal/gui -run
Tray (darwin, with the tray image tests): ok.
- New TestWindowPace, TestWithWindowStarts (input not mutated),
TestTrayUsagePace (off unchanged, used and left, rows, tooltip).
- quota-pace.test.cjs, chromium and webkit: 4 pass; cards in en, zh,
zh-TW, ja, de at 1100 and 420px, used and left, amber, tooltips, no
sideways scroll, a click moves nothing; the Settings row in all five
at both widths, On posts trayPace, a currency save keeps it, no
scroll; hidden with no card and on Windows, shown on Linux. Red with
paceLine not called, with trayPace out of prefsKeep, and with the
Left-mode sign not turned.
- gui-de, gui-ja, gui-zh-tw, i18n-keys: 12 pass; tray-bird 6, quota-holds
2, quota-read-at 4 pass.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows clean.
Not tried: the real menu bar on a Mac or Linux tray.
This commit is contained in:
@@ -292,6 +292,7 @@ covers it.
|
||||
- The requests magpie makes by itself (a routing classifier's, a web search's, an image description's) are told apart from the agents' on the Usage page (#1839): magpie's row among the agents and its rows in the ledger carry a "magpie's own" mark (`ownBadge`), an account's, key's or model's row adds "{n} by magpie itself" from the summary's `own`, and an account's card says how many of the period's requests were magpie's own (`ownLine`, drawn again once the summary comes after the allowances). See `own-requests.test.cjs` and `TestSummaryCountsMagpiesOwnCallsApart`.
|
||||
- Opening the allowances is asking to see them (#1588, `quotasOpened` in `app.js`): the Usage page from the nav or its Overview tab picked, the window brought back to the front on the Overview, the tray panel's Allowances tab picked or the panel brought up on it, and a menu bar cell clicked each load `usage/quotas?asked=1`, as Refresh now does. An asked read makes the backend read every account again (`AskClaudeUsage`), so an opening within 30s (`QUOTAS_OPEN_GAP`) of the last asked read sends an ordinary read instead, which joins one on its way; Refresh now always asks. A panel page loaded while it is put away (hidden, or without focus) doesn't ask. The timed refresh is unchanged and never asks. See `allowance-open-read.test.cjs`.
|
||||
- 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.SummarizeTop(p, 0)` (the Overview's cached summary) and asks no vendor when only totals are picked; `trayTotalCard` makes the tokens (in and out, as `tokensOf`) 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 Overview at the period (`quotaView`, `?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`.
|
||||
- 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`.
|
||||
- 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. 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`.
|
||||
|
||||
@@ -180,7 +180,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})
|
||||
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})
|
||||
profile.Save("work", profile.Profile{Fields: map[string]string{"claude.model": "x"}})
|
||||
same := cfg
|
||||
same.Passphrase = cfg.Password
|
||||
@@ -225,7 +225,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 {
|
||||
if s := settings.Load(); len(s.TrayUsages) != 0 || s.TrayUsage != "" || s.TrayUsageEvery == 5 || s.TrayNoLogos || s.TrayNoBird || s.TrayPace {
|
||||
t.Fatalf("b's menu bar: %+v", s)
|
||||
}
|
||||
if ps, _ := profile.Load(); len(ps) != 1 {
|
||||
|
||||
+3
-2
@@ -1263,9 +1263,10 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
|
||||
onDock(in)
|
||||
}
|
||||
// the cards the menu bar shows, any of them (TrayUsage is only the first),
|
||||
// how often, with their logos or not, and beside the bird or not
|
||||
// how often, with their logos or not, beside the bird or not, and
|
||||
// with their Pace numbers or not
|
||||
if (!slices.Equal(settings.Load().TrayUsages, cur.TrayUsages) || in.TrayUsageEvery != cur.TrayUsageEvery ||
|
||||
in.TrayNoLogos != cur.TrayNoLogos || in.TrayNoBird != cur.TrayNoBird) && onTrayUsage != nil {
|
||||
in.TrayNoLogos != cur.TrayNoLogos || in.TrayNoBird != cur.TrayNoBird || in.TrayPace != cur.TrayPace) && onTrayUsage != nil {
|
||||
onTrayUsage()
|
||||
}
|
||||
// an alert turned on or moved is looked at now, the Mac asked for its
|
||||
|
||||
@@ -822,6 +822,10 @@ body.window .field.solo { grid-column: auto; }
|
||||
.quota-windows.stacked .quota-n > span { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
|
||||
.quota-reset { display: flex; flex-wrap: wrap; column-gap: 4px; margin-top: 4px; font-size: 10px; color: var(--faint); font-variant-numeric: tabular-nums; }
|
||||
.quota-reset > span { white-space: nowrap; }
|
||||
/* a window's Pace number (fflake33): faint like its line, amber when more
|
||||
is used than an even pace would have */
|
||||
.quota-reset .quota-pace { font-variant-numeric: tabular-nums; }
|
||||
.quota-reset .quota-pace.over { color: var(--amber); }
|
||||
/* a window's whole (WindowHolds): a line of its own under the reset */
|
||||
.quota-reset .quota-holds { flex-basis: 100%; display: flex; flex-wrap: wrap; column-gap: 4px; min-width: 0; }
|
||||
.quota-reset .quota-holds > span { white-space: nowrap; }
|
||||
|
||||
@@ -13036,6 +13036,36 @@ function quotaText(w) {
|
||||
const count = quotaCount(w);
|
||||
return count ? count + " · " + pct : pct;
|
||||
}
|
||||
// quotaPace: how far a window is from an even pace through it, as a
|
||||
// number (fflake33 on Discord): the figure the meter shows less what an
|
||||
// even pace would show by now, in points of the window, rounded — used
|
||||
// 60% halfway through is +10, and left it is −10; null where the window's
|
||||
// start or reset isn't known (startsAt is the gateway's,
|
||||
// provider.WithWindowStarts). over says more is used than an even pace
|
||||
// would have, whichever way the meter reads.
|
||||
function quotaPace(w, now = Date.now()) {
|
||||
if (w.unlimited || w.historyMissing || !w.startsAt || !w.resetsAt) return null;
|
||||
const s = Date.parse(w.startsAt), e = Date.parse(w.resetsAt);
|
||||
if (!(e > s) || now < s || now >= e) return null;
|
||||
const d = Math.max(0, Math.min(100, w.used)) - (100 * (now - s)) / (e - s);
|
||||
const n = Math.round(quotaLeft ? -d : d);
|
||||
return { n: n === 0 ? 0 : n, over: Math.round(d) > 0, under: Math.round(d) < 0, by: Math.abs(Math.round(d)) };
|
||||
}
|
||||
// paceNumber: +12%, −8% (a true minus), ±0%
|
||||
function paceNumber(n) {
|
||||
return (n > 0 ? "+" : n < 0 ? "−" : "±") + Math.abs(n) + "%";
|
||||
}
|
||||
// paceLine: a window's Pace number for its reset line, with what it means
|
||||
// in its tooltip; null with none
|
||||
function paceLine(w) {
|
||||
const p = quotaPace(w);
|
||||
if (!p) return null;
|
||||
const span = el("span", "quota-pace" + (p.over ? " over" : ""), t("Pace {n}", { n: paceNumber(p.n) }));
|
||||
span.title = p.over ? t("{n} more of this window is used than an even pace through it would have used by now: at this rate it runs out before it resets", { n: p.by + "%" })
|
||||
: p.under ? t("{n} less of this window is used than an even pace through it would have used by now: at this rate it lasts until it resets", { n: p.by + "%" })
|
||||
: t("Right on an even pace through this window");
|
||||
return span;
|
||||
}
|
||||
// quotaCount: a window's own count, when its vendor counts in amounts
|
||||
// (WorkBuddy's credits, #659) — "355 / 500 credits" used, or what is left
|
||||
// of them, as the share beside it says; the vendor's own text otherwise.
|
||||
@@ -17010,6 +17040,13 @@ function quotaWindows(sub) {
|
||||
quota.append(r);
|
||||
quota.title = sub.history ? t("Last reading {when}", { when: quotaCycleDate(w.recordedAt) }) : resetText(at, at.toLocaleString(intlLang()));
|
||||
}
|
||||
// how far it is from an even pace through the window, as a number
|
||||
// (fflake33 on Discord), on the reset's line
|
||||
const pace = !sub.history && r ? paceLine(w) : null;
|
||||
if (pace) {
|
||||
r.lastChild.textContent += " ·";
|
||||
r.append(" ", pace);
|
||||
}
|
||||
// credits that run out before then, or with no reset at all
|
||||
const out = runsOutText(w);
|
||||
if (out) {
|
||||
@@ -21753,6 +21790,11 @@ function renderTrayUsage(s, keep) {
|
||||
$("#trayBirdRow").hidden = !ids.length || !mac;
|
||||
$("#trayBirdSegs").replaceChildren(segs([["off", t("Off")], ["on", t("On")]], s.trayNoBird ? "off" : "on",
|
||||
(v) => savePrefs({ ...keep, trayNoBird: v === "off" })));
|
||||
// and each window's Pace number beside its figure (fflake33), off unless
|
||||
// asked for, as it widens every card; not where the tray shows no text
|
||||
$("#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" })));
|
||||
}
|
||||
const TRAY_EVERY = [1, 3, 5, 10, 30];
|
||||
// the totals the menu bar can show beside the allowances (gui.trayTotal)
|
||||
@@ -23644,7 +23686,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, refusalRetries: s.refusalRetries ?? null,
|
||||
noUpdatePill: !!s.noUpdatePill, noAutoUpdate: !!s.noAutoUpdate, updateEvery: s.updateEvery || 360,
|
||||
trayUsage: s.trayUsage || "", trayUsageEvery: s.trayUsageEvery || 3, trayNoLogos: !!s.trayNoLogos, trayNoBird: !!s.trayNoBird, vision: s.vision || "", visionEffort: s.visionEffort || "", searcherEffort: s.searcherEffort || "", imageGen: s.imageGen || "", 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, vision: s.vision || "", visionEffort: s.visionEffort || "", searcherEffort: s.searcherEffort || "", imageGen: s.imageGen || "", 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 };
|
||||
}
|
||||
|
||||
@@ -868,6 +868,12 @@ const I18N = {
|
||||
"How often the allowances beside the icon are asked for again": "图标旁的额度多久重新获取一次",
|
||||
"Menu bar logos": "菜单栏订阅图标",
|
||||
"Menu bar magpie icon": "菜单栏 magpie 图标",
|
||||
"Pace {n}": "配速 {n}",
|
||||
"{n} more of this window is used than an even pace through it would have used by now: at this rate it runs out before it resets": "比匀速多用了 {n}:按这个速度,会在重置前用完",
|
||||
"{n} less of this window is used than an even pace through it would have used by now: at this rate it lasts until it resets": "比匀速少用了 {n}:按这个速度,能撑到重置",
|
||||
"Right on an even pace through this window": "正好是匀速",
|
||||
"Menu bar pace": "菜单栏配速",
|
||||
"Each window's Pace number beside its figure, as on the Usage page: +12% is 12% more of the window used than an even pace would have used by now, −8% that much less": "在每个窗口的数字旁显示配速,和用量页一样:+12% 表示比匀速多用了窗口的 12%,−8% 表示少用了这么多",
|
||||
"magpie's icon before the allowances; off, the allowances alone, and a click on one still opens the panel": "额度前面的 magpie 图标;关闭后只显示额度,点击额度仍会打开面板",
|
||||
"Each subscription's logo before its numbers; off, the numbers alone with a thin line between subscriptions": "每个订阅的数字前显示它的图标;关闭后只显示数字,订阅之间以细线分隔",
|
||||
"Allowance display": "额度显示",
|
||||
@@ -5015,6 +5021,12 @@ const I18N = {
|
||||
"How often the allowances beside the icon are asked for again": "圖示旁的額度多久重新取得一次",
|
||||
"Menu bar logos": "選單列訂閱圖示",
|
||||
"Menu bar magpie icon": "選單列 magpie 圖示",
|
||||
"Pace {n}": "配速 {n}",
|
||||
"{n} more of this window is used than an even pace through it would have used by now: at this rate it runs out before it resets": "比勻速多用了 {n}:照這個速度,會在重置前用完",
|
||||
"{n} less of this window is used than an even pace through it would have used by now: at this rate it lasts until it resets": "比勻速少用了 {n}:照這個速度,能撐到重置",
|
||||
"Right on an even pace through this window": "正好是勻速",
|
||||
"Menu bar pace": "選單列配速",
|
||||
"Each window's Pace number beside its figure, as on the Usage page: +12% is 12% more of the window used than an even pace would have used by now, −8% that much less": "在每個視窗的數字旁顯示配速,和用量頁一樣:+12% 表示比勻速多用了視窗的 12%,−8% 表示少用了這麼多",
|
||||
"magpie's icon before the allowances; off, the allowances alone, and a click on one still opens the panel": "額度前面的 magpie 圖示;關閉後只顯示額度,點選額度仍會打開面板",
|
||||
"Each subscription's logo before its numbers; off, the numbers alone with a thin line between subscriptions": "每個訂閱的數字前顯示它的圖示;關閉後只顯示數字,訂閱之間以細線分隔",
|
||||
"Allowance display": "額度顯示",
|
||||
@@ -12313,6 +12325,12 @@ const I18N = {
|
||||
"Video · 24 hours": "動画 · 24 時間",
|
||||
"Video · 7 days": "動画 · 7 日",
|
||||
"Menu bar magpie icon": "メニューバーの magpie アイコン",
|
||||
"Pace {n}": "ペース {n}",
|
||||
"{n} more of this window is used than an even pace through it would have used by now: at this rate it runs out before it resets": "均等なペースより {n} 多く使っています。このペースだとリセット前に使い切ります",
|
||||
"{n} less of this window is used than an even pace through it would have used by now: at this rate it lasts until it resets": "均等なペースより {n} 少なく使っています。このペースならリセットまで持ちます",
|
||||
"Right on an even pace through this window": "ちょうど均等なペースです",
|
||||
"Menu bar pace": "メニューバーのペース",
|
||||
"Each window's Pace number beside its figure, as on the Usage page: +12% is 12% more of the window used than an even pace would have used by now, −8% that much less": "使用量ページと同じく、各枠の数値の横にペースを表示します。+12% は均等なペースより枠の 12% 多く、−8% はその分少なく使っていることを表します",
|
||||
"magpie's icon before the allowances; off, the allowances alone, and a click on one still opens the panel": "利用枠の前に magpie のアイコンを表示します。オフにすると利用枠だけになり、クリックすると引き続きパネルが開きます",
|
||||
"At its cap · {agent} still uses it": "上限に到達 · {agent} は引き続き使用中",
|
||||
"A usage window is at {n}%, past this account's {cap}% cap: requests through magpie are refused with a usage-cap error until it renews": "利用枠が {n}% に達し、このアカウントの上限 {cap}% を超えています。更新されるまで、magpie 経由のリクエストは使用量上限エラーで拒否されます",
|
||||
@@ -13259,6 +13277,12 @@ const I18N = {
|
||||
"How often the allowances beside the icon are asked for again": "Wie oft die Kontingente neben dem Symbol neu abgefragt werden",
|
||||
"Menu bar logos": "Logos in der Menüleiste",
|
||||
"Menu bar magpie icon": "magpie-Symbol in der Menüleiste",
|
||||
"Pace {n}": "Tempo {n}",
|
||||
"{n} more of this window is used than an even pace through it would have used by now: at this rate it runs out before it resets": "{n} mehr von diesem Fenster verbraucht, als ein gleichmäßiges Tempo bis jetzt verbraucht hätte: So ist es vor dem Zurücksetzen aufgebraucht",
|
||||
"{n} less of this window is used than an even pace through it would have used by now: at this rate it lasts until it resets": "{n} weniger von diesem Fenster verbraucht, als ein gleichmäßiges Tempo bis jetzt verbraucht hätte: So reicht es bis zum Zurücksetzen",
|
||||
"Right on an even pace through this window": "Genau im gleichmäßigen Tempo",
|
||||
"Menu bar pace": "Tempo in der Menüleiste",
|
||||
"Each window's Pace number beside its figure, as on the Usage page: +12% is 12% more of the window used than an even pace would have used by now, −8% that much less": "Neben der Zahl jedes Fensters sein Tempo, wie auf der Nutzungsseite: +12% heißt 12% des Fensters mehr verbraucht, als ein gleichmäßiges Tempo bis jetzt verbraucht hätte, −8% so viel weniger",
|
||||
"magpie's icon before the allowances; off, the allowances alone, and a click on one still opens the panel": "magpie-Symbol vor den Kontingenten; aus: nur die Kontingente, und ein Klick auf eines öffnet weiterhin das Panel",
|
||||
"Each subscription's logo before its numbers; off, the numbers alone with a thin line between subscriptions": "Logo jedes Abos vor seinen Zahlen; ausgeschaltet nur die Zahlen mit einer dünnen Linie zwischen den Abos",
|
||||
"Allowance display": "Kontingentanzeige",
|
||||
|
||||
@@ -378,6 +378,10 @@
|
||||
<div class="who"><div class="name" data-t>Menu bar magpie icon</div><div class="sub" data-t>magpie's icon before the allowances; off, the allowances alone, and a click on one still opens the panel</div></div>
|
||||
<div id="trayBirdSegs"></div>
|
||||
</div>
|
||||
<div class="row pref" id="trayPaceRow" hidden>
|
||||
<div class="who"><div class="name" data-t>Menu bar pace</div><div class="sub" data-t>Each window's Pace number beside its figure, as on the Usage page: +12% is 12% more of the window used than an even pace would have used by now, −8% that much less</div></div>
|
||||
<div id="trayPaceSegs"></div>
|
||||
</div>
|
||||
<div class="row pref">
|
||||
<div class="who"><div class="name" data-t>Allowance display</div><div class="sub" data-t>How much of each window is used, or how much is left, on the Usage page, the panel and the menu bar</div></div>
|
||||
<div id="quotaLeftSegs"></div>
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// fflake33 on Discord: a window's Pace as a number, "Pace +20%" on its
|
||||
// reset's line, against an even pace through the window (the gateway gives
|
||||
// its start, provider.WithWindowStarts): amber when more is used than an
|
||||
// even pace would have, its sign turned with the meter when it shows what
|
||||
// is left, what it means in its tooltip, nothing for a window whose start
|
||||
// isn't known; whole at 1100 and 420px in every language. And Settings ›
|
||||
// Menu bar pace: off unless asked for, On posts trayPace, another save
|
||||
// keeps it, no row on Windows (its tray shows no text), no click moves the
|
||||
// page. 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 assets = path.resolve(__dirname, "../assets");
|
||||
const at = (h) => new Date(Date.now() + h * 3600e3).toISOString();
|
||||
// half of each window gone by: 70% used is 20 over, 20% used 30 under
|
||||
const quotas = () => [
|
||||
{ provider: "claude", name: "Claude Code", icon: "claude-color", plan: "max", user: "dee@example.com", windows: [
|
||||
{ name: "5 hours", used: 70, startsAt: at(-2.5), resetsAt: at(2.5) },
|
||||
{ name: "7 days", used: 20, startsAt: at(-84), resetsAt: at(84) },
|
||||
{ name: "Credits", used: 40, resetsAt: at(10) },
|
||||
] },
|
||||
];
|
||||
|
||||
function settingsPayload(over) {
|
||||
return {
|
||||
theme: "light", tray: "panel", quotaLeft: false, currency: "usd",
|
||||
dock: false, dockWindow: false, proxy: "", redact: false, redactPersonal: false, redactWords: [],
|
||||
codexWarmup: "", claudeWarmup: "", codexWarmAt: "", claudeWarmAt: "", workbuddyCheckin: false, noStats: false,
|
||||
trayUsage: "claude|dee@example.com", trayUsages: ["claude|dee@example.com"], trayUsageEvery: 3, vision: "", imageGen: "",
|
||||
version: "0.1.400", dir: "~/.config/magpie", gateway: "http://127.0.0.1:3999",
|
||||
proxyNow: "none", proxySource: "none", login: false,
|
||||
visionModels: [], imageGenModels: [], workbuddyCheckins: [], lanURLs: [],
|
||||
fx: { rate: 7.2, at: new Date().toISOString(), stale: false },
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
function serve(lang, posts, over) {
|
||||
let cur = settingsPayload({ lang, ...over });
|
||||
return async (r) => {
|
||||
const req = r.request(), url = new URL(req.url());
|
||||
const json = (data) => r.fulfill({ json: data });
|
||||
if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:false};` });
|
||||
if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light", quotaLeft: cur.quotaLeft }, fx: cur.fx });
|
||||
if (url.pathname === "/api/settings") {
|
||||
if (req.method() === "POST") {
|
||||
const body = req.postDataJSON();
|
||||
posts.push(body);
|
||||
cur = { ...cur, ...body, trayUsage: (body.trayUsages || [])[0] || "" };
|
||||
}
|
||||
return json(cur);
|
||||
}
|
||||
if (url.pathname === "/api/gateway/trace") return url.searchParams.get("wait") ? new Promise(() => {}) : json({ mine: true, now: new Date().toISOString(), seq: 0, totals: {}, routes: [] });
|
||||
if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] });
|
||||
if (url.pathname === "/api/groups") return json({ models: [], groups: [], pools: [] });
|
||||
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } });
|
||||
if (url.pathname === "/api/usage/quotas") return json(quotas());
|
||||
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 r.fulfill({ body: await fs.readFile(file), contentType }); } catch { await r.fulfill({ status: 404, body: "" }); }
|
||||
};
|
||||
}
|
||||
|
||||
const want = {
|
||||
en: { pace: "Pace", over: "20% more of this window is used", under: "30% less of this window is used", row: "Menu bar pace", off: "Off", on: "On" },
|
||||
zh: { pace: "配速", over: "比匀速多用了 20%", under: "比匀速少用了 30%", row: "菜单栏配速", off: "关闭", on: "开启" },
|
||||
"zh-TW": { pace: "配速", over: "比勻速多用了 20%", under: "比勻速少用了 30%", row: "選單列配速" },
|
||||
ja: { pace: "ペース", over: "均等なペースより 20% 多く", under: "均等なペースより 30% 少なく", row: "メニューバーのペース" },
|
||||
de: { pace: "Tempo", over: "20% mehr von diesem Fenster", under: "30% weniger von diesem Fenster", row: "Tempo in der Menüleiste" },
|
||||
};
|
||||
|
||||
async function open(browser, lang, width, over = {}, posts = [], platform = "MacIntel", view = "usage") {
|
||||
const context = await browser.newContext({ viewport: { width, height: view === "usage" ? 900 : 420 }, reducedMotion: "reduce" });
|
||||
await context.addInitScript((p) => Object.defineProperty(Navigator.prototype, "platform", { get: () => p }), platform);
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
await page.route("**/*", serve(lang, posts, over));
|
||||
await page.goto("http://magpie.test/?view=usage");
|
||||
return { context, page };
|
||||
}
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
test(engine + ": a window's Pace number on its card", async (t) => {
|
||||
assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
for (const lang of Object.keys(want)) {
|
||||
for (const width of [1100, 420]) {
|
||||
for (const left of [false, true]) {
|
||||
const where = `${lang} ${width}px ${left ? "left" : "used"}`;
|
||||
const errors = [];
|
||||
const { context, page } = await open(browser, lang, width, { quotaLeft: left });
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.locator(".subscription-card .quota-pace").nth(1).waitFor();
|
||||
if (left) await page.waitForFunction(() => document.querySelector(".quota-pace")?.textContent.includes("−"));
|
||||
const got = await page.evaluate(() => [...document.querySelectorAll(".quota")].map((q) => {
|
||||
const p = q.querySelector(".quota-pace");
|
||||
if (!p) return null;
|
||||
const card = p.closest(".subscription-card").getBoundingClientRect(), b = p.getBoundingClientRect();
|
||||
return {
|
||||
text: p.textContent, title: p.title, over: p.classList.contains("over"),
|
||||
color: getComputedStyle(p).color, line: p.closest(".quota-reset")?.textContent,
|
||||
inCard: b.left >= card.left - 1 && b.right <= card.right + 1 && p.scrollWidth <= p.clientWidth + 1,
|
||||
};
|
||||
}).concat([{ amber: (() => { const s = document.createElement("span"); s.style.color = "var(--amber)"; document.body.append(s); const c = getComputedStyle(s).color; s.remove(); return c; })(), scroll: document.documentElement.scrollWidth > document.documentElement.clientWidth + 1 }]));
|
||||
const meta = got.pop();
|
||||
const [five, week, credits] = got;
|
||||
const w = want[lang];
|
||||
assert.equal(credits, null, `${where}: a window whose start isn't known has no Pace`);
|
||||
assert.equal(five.text, `${w.pace} ${left ? "−" : "+"}20%`, where);
|
||||
assert.equal(week.text, `${w.pace} ${left ? "+" : "−"}30%`, where);
|
||||
assert.ok(five.over && !week.over, `${where}: over is by use, whichever way the meter reads`);
|
||||
assert.equal(five.color, meta.amber, `${where}: over is amber`);
|
||||
assert.notEqual(week.color, meta.amber, where);
|
||||
assert.ok(five.title.includes(w.over), `${where}: ${five.title}`);
|
||||
assert.ok(week.title.includes(w.under), `${where}: ${week.title}`);
|
||||
assert.match(five.line, /· \S+ [+−]20%$/u, `${where}: on the reset's line after its wait: ${five.line}`);
|
||||
for (const p of [five, week]) assert.ok(p.inCard, `${where}: "${p.text}" is cut or past its card`);
|
||||
assert.equal(meta.scroll, false, `${where}: the page scrolls sideways`);
|
||||
// a click on it moves nothing
|
||||
const before = await page.evaluate(() => [scrollY, document.querySelector("#view-usage")?.scrollTop]);
|
||||
await page.locator(".quota-pace").first().click();
|
||||
await page.waitForTimeout(100);
|
||||
assert.deepEqual(await page.evaluate(() => [scrollY, document.querySelector("#view-usage")?.scrollTop]), before, where);
|
||||
assert.deepEqual(errors, [], where);
|
||||
await context.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test(engine + ": Settings › Menu bar pace", async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
const prefs = async (page) => {
|
||||
await page.locator("#prefs").click();
|
||||
await page.locator(":is(#setTab-usage, .nav-s[data-of=setTab-usage]):visible").click();
|
||||
await page.locator("#trayUsagePick button").waitFor();
|
||||
};
|
||||
const scrolled = (page) => page.locator("#view-settings").evaluate((v) => v.scrollTop);
|
||||
for (const lang of Object.keys(want)) {
|
||||
for (const width of [1100, 420]) {
|
||||
const where = `${lang} ${width}px`;
|
||||
const errors = [], posts = [];
|
||||
const { context, page } = await open(browser, lang, width, {}, posts, "MacIntel", "settings");
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await prefs(page);
|
||||
const row = page.locator("#trayPaceRow");
|
||||
await row.waitFor();
|
||||
assert.equal((await row.locator(".name").textContent()).trim(), want[lang].row, where);
|
||||
assert.equal(await row.evaluate((r) => r.previousElementSibling.id), "trayBirdRow", `${where}: under the magpie icon row`);
|
||||
assert.equal(await row.evaluate((r) => getComputedStyle(r).borderLeftWidth), "0px");
|
||||
assert.equal(await row.evaluate((r) => r.scrollWidth <= r.clientWidth + 1 && r.getBoundingClientRect().right <= innerWidth), true, `${where}: the row is cut`);
|
||||
const opts = row.locator("#trayPaceSegs .opt");
|
||||
if (want[lang].off) assert.deepEqual((await opts.allTextContents()).map((s) => s.trim()), [want[lang].off, want[lang].on]);
|
||||
assert.equal(await opts.nth(0).evaluate((b) => b.classList.contains("on")), true, `${where}: off unless asked for`);
|
||||
|
||||
// scrolled down with a real wheel, the row in sight; then clicked: no scroll
|
||||
await page.waitForTimeout(500);
|
||||
await page.locator("#trayUsagePick button").hover();
|
||||
for (let i = 0; i < 20 && !(await scrolled(page)); i++) { await page.mouse.wheel(0, 120); await page.waitForTimeout(20); }
|
||||
await row.scrollIntoViewIfNeeded();
|
||||
await page.waitForTimeout(300);
|
||||
const before = await scrolled(page);
|
||||
assert(before > 0, `${where}: the settings list must be scrolled`);
|
||||
await opts.nth(1).click();
|
||||
for (let i = 0; i < 50 && !posts.length; i++) await page.waitForTimeout(50);
|
||||
assert.equal(posts.at(-1).trayPace, true, `${where}: On posts trayPace`);
|
||||
await page.waitForFunction(() => document.querySelectorAll("#trayPaceSegs .opt")[1].classList.contains("on"));
|
||||
await page.waitForTimeout(300);
|
||||
assert.equal(await scrolled(page), before, `${where}: On moved the page`);
|
||||
|
||||
// another setting saved keeps it
|
||||
const sent = posts.length;
|
||||
await page.locator("#currencySegs .opt").nth(1).evaluate((b) => b.click());
|
||||
for (let i = 0; i < 50 && posts.length === sent; i++) await page.waitForTimeout(50);
|
||||
assert.equal(posts.at(-1).currency, "cny");
|
||||
assert.equal(posts.at(-1).trayPace, true, `${where}: a save of another setting keeps it`);
|
||||
assert.deepEqual(errors, [], where);
|
||||
await context.close();
|
||||
}
|
||||
}
|
||||
// no card in the menu bar, or on Windows: no row; on Linux it's there
|
||||
for (const [platform, over, shown] of [["MacIntel", { trayUsage: "", trayUsages: [] }, false], ["Win32", {}, false], ["Linux x86_64", {}, true]]) {
|
||||
const { context, page } = await open(browser, "en", 1100, over, [], platform, "settings");
|
||||
await prefs(page);
|
||||
await page.waitForTimeout(200);
|
||||
assert.equal(await page.locator("#trayPaceRow").isVisible(), shown, platform + " " + JSON.stringify(over));
|
||||
await context.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -21,7 +21,7 @@ func TestTrayImage(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cells, _, _ := trayUsageView(trayCards(), time.Now(), false)
|
||||
cells, _, _ := trayUsageView(trayCards(), time.Now(), false, false)
|
||||
out := os.Getenv("MAGPIE_TRAY_PREVIEW")
|
||||
widths := map[bool][]int{}
|
||||
for _, dark := range []bool{false, true} {
|
||||
@@ -88,7 +88,7 @@ func TestTrayImageCellAt(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cells, _, _ := trayUsageView(trayCards(), time.Now(), false)
|
||||
cells, _, _ := trayUsageView(trayCards(), time.Now(), false, false)
|
||||
const h = 22.0
|
||||
_, w, _ := trayImagePNG(cells, bird, h, 2, false, false)
|
||||
width := float64(w) / 2
|
||||
@@ -231,7 +231,7 @@ func TestTrayImageClickIdentity(t *testing.T) {
|
||||
onTrayCellClick = func(id string) { clicked <- id }
|
||||
cards := trayCards()
|
||||
cards[1].User = "a\"b\\c@例子.test"
|
||||
cells, _, _ := trayUsageView(cards, time.Now(), false)
|
||||
cells, _, _ := trayUsageView(cards, time.Now(), false, false)
|
||||
for _, layout := range [][]trayCell{cells, trayPlain(cells)} {
|
||||
if trayImageClickAt(layout, true, 22, 5, 0) {
|
||||
t.Fatal("bird intercepted")
|
||||
@@ -265,7 +265,7 @@ func TestTrayImageClickWithoutBird(t *testing.T) {
|
||||
t.Cleanup(func() { onTrayCellClick = prior })
|
||||
clicked := make(chan string, 1)
|
||||
onTrayCellClick = func(id string) { clicked <- id }
|
||||
cells, _, _ := trayUsageView(trayCards(), time.Now(), false)
|
||||
cells, _, _ := trayUsageView(trayCards(), time.Now(), false, false)
|
||||
for _, layout := range [][]trayCell{cells, trayPlain(cells)} {
|
||||
for i := range layout {
|
||||
x := trayImageCellStart(layout, 22, i) - (22 + 2) + 1 // the same cell, with no bird before it
|
||||
|
||||
@@ -20,7 +20,7 @@ func TestTrayImageNoBird(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cells, _, _ := trayUsageView(trayCards(), time.Now(), false)
|
||||
cells, _, _ := trayUsageView(trayCards(), time.Now(), false, false)
|
||||
for _, cs := range [][]trayCell{cells[:2], trayPlain(cells[:2])} {
|
||||
for _, dark := range []bool{false, true} {
|
||||
wb, ww, h := trayImagePNG(cs, bird, 22, 2, dark, false)
|
||||
|
||||
@@ -20,7 +20,7 @@ func TestTrayImagePlain(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cells, _, _ := trayUsageView(trayCards(), time.Now(), false)
|
||||
cells, _, _ := trayUsageView(trayCards(), time.Now(), false, false)
|
||||
cells = cells[:2]
|
||||
plain := trayPlain(cells)
|
||||
for _, dark := range []bool{false, true} {
|
||||
|
||||
@@ -63,8 +63,9 @@ func trayWindows(q provider.SubscriptionQuota) []provider.QuotaWindow {
|
||||
|
||||
// trayUsageText 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.
|
||||
func trayUsageText(q provider.SubscriptionQuota, now time.Time, left bool) (label, tip string) {
|
||||
// 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) {
|
||||
if strings.HasPrefix(q.Provider, trayTotal) {
|
||||
return q.Balance, q.Name // trayTotalCard's: its rows, and its tooltip
|
||||
}
|
||||
@@ -79,6 +80,10 @@ func trayUsageText(q provider.SubscriptionQuota, now time.Time, left bool) (labe
|
||||
}
|
||||
return q.Balance, q.Name + " · " + q.Balance + trayAsOf(q)
|
||||
}
|
||||
readAt := now
|
||||
if q.ReadAt != nil && !q.ReadAt.After(now) {
|
||||
readAt = *q.ReadAt
|
||||
}
|
||||
var short, long []string
|
||||
for _, w := range ws {
|
||||
used := math.Max(0, math.Min(100, w.Used))
|
||||
@@ -89,7 +94,12 @@ func trayUsageText(q provider.SubscriptionQuota, now time.Time, left bool) (labe
|
||||
n, word = 100-n, "left"
|
||||
}
|
||||
pct := fmt.Sprintf("%d%%", n)
|
||||
short = append(short, pct)
|
||||
row, paceNote := pct, ""
|
||||
if p, ok := w.Pace(readAt, now); pace && ok {
|
||||
row = pct + " " + trayPace(p, left)
|
||||
paceNote = " · pace " + trayPace(p, left)
|
||||
}
|
||||
short = append(short, row)
|
||||
tipPct := pct
|
||||
if used != math.Trunc(used) {
|
||||
tipPct = fmt.Sprintf("%.1f%%", used)
|
||||
@@ -98,6 +108,7 @@ func trayUsageText(q provider.SubscriptionQuota, now time.Time, left bool) (labe
|
||||
if c := w.Count(left); c != "" {
|
||||
line = w.Name + " " + c + " · " + tipPct + " " + word
|
||||
}
|
||||
line += paceNote
|
||||
if at := resetAt(w, now); !at.IsZero() && at.After(now) {
|
||||
line += " · resets in " + until(at.Sub(now))
|
||||
}
|
||||
@@ -109,6 +120,25 @@ func trayUsageText(q provider.SubscriptionQuota, now time.Time, left bool) (labe
|
||||
return strings.Join(short, " · "), q.Name + "\n" + strings.Join(long, "\n") + trayAsOf(q)
|
||||
}
|
||||
|
||||
// trayPace is a window's Pace number as the Usage page writes it
|
||||
// (paceNumber in app.js): "+12%", "−8%" with a true minus, "±0%". It
|
||||
// follows the figure beside it, so where what is left is shown (left) its
|
||||
// sign is turned: +12% left is twelve points more to spare than an even
|
||||
// pace would have.
|
||||
func trayPace(p float64, left bool) string {
|
||||
if left {
|
||||
p = -p
|
||||
}
|
||||
switch n := int(math.Round(p)); {
|
||||
case n > 0:
|
||||
return fmt.Sprintf("+%d%%", n)
|
||||
case n < 0:
|
||||
return fmt.Sprintf("−%d%%", -n)
|
||||
default:
|
||||
return "±0%"
|
||||
}
|
||||
}
|
||||
|
||||
// trayAsOf is the tooltip's word that a card stands in for one that
|
||||
// couldn't be read just now, and when it was read (the Usage page's
|
||||
// "As of …"); nothing for a reading just made.
|
||||
@@ -352,10 +382,10 @@ func trayPlain(cells []trayCell) []trayCell {
|
||||
// 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.
|
||||
func trayUsageView(cards []provider.SubscriptionQuota, now time.Time, left bool) (cells []trayCell, label, tip string) {
|
||||
func trayUsageView(cards []provider.SubscriptionQuota, now time.Time, left, pace bool) (cells []trayCell, label, tip string) {
|
||||
var labels, tips []string
|
||||
for _, q := range cards {
|
||||
l, t := trayUsageText(q, now, left)
|
||||
l, t := trayUsageText(q, now, left, pace)
|
||||
if t != "" {
|
||||
tips = append(tips, t)
|
||||
}
|
||||
|
||||
@@ -16,11 +16,11 @@ func TestTrayNamesTheAccountByItsAlias(t *testing.T) {
|
||||
at := now.Add(2 * time.Hour)
|
||||
q := provider.SubscriptionQuota{Provider: "zcode-plugin", Name: "ZCode", User: "31****36@qq.com", Alias: "某某·GLM高级版",
|
||||
Windows: []provider.QuotaWindow{{Name: "5 hours", Used: 12, ResetsAt: &at, Span: 5 * time.Hour}}}
|
||||
if _, tip := trayUsageText(q, now, false); !strings.HasPrefix(tip, "ZCode · 某某·GLM高级版\n") {
|
||||
if _, tip := trayUsageText(q, now, false, false); !strings.HasPrefix(tip, "ZCode · 某某·GLM高级版\n") {
|
||||
t.Fatalf("tip %q", tip)
|
||||
}
|
||||
q.Error = "BigModel API keys: not JSON"
|
||||
if _, tip := trayUsageText(q, now, false); !strings.HasPrefix(tip, "ZCode · 某某·GLM高级版: ") {
|
||||
if _, tip := trayUsageText(q, now, false, false); !strings.HasPrefix(tip, "ZCode · 某某·GLM高级版: ") {
|
||||
t.Fatalf("error tip %q", tip)
|
||||
}
|
||||
other := q
|
||||
@@ -31,7 +31,7 @@ func TestTrayNamesTheAccountByItsAlias(t *testing.T) {
|
||||
if !ok {
|
||||
t.Fatal("no card")
|
||||
}
|
||||
if _, tip := trayUsageText(c, now, false); !strings.HasPrefix(tip, "ZCode · 某某·GLM高级版: ") {
|
||||
if _, tip := trayUsageText(c, now, false, false); !strings.HasPrefix(tip, "ZCode · 某某·GLM高级版: ") {
|
||||
t.Fatalf("in use tip %q", tip)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,7 +52,7 @@ func TestTrayUsageCells(t *testing.T) {
|
||||
{[]string{"claude|a@b.c", "codex|x@y.z", "copilot", "deepseek"},
|
||||
[][]string{{"42%", "18%"}, {"8%", "100%"}, {"63%"}, {"¥12.30"}}, "42% · 18% | 8% · 100% | 63% | ¥12.30"},
|
||||
} {
|
||||
cells, label, tip := trayUsageView(trayPick(cards, tc.ids, now), now, false)
|
||||
cells, label, tip := trayUsageView(trayPick(cards, tc.ids, now), now, false, false)
|
||||
if label != tc.label {
|
||||
t.Errorf("%v: label %q, want %q", tc.ids, label, tc.label)
|
||||
}
|
||||
@@ -71,7 +71,7 @@ func TestTrayUsageCells(t *testing.T) {
|
||||
|
||||
// each cell with its logo as the page draws it: its own colours, or a
|
||||
// black glyph to tint; the name's letter always there to fall back on
|
||||
cells, _, _ := trayUsageView(cards, now, false)
|
||||
cells, _, _ := trayUsageView(cards, now, false, false)
|
||||
for i, want := range []struct {
|
||||
mono bool
|
||||
letter string
|
||||
@@ -83,7 +83,7 @@ func TestTrayUsageCells(t *testing.T) {
|
||||
}
|
||||
}
|
||||
// what is left, as Settings says
|
||||
if cells, label, _ := trayUsageView(cards[:2], now, true); label != "58% · 82% | 92% · 0%" || !slices.Equal(cells[1].Rows, []string{"92%", "0%"}) {
|
||||
if cells, label, _ := trayUsageView(cards[:2], now, true, false); label != "58% · 82% | 92% · 0%" || !slices.Equal(cells[1].Rows, []string{"92%", "0%"}) {
|
||||
t.Errorf("left: %q %+v", label, cells)
|
||||
}
|
||||
|
||||
@@ -97,7 +97,7 @@ func TestTrayUsageCells(t *testing.T) {
|
||||
{Provider: "zcode", Name: "ZCode", Icon: "zcode", Windows: []provider.QuotaWindow{{Name: "5 小时", Used: 1}}},
|
||||
{Provider: "x", Name: "", Icon: "../api", Balance: "1"},
|
||||
}
|
||||
cells, label, tip := trayUsageView(odd, now, false)
|
||||
cells, label, tip := trayUsageView(odd, now, false, false)
|
||||
if label != "$3 | 1% | 1" || tip != "Codex: signed out\n\nmy plan · $3\n\nZCode\n5 小时 1% used\n\n · 1" {
|
||||
t.Errorf("odd: %q %q", label, tip)
|
||||
}
|
||||
@@ -106,11 +106,11 @@ func TestTrayUsageCells(t *testing.T) {
|
||||
}
|
||||
// a balance too long for the bar is cut there, whole in the tooltip
|
||||
long := provider.SubscriptionQuota{Provider: "p", Name: "Plan", Balance: "12,345.67 credits left"}
|
||||
if cells, label, tip := trayUsageView([]provider.SubscriptionQuota{long}, now, false); len(cells) != 1 ||
|
||||
if cells, label, tip := trayUsageView([]provider.SubscriptionQuota{long}, now, false, false); len(cells) != 1 ||
|
||||
!slices.Equal(cells[0].Rows, []string{"12,345.67…"}) || label != long.Balance || !strings.Contains(tip, long.Balance) {
|
||||
t.Errorf("long: %+v %q %q", cells, label, tip)
|
||||
}
|
||||
if cells, label, tip := trayUsageView(odd[:2], now, false); cells != nil || label != "" || tip != "Codex: signed out" {
|
||||
if cells, label, tip := trayUsageView(odd[:2], now, false, false); cells != nil || label != "" || tip != "Codex: signed out" {
|
||||
t.Errorf("nothing to draw: %+v %q %q", cells, label, tip)
|
||||
}
|
||||
}
|
||||
@@ -121,7 +121,7 @@ func TestTrayCellsCards(t *testing.T) {
|
||||
cards := trayCards()
|
||||
cards[0].User = "a\"b\\c@例子.test"
|
||||
cards[1].Error = "signed out"
|
||||
cells, _, _ := trayUsageView(cards, time.Now(), false)
|
||||
cells, _, _ := trayUsageView(cards, time.Now(), false, false)
|
||||
plain := trayPlain(cells)
|
||||
if len(cells) != len(cards)-1 {
|
||||
t.Fatalf("cells: %d", len(cells))
|
||||
|
||||
@@ -39,7 +39,7 @@ func TestTrayInUse(t *testing.T) {
|
||||
if got[2].Name != "DeepSeek" || got[3].User != "a@x.y" || got[3].Name != "Claude Code" {
|
||||
t.Errorf("named ones as they were: %+v", got[2:])
|
||||
}
|
||||
if label, tip := trayUsageText(got[0], time.Now(), false); label != "70%" || tip != "Claude Code · B@x.y\n5-hour 70% used" {
|
||||
if label, tip := trayUsageText(got[0], time.Now(), false, false); label != "70%" || tip != "Claude Code · B@x.y\n5-hour 70% used" {
|
||||
t.Errorf("text: %q %q", label, tip)
|
||||
}
|
||||
// switched: the card follows
|
||||
@@ -74,7 +74,7 @@ func TestTrayInUseFollowsWhoAnswered(t *testing.T) {
|
||||
if len(got) != 1 || got[0].User != "b@x.y" || got[0].Name != "Codex · b@x.y" {
|
||||
t.Fatalf("in use: %+v", got)
|
||||
}
|
||||
if label, _ := trayUsageText(got[0], now, false); label != "12%" {
|
||||
if label, _ := trayUsageText(got[0], now, false, false); label != "12%" {
|
||||
t.Errorf("label %q", label)
|
||||
}
|
||||
// nothing answered lately: whom the gateway goes to first
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// The menu bar's Pace number (settings.TrayPace, fflake33 on Discord): off,
|
||||
// the rows are as they were; on, each window's figure has its Pace beside
|
||||
// it, turned where what is left is shown, and the tooltip says it too.
|
||||
func TestTrayUsagePace(t *testing.T) {
|
||||
now := time.Date(2026, 9, 27, 12, 0, 0, 0, time.UTC)
|
||||
in := func(d time.Duration) *time.Time { at := now.Add(d); return &at }
|
||||
q := provider.SubscriptionQuota{Provider: "claude", Name: "Claude", User: "a@b.c", Windows: []provider.QuotaWindow{
|
||||
// 2h 50m of 5h gone by (56.7%), 42.2% used: 14 points under
|
||||
{Name: "5-hour", Used: 42.2, ResetsAt: in(2*time.Hour + 10*time.Minute), Span: 5 * time.Hour},
|
||||
// 4 of 7 days gone by (57.1%), 70% used: 13 points over
|
||||
{Name: "Weekly", Used: 70, ResetsAt: in(3 * 24 * time.Hour), Span: 7 * 24 * time.Hour},
|
||||
}}
|
||||
|
||||
label, tip := trayUsageText(q, now, false, false)
|
||||
if label != "42% · 70%" || tip != "Claude\n5-hour 42.2% used · resets in 2h 10m\nWeekly 70% used · resets in 3d 0h" {
|
||||
t.Errorf("pace off: %q %q", label, tip)
|
||||
}
|
||||
|
||||
label, tip = trayUsageText(q, now, false, true)
|
||||
if label != "42% −14% · 70% +13%" {
|
||||
t.Errorf("used label %q", label)
|
||||
}
|
||||
if want := "Claude\n5-hour 42.2% used · pace −14% · resets in 2h 10m\nWeekly 70% used · pace +13% · resets in 3d 0h"; tip != want {
|
||||
t.Errorf("used tip %q, want %q", tip, want)
|
||||
}
|
||||
|
||||
label, tip = trayUsageText(q, now, true, true)
|
||||
if label != "58% +14% · 30% −13%" {
|
||||
t.Errorf("left label %q", label)
|
||||
}
|
||||
if want := "Claude\n5-hour 57.8% left · pace +14% · resets in 2h 10m\nWeekly 30% left · pace −13% · resets in 3d 0h"; tip != want {
|
||||
t.Errorf("left tip %q, want %q", tip, want)
|
||||
}
|
||||
|
||||
// each row still fits the menu bar whole, at its widest
|
||||
cells, _, _ := trayUsageView([]provider.SubscriptionQuota{q}, now, false, true)
|
||||
if len(cells) != 1 || !slices.Equal(cells[0].Rows, []string{"42% −14%", "70% +13%"}) {
|
||||
t.Fatalf("cells %+v", cells)
|
||||
}
|
||||
if r := trayRow("100% −100%"); r != "100% −100%" {
|
||||
t.Errorf("widest row cut: %q", r)
|
||||
}
|
||||
|
||||
// a window whose start can't be known, or with no limit, has no Pace
|
||||
q.Windows = []provider.QuotaWindow{
|
||||
{Name: "Credits", Used: 40, ResetsAt: in(time.Hour)},
|
||||
{Name: "Daily", Used: 0, Unlimited: true, ResetsAt: in(time.Hour)},
|
||||
}
|
||||
if label, _ := trayUsageText(q, now, false, true); label != "40% · 0%" {
|
||||
t.Errorf("unknown span %q", label)
|
||||
}
|
||||
|
||||
for p, want := range map[float64]string{12.4: "+12%", -8: "−8%", 0.4: "±0%", -0.4: "±0%"} {
|
||||
if got := trayPace(p, false); got != want {
|
||||
t.Errorf("trayPace(%v) = %q, want %q", p, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
// logos make it look worse): each cell is then its windows alone, with no
|
||||
// logo nor letter to draw, the rows as they were.
|
||||
func TestTrayPlain(t *testing.T) {
|
||||
cells, _, _ := trayUsageView(trayCards(), time.Now(), false)
|
||||
cells, _, _ := trayUsageView(trayCards(), time.Now(), false, false)
|
||||
plain := trayPlain(cells)
|
||||
if len(plain) != len(cells) {
|
||||
t.Fatalf("%d cells, want %d", len(plain), len(cells))
|
||||
|
||||
@@ -19,7 +19,7 @@ func TestTrayUsageText(t *testing.T) {
|
||||
{Name: "Opus weekly", Used: 90, Model: "opus", Span: 7 * 24 * time.Hour},
|
||||
{Name: "Extra usage", Used: 5, Aside: true},
|
||||
}}
|
||||
label, tip := trayUsageText(q, now, false)
|
||||
label, tip := trayUsageText(q, now, false, false)
|
||||
if label != "42% · 18%" {
|
||||
t.Errorf("label %q", label)
|
||||
}
|
||||
@@ -27,7 +27,7 @@ func TestTrayUsageText(t *testing.T) {
|
||||
t.Errorf("tip %q, want %q", tip, want)
|
||||
}
|
||||
// or what is left of each, as Settings or the Usage page says (#122)
|
||||
label, tip = trayUsageText(q, now, true)
|
||||
label, tip = trayUsageText(q, now, true, false)
|
||||
if label != "58% · 82%" {
|
||||
t.Errorf("left label %q", label)
|
||||
}
|
||||
@@ -44,7 +44,7 @@ func TestTrayUsageText(t *testing.T) {
|
||||
{Name: "Weekly", Used: -3, ResetSecs: 90},
|
||||
{Name: "Monthly", Used: 1},
|
||||
}}
|
||||
label, tip = trayUsageText(q, now, false)
|
||||
label, tip = trayUsageText(q, now, false, false)
|
||||
if label != "100% · 0%" {
|
||||
t.Errorf("label %q", label)
|
||||
}
|
||||
@@ -56,32 +56,32 @@ func TestTrayUsageText(t *testing.T) {
|
||||
}
|
||||
|
||||
q = provider.SubscriptionQuota{Name: "Copilot", Windows: []provider.QuotaWindow{{Name: "Premium", Used: 187418.3 / 218000 * 100}}}
|
||||
label, tip = trayUsageText(q, now, false)
|
||||
label, tip = trayUsageText(q, now, false, false)
|
||||
if label != "86%" || tip != "Copilot\nPremium 86.0% used" {
|
||||
t.Errorf("copilot used: %q %q", label, tip)
|
||||
}
|
||||
label, tip = trayUsageText(q, now, true)
|
||||
label, tip = trayUsageText(q, now, true, false)
|
||||
if label != "14%" || tip != "Copilot\nPremium 14.0% left" {
|
||||
t.Errorf("copilot left: %q %q", label, tip)
|
||||
}
|
||||
|
||||
// a balance, an error, nothing
|
||||
if label, _ = trayUsageText(provider.SubscriptionQuota{Name: "DeepSeek", Balance: "¥12.30"}, now, false); label != "¥12.30" {
|
||||
if label, _ = trayUsageText(provider.SubscriptionQuota{Name: "DeepSeek", Balance: "¥12.30"}, now, false, false); label != "¥12.30" {
|
||||
t.Errorf("balance label %q", label)
|
||||
}
|
||||
// one read a while ago, standing in for one that couldn't be read now,
|
||||
// says when it was read (#420)
|
||||
read := time.Date(2026, 9, 27, 9, 5, 0, 0, time.Local)
|
||||
if label, tip = trayUsageText(provider.SubscriptionQuota{Name: "Relay", Balance: "$4.20", AsOf: &read}, now, false); label != "$4.20" || tip != "Relay · $4.20\nas of Sep 27 09:05, couldn't be read just now" {
|
||||
if label, tip = trayUsageText(provider.SubscriptionQuota{Name: "Relay", Balance: "$4.20", AsOf: &read}, now, false, false); label != "$4.20" || tip != "Relay · $4.20\nas of Sep 27 09:05, couldn't be read just now" {
|
||||
t.Errorf("balance as of: %q %q", label, tip)
|
||||
}
|
||||
if _, tip = trayUsageText(provider.SubscriptionQuota{Name: "Kimi", AsOf: &read, Windows: []provider.QuotaWindow{{Name: "Weekly", Used: 10}}}, now, false); tip != "Kimi\nWeekly 10% used\nas of Sep 27 09:05, couldn't be read just now" {
|
||||
if _, tip = trayUsageText(provider.SubscriptionQuota{Name: "Kimi", AsOf: &read, Windows: []provider.QuotaWindow{{Name: "Weekly", Used: 10}}}, now, false, false); tip != "Kimi\nWeekly 10% used\nas of Sep 27 09:05, couldn't be read just now" {
|
||||
t.Errorf("windows as of: %q", tip)
|
||||
}
|
||||
if label, tip = trayUsageText(provider.SubscriptionQuota{Name: "Codex", Error: "signed out"}, now, false); label != "" || tip != "Codex: signed out" {
|
||||
if label, tip = trayUsageText(provider.SubscriptionQuota{Name: "Codex", Error: "signed out"}, now, false, false); label != "" || tip != "Codex: signed out" {
|
||||
t.Errorf("error: %q %q", label, tip)
|
||||
}
|
||||
if label, tip = trayUsageText(provider.SubscriptionQuota{Name: "Empty"}, now, false); label != "" || tip != "" {
|
||||
if label, tip = trayUsageText(provider.SubscriptionQuota{Name: "Empty"}, now, false, false); label != "" || tip != "" {
|
||||
t.Errorf("empty: %q %q", label, tip)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ func TestTrayTotals(t *testing.T) {
|
||||
if !slices.Equal(asked, []usage.Period{usage.Week, usage.Today}) {
|
||||
t.Fatalf("summed %v, want 7d then today", asked)
|
||||
}
|
||||
cells, label, tip := trayUsageView(cards, time.Now(), false)
|
||||
cells, label, tip := trayUsageView(cards, time.Now(), false, false)
|
||||
if label != "47M · $128 | 1.2M · $3.40+" {
|
||||
t.Errorf("label %q", label)
|
||||
}
|
||||
@@ -87,7 +87,7 @@ func TestTrayTotalsBesideCards(t *testing.T) {
|
||||
t.Cleanup(func() { trayTotalSum = old })
|
||||
cards := append(trayCards(), trayTotalCard("usage:today", trayTotalSum(usage.Today), "usd", 0))
|
||||
now := time.Date(2026, 9, 30, 12, 0, 0, 0, time.UTC)
|
||||
cells, label, _ := trayUsageView(trayPick(cards, []string{"usage:today", "claude|a@b.c"}, now), now, false)
|
||||
cells, label, _ := trayUsageView(trayPick(cards, []string{"usage:today", "claude|a@b.c"}, now), now, false, false)
|
||||
if label != "6.0K · $0.120 | 42% · 18%" {
|
||||
t.Errorf("label %q", label)
|
||||
}
|
||||
|
||||
@@ -40,7 +40,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)
|
||||
cells, label, tip := trayUsageView(trayUsageCards(ctx, s.TrayUsages), time.Now(), s.QuotaLeft, s.TrayPace)
|
||||
cancel()
|
||||
if s.TrayNoLogos {
|
||||
cells = trayPlain(cells)
|
||||
|
||||
@@ -188,6 +188,8 @@ func usageRoutes(mux *http.ServeMux, w Windows) {
|
||||
qs := provider.WithCheckins(provider.Quotas(ctx))
|
||||
// and what each window holds whole, by what magpie routed in it
|
||||
qs = usage.WithWindowHolds(qs, usage.Clock())
|
||||
// and when each began, for its Pace number (fflake33)
|
||||
qs = provider.WithWindowStarts(qs, usage.Clock())
|
||||
// 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() {
|
||||
@@ -207,7 +209,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, usage.WithWindowHolds(provider.WithCheckins(provider.Quotas(ctx)), usage.Clock()))
|
||||
writeJSON(rw, provider.WithWindowStarts(usage.WithWindowHolds(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
|
||||
|
||||
@@ -86,6 +86,10 @@ type QuotaWindow struct {
|
||||
// HoldsCredits. Empty where no whole is ever told (a pool, a family,
|
||||
// money aside, another magpie's card).
|
||||
HoldsWhy string `json:"holdsWhy,omitempty"`
|
||||
// StartsAt is when the window began (Bounds), for the GUI only
|
||||
// (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"`
|
||||
// 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:
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package provider
|
||||
|
||||
import "time"
|
||||
|
||||
// Pace is how far w's use, read at readAt, is from an even pace through
|
||||
// the window at now, in points of the window (fflake33 on Discord): what
|
||||
// is used less the share of the window gone by. +12 is twelve points more
|
||||
// used than an even pace would have used by now, so at this rate the
|
||||
// window runs out before it resets; -8 is eight points to spare. ok is
|
||||
// false for a window with no limit, or whose start or reset isn't known,
|
||||
// or when now is outside it.
|
||||
func (w QuotaWindow) Pace(readAt, now time.Time) (pace float64, ok bool) {
|
||||
if w.Unlimited {
|
||||
return 0, false
|
||||
}
|
||||
start, end, ok := w.Bounds(readAt)
|
||||
if !ok || !end.After(start) || now.Before(start) || !now.Before(end) {
|
||||
return 0, false
|
||||
}
|
||||
even := 100 * float64(now.Sub(start)) / float64(end.Sub(start))
|
||||
return max(0, min(100, w.Used)) - even, true
|
||||
}
|
||||
|
||||
// WithWindowStarts is qs with each window's StartsAt set where its bounds
|
||||
// are known, for the GUI's Pace number; qs and its windows, which the
|
||||
// caches share, are left as they were.
|
||||
func WithWindowStarts(qs []SubscriptionQuota, now time.Time) []SubscriptionQuota {
|
||||
out := make([]SubscriptionQuota, len(qs))
|
||||
for i, q := range qs {
|
||||
readAt := now
|
||||
if q.ReadAt != nil && !q.ReadAt.After(now) {
|
||||
readAt = *q.ReadAt
|
||||
}
|
||||
if len(q.Windows) > 0 {
|
||||
ws := make([]QuotaWindow, len(q.Windows))
|
||||
for j, w := range q.Windows {
|
||||
if w.StartsAt == nil && !w.Unlimited {
|
||||
if start, _, ok := w.Bounds(readAt); ok {
|
||||
w.StartsAt = &start
|
||||
}
|
||||
}
|
||||
ws[j] = w
|
||||
}
|
||||
q.Windows = ws
|
||||
}
|
||||
out[i] = q
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"math"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestWindowPace(t *testing.T) {
|
||||
now := time.Date(2026, 9, 27, 12, 0, 0, 0, time.UTC)
|
||||
at := func(d time.Duration) *time.Time { t := now.Add(d); return &t }
|
||||
|
||||
// half of a 10-hour window gone by: 62% used is 12 points over, 42% 8 under
|
||||
w := QuotaWindow{Name: "10h", Used: 62, ResetsAt: at(5 * time.Hour), Span: 10 * time.Hour}
|
||||
if p, ok := w.Pace(now, now); !ok || math.Abs(p-12) > 1e-9 {
|
||||
t.Errorf("over: %v %v", p, ok)
|
||||
}
|
||||
w.Used = 42
|
||||
if p, ok := w.Pace(now, now); !ok || math.Abs(p+8) > 1e-9 {
|
||||
t.Errorf("under: %v %v", p, ok)
|
||||
}
|
||||
// the span from the window's name when the vendor gave none
|
||||
if p, ok := (QuotaWindow{Name: "Weekly", Used: 50, ResetsAt: at(84 * time.Hour)}).Pace(now, now); !ok || math.Abs(p) > 1e-9 {
|
||||
t.Errorf("weekly: %v %v", p, ok)
|
||||
}
|
||||
// a reset given as seconds counts from when the card was read
|
||||
readAt := now.Add(-time.Hour)
|
||||
if p, ok := (QuotaWindow{Used: 50, ResetSecs: 5400, Span: 2 * time.Hour}).Pace(readAt, now); !ok || math.Abs(p+25) > 1e-9 {
|
||||
t.Errorf("reset secs: %v %v", p, ok)
|
||||
}
|
||||
// used past the whole counts as the whole
|
||||
if p, ok := (QuotaWindow{Name: "10h", Used: 130, ResetsAt: at(5 * time.Hour), Span: 10 * time.Hour}).Pace(now, now); !ok || math.Abs(p-50) > 1e-9 {
|
||||
t.Errorf("clamped: %v %v", p, ok)
|
||||
}
|
||||
for name, w := range map[string]QuotaWindow{
|
||||
"unlimited": {Name: "10h", Unlimited: true, ResetsAt: at(time.Hour), Span: 10 * time.Hour},
|
||||
"no reset": {Name: "Weekly", Used: 10},
|
||||
"no span": {Name: "Credits", Used: 10, ResetsAt: at(time.Hour)},
|
||||
"already over": {Name: "10h", Used: 10, ResetsAt: at(-time.Minute), Span: 10 * time.Hour},
|
||||
"not begun": {Name: "1h", Used: 10, ResetsAt: at(2 * time.Hour), Span: time.Hour},
|
||||
} {
|
||||
if p, ok := w.Pace(now, now); ok {
|
||||
t.Errorf("%s: pace %v", name, p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithWindowStarts(t *testing.T) {
|
||||
now := time.Date(2026, 9, 27, 12, 0, 0, 0, time.UTC)
|
||||
reset := now.Add(2 * time.Hour)
|
||||
monthEnd := time.Date(2026, 10, 15, 0, 0, 0, 0, time.UTC)
|
||||
readAt := now.Add(-time.Hour)
|
||||
qs := []SubscriptionQuota{{Name: "A", ReadAt: &readAt, Windows: []QuotaWindow{
|
||||
{Name: "5-hour", ResetsAt: &reset, Span: 5 * time.Hour},
|
||||
{Name: "Monthly", ResetsAt: &monthEnd},
|
||||
{Name: "Seconds", ResetSecs: 3600, Span: 2 * time.Hour},
|
||||
{Name: "Credits", ResetsAt: &reset},
|
||||
{Name: "Daily", Unlimited: true, ResetsAt: &reset},
|
||||
}}, {Name: "B"}}
|
||||
got := WithWindowStarts(qs, now)
|
||||
|
||||
ws := got[0].Windows
|
||||
if ws[0].StartsAt == nil || !ws[0].StartsAt.Equal(reset.Add(-5*time.Hour)) {
|
||||
t.Errorf("5-hour start %v", ws[0].StartsAt)
|
||||
}
|
||||
if ws[1].StartsAt == nil || !ws[1].StartsAt.Equal(time.Date(2026, 9, 15, 0, 0, 0, 0, time.UTC)) {
|
||||
t.Errorf("monthly start %v", ws[1].StartsAt)
|
||||
}
|
||||
// ResetSecs counts from when the card was read, not from now
|
||||
if ws[2].StartsAt == nil || !ws[2].StartsAt.Equal(readAt.Add(-time.Hour)) {
|
||||
t.Errorf("seconds start %v", ws[2].StartsAt)
|
||||
}
|
||||
if ws[3].StartsAt != nil || ws[4].StartsAt != nil {
|
||||
t.Errorf("unknown span or no limit given a start: %v %v", ws[3].StartsAt, ws[4].StartsAt)
|
||||
}
|
||||
if len(got) != 2 || got[1].Name != "B" {
|
||||
t.Errorf("cards %+v", got)
|
||||
}
|
||||
// the caches' own cards are left as they were
|
||||
for _, w := range qs[0].Windows {
|
||||
if w.StartsAt != nil {
|
||||
t.Fatalf("input window %q given a start", w.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -292,6 +292,10 @@ type Settings struct {
|
||||
// cards are there, the cards alone (KevinXC on Discord); a click on one
|
||||
// still opens the panel, and with no cards the bird is shown.
|
||||
TrayNoBird bool `json:"trayNoBird,omitempty"`
|
||||
// TrayPace puts each window's Pace number beside its figure in the
|
||||
// menu bar ("42% +12%"), as the Usage page's cards have it (fflake33
|
||||
// on Discord); off by default, as it widens every card.
|
||||
TrayPace bool `json:"trayPace,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
|
||||
@@ -880,7 +884,7 @@ func (s *Settings) KeepOwn(cur Settings) {
|
||||
s.UIFont, s.CodeFont = cur.UIFont, cur.CodeFont
|
||||
s.Window, s.Proxy, s.Port, s.Dock, s.DockWindow, s.Lightweight = cur.Window, cur.Proxy, cur.Port, cur.Dock, cur.DockWindow, cur.Lightweight
|
||||
s.WindowMaximised, s.KeepAwake, s.KeepAwakeDisplay = cur.WindowMaximised, cur.KeepAwake, cur.KeepAwakeDisplay
|
||||
s.TrayUsages, s.TrayUsage, s.TrayUsageEvery, s.TrayNoLogos, s.TrayNoBird = cur.TrayUsages, cur.TrayUsage, cur.TrayUsageEvery, cur.TrayNoLogos, cur.TrayNoBird
|
||||
s.TrayUsages, s.TrayUsage, s.TrayUsageEvery, s.TrayNoLogos, s.TrayNoBird, s.TrayPace = cur.TrayUsages, cur.TrayUsage, cur.TrayUsageEvery, cur.TrayNoLogos, cur.TrayNoBird, cur.TrayPace
|
||||
s.GatewayMode = cur.GatewayMode
|
||||
s.NoWSLAgents = cur.NoWSLAgents
|
||||
s.QuotaReads = cur.QuotaReads
|
||||
|
||||
Reference in New Issue
Block a user