diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md index 277757c48..e0b8c6818 100644 --- a/docs/subsystems/gui-shell.md +++ b/docs/subsystems/gui-shell.md @@ -60,6 +60,9 @@ 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. +Redrawing the cards preserves their refresh controls and any running turn. +The reply updates the reading immediately; the icon then finishes its +current full turn before stopping (no rotation under reduced motion). ### Streamed output speed diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 8b25e294e..88627ec1f 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -985,14 +985,20 @@ body.window .field.solo { grid-column: auto; } /* a card's own refresh, left of when it was read (or of why it couldn't be), opening as the card is hovered: at rest the line starts where the 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, .pq-card:hover .quota-refresh, .quota-refresh.busy { width: 14px; margin: 0 3px 0 -2px; opacity: 1; } +.quota-refresh { display: inline-grid; place-items: center; width: 0; margin: 0; padding: 0; border: 0; border-radius: 4px; background: none; color: var(--faint); vertical-align: baseline; opacity: 0; overflow: hidden; cursor: pointer; transition: width .12s, margin .12s, opacity .12s; } +/* Inherited text supplies the inline baseline; the icon shares its centered cell. */ +.quota-refresh::before { content: "\00a0"; grid-area: 1 / 1; } +.quota-refresh svg { grid-area: 1 / 1; } +.subscription-card:hover .quota-refresh, .pq-card:hover .quota-refresh, .quota-refresh.busy, .quota-refresh.kept { 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); } .quota-refresh.busy { cursor: default; } -.quota-refresh.busy svg > * { transform-box: view-box; transform-origin: 50% 50%; animation: spin .8s linear infinite; } +.quota-refresh.busy svg > * { transform-box: view-box; transform-origin: 50% 50%; } +/* the other place's copy of a control that is turning (the tray panel's and the + Usage page's draw the same account) turns by itself */ +.quota-refresh.spun svg > * { animation: spin .8s linear infinite; } +@media (prefers-reduced-motion: reduce) { .quota-refresh.spun svg > * { animation: none; } } @media (hover: none) { .quota-refresh { width: 14px; margin: 0 3px 0 -2px; opacity: 1; } } @media (prefers-reduced-motion: reduce) { .quota-refresh { transition: none; } } .skeleton { display: block; border-radius: 5px; background: linear-gradient(90deg, var(--skel, var(--pill)) 25%, var(--skel-hi, var(--pill-hover)) 45%, var(--skel, var(--pill)) 65%); background-size: 240% 100%; animation: skeleton-shift 1.4s ease-in-out infinite; } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 3c5716a30..d0bcf1477 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -15093,6 +15093,7 @@ function renderQuotas() { renderPanelQuota(); const subscriptions = $("#subscriptionUsage"); const restoreFlash = keepQuotaFlash(subscriptions); + const restoreRefresh = keepQuotaRefresh(subscriptions); subscriptions.replaceChildren(); // the allowances' own heading, apart from the period's cost: used or // left turns their meters, and is only there when some card has one (a @@ -15119,9 +15120,10 @@ function renderQuotas() { subscriptions.append(card); } packUsageNow(subscriptions); + restoreRefresh(); return; } - if (usageArranging) { usageRenderPending = true; return; } + if (usageArranging) { usageRenderPending = true; restoreRefresh(); return; } subscriptions.hidden = !quotas.length; // an agent with several accounts is one card, a section per account const groups = []; @@ -15240,6 +15242,7 @@ function renderQuotas() { markUpstream(); packUsageNow(subscriptions); restoreFlash(); + restoreRefresh(); requestAnimationFrame(focusQuotaCard); } @@ -17554,20 +17557,43 @@ setInterval(() => { // as they were read (Hu9956, #840: 单独刷新某个套餐,而不用刷新全部). A // Claude account's is read by running Claude Code's own /usage, as the // page's Refresh does. -const quotaRefreshing = new Set(); +const quotaRefreshing = new Map(); +let keptQuotaRefresh = null; +// a redraw reuses the controls, so no reading restarts their motion +function keepQuotaRefresh(box) { + const buttons = [...box.querySelectorAll(".quota-refresh")]; + const focused = buttons.find(b => b === document.activeElement); + keptQuotaRefresh = new Map(buttons.map(b => [b.dataset.key, b])); + const shown = buttons.filter(b => b.getBoundingClientRect().width > 0); + for (const b of shown) b.classList.add("kept"); + return () => { + keptQuotaRefresh = null; + if (focused?.isConnected) focused.focus({ preventScroll: true }); + // a frame for the new hover state, so the reading doesn't slide + requestAnimationFrame(() => { for (const b of shown) b.classList.remove("kept"); }); + }; +} function quotaRefresh(q) { const key = usageAcctKey(q); - const b = el("button", "quota-refresh" + (quotaRefreshing.has(key) ? " busy" : "")); + // only one its redraw took out: the panel and Usage page each draw it + const kept = [quotaRefreshing.get(key)?.button, keptQuotaRefresh?.get(key)].find((k) => k && !k.isConnected); + const b = kept || el("button", "quota-refresh"); + if (quotaRefreshing.has(key) && b !== quotaRefreshing.get(key).button) b.classList.add("busy", "spun"); + b.dataset.key = key; b.type = "button"; b.title = t(q.provider === "claude" ? "Read this card again, by running Claude Code's own /usage" : "Read this card again"); b.setAttribute("aria-label", t("Refresh this card")); - b.innerHTML = ''; + if (!kept) b.innerHTML = ''; b.onclick = async (e) => { e.stopPropagation(); if (quotaRefreshing.has(key)) return; - quotaRefreshing.add(key); for (const k of quotaCycleHolds.keys()) if (k.startsWith(key + "\0")) quotaCycleHolds.delete(k); b.classList.add("busy"); + const animation = !calm() && b.querySelector("path").animate([ + { transform: "rotate(0deg)" }, { transform: "rotate(360deg)" }, + ], { duration: 800, iterations: Infinity }); + const refreshing = { button: b, animation }; + quotaRefreshing.set(key, refreshing); const began = quotaRefreshVersion; try { const qs = await api("usage/quotas/refresh?provider=" + encodeURIComponent(q.provider) + (q.user ? "&user=" + encodeURIComponent(q.user) : ""), {}); @@ -17599,8 +17625,20 @@ function quotaRefresh(q) { } catch (err) { status(err.message, "err"); } finally { - quotaRefreshing.delete(key); + // the reading now; the icon ends its turn (at least one) renderQuotas(); + const done = () => { + if (quotaRefreshing.get(key) !== refreshing) return; + quotaRefreshing.delete(key); + b.classList.remove("busy"); + for (const o of document.querySelectorAll(".quota-refresh.spun")) if (o.dataset.key === key) o.classList.remove("busy", "spun"); + if (animation) animation.cancel(); + }; + if (animation && !calm()) { + const duration = animation.effect.getTiming().duration; + animation.effect.updateTiming({ iterations: Math.max(1, Math.ceil((animation.currentTime || 0) / duration)) }); + animation.finished.then(done, done); + } else done(); } }; return b; diff --git a/internal/gui/core_budget_test.go b/internal/gui/core_budget_test.go index 129d11b41..53375637e 100644 --- a/internal/gui/core_budget_test.go +++ b/internal/gui/core_budget_test.go @@ -15,7 +15,7 @@ import ( // so a page can't quietly grow back into the core; a change that needs more // raises them and says why in its commit. const ( - appScriptBudget = 1_250_000 // app.js: 1,198,239 after Usage left (P2); 1,218,098 with the 10-15 fixes to pages still in the core; 1,232,466 with the provider editor's Advanced fold and every dialog holding its place, the core's own (10-16) + appScriptBudget = 1_269_000 // app.js: 1,198,239 after Usage left (P2); 1,218,098 with the 10-15 fixes to pages still in the core; 1,232,466 with the provider editor's Advanced fold and every dialog holding its place, the core's own (10-16); 1,250,533 with the quota refresh kept through redraws, the core's own since the tray panel draws it too, plus 1.5% (#2397) coreScriptBudget = 1_447_000 // every core script: 1,358,034 after Usage left; 1,380,003 with them; 1,405,937 with the fold; 1,426,102 with 10-16's core work (the GitHub list loading, the move to plugins, Settings › Long conversations), plus 1.5% (#2612) ) diff --git a/internal/gui/tests/quota-refresh-order.test.cjs b/internal/gui/tests/quota-refresh-order.test.cjs index e510b9c25..248ce302d 100644 --- a/internal/gui/tests/quota-refresh-order.test.cjs +++ b/internal/gui/tests/quota-refresh-order.test.cjs @@ -23,7 +23,9 @@ function page() { const usageAcctKey = q => q.provider + "\\n" + (q.user || "").toLowerCase(); const quotaCycleHolds = new Map(); // past cycles' estimates (#2009), cleared by a refresh const t = x => x; - const el = () => ({ classList: { add() {} }, setAttribute() {} }); + const calm = () => true; + const document = { querySelectorAll: () => [] }; + const el = () => ({ dataset: {}, classList: { add() {}, remove() {} }, setAttribute() {} }); function renderQuotas() {} function loadUpstream() {} function status(x) { errors.push(x); } diff --git a/internal/gui/tests/usage-card-refresh.test.cjs b/internal/gui/tests/usage-card-refresh.test.cjs index ad5b8e285..9508042cd 100644 --- a/internal/gui/tests/usage-card-refresh.test.cjs +++ b/internal/gui/tests/usage-card-refresh.test.cjs @@ -5,13 +5,15 @@ // at rest the line starts where the card's others do. A click reads that card alone // (POST /api/usage/quotas/refresh?provider=&user=), turns while it does, and // draws what came back; no other card is asked, and the page doesn't scroll. -// Button controls in English and Chinese; refresh ordering and deferred -// readings in all five languages. No backend: the API is faked here. +// Button controls in English and Chinese; refresh ordering, deferred +// readings and icon alignment in all five languages, wide and narrow. +// 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 { inView } = require("./reader.cjs"); const assets = process.env.MAGPIE_QUOTA_ASSETS || path.resolve(__dirname, "../assets"); const H = 3600e3, M = 60e3; @@ -38,7 +40,7 @@ function serve(lang, state) { 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/providers") return json({ providers: state.providers || [], presets: [], excluded: [], gateway: { running: true, window: true } }); if (url.pathname === "/api/usage/quotas") { state.gets++; const snapshot = JSON.parse(JSON.stringify(state.quotas)); @@ -120,6 +122,149 @@ const words = { zh: { updated: "40分钟前更新", label: "刷新这张卡片", now: /^(刚刚|\d+秒前)更新$/ }, }; +function layoutFixtures(now) { + const quotas = fixtures(now); + quotas[0].asOf = quotas[0].readAt; + quotas[0].windows[0].resetsAt = iso(now - H); + quotas[1].readAt = iso(now); + // The provider's real missing-access-key reply, including its settings action. + quotas[2] = { provider: "volcengine", name: "Volcengine Ark", icon: "volcengine", plan: "Coding Plan", windows: [], needsAccessKey: true, + error: "this plan's usage is read with the account's access key: give its AccessKey ID and Secret in Volcengine Ark's settings" }; + return { quotas, gets: 0, refreshes: [], providers: [ + { id: "volcengine", name: "Volcengine Ark", icon: "volcengine", preset: "volcengine", chat: "https://ark.cn-beijing.volces.com/api/coding/v3", + responses: "", anthropic: "", catalog: "", models: [], agents: [], fallback: [], headers: {}, key: { set: true, masked: "test-key" }, keyList: [], + accessKey: { vendor: "volcengine", id: "", secretSet: false } }, + ] }; +} + +async function showRefresh(row) { + await row.hover(); + await row.locator(".quota-refresh").evaluate(e => new Promise(done => { + const tick = () => getComputedStyle(e).opacity === "1" && e.getBoundingClientRect().width >= 14 ? done() : requestAnimationFrame(tick); + tick(); + })); +} + +async function assertRefreshAligned(row) { + const boxes = await row.evaluate((e) => { + const button = e.querySelector(".quota-refresh"); + const text = e.querySelector(".quota-ago")?.firstChild || [...e.childNodes].find(n => n.nodeType === Node.TEXT_NODE && n.textContent.trim()); + const range = document.createRange(); + range.selectNodeContents(text); + const rect = (r) => ({ x: r.x, right: r.right, cy: r.y + r.height / 2 }); + return { icon: rect(button.querySelector("svg").getBoundingClientRect()), text: rect(range.getClientRects()[0]) }; + }); + assert.ok(boxes.icon.right <= boxes.text.x, "the refresh icon stays left of the first line"); + assert.ok(Math.abs(boxes.icon.cy - boxes.text.cy) <= 0.75, + "the refresh icon and the first text line must share a vertical center: " + JSON.stringify(boxes)); +} + +async function assertInlineSettings(row, multiline) { + const layout = await row.evaluate(e => { + const range = document.createRange(); + range.selectNodeContents([...e.childNodes].find(n => n.nodeType === Node.TEXT_NODE && n.textContent.trim())); + const rect = r => ({ x: r.x, y: r.y, right: r.right, bottom: r.bottom, width: r.width, height: r.height }); + return { row: rect(e.getBoundingClientRect()), text: [...range.getClientRects()].map(rect), settings: rect(e.querySelector(".quota-fix").getBoundingClientRect()) }; + }); + if (multiline) assert.ok(layout.text.length > 1, "the narrow-window fixture really wraps"); + for (const line of [...layout.text, layout.settings]) { + assert.ok(line.x >= layout.row.x - 0.75 && line.right <= layout.row.right + 0.75, "the error and settings fit the card: " + JSON.stringify(layout)); + } + for (const line of layout.text.slice(1)) assert.ok(Math.abs(line.x - layout.row.x) < 0.75, "wrapped text uses the full row, not an indented flex item"); + const last = layout.text.at(-1), go = layout.settings; + if (last.right + go.width + 5 < layout.row.right) { + assert.ok(go.y < last.bottom && go.bottom > last.y && go.x >= last.right, + "settings follows the last text line when it fits: " + JSON.stringify(layout)); + } +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(`${engine}: a refresh keeps its turn and reading position through redraws, then finishes a whole turn`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await browser.newPage({ viewport: { width: 1250, height: 900 }, reducedMotion: "no-preference" }); + page.setDefaultTimeout(5000); + const errors = []; + page.on("pageerror", e => errors.push(e.message)); + let release, releaseRead, readStarted; + const state = { quotas: fixtures(Date.now()), gets: 0, refreshes: [], gate: new Promise(r => { release = r; }) }; + t.after(() => { release(); releaseRead?.(); }); + await page.route("**/*", serve("zh", state)); + await page.goto("http://magpie.test/?view=usage"); + const row = page.locator('.subscription-card[data-provider="codex"] .quota-read'); + await showRefresh(row); + const started = new Promise(r => { readStarted = r; }); + state.readStarted = readStarted; + state.readGate = new Promise(r => { releaseRead = r; }); + await page.evaluate(() => { void loadQuotas(); }); + await started; + await row.locator(".quota-refresh").click(); + await row.evaluate(e => { + const button = e.querySelector(".quota-refresh"), animation = button.querySelector("path").getAnimations()[0]; + animation.pause(); + animation.currentTime = 1200; // Mid-turn, independent of the runner's speed. + window.refreshMotion = { button, animation, x: e.querySelector(".quota-ago").getBoundingClientRect().x }; + }); + releaseRead(); + await page.evaluate(() => quotasLoading); + assert.equal(await row.evaluate(e => e.querySelector(".quota-refresh") === window.refreshMotion.button), true, "a background reading replaced the spinning control"); + assert.equal(await row.evaluate(e => e.querySelector("path").getAnimations()[0] === window.refreshMotion.animation), true, "a background reading restarted the turn"); + release(); + await page.locator('.subscription-card[data-provider="codex"] .quota-n', { hasText: "61%" }).waitFor(); + const end = await row.evaluate(e => { + const { button, animation, x } = window.refreshMotion; + return { same: e.querySelector(".quota-refresh") === button, busy: button.classList.contains("busy"), time: animation.currentTime, + turns: animation.effect.getTiming().iterations, duration: animation.effect.getTiming().duration, shift: e.querySelector(".quota-ago").getBoundingClientRect().x - x }; + }); + assert.deepEqual(end, { same: true, busy: true, time: 1200, turns: 2, duration: 800, shift: 0 }, "the reply interrupted the turn or shifted the reading"); + await page.evaluate(() => window.refreshMotion.animation.finish()); + await row.locator(".quota-refresh:not(.busy)").waitFor(); + assert.equal(await row.evaluate(e => e.querySelector(".quota-refresh") === window.refreshMotion.button && getComputedStyle(window.refreshMotion.button).opacity === "1"), true, "finishing the turn hid or replaced the button"); + // A response already available still gets one complete turn. + state.gate = undefined; + await row.locator(".quota-refresh").click(); + await page.waitForFunction(() => document.querySelector('.subscription-card[data-provider="codex"] path').getAnimations()[0]?.effect.getTiming().iterations === 1); + await row.evaluate(e => e.querySelector("path").getAnimations()[0].finish()); + await row.locator(".quota-refresh:not(.busy)").waitFor(); + assert.deepEqual(errors, []); + }); +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of Object.keys(deferredWords)) { + for (const width of [900, 420]) test(`${engine} ${lang} ${width}px: refresh icons align with their reading or error`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await browser.newPage({ viewport: { width, height: 800 }, reducedMotion: "reduce" }); + page.setDefaultTimeout(5000); + const errors = []; + page.on("pageerror", e => errors.push(e.message)); + const now = Date.now(); + const state = layoutFixtures(now); + await page.route("**/*", serve(lang, state)); + await page.goto("http://magpie.test/?view=usage"); + + // Fresh, stale and balance readings, plus a failed reading's first line. + for (const name of ["Codex", "Claude Code", "Relay", "Volcengine Ark"]) { + const card = page.locator(".subscription-card", { hasText: name }); + const row = card.locator(".quota-read, .subscription-error"); + await inView(page, row); + await showRefresh(row); + await assertRefreshAligned(row); + } + const error = page.locator(".subscription-error"); + await assertInlineSettings(error, width === 420); + await inView(page, error); + await error.locator(".quota-fix").click(); + await page.waitForURL(/view=providers/); + assert.equal(new URL(page.url()).searchParams.get("edit"), "volcengine"); + await page.locator(".editor .volc-ak").waitFor(); + assert.deepEqual(state.refreshes, [], "showing a card's refresh doesn't read it"); + assert.deepEqual(errors, []); + }); + } +} + for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { for (const lang of ["en", "zh"]) { const w = words[lang]; @@ -157,6 +302,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.equal(await opacity(), "1"); const [b, when] = [await btn.boundingBox(), await ago.boundingBox()]; assert.ok(b.width >= 14 && b.x + b.width <= when.x + 0.5 && Math.abs(b.y + b.height / 2 - (when.y + when.height / 2)) < 4, JSON.stringify({ b, when })); + await assertRefreshAligned(read); // a failed reading and a balance have one too const kimi = page.locator(".subscription-card", { hasText: "Kimi" }); @@ -172,6 +318,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await btn.click(); await page.waitForFunction(() => document.querySelector(".quota-refresh.busy")); assert.equal(await claude.locator(".quota-refresh.busy").count(), 1, "turns while it reads"); + await assertRefreshAligned(read); open(); await claude.locator(".quota-n", { hasText: "61%" }).waitFor(); assert.deepEqual(state.refreshes, ["?provider=claude&user=a%40x.com"]);