diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 567fbb80d..7180b06b2 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -16966,6 +16966,18 @@ function planSpan(q) { // move (panelArrange); panelPeek: the card a menu bar cell asked for, shown // though the tab hides it, until the panel is put away or the tab left. let panelArranging = false, panelPeek = ""; +// the Allowances tab's cards at 0 (quotaAtZero) in sight, as the reader chose +let panelZeroOpen = kept("panelZeroOpen", false); +// quotaAtZero: a fresh reading with nothing left: each window used up and +// any balance 0 or less (runking on Discord); not a failed or old one, a +// percent, a text or unlimited window, Codex's credits, resets or a check-in +function quotaAtZero(q) { + if (q.error || q.asOf || q.resets?.count || q.checkins || creditsOn(q)) return false; + const ns = (q.balanceParts?.length ? q.balanceParts.map((p) => p.text) : q.balance ? [q.balance] : []).map((s) => String(s || "").match(/^(-?)[^\d-]*(-?)(\d[\d,]*(?:\.\d+)?)[^\d%]*$/)); + const ws = q.windows || []; + return ws.length + ns.length > 0 && ns.every((m) => m && (m[1] || m[2] || !(+m[3].replace(/,/g, "") > 0))) + && ws.every((w) => w.heldBy || (w.balance != null ? !(w.balance > 0) : !w.unlimited && !quotaNoShare(w) && w.used >= 100)); +} if (mode === "panel") document.addEventListener("visibilitychange", () => { if (!document.hidden) return; // an account its eye showed is hidden again once the panel is put away @@ -17356,7 +17368,7 @@ function renderPanelUse() { function renderPanelQuota(lazy) { const box = $("#panelQuota"); if (mode !== "panel" || !box) return; - const drawn = JSON.stringify([quotas, quotaHistV, quotaLeft, quotaRange, [...panelOptsFolded], state?.settings, locale, panelTab, panelPeek, panelArranging, usageArranging, Math.floor(Date.now() / 60e3)]); + const drawn = JSON.stringify([quotas, quotaHistV, quotaLeft, quotaRange, [...panelOptsFolded], state?.settings, locale, panelTab, panelPeek, panelArranging, panelZeroOpen, usageArranging, Math.floor(Date.now() / 60e3)]); if (lazy && renderPanelQuota.drawn === drawn) return; renderPanelQuota.drawn = drawn; const subs = byUsageOrder(keyCards(quotas || []).filter((q) => q.balance || q.error || q.windows?.length)); @@ -17399,6 +17411,9 @@ function renderPanelQuota(lazy) { const hidden = new Set(state.settings?.panelUsageHidden || []); const peek = (q) => !!panelPeek && (trayCardID(q) === panelPeek || q.balanceCard === panelPeek || q.provider === panelPeek); const away = new Set(subs.filter((q) => hidden.has(q.provider) && !peek(q)).map((q) => q.provider)); + // a balance, or a vendor's every account, at 0: behind the foot's button + const zero = new Set(subs.filter((q) => quotaAtZero(q) && !peek(q))); + let atZero = 0; // the sections in order: a vendor's accounts, or a run of balances const parts = [], groups = new Map(); for (const q of subs) { @@ -17406,6 +17421,7 @@ function renderPanelQuota(lazy) { // a balance with windows (Command Code's credits beside its 5-hour and // weekly windows) is the windows' card; a balance alone, a figure if (q.balance && !q.windows?.length) { + if (zero.has(q) && ++atZero && !panelZeroOpen) continue; const last = parts[parts.length - 1]; if (last?.bals) last.bals.push(q); else parts.push({ bals: [q] }); @@ -17417,6 +17433,7 @@ function renderPanelQuota(lazy) { for (const part of parts) { if (part.bals) { box.append(panelBalances(part.bals)); continue; } const { name, qs } = part; + if (qs.every((q) => zero.has(q)) && (atZero += qs.length) && !panelZeroOpen) continue; const g = el("div", "pq-group"); const head = el("div", "pq-gh"); head.append(icon(qs[0].icon), el("span", "pq-gn", name)); @@ -17454,6 +17471,14 @@ function renderPanelQuota(lazy) { arrange.title = t("Choose which subscriptions this tab shows, and their order"); arrange.onclick = () => { panelArranging = true; panelPeek = ""; renderPanelQuota(); $("#panelQuota .pq-arow .pq-ahandle")?.focus(NO_SCROLL); }; foot.append(arrange); + if (atZero) { + const z = el("button", "pq-more pq-zero", panelZeroOpen ? t("Fold the ones at 0") : t("{n} at 0", { n: atZero })); + z.type = "button"; + z.title = t("Nothing left here: every window used up, or a balance of 0"); + z.setAttribute("aria-expanded", String(panelZeroOpen)); + z.onclick = () => { panelZeroOpen = !panelZeroOpen; try { localStorage.setItem("magpie.panelZeroOpen", panelZeroOpen); } catch {} renderPanelQuota(); box.querySelector(".pq-zero")?.focus(NO_SCROLL); }; + foot.append(z); + } if (away.size) foot.append(el("span", "pq-hidden", t("{n} hidden", { n: away.size }))); box.append(foot); restoreFlash(); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 5486a560d..b0c73d318 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -610,6 +610,9 @@ const I18N = { "Drag to put them in the order {agent} lists them; new models go last": "拖动排列 {agent} 列表中的顺序;新模型排在最后", "Drag to put them in the order magpie hands them to {agent}; new models go last": "拖动排列 magpie 交给 {agent} 的模型顺序;新模型排在最后", "{n} hidden": "已隐藏 {n} 个", + "{n} at 0": "{n} 个为 0", + "Fold the ones at 0": "收起为 0 的", + "Nothing left here: every window used up, or a balance of 0": "已没有剩余额度的账号和密钥:每个额度窗口都已用完,或余额为 0", "{n} hidden agents": "已隐藏的 Agent({n} 个)", "Hidden ({n})": "已隐藏({n})", "Hidden by you · click to see them": "你隐藏的 Agent · 点击查看", @@ -5226,6 +5229,9 @@ const I18N = { "Drag to put them in the order {agent} lists them; new models go last": "拖動排列 {agent} 列表中的順序;新模型排在最後", "Drag to put them in the order magpie hands them to {agent}; new models go last": "拖動排列 magpie 交給 {agent} 的模型順序;新模型排在最後", "{n} hidden": "已隱藏 {n} 個", + "{n} at 0": "{n} 個為 0", + "Fold the ones at 0": "收起為 0 的", + "Nothing left here: every window used up, or a balance of 0": "已沒有剩餘額度的帳號和金鑰:每個額度時段都已用完,或餘額為 0", "{n} hidden agents": "已隱藏的 Agent({n} 個)", "Hidden ({n})": "已隱藏({n})", "Hidden by you · click to see them": "你隱藏的 Agent · 點擊查看", @@ -9807,6 +9813,9 @@ const I18N = { "Drag to put them in the order {agent} lists them; new models go last": "ドラッグで {agent} の一覧の並び順を変更。新しいモデルは末尾に追加されます", "Drag to put them in the order magpie hands them to {agent}; new models go last": "ドラッグで magpie が {agent} に渡すモデルの並び順を変更。新しいモデルは末尾に追加されます", "{n} hidden": "{n} 件非表示", + "{n} at 0": "{n} 件が 0", + "Fold the ones at 0": "0 のものをたたむ", + "Nothing left here: every window used up, or a balance of 0": "残りがないアカウントとキー:すべてのウィンドウを使い切ったか、残高が 0", "{n} hidden agents": "非表示のエージェント({n})", "Hidden ({n})": "非表示({n})", "Hidden by you · click to see them": "自分で非表示にしたエージェント · クリックで表示", @@ -14406,6 +14415,9 @@ const I18N = { "Drag to put them in the order {agent} lists them; new models go last": "Ziehen, um die Reihenfolge in {agent} festzulegen; neue Modelle kommen ans Ende", "Drag to put them in the order magpie hands them to {agent}; new models go last": "Ziehen, um die Reihenfolge festzulegen, in der magpie {agent} die Modelle übergibt; neue Modelle kommen ans Ende", "{n} hidden": "{n} ausgeblendet", + "{n} at 0": "{n} bei 0", + "Fold the ones at 0": "Die bei 0 einklappen", + "Nothing left here: every window used up, or a balance of 0": "Konten und Schlüssel ohne Rest: jedes Zeitfenster aufgebraucht oder ein Guthaben von 0", "{n} hidden agents": "{n} ausgeblendete Agenten", "Hidden ({n})": "Ausgeblendet ({n})", "Hidden by you · click to see them": "Von dir ausgeblendet · zum Ansehen klicken", diff --git a/internal/gui/tests/panel-zero-fold.test.cjs b/internal/gui/tests/panel-zero-fold.test.cjs new file mode 100644 index 000000000..4fa03f9f5 --- /dev/null +++ b/internal/gui/tests/panel-zero-fold.test.cjs @@ -0,0 +1,138 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// The tray panel's Allowances tab folds what has nothing left (runking on +// Discord): an account whose every window is used up, a balance of 0 or +// less, behind "{n} at 0" in the foot, a click away and remembered. A failed +// or old reading, a window used part way, Codex's credits and a vendor with +// one account still going stay in sight; a menu bar cell still opens a folded +// card. APIs are mocked. +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_ZERO_ASSETS || path.resolve(__dirname, "../assets")); +const quotas = [ + // at 0: used up, a balance of nothing, a balance below nothing + { provider: "claude", name: "Claude Code", icon: "claude-color", user: "a@b.c", windows: [{ name: "Weekly", used: 100 }, { name: "5-hour", used: 100 }] }, + { provider: "deepseek", name: "DeepSeek", icon: "deepseek-color", windows: [], balance: "¥0.00" }, + { provider: "openrouter", name: "OpenRouter", icon: "openrouter", windows: [], balance: "-$1.20" }, + // not at 0 + { provider: "moonshot", name: "Moonshot", icon: "moonshot", windows: [], balance: "$5.00" }, + { provider: "kimi", name: "Kimi Code", icon: "kimi-color", windows: [{ name: "Weekly", used: 100 }], asOf: "2026-11-04T10:00:00Z" }, + { provider: "glm", name: "GLM Coding Plan", icon: "zhipu-color", windows: [], error: "401 token expired" }, + { provider: "codex", name: "Codex", icon: "codex-color", user: "x@y.z", windows: [{ name: "5-hour", used: 100 }, { name: "Weekly", used: 100 }] }, + { provider: "minimax", name: "MiniMax", icon: "minimax-color", windows: [{ name: "5-hour", used: 100 }, { name: "Weekly", used: 30 }] }, + { provider: "gemini", name: "Gemini", icon: "gemini-color", user: "g1@b.c", windows: [{ name: "Daily", used: 100 }] }, + { provider: "gemini", name: "Gemini", icon: "gemini-color", user: "g2@b.c", windows: [{ name: "Daily", used: 40 }] }, +]; +const folded = ["claude|a@b.c", "deepseek", "openrouter"]; +const always = ["moonshot", "kimi", "glm", "codex|x@y.z", "minimax"]; + +function serve(lang) { + const settings = { theme: "light", lang, tray: "panel", quotaLeft: false, currency: "usd", usageOrder: [], panelUsageHidden: [] }; + 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:false};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings }); + 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") return json(quotas); + if (url.pathname === "/api/usage") return json({ days: [] }); + 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: "" }); } + }; +} + +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}: the panel's Allowances tab folds what has nothing left`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(async () => { await browser.close(); }); + const errors = []; + const context = await browser.newContext({ viewport: { width: 440, height: 300 }, reducedMotion: "reduce" }); + await context.addInitScript(() => { + try { if (!sessionStorage.getItem("set")) { localStorage.setItem("magpie.panelTab", "usage"); sessionStorage.setItem("set", "1"); } } catch {} + window.__scrolled = 0; + const scroll = Element.prototype.scrollIntoView; + Element.prototype.scrollIntoView = function (o) { window.__scrolled++; scroll.call(this, o); }; + }); + const page = await context.newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang)); + const open = async () => { + await page.goto("http://magpie.test/?mode=panel"); + await page.waitForFunction(() => document.querySelectorAll("#panelQuota .pq-card").length >= 3 && document.querySelector("#panelQuota .pq-foot")); + }; + await open(); + const tr = (s, v) => page.evaluate(([s, v]) => t(s, v), [s, v]); + const cards = () => page.evaluate(() => [...document.querySelectorAll("#panelQuota [data-card]")].map((c) => c.dataset.card)); + const zero = page.locator("#panelQuota .pq-foot .pq-zero"); + const view = page.locator("#view-agents"); + const noSideways = async () => assert(await page.evaluate(() => { + const v = document.querySelector("#view-agents"); + return v.scrollWidth <= v.clientWidth && document.scrollingElement.scrollWidth <= innerWidth + && [...document.querySelectorAll("#panelQuota .pq-foot, #panelQuota .pq-foot > *")].every((r) => r.getBoundingClientRect().right <= innerWidth); + }), "nothing runs off sideways at 440px"); + + // folded: the three with nothing left, and the foot says how many + let shown = await cards(); + for (const id of folded) assert(!shown.includes(id), `${id} is folded`); + for (const id of always) assert(shown.includes(id), `${id} stays in sight`); + assert(shown.includes("gemini|g1@b.c") || shown.includes("gemini|g2@b.c") || shown.includes("gemini"), "a vendor with one account still going stays"); + assert.equal(await zero.textContent(), await tr("{n} at 0", { n: 3 })); + assert.equal(await zero.getAttribute("aria-expanded"), "false"); + assert.equal(await zero.getAttribute("title"), await tr("Nothing left here: every window used up, or a balance of 0")); + assert.equal(await zero.evaluate((b) => getComputedStyle(b).borderLeftWidth === getComputedStyle(b).borderRightWidth && getComputedStyle(b).borderLeftColor === getComputedStyle(b).borderRightColor), true, "no stripe down the button's left"); + assert.equal(await page.locator("#panelQuota .pq-foot .pq-hidden").count(), 0, "folded is not counted as hidden"); + await noSideways(); + + // a click shows them, without moving the page, the keyboard on the button + await page.mouse.move(220, 150); + // the reader scrolls to the foot by the wheel, a turn at a time + for (let i = 0; i < 20; i++) { + const [left, was] = await view.evaluate((v) => [v.scrollHeight - v.clientHeight - v.scrollTop, v.scrollTop]); + if (left <= 1) break; + await page.mouse.wheel(0, 200); + await page.waitForFunction((was) => document.querySelector("#view-agents").scrollTop !== was, was, { timeout: 1000 }).catch(() => {}); + } + assert(await view.evaluate((v) => v.scrollTop > 0), "the reader scrolled down"); + const keep = await view.evaluate((v) => v.scrollTop); + await zero.click(); + await page.waitForFunction(() => document.querySelector('#panelQuota [data-card="deepseek"]')); + shown = await cards(); + for (const id of [...folded, ...always]) assert(shown.includes(id), `${id} is shown once opened`); + assert.equal(await zero.textContent(), await tr("Fold the ones at 0")); + assert.equal(await zero.getAttribute("aria-expanded"), "true"); + assert(await page.evaluate(() => document.activeElement?.matches("#panelQuota .pq-zero")), "the keyboard stays on the button"); + const after = await view.evaluate((v) => [v.scrollTop, v.scrollHeight - v.clientHeight]); + assert.equal(after[0], Math.min(keep, after[1]), "the click keeps the reader where they were"); + assert.equal(await page.evaluate(() => window.__scrolled), 0, "nothing scrolled itself"); + await noSideways(); + + // the choice is kept: open after a reload, folded again after one more + await open(); + assert((await cards()).includes("deepseek"), "open after a reload"); + await zero.click(); + await page.waitForFunction(() => !document.querySelector('#panelQuota [data-card="deepseek"]')); + await open(); + assert(!(await cards()).includes("deepseek"), "folded after a reload"); + assert.equal(await zero.textContent(), await tr("{n} at 0", { n: 3 })); + + // a menu bar cell for a folded card opens it all the same + await page.evaluate(() => panelQuotaFocus("claude|a@b.c")); + await page.waitForFunction(() => document.querySelector('#panelQuota [data-card="claude|a@b.c"]')); + assert.equal(await zero.textContent(), await tr("{n} at 0", { n: 2 }), "the one asked for isn't counted as folded"); + + assert.deepEqual(errors, []); + }); + } +}