diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md index 30e41f3ff..d20644bce 100644 --- a/docs/subsystems/gui-shell.md +++ b/docs/subsystems/gui-shell.md @@ -53,6 +53,13 @@ refreshing it preserves local providers and other remote magpies. `usage-card-refresh.test.cjs` checks the real button in both browser engines and all five languages. A cached `readDeferred` card says no refresh was requested this time; a failed read retains its failure notice. +The tray panel's Allowances cards use the same `quotaRefresh`, at the +start of the line under the account (the reset deadline, the error, or a +balance's name), opened as the card is hovered or the button is focused. +That line names the deadline ("Resets 14:26"), so no bare `↻` stands for +it; `renderPanelQuota` puts the focus back on the button after the redraw. +`panel-quota-refresh.test.cjs` covers it in both engines, all five +languages, at 440 and 360px. ### Streamed output speed diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index c08d6fdc9..920aab35b 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -979,7 +979,7 @@ body.window .field.solo { grid-column: auto; } card's other lines do (#840) */ .quota-refresh { display: inline-flex; align-items: center; justify-content: center; width: 0; height: 14px; margin: 0; padding: 0; border: 0; border-radius: 4px; background: none; color: var(--faint); vertical-align: -3px; opacity: 0; overflow: hidden; cursor: pointer; transition: width .12s, margin .12s, opacity .12s; } .quota-refresh svg { flex: none; } -.subscription-card:hover .quota-refresh, .quota-refresh.busy { width: 14px; margin: 0 3px 0 -2px; opacity: 1; } +.subscription-card:hover .quota-refresh, .pq-card:hover .quota-refresh, .quota-refresh.busy { width: 14px; margin: 0 3px 0 -2px; opacity: 1; } /* apart: Safari before 15.4 drops a whole selector list with :focus-visible in it */ .quota-refresh:focus-visible { width: 14px; margin: 0 3px 0 -2px; opacity: 1; } .quota-refresh:hover { color: var(--fg); background: var(--pill-hover); } @@ -1813,6 +1813,12 @@ body.panel .profiles #save { height: 25px; } /* the field's: the line keeps its .pq-bn { display: flex; align-items: center; gap: 6px; } .pq-bn > span:last-child { min-width: 0; overflow: hidden; text-overflow: ellipsis; } .pq-bn .ic { width: 14px; height: 14px; flex: none; } +/* the card's own refresh before the logo: closed, the row's gap closed with + it; open, as wide as on the Usage page (#840) */ +.pq-bn > .quota-refresh { margin-right: -6px; } +.pq-card:hover .pq-bn > .quota-refresh, .pq-bn > .quota-refresh.busy { margin: 0 -3px 0 -2px; } +.pq-bn > .quota-refresh:focus-visible { margin: 0 -3px 0 -2px; } +@media (hover: none) { .pq-bn > .quota-refresh { margin: 0 -3px 0 -2px; } } .pq-amt { font-size: 15px; font-weight: 600; letter-spacing: -.01em; color: var(--fg); font-variant-numeric: tabular-nums; } /* a balance field's several amounts on a balance's card (#420) */ .pq-lead { display: flex; align-items: baseline; gap: 6px; min-width: 0; } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index c7182e689..13cac67c2 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -16050,6 +16050,9 @@ function renderPanelQuota() { // a row held in the arranging: drawn when it's let go if (usageArranging && box.querySelector(".pq-arow")) { usageRenderPending = true; return; } const view = box.closest(".view"), keep = view?.scrollTop; + // a card's own refresh keeps the keyboard's focus through the redraw + const focused = document.activeElement?.matches?.("#panelQuota .quota-refresh") + ? document.activeElement.closest(".pq-card")?.dataset.card : ""; const restoreFlash = keepQuotaFlash(box); box.replaceChildren(); if (none) { quotaFocus = ""; panelArranging = false; fit(); return; } @@ -16129,6 +16132,7 @@ function renderPanelQuota() { if (away.size) foot.append(el("span", "pq-hidden", t("{n} hidden", { n: away.size }))); box.append(foot); restoreFlash(); + if (focused) box.querySelector(`.pq-card[data-card="${CSS.escape(focused)}"] .quota-refresh`)?.focus({ preventScroll: true }); if (view && view.scrollTop !== keep && !box.querySelector(".pq-card.flash")) view.scrollTop = keep; panelAge(); fit(); @@ -16149,7 +16153,7 @@ function panelBalances(bals) { card.title = [q.name, q.user].filter(Boolean).join(" · "); // whose balance, at a glance: the provider's logo before its name const who = el("span", "pq-sub pq-bn"); - who.append(icon(q.icon || "generic"), el("span", "", q.name)); + who.append(quotaRefresh(q), icon(q.icon || "generic"), el("span", "", q.name)); card.append(who); // a balance field with several amounts: the first as the figure, // the others each a quiet line, a percent a meter (#420) @@ -16282,7 +16286,9 @@ function panelQuotaCard(q) { card.title = [q.name, q.alias, q.user, q.seat && q.seat !== q.alias && "≡ " + q.seat, q.plan, q.until ? planTerm(q) : "", q.balance && t("Balance") + " " + q.balance].filter(Boolean).join(" · "); if (q.error) { card.classList.add("err"); - card.append(el("span", "pq-sub err", quotaError(q.error))); + const why = el("span", "pq-sub err", quotaError(q.error)); + why.prepend(quotaRefresh(q)); + card.append(why); card.title += "\n" + q.error; return card; } @@ -16294,7 +16300,9 @@ function panelQuotaCard(q) { // a pool's 5-hour and weekly rings, two pools of them, else three const fam = familyWindows(q.windows.filter((w) => !w.unlimited)); if (!fam.length && q.windows.some((w) => w.unlimited)) { - card.append(el("span", "pq-sub", t("Unlimited"))); + const sub = el("span", "pq-sub", t("Unlimited")); + sub.prepend(quotaRefresh(q)); + card.append(sub); if (balance) card.append(balance); return card; } @@ -16304,19 +16312,23 @@ function panelQuotaCard(q) { const sub = el("span", "pq-sub", begun.length ? begun.map((w, i) => { const at = new Date(w.resetsAt); + // the first deadline named as one: a bare "↻ 14:26" read as a + // refresh to click (#840, hhh2210) return at <= Date.now() ? (i || w.members ? ringName(w) + " " : "") + resetText(at) - : (i || w.members ? ringName(w) + " " : "↻ ") + resetClock(at); + : i || w.members ? ringName(w) + " " + resetClock(at) : resetText(at); }).join(" · ") : t("Not used yet")); // The first window's own pace as well, in the line already about its // deadline: the thin line under it has no room for what it only hints at, // and a card with no readings of that window has nothing to say (#2079). // Only while that line is drawn (curves on), and only when the deadline - // the line names is that window's alone: after "↻ 14:26 · Weekly Oct 31" + // the line names is that window's alone: after "Resets 14:26 · Weekly Oct 31" // it would read as the week's. const line = quotaRange !== "off" && begun.length === 1 && begun[0] === ws[0] && !ws[0].tiers ? quotaWindowLine(q, ws[0]) : null; const pace = line ? quotaEtaText(line, Date.now()) : ""; if (pace) sub.append(el("span", "pq-pace", " · " + pace)); + // the card's own refresh, as on the Usage page: shown as it's hovered + sub.prepend(quotaRefresh(q)); card.append(sub); const rings = el("span", "pq-rings"); for (const w of ws) { diff --git a/internal/gui/tests/panel-quota-refresh.test.cjs b/internal/gui/tests/panel-quota-refresh.test.cjs new file mode 100644 index 000000000..007dae139 --- /dev/null +++ b/internal/gui/tests/panel-quota-refresh.test.cjs @@ -0,0 +1,160 @@ +// #840 (hhh2210): the tray's Allowances tab names a card's reset deadline +// ("Resets 14:26", not a bare "↻ 14:26" that read as a button to click), +// and each card has the Usage page's own refresh: opened as the card is +// hovered or the key reaches it, reading that account alone, the page not +// moving and the focus kept. Real page, isolated responses: no vendor, +// account or installed app is used. +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 = process.env.MAGPIE_QUOTA_ASSETS || path.resolve(__dirname, "../assets"); +const iso = n => new Date(n).toISOString(); +const words = { + en: { reset: "Resets", label: "Refresh this card" }, + zh: { reset: "重置于", label: "刷新这张卡片" }, + "zh-TW": { reset: "重置於", label: "重新整理這張卡片" }, + ja: { reset: "にリセット", label: "このカードを更新" }, + de: { reset: "Zurückgesetzt", label: "Diese Karte aktualisieren" }, +}; +function fixtures() { + const now = Date.now(), readAt = iso(now - 40 * 60000), resetsAt = iso(now + 2 * 3600000); + return [ + { provider: "claude", name: "Claude Code", icon: "claude-color", user: "a@example.com", plan: "Pro", readAt, asOf: readAt, readDeferred: true, windows: [{ name: "5 hours", used: 28, resetsAt }] }, + { provider: "codex", name: "Codex", icon: "openai", user: "b@example.com", plan: "Pro", readAt, windows: [{ name: "5 hours", used: 50, resetsAt }] }, + { provider: "kimi", name: "Kimi", error: "HTTP 503", windows: [] }, + { provider: "relay", name: "Relay", balance: "$2.00", readAt, windows: [] }, + { provider: "unlimited", name: "Unlimited plan", readAt, windows: [{ name: "Requests", unlimited: true }] }, + ]; +} +function serve(lang, data) { + const settings = { theme: "light", lang, tray: "panel", quotaLeft: false, currency: "usd" }; + return async route => { + const url = new URL(route.request().url()), json = body => route.fulfill({ json: body }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = ${JSON.stringify({ 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/quotas") { data.gets++; return json(data.quotas); } + if (url.pathname === "/api/usage/quotas/refresh") { + assert.equal(route.request().method(), "POST"); + data.posts.push(url.search); + await data.gate; + if (data.behavior === "fail") return route.fulfill({ status: 503, body: "fixture offline" }); + const q = data.quotas.find(q => q.provider === url.searchParams.get("provider") && (q.user || "") === (url.searchParams.get("user") || "")); + assert.ok(q, "refresh addressed a different account"); + if (data.behavior !== "cached") { + delete q.error; delete q.asOf; delete q.readDeferred; + q.readAt = iso(Date.now()); + if (q.balance) q.balance = "$3.00"; + else if (!q.windows.length) q.windows = [{ name: "Week", used: 10 }]; + else if (!q.windows[0].unlimited) q.windows[0].used = 61; + } + return json(data.quotas); + } + if (url.pathname === "/api/usage/quotas/history") return json([]); + if (url.pathname === "/api/usage") return json({ calls: 0, cost: 0, days: [], agents: [], models: [], keys: [] }); + if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + try { await route.fulfill({ body: await fs.readFile(file), contentType }); } + catch { await route.fulfill({ status: 404, body: "" }); } + }; +} +async function open(t, engine, lang, width = 440) { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await browser.newPage({ viewport: { width, height: 640 }, reducedMotion: "reduce" }); + page.setDefaultTimeout(5000); + const errors = [], data = { quotas: fixtures(), gets: 0, posts: [], behavior: "fresh" }; + page.on("pageerror", e => errors.push(e.message)); + await page.route("**/*", serve(lang, data)); + await page.goto("http://magpie.test/?mode=panel"); + await page.locator('#ptabs [data-ptab="usage"]').click(); + await page.locator('.pq-card[data-card="claude|a@example.com"]').waitFor(); + await page.evaluate(() => quotasLoading); + return { page, data, errors }; +} +const shown = (b) => b.evaluate((x) => x.getBoundingClientRect().width >= 12 && getComputedStyle(x).opacity === "1"); +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const [lang, w] of Object.entries(words)) { + for (const width of [440, 360]) { + test(`${engine} ${lang} ${width}px: a tray card's reset deadline is named, and its own refresh reads that account alone`, async (t) => { + const { page, data, errors } = await open(t, engine, lang, width); + await page.mouse.move(1, 1); + const card = page.locator('.pq-card[data-card="codex|b@example.com"]'); + const deadline = card.locator("> .pq-sub").first(); + const text = await deadline.textContent(); + assert.ok(text.includes(w.reset), `the deadline says ${w.reset}, got ${text}`); + assert.ok(!text.includes("↻"), "no bare ↻ standing for a deadline"); + + // every kind of tray card has the one refresh, closed at rest + for (const id of ["claude|a@example.com", "codex|b@example.com", "kimi", "relay", "unlimited"]) { + const b = page.locator(`.pq-card[data-card="${id}"] .quota-refresh`); + assert.equal(await b.count(), 1, `${id} has its own refresh`); + assert.equal(await b.getAttribute("aria-label"), w.label); + assert.equal(await shown(b), false, `${id}'s refresh is closed until hovered`); + // closed, it takes no room: the card and its line's text sit where they did + const [was, without] = await b.evaluate((x) => { + const at = () => { const c = x.closest(".pq-card").getBoundingClientRect(), n = x.nextSibling, r = document.createRange(); r.selectNodeContents(n || x.parentElement); return [c.height, Math.round(r.getBoundingClientRect().left)]; }; + const a = at(); x.style.display = "none"; const z = at(); x.style.display = ""; return [a, z]; + }); + assert.deepEqual(was, without, `${id}'s closed refresh moves nothing`); + } + const button = card.locator(".quota-refresh"); + await card.hover(); + await page.waitForFunction((b) => b.getBoundingClientRect().width >= 12, await button.elementHandle()); + assert.ok(await shown(button), "hovering the card opens its refresh"); + await page.mouse.move(1, 1); + + // the key reaches it (macOS WebKit tabs to buttons with Option-Tab) + const tab = engine === "webkit" && process.platform === "darwin" ? "Alt+Tab" : "Tab"; + for (let i = 0; i < 60 && !(await button.evaluate((b) => b === document.activeElement)); i++) await page.keyboard.press(tab); + assert.ok(await button.evaluate((b) => b === document.activeElement), "the refresh is reachable by keyboard"); + assert.ok(await shown(button), "focused, the refresh is in sight"); + + const scroll = () => page.evaluate(() => [scrollY, document.querySelector("#panelQuota").closest(".view").scrollTop]); + const y = await scroll(), gets = data.gets; + let release; data.gate = new Promise((r) => { release = r; }); t.after(() => release()); + await page.keyboard.press("Enter"); + await card.locator(".quota-refresh.busy").waitFor(); + await page.keyboard.press("Enter"); // a second press while reading asks nothing more + release(); data.gate = null; + await card.locator(".pq-dial b", { hasText: "61%" }).waitFor(); + assert.deepEqual(data.posts, ["?provider=codex&user=b%40example.com"], "that account alone, once"); + assert.equal(data.gets, gets, "no read of every account"); + assert.equal(await page.locator('.pq-card[data-card="claude|a@example.com"] .pq-dial b').first().textContent(), "28%", "another card left as it was"); + assert.ok(await page.locator('.pq-card[data-card="codex|b@example.com"] .quota-refresh').evaluate((b) => b === document.activeElement), "the redraw keeps the focus"); + assert.deepEqual(await scroll(), y, "a refresh never moves the page"); + + // a failed read: the figures stay, the failure is said + data.behavior = "fail"; + await page.keyboard.press("Enter"); + await page.locator("#status.err").waitFor({ state: "visible" }); + assert.equal(await card.locator(".pq-dial b").first().textContent(), "61%", "a failure keeps what was read"); + + // an error card and a balance read again from the tray too + data.behavior = "fresh"; + await page.locator('.pq-card[data-card="kimi"] .quota-refresh').focus(); + await page.keyboard.press("Enter"); + await page.locator('.pq-card[data-card="kimi"] .pq-dial b', { hasText: "10%" }).waitFor(); + await page.locator('.pq-card[data-card="relay"] .quota-refresh').focus(); + await page.keyboard.press("Enter"); + await page.locator('.pq-card[data-card="relay"] .pq-amt', { hasText: "$3.00" }).waitFor(); + assert.deepEqual(data.posts.slice(-2), ["?provider=kimi", "?provider=relay"]); + + assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), "nothing wider than the panel"); + if (process.env.ARTIFACT_DIR) { + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + await card.hover(); + await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `panel-refresh-${engine}-${lang}-${width}.png`), fullPage: true }); + } + assert.deepEqual(errors, []); + }); + } + } +} diff --git a/internal/gui/tests/quota-curve.test.cjs b/internal/gui/tests/quota-curve.test.cjs index 3dd02a1bd..3d8ef69ed 100644 --- a/internal/gui/tests/quota-curve.test.cjs +++ b/internal/gui/tests/quota-curve.test.cjs @@ -392,7 +392,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.equal(await spark.locator("path.qc-line").count(), 1); assert.equal((((await spark.locator("path.qc-line").getAttribute("d")).match(/M/g)) || []).length, 1, "the current cycle only"); assert.equal(await spark.locator("line.qc-even").count(), 1); - // Both windows begun: the line reads "↻ 14:26 · Weekly …", and a pace + // Both windows begun: the line names both reset times, and a pace // after it would read as the week's, so none is said there (#2079) assert.equal(await pcard.locator(".pq-pace").count(), 0, "no pace beside another window's deadline"); // the 5-hour window the only one begun: its pace, by its deadline @@ -412,7 +412,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const scard = silent.locator(".pq-card", { hasText: "a@x.com" }); await scard.waitFor(); assert.equal(await scard.locator(".pq-pace").count(), 0, "nothing to say, nothing said"); - assert.ok((await scard.locator(".pq-sub").textContent()).includes("↻"), "the deadline is still said"); + assert.ok((await scard.locator(".pq-sub").textContent()).includes(lang === "zh" ? "重置于" : "Resets"), "the deadline is still named"); // the line ends at now already; in 16px a dotted now line read as a // stray mark under the curve (#1601) assert.equal(await spark.locator("line.qc-now").count(), 0, "no now line in the thin spark");