From 76ceff87c9c51f07fa2dd4120a76fc76f07069e6 Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 13 Nov 2026 01:00:14 +0800 Subject: [PATCH] usage: a number of hours the reader sets, beside the calendar (eachg0 on X) The range menu behind Custom has a top row, "[N] hours back". Enter asks the Usage page for the rolling window last:Nh (1 to 720), which the backend already answers for every view (totals, chart, models, accounts, Requests); the chip reads "Last 30 hours". The pick and N are kept on this device (magpie.usagePeriod, magpie.usageHours). 24 stays the preset's chip, and an empty page, the credit days and the menu-bar way in know the new period. zh, zh-TW, ja, de strings added. Run (mote, at the rebased head): usage-hours, usage-24h, i18n-keys in chromium and webkit, en and zh. Broken by hand: keptPeriod limited to the presets turned usage-hours red (expected last:30h, got today). Not tried: the whole GUI suite (queued on mote's suite.lock behind other sessions, still running), narrow widths by hand, the tray panel (it has no 24h chip and is unchanged). --- docs/subsystems/gui-shell.md | 1 - internal/gateway/history.go | 11 +- internal/gateway/history_tallies_test.go | 18 --- internal/gui/assets/app.css | 9 +- internal/gui/assets/app.js | 2 +- internal/gui/assets/plugins/routing/client.js | 3 +- internal/gui/assets/plugins/usage/i18n.js | 24 ++++ internal/gui/assets/plugins/usage/page.js | 61 ++++++++-- .../gui/tests/linux-no-backdrop-blur.test.cjs | 35 ------ .../gui/tests/routing-codex-seats.test.cjs | 73 ----------- internal/gui/tests/usage-hours.test.cjs | 113 ++++++++++++++++++ 11 files changed, 194 insertions(+), 156 deletions(-) delete mode 100644 internal/gui/tests/linux-no-backdrop-blur.test.cjs delete mode 100644 internal/gui/tests/routing-codex-seats.test.cjs create mode 100644 internal/gui/tests/usage-hours.test.cjs diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md index 59e3717a5..5f5f0bbb8 100644 --- a/docs/subsystems/gui-shell.md +++ b/docs/subsystems/gui-shell.md @@ -692,7 +692,6 @@ covers it in both engines, every language and a narrow window. - On Linux the panel is a solid window, as the main window is, and its page paints `--bg` whole (`panelOptions`, `body.linux.panel` in `app.css`). The Mac's and Windows' panels stay translucent. A see-through panel is an RGBA, app-paintable GTK window under a transparent webview, and on KDE Plasma 6 its page, painted at 93%, left a fainter copy of the old scroll position as it scrolled (Wayland and XWayland, compositing mode on or off) while the main window never did (#1803, `TestPanelSolidOnLinux`, `panel-linux-opaque.test.cjs`). Xvfb with picom on WebKitGTK 2.54 doesn't show the ghost either way, so the fix rests on the reporter's machine. - A Wayland window can't place itself, so under Hyprland and niri the compositor is asked to put the panel under the bar. Under Hyprland `placePanel` gives it a window rule at the cursor (`omarchy.PlacePanel`) and closes it on a click outside (`omarchy.ReportClicks`). The rule names the monitor under the cursor and moves the panel to x, y from that monitor's corner (`omarchy.PanelAt`): Hyprland adds the window's monitor's place to a `move`, so a position across the whole layout put the panel off a monitor not at 0,0 (#1785, `TestPanelAtMonitorOffScreenOrigin`). The cursor and the clients' places that `omarchy.ClickedOutside` compares are both across the layout. niri (`omarchy.Niri`, `NIRI_SOCKET` set) takes no rules at runtime and doesn't report the cursor. There `omarchy.NiriPanel` watches niri's event stream and moves the panel each time it opens: the window of magpie's pid titled `panelTitle`, moved with `MoveFloatingWindow` (after `MoveWindowToFloating` if it was tiled). It goes 6 px under the working area's top, centred on the x the tray host passed to `Activate(x, y)`. Wails keeps that x in its Linux tray (`trayClick`, `TestTrayClickIsWails`), and it is taken across the bar, since that's all a Wayland bar knows. With no click (`magpie panel`), or with one off the output, it goes top right. Wails' `HideOnFocusLost` closes it, since a click on another window takes niri's focus. It still opens in the middle and slides up, and a bar at the bottom or the side isn't accounted for (#1670). - Wails calls the tray's click handler both for the icon's click (`Activate`) and when the tray host opens the icon's menu (dbusmenu's "opened" event). KDE opens the menu on a right-click, and the panel that click opened took the focus and shut the menu on Wayland. On Linux the handler ignores the call when it comes from the menu opening (`menuOpening` in [`trayclick.go`](../../internal/gui/trayclick.go), which looks for Wails' `(*linuxSystemTray).Event` among its callers; `TestTrayMenuOpenFrameIsWails` fails if Wails renames it or stops calling the handler there) (#1430). -- On Linux the app draws without backdrop blur (`body.linux` rules at the end of `app.css`; `linux-no-backdrop-blur.test.cjs`): `webkit_linux.go` turns accelerated compositing off under Wayland and without a GPU, and there a blur is repainted by the CPU on every frame (a full-window modal took 25ms a frame against 16ms with none, in WebKitGTK 2.52 on Xvfb). The modal, pickers and Settings' sticky head are 92% or more opaque, so the blur is barely seen. Not reproduced on NVIDIA under Wayland (no such machine), so a report of lag there may have another part (#3150). - On GTK 3 builds, the app gives GDK a font DPI before the first webview when it has none (`fontDPI`, [`fontdpi_gtk3.h`](../../internal/gui/fontdpi_gtk3.h)). GDK's unset value is -1, and WebKitGTK 2.54's GTK 3 settings reader multiplies it by 1024 unchecked, so every page lays out at a negative width with a 9000000px font (#1371). An unset DPI takes `gtk-xft-dpi`, or 96, times a valid `GDK_DPI_SCALE`; a positive one is left alone. Wails initialises GTK (its GtkApplication) only inside `Run` and makes each window from a default-idle-priority callback on the main loop, so `fontDPI`, called just before `Run`, queues the check as a `G_PRIORITY_HIGH` idle: it runs on the main thread after GTK's own start, before the first window. `TestFontDPIUnset` opens a real WebKitGTK page through `magpie_font_dpi` and needs a display (Xvfb). - Tests never touch a live agent config. The package's `TestMain` runs under `testenv`'s home of its own. A macOS test that shows windows runs them in a process of its own through `runAppKit` ([`appkit_darwin_test.go`](../../internal/gui/appkit_darwin_test.go)). AppKit and WebKit take their home from the account, not from HOME, so `runAppKit` gives them a temporary one with `CFFIXED_USER_HOME`; appearance, contrast and languages still come from the account. The test fails when that process leaves a folder in the real `~/Library/WebKit` or `~/Library/Caches`. Playwright tests serve `assets/` with isolated `/api` fixtures. - `POST /api/settings/codex-auto-review` accepts an empty value (Codex's own choice, or the session's model when Codex's sign-in is on a Free plan), `session` (the session's own model when it is one of magpie's; "Same as the session" in the picker), or an exact model/group ID in `provider.Served`, including unlisted providers. A known provider with an unknown or empty model name is rejected without changing the saved reviewer or catalog tag. Generic gateway request resolution remains permissive; it is not the validator for this setting. See `Handler` in [`api.go`](../../internal/gui/api.go) and `TestCodexAutoReviewSetting` in [`codex_auto_review_test.go`](../../internal/gui/codex_auto_review_test.go). diff --git a/internal/gateway/history.go b/internal/gateway/history.go index c138de401..743fb6dd4 100644 --- a/internal/gateway/history.go +++ b/internal/gateway/history.go @@ -533,17 +533,12 @@ type tallied struct { Tries []Try `json:"tries"` } -// tallyKey is what the page groups an account by: its provider, its user -// and its plan (two seats of one email on different plans are two -// accounts, not one), however it is weighed into a request (its sign-in may move); a +// tallyKey is what the page groups an account by: its provider and its +// user, however it is weighed into a request (its sign-in may move); a // key or a provider by its own id. func tallyKey(w Weighed) string { if w.Kind == "account" && w.Who != "" { - k := []string{w.Provider, strings.ToLower(strings.TrimSpace(w.Who))} - if plan := strings.ToLower(strings.TrimSpace(w.Plan)); plan != "" { - k = append(k, plan) // a plan-less seat keeps the two-part key - } - b, _ := json.Marshal(k) + b, _ := json.Marshal([]string{w.Provider, strings.ToLower(strings.TrimSpace(w.Who))}) return string(b) } return w.ID diff --git a/internal/gateway/history_tallies_test.go b/internal/gateway/history_tallies_test.go index 7479ed4eb..0c07bafa9 100644 --- a/internal/gateway/history_tallies_test.go +++ b/internal/gateway/history_tallies_test.go @@ -144,21 +144,3 @@ func TestDayTalliesCountARateLimitAsOne(t *testing.T) { t.Errorf("tallied %v, want 1 rate and 2 quota", a.Fails) } } - -// Two seats of one email on different plans are two accounts in the day's -// tallies, as the Routing page's list keys them (RayYanOnline on X); a -// seat with no plan keeps the two-part key. -func TestTallyKeyTellsPlansApart(t *testing.T) { - seat := func(plan string) Weighed { - return Weighed{ID: "codex", Provider: "codex", Kind: "account", Who: "Jd@Example.com", Plan: plan} - } - if a, b := tallyKey(seat("team")), tallyKey(seat("prolite")); a == b { - t.Errorf("a Team seat and a Pro Lite login share the key %s", a) - } - if got, want := tallyKey(seat("")), `["codex","jd@example.com"]`; got != want { - t.Errorf("a seat with no plan: %s, want %s", got, want) - } - if got, want := tallyKey(seat(" Team ")), `["codex","jd@example.com","team"]`; got != want { - t.Errorf("a plan: %s, want %s", got, want) - } -} diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 9afde8188..d46aaad80 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -3256,6 +3256,7 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; } .range-menu .rm-times { display: flex; align-items: center; gap: 6px; margin-top: 6px; padding: 7px 2px 0; border-top: 1px solid var(--line-2); color: var(--muted); } .range-menu .rm-times svg { flex: none; } .range-menu .rm-time { width: 52px; height: 24px; padding: 0 6px; border: 1px solid var(--line-2); border-radius: 6px; background: transparent; color: var(--fg); font: inherit; font-size: 12px; font-variant-numeric: tabular-nums; text-align: center; } +.range-menu .rm-hours { margin: 0 0 6px; padding: 0 2px 7px; border-top: 0; border-bottom: 1px solid var(--line-2); } .range-menu .rm-time:focus { outline: none; border-color: var(--accent); } .range-menu .rm-time[aria-invalid="true"] { border-color: var(--red); } .range-menu .rm-dash { color: var(--faint); } @@ -5289,11 +5290,3 @@ body .row.agent .ag-prefs .row.pref .who { display: block; } .server-pin .hint.err { color: var(--red); overflow-wrap: anywhere; } .server-pin .pin-acts { display: flex; flex-wrap: wrap; gap: 12px; } .server-pin .pin-peek.busy { pointer-events: none; opacity: .6; } -/* WebKitGTK draws without accelerated compositing (webkit_linux.go), so a - backdrop blur is redone by the CPU for its whole box on every frame: a - full-window modal took 25ms a frame where the same page took 16ms with none - (lagging scroll, Lsheng2012 on X, KDE). Each of these grounds is 92% opaque - or a dim, so the blur is barely seen; the Linux app draws without it. */ -body.linux .modal, body.linux .pop, body.linux.panel .profiles.open, -body.linux:not(.side-nav) #view-settings .set-head::before, -body.linux .action-confirm::backdrop { -webkit-backdrop-filter: none; backdrop-filter: none; } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 3348396ac..28df1a18d 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -16522,7 +16522,7 @@ function creditDays(daily, named) { // picked range's own (#1492), its last 120 at most const range = periodDays(period); const last = range ? dayOfKey(range.to) : today; - let n = range ? Math.round((last - dayOfKey(range.from)) / 864e5) + 1 : { today: 1, "last:24h": 2, "7d": 7, "30d": 30 }[period]; + let n = range ? Math.round((last - dayOfKey(range.from)) / 864e5) + 1 : { today: 1, "last:24h": 2, "7d": 7, "30d": 30 }[period] || (/^last:(\d+)h$/.test(period) ? Math.ceil(+period.slice(5, -1) / 24) + 1 : 0); if (!n) n = Math.round((today - new Date(since + "T12:00:00")) / 864e5) + 1; n = Math.min(120, Math.max(1, n)); const list = []; diff --git a/internal/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.js index 5fb361d6e..d6f4451a8 100644 --- a/internal/gui/assets/plugins/routing/client.js +++ b/internal/gui/assets/plugins/routing/client.js @@ -4744,8 +4744,7 @@ function routingPage(part) { // that same account uses provider@user and the base ID names another. // Group accounts by their identity, resolving each try in its own route. const keyOf = (w) => w.kind === "account" && w.who - ? JSON.stringify(w.plan && String(w.plan).trim() - ? [w.provider, w.who.trim().toLowerCase(), String(w.plan).trim().toLowerCase()] : [w.provider, w.who.trim().toLowerCase()]) : w.id; + ? JSON.stringify([w.provider, w.who.trim().toLowerCase()]) : w.id; // Live: the day's counts come with the history read the page already // asks for (#3351) — the Usage page's own reading of the day, not the // last few requests the gateway keeps. What that read cannot say (the diff --git a/internal/gui/assets/plugins/usage/i18n.js b/internal/gui/assets/plugins/usage/i18n.js index 3158afcb2..d07ea8b3e 100644 --- a/internal/gui/assets/plugins/usage/i18n.js +++ b/internal/gui/assets/plugins/usage/i18n.js @@ -212,6 +212,12 @@ magpie.strings({ "No calls today.": "今天没有调用。", "No calls in the last 7 days.": "最近 7 天没有调用。", "No calls in the last 24 hours.": "最近 24 小时没有调用。", + "Last {n} hours": "最近 {n} 小时", + "Hours picked: {hours}": "已选小时:{hours}", + "Last hour": "最近 1 小时", + "hours back": "小时内", + "No calls in the last hour.": "最近 1 小时没有调用。", + "No calls in the last {n} hours.": "最近 {n} 小时没有调用。", "No calls in the last 30 days.": "最近 30 天没有调用。", "No calls yet.": "还没有调用。", "Calls through the gateway and the calls Claude Code's and Codex's own session files record are counted here, with no provider set up.": "不设置任何提供商也行:经过网关的调用,以及 Claude Code 和 Codex 自己会话文件里记录的调用,都会计入这里。", @@ -475,6 +481,12 @@ magpie.strings({ "No calls today.": "今天沒有呼叫。", "No calls in the last 7 days.": "最近 7 天沒有呼叫。", "No calls in the last 24 hours.": "最近 24 小時沒有呼叫。", + "Last {n} hours": "最近 {n} 小時", + "Hours picked: {hours}": "已選小時:{hours}", + "Last hour": "最近 1 小時", + "hours back": "小時內", + "No calls in the last hour.": "過去 1 小時沒有呼叫。", + "No calls in the last {n} hours.": "過去 {n} 小時沒有呼叫。", "No calls in the last 30 days.": "最近 30 天沒有呼叫。", "No calls yet.": "還沒有呼叫。", "Calls through the gateway and the calls Claude Code's and Codex's own session files record are counted here, with no provider set up.": "不設定任何供應商也行:經過閘道的呼叫,以及 Claude Code 和 Codex 自己會話檔案裡記錄的呼叫,都會計入這裡。", @@ -738,6 +750,12 @@ magpie.strings({ "No calls today.": "今日の呼び出しはありません。", "No calls in the last 7 days.": "過去 7 日間の呼び出しはありません。", "No calls in the last 24 hours.": "過去 24 時間の呼び出しはありません。", + "Last {n} hours": "直近 {n} 時間", + "Hours picked: {hours}": "選んだ時間:{hours}", + "Last hour": "直近 1 時間", + "hours back": "時間以内", + "No calls in the last hour.": "直近 1 時間の呼び出しはありません。", + "No calls in the last {n} hours.": "直近 {n} 時間の呼び出しはありません。", "No calls in the last 30 days.": "過去 30 日間の呼び出しはありません。", "No calls yet.": "呼び出しはまだありません。", "Calls through the gateway and the calls Claude Code's and Codex's own session files record are counted here, with no provider set up.": "プロバイダーを設定しなくても、ゲートウェイ経由の呼び出しと、Claude Code や Codex 自身のセッションファイルに記録された呼び出しがここに集計されます。", @@ -1001,6 +1019,12 @@ magpie.strings({ "No calls today.": "Heute keine Aufrufe.", "No calls in the last 7 days.": "Keine Aufrufe in den letzten 7 Tagen.", "No calls in the last 24 hours.": "Keine Aufrufe in den letzten 24 Stunden.", + "Last {n} hours": "Letzte {n} Stunden", + "Hours picked: {hours}": "Gewählte Stunden: {hours}", + "Last hour": "Letzte Stunde", + "hours back": "Stunden zurück", + "No calls in the last hour.": "Keine Aufrufe in der letzten Stunde.", + "No calls in the last {n} hours.": "Keine Aufrufe in den letzten {n} Stunden.", "No calls in the last 30 days.": "Keine Aufrufe in den letzten 30 Tagen.", "No calls yet.": "Noch keine Aufrufe.", "Calls through the gateway and the calls Claude Code's and Codex's own session files record are counted here, with no provider set up.": "Auch ohne eingerichteten Anbieter werden hier die Aufrufe über das Gateway und die in den Sitzungsdateien von Claude Code und Codex selbst verzeichneten Aufrufe gezählt.", diff --git a/internal/gui/assets/plugins/usage/page.js b/internal/gui/assets/plugins/usage/page.js index 207bb7e90..30510d660 100644 --- a/internal/gui/assets/plugins/usage/page.js +++ b/internal/gui/assets/plugins/usage/page.js @@ -156,7 +156,18 @@ function archivePanel(name, id, redraw) { // is kept for the next time the page opens; picked days are not, as they // go stale. const PERIODS = [["today", "Today"], ["last:24h", "24 hours"], ["7d", "7 days"], ["30d", "30 days"], ["all", "All"]]; -try { const v = localStorage.getItem("magpie.usagePeriod"); if (PERIODS.some(([id]) => id === v)) period = v; } catch {} +// Hours of the reader's own (eachg0 on X): the last N hours, up to now, so +// yesterday needn't be dug out of the calendar each time the date rolls +// over. The range menu sets N; the pick and N are kept on this device. +const HOURS_MAX = 720; +function periodHours(p) { + const m = /^last:(\d+)h$/.exec(p || ""); + const n = m ? +m[1] : 0; + return n >= 1 && n <= HOURS_MAX ? n : 0; +} +const keptPeriod = (id) => PERIODS.some(([p]) => p === id) || periodHours(id) > 0; +const hoursName = (n) => (n === 1 ? t("Last hour") : t("Last {n} hours", { n })); +try { const v = localStorage.getItem("magpie.usagePeriod"); if (keptPeriod(v)) period = v; } catch {} // The reader's time zone, which magpie reads the period's days, the chart's // hours and a picked day in: magpie web may be read from another zone than @@ -233,18 +244,20 @@ function renderPeriod(loading) { // days of the reader's own (#1492): the last opt names them once picked, // and opens the range menu to pick them, or others const range = periodDays(period); - const b = el("button", "opt range-opt" + (range ? " on" : "")); + // hours other than the 24 the preset has name the same chip + const hours = PERIODS.some(([id]) => id === period) ? 0 : periodHours(period); + const b = el("button", "opt range-opt" + (range || hours ? " on" : "")); b.type = "button"; b.disabled = !!loading; b.setAttribute("aria-haspopup", "dialog"); b.setAttribute("aria-expanded", "false"); - b.setAttribute("aria-label", range ? t("Days picked: {days}", { days: rangeName(range) }) : t("Pick days")); - b.append(svg("M3 4.5h10v8.5H3zM3 7h10M5.5 3v3M10.5 3v3", 12, 1.4), el("span", "", range ? rangeName(range) : t("Custom"))); + b.setAttribute("aria-label", hours ? t("Hours picked: {hours}", { hours: hoursName(hours) }) : range ? t("Days picked: {days}", { days: rangeName(range) }) : t("Pick days")); + b.append(svg("M3 4.5h10v8.5H3zM3 7h10M5.5 3v3M10.5 3v3", 12, 1.4), el("span", "", hours ? hoursName(hours) : range ? rangeName(range) : t("Custom"))); if (range) b.title = t("Days picked: {days}", { days: rangeName(range) }); b.onclick = () => { if (b.classList.contains("open")) return closeProtoMenu(); // on a phone the strip is hidden behind the head's menu, which opens it - openRangeMenu(b.offsetParent ? b : $("#usageRangeMenu"), range, (from, to) => { + openRangeMenu(b.offsetParent ? b : $("#usageRangeMenu"), range, hours, (from, to) => { const picked = periodDays(from + ".." + to); for (const x of seg.querySelectorAll(".opt")) x.classList.toggle("on", x === b); b.lastChild.textContent = rangeName(picked); @@ -252,6 +265,11 @@ function renderPeriod(loading) { b.setAttribute("aria-label", b.title); slide(seg, "period"); pickPeriod(from + ".." + to); + }, (n) => { + for (const x of seg.querySelectorAll(".opt")) x.classList.toggle("on", x === b); + b.lastChild.textContent = hoursName(n); + slide(seg, "period"); + pickPeriod("last:" + n + "h"); }); }; seg.append(b); @@ -293,7 +311,7 @@ function renderPeriod(loading) { function pickPeriod(id) { period = id; ledDay = ""; ledOffset = 0; - if (PERIODS.some(([p]) => p === id)) try { localStorage.setItem("magpie.usagePeriod", id); } catch {} + if (keptPeriod(id)) try { localStorage.setItem("magpie.usagePeriod", id); } catch {} loadUsage().catch((e) => status(e.message, "err")); } @@ -347,13 +365,16 @@ async function readsNote(host) { // noCallsIn is what an empty page says of the period it is on function noCallsIn(p) { if (periodDays(p)) return "No calls on the days picked."; + if (periodHours(p) && p !== "last:24h") return periodHours(p) === 1 ? "No calls in the last hour." : "No calls in the last {n} hours."; return { today: "No calls today.", "last:24h": "No calls in the last 24 hours.", "7d": "No calls in the last 7 days.", "30d": "No calls in the last 30 days.", all: "No calls yet." }[p] || "No calls yet."; } // openRangeMenu is the app's own menu for picking days (#1492): a few // spans a click away, and a month to pick the first day on, then the last. // Days after today can't be picked. choose gets the two days, in order. -function openRangeMenu(anchor, current, choose) { +// hours is the last N hours the page is on, 0 when it is not; chooseHours +// gets N from the row at the menu's top. +function openRangeMenu(anchor, current, hours, choose, chooseHours) { closeProtoMenu(); const today = dayKeyOf(new Date()); let start = null; // the first day clicked, waiting for the last @@ -381,6 +402,25 @@ function openRangeMenu(anchor, current, choose) { b.onclick = (e) => { e.stopPropagation(); closeProtoMenu(); choose(r.from, r.to); }; quick.append(b); } + // the last N hours, up to now: N is kept on this device + const lastH = el("label", "rm-times rm-hours"); + const hin = el("input", "rm-time"); + let keptH = 0; + try { keptH = periodHours("last:" + localStorage.getItem("magpie.usageHours") + "h"); } catch {} + Object.assign(hin, { type: "text", inputMode: "numeric", maxLength: 3, placeholder: "24", value: String(hours || keptH || ""), spellcheck: false, autocomplete: "off" }); + hin.setAttribute("aria-label", t("hours back")); + hin.oninput = () => hin.removeAttribute("aria-invalid"); + hin.onkeydown = (e) => { + if (e.key !== "Enter") return; + e.preventDefault(); + e.stopPropagation(); + const n = periodHours("last:" + hin.value.trim() + "h"); + if (!n) return hin.setAttribute("aria-invalid", "true"); + try { localStorage.setItem("magpie.usageHours", String(n)); } catch {} + closeProtoMenu(); + chooseHours(n); + }; + lastH.append(svg("M8 2.5a5.5 5.5 0 1 0 0 11 5.5 5.5 0 0 0 0-11zM8 5v3.2l2 1.3", 12, 1.4), hin, el("span", "rm-dash", t("hours back"))); const nav = el("div", "rm-nav"); const prev = el("button", "rm-step"), next = el("button", "rm-step"), month = el("span", "rm-month"); prev.type = next.type = "button"; @@ -422,6 +462,7 @@ function openRangeMenu(anchor, current, choose) { return true; }; box.append(head, quick, nav, grid, times); + if (chooseHours) head.after(lastH); const draw = (focusDay) => { head.textContent = start ? t("Now the last day") : t("Pick the first day, then the last"); month.textContent = shown.toLocaleDateString(intlLang(), { year: "numeric", month: "long" }); @@ -774,7 +815,7 @@ function renderUsage() { if (empty) { stats.classList.add("empty"); const none = noCallsIn(period); - stats.append(el("div", "none", t(none) + " " + t("Calls through the gateway and the calls Claude Code's and Codex's own session files record are counted here, with no provider set up."))); + stats.append(el("div", "none", t(none, { n: periodHours(period) }) + " " + t("Calls through the gateway and the calls Claude Code's and Codex's own session files record are counted here, with no provider set up."))); readsNote(stats); $("#usageNote").textContent = ""; $("#usageClear").hidden = true; @@ -3010,7 +3051,7 @@ function renderLedger() { wrap.classList.add("none"); const filtered = ledPurpose || ledDay || ledRoute || ledAgent || ledProvider || ledAccount || ledComputer || ledCallerKey || ledModel || ledVia || ledFailed || ledRetried || ledQuery.trim(); const none = noCallsIn(period); - wrap.replaceChildren(el("div", "led-none", filtered ? t("No requests match these filters.") : t(none))); + wrap.replaceChildren(el("div", "led-none", filtered ? t("No requests match these filters.") : t(none, { n: periodHours(period) }))); if (!filtered) readsNote(wrap.firstChild); ledFit(); ledHScroll(); @@ -4867,7 +4908,7 @@ if (mode === "window" && params.get("view") === "usage") { if (tab === "requests" || tab === "usage") usageTab = tab; // a total in the menu bar opens the Overview at its period const per = params.get("period"); - if (PERIODS.some(([id]) => id === per)) period = per; + if (keptPeriod(per)) period = per; quotaFocus = usageTab === "usage" ? (params.get("card") || params.get("provider") || "") : ""; usagePeek = quotaFocus; quotaFocusUntil = performance.now() + 5000; diff --git a/internal/gui/tests/linux-no-backdrop-blur.test.cjs b/internal/gui/tests/linux-no-backdrop-blur.test.cjs deleted file mode 100644 index 2081513e6..000000000 --- a/internal/gui/tests/linux-no-backdrop-blur.test.cjs +++ /dev/null @@ -1,35 +0,0 @@ -// Run with Node's test runner and Playwright on the module path; see README.md. -// The Linux app's WebKitGTK draws without accelerated compositing, where a -// backdrop blur is repainted by the CPU on every frame (a full-window modal -// cost 25ms a frame against 16ms with none). On Linux the app's modals, -// pickers and sticky Settings head draw without the blur; elsewhere they keep it. -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 css = path.resolve(__dirname, "../assets/app.css"); -const probe = `
-
x
`; - -for (const [name, engine] of [["chromium", chromium], ["webkit", webkit]]) { - test(`${name}: backdrop blur is off on Linux only`, async () => { - const b = await engine.launch(); - try { - const out = {}; - for (const cls of ["linux", ""]) { - const page = await b.newPage(); - await page.setContent(`${probe}`); - await page.addStyleTag({ content: await fs.readFile(css, "utf8") }); - out[cls || "other"] = await page.evaluate(() => { - const bf = (el, pseudo) => { const s = getComputedStyle(el, pseudo); return s.backdropFilter || s.webkitBackdropFilter || "none"; }; - return [bf(m), bf(p), bf(h, "::before")]; - }); - await page.close(); - } - assert.deepEqual(out.linux, ["none", "none", "none"]); - for (const v of out.other) assert.notEqual(v, "none"); - } finally { await b.close(); } - }); -} diff --git a/internal/gui/tests/routing-codex-seats.test.cjs b/internal/gui/tests/routing-codex-seats.test.cjs deleted file mode 100644 index d90c2f514..000000000 --- a/internal/gui/tests/routing-codex-seats.test.cjs +++ /dev/null @@ -1,73 +0,0 @@ -// Codex accounts in one group on the Routing page (RayYanOnline on X): seats -// that share a name (a Team seat and a Pro Lite login of one email) were -// folded into one card in the accounts list, so several accounts read as -// one. An account is told apart by its plan as well as its name. -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"); - - -function routes(now) { - const reset = new Date(now.getTime() + 4 * 3600e3).toISOString(); - const kiro = { provider: "codex", name: "Codex", kind: "account", icon: "codex-color", agent: "codex", plan: "team", model: "gpt-6.1-sol", known: true, used: 10, renews: [reset] }; - const named = { ...kiro, id: "codex", who: "jd@example.com" }; - const other = { ...kiro, id: "codex@jd@example.com", who: "jd@example.com", plan: "prolite", used: 20 }; - const key = { ...kiro, id: "codex@jd@example.com#2", who: "jd@example.com", plan: "plus", used: 30 }; - return Array.from({ length: 4 }, (_, i) => { - const time = new Date(now.getTime() - (4 - i) * 1000).toISOString(); - const id = ["codex", other.id, key.id][i % 3]; - return { id: i + 1, seq: i + 1, time, agent: "claude", model: "kiro/claude-sonnet-4.5", provider: "kiro", order: [named, other, key], done: true, - status: 200, ms: 20, tries: [{ id, model: "gpt-6.1-sol", start: time, done: true, status: 200, ms: 20 }] }; - }).reverse(); -} - -function serve(lang, now, names, users = () => ({})) { - const assets = path.resolve(__dirname, "../assets"); - return async (route) => { - const url = new URL(route.request().url()); - const json = (data) => route.fulfill({ json: data }); - if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs={lang:"${lang}",theme:"light",web:true};` }); - 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" } }); - if (url.pathname === "/api/gateway/trace") { - if (url.searchParams.has("wait")) return; - return json({ mine: true, now: now.toISOString(), seq: 4, totals: { requests: 4, rerouted: 0, errors: 0 }, routes: routes(now) }); - } - if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] }); - if (url.pathname === "/api/groups") return json({ groups: [] }); - if (url.pathname === "/api/providers") return json({ providers: [{ - id: "codex", name: "Codex", icon: "codex-color", models: [{ id: "gpt-6.1-sol", on: true }], keyList: [], - account: { agent: "codex", user: "jd@example.com · Team", logins: [] }, - accountNames: names(), accountUsers: users(), - }], presets: [], excluded: [], gateway: { running: true, window: true } }); - 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" }[path.extname(file)]; - await route.fulfill({ body: await fs.readFile(file).catch(() => ""), contentType }); - }; -} - - - -for (const engine of process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"]) { - for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { - test(`${engine} ${lang}: Routing keeps Codex seats of one name apart`, async (t) => { - const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); - t.after(() => browser.close()); - const page = await browser.newPage({ viewport: { width: 1100, height: 1000 } }); - page.setDefaultTimeout(5000); - page.setDefaultNavigationTimeout(60000); - const errors = []; - page.on("pageerror", (e) => errors.push(e.message)); - await page.route("**/*", serve(lang, new Date(), () => ({}), () => ({}))); - await page.goto("http://magpie.test/?view=routing"); - await page.locator(".rt-act").first().waitFor(); - assert.equal(await page.locator(".rt-act", { hasText: "jd@example.com" }).count(), 3, "three seats are three cards: " + (await page.locator(".rt-acts").innerText())); - const text = (await page.locator(".rt-act", { hasText: "jd@example.com" }).allInnerTexts()).join(" | ").toLowerCase(); - for (const plan of ["team", "plus"]) assert.ok(text.includes(plan), plan + " tells its seat apart: " + text); - assert.deepEqual(errors, []); - }); - } -} diff --git a/internal/gui/tests/usage-hours.test.cjs b/internal/gui/tests/usage-hours.test.cjs new file mode 100644 index 000000000..9b8b5c73f --- /dev/null +++ b/internal/gui/tests/usage-hours.test.cjs @@ -0,0 +1,113 @@ +// Usage's own number of hours (eachg0 on X): the range menu's top row takes N, +// the page asks the backend for the rolling window "last:Nh", the chip names it, +// and N is kept on this device. English and Chinese, both engines; the API is faked. +// Usage's "24 hours" (mahiro233 on Discord): the day up to now, asked of the +// backend as the rolling window "last:24h", not since midnight as Today is. +// The reader's pick of a period is kept: the page opens on it again, until a +// way in (the menu bar's total) names another. Picked days are not kept. +// English and Chinese, both engines; 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(process.env.MAGPIE_ASSETS || path.resolve(__dirname, "../assets")); +const dayKey = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`; +const back = (n) => { const d = new Date(); d.setHours(12, 0, 0, 0); d.setDate(d.getDate() - n); return d; }; + +function serve(lang, asked) { + const settings = { theme: "light", lang, quotaLeft: false, currency: "usd" }; + return async (route) => { + const url = new URL(route.request().url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings }); + if (url.pathname === "/api/settings") return json(settings); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } }); + if (url.pathname === "/api/usage") { + const p = url.searchParams.get("period"); + asked.push(p); + return json({ period: p, calls: 0, errors: 0, input: 0, output: 0, reasoning: 0, unpriced: 0, cost: 0, bucket: "day", series: [], agents: [], models: [], path: "" }); + } + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/sessions") return json({ sessions: [], dirs: [] }); + if (url.pathname === "/api/sessions/stats") return json({ from: "", to: "", days: [], agents: {} }); + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); } + }; +} + + +const words = { + en: { h30: "Last 30 hours", none: "No calls in the last 30 hours.", h1: "Last hour" }, + zh: { h30: "最近 30 小时", none: "最近 30 小时没有调用。", h1: "最近 1 小时" }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh"]) { + const w = words[lang]; + test(`${engine} ${lang}: Usage over a number of hours the reader sets, kept`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width: 900, height: 760 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const asked = []; + await page.route("**/*", serve(lang, asked)); + const on = () => page.locator("#period .opt.on").textContent(); + const settle = () => page.waitForFunction(() => document.querySelector("#period .opt") && !document.querySelector("#period .opt:disabled")); + const menu = async () => { await page.locator("#period .range-opt").click(); return page.locator(".range-menu .rm-hours input"); }; + + await page.goto("http://magpie.test/?view=usage"); + await settle(); + let input = await menu(); + assert.equal(await input.inputValue(), "", "nothing is guessed for a first time"); + await input.fill("0"); + await input.press("Enter"); + assert.equal(await input.getAttribute("aria-invalid"), "true", "0 hours is no window"); + await input.fill("30"); + await input.press("Enter"); + await page.waitForFunction(() => document.querySelector("#view-usage .none")); + assert.equal(asked.at(-1), "last:30h"); + assert.equal((await on()).trim(), w.h30); + assert.ok((await page.locator("#view-usage .none").textContent()).startsWith(w.none)); + assert.equal(await page.locator(".range-menu").count(), 0, "the menu closes on the pick"); + + // opened again: on the pick, and the menu has its number + asked.length = 0; + await page.reload(); + await settle(); + assert.equal(asked[0], "last:30h"); + assert.equal((await on()).trim(), w.h30); + input = await menu(); + assert.equal(await input.inputValue(), "30"); + + // 24 is the preset's own chip; 1 reads in the singular + await input.fill("24"); + await input.press("Enter"); + await settle(); + assert.equal(asked.at(-1), "last:24h"); + assert.equal(await page.locator("#period .range-opt.on").count(), 0); + input = await menu(); + await input.fill("1"); + await input.press("Enter"); + await settle(); + assert.equal((await on()).trim(), w.h1); + + // the menu bar's total names its own period, which isn't kept + asked.length = 0; + await page.goto("http://magpie.test/?view=usage&period=7d"); + await settle(); + assert.equal(asked[0], "7d"); + assert.deepEqual(errors, []); + }); + } +}