From e47abdf468519dd681cb1e4897144e6fa011a2b7 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 16 Nov 2026 04:39:11 +0800 Subject: [PATCH] usage: the allowances' trend takes any last N days; a curve's hover reads the exact numbers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit shangyuan0818 on X asked for exact numbers on the Overview's quota curves when hovered, and for the trend to take any "last N days". - Usage → Overview, the allowances' "Trends: …" button: the menu now has 7 days and 30 days beside Off, 2 days and Cycle, and "Other number of days…", which turns the button into a field for 1 to 45 (the days of history magpie keeps). Enter or leaving the field keeps it; Escape leaves the range as it was; a number out of range says so and keeps the old one. A custom N stays in the menu, and is kept across a reload (magpie.quotaRange). - Hovering a quota curve shows a small tip at the reading nearest the pointer: when it was read, then each window's left to two decimals (70.46%), with a hairline at that time. A balance curve shows the balance in the card's currency. The curve's own tooltip (what the dashes mean) waits while the tip shows. A touch still zooms, as before. - The trend menu, the days field and the hover live in the usage plugin's page.js, so app.js stays inside its budget. - No animation: the tip follows the pointer, which a movement would lag. Run, at d597b4d01 + this change, on mote and mica: - quota-trend-days.test.cjs (new), 5 languages x 2 engines: red on 2d106b5c1 ("7 and 30 days are offered"), green 10/10. - The 18 GUI files that draw or pick the allowances' curves, i18n-keys and i18n-en-no-cjk, plus usage-exact-cost and quota-holds: 201 pass. The 6 reds are red alike on origin/main 2d106b5c1, each filed: quota-curve's "quota cards draw what was left over time" (#6789) and usage-fold's "17 subscriptions and 29 accounts" (#3415, #6003). - go test ./internal/gui: ok (app.js 228 bytes inside appScriptBudget) Not tried: Windows (WebView2) and the panel's Allowances tab by hand, a real account's history, a touch screen. --- internal/gui/assets/app.css | 10 ++ internal/gui/assets/app.js | 45 +++-- internal/gui/assets/i18n.js | 12 ++ internal/gui/assets/plugins/usage/page.js | 102 +++++++++++ internal/gui/tests/quota-trend-days.test.cjs | 180 +++++++++++++++++++ 5 files changed, 324 insertions(+), 25 deletions(-) create mode 100644 internal/gui/tests/quota-trend-days.test.cjs diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 26ca825eb..5c8587dc9 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -1243,6 +1243,16 @@ body.panel .row.pref.flash { border-radius: 10px; } .qc-line.qc-short { stroke-width: 1.25; opacity: .7; } .qc-even { stroke-width: 1; stroke-dasharray: 3 3; opacity: .45; vector-effect: non-scaling-stroke; } .qc-now { stroke: var(--faint); stroke-width: 1; stroke-dasharray: 1 2; vector-effect: non-scaling-stroke; } +.qc-hot { stroke: var(--muted); stroke-width: 1; vector-effect: non-scaling-stroke; pointer-events: none; } +.quota-curve { position: relative; } +.quota-curve .qc-tip { position: absolute; z-index: 3; min-width: 140px; max-width: 240px; padding: 7px 9px 6px; background: var(--pop-bg); border-radius: 9px; box-shadow: var(--shadow); font-size: 11px; color: var(--fg); pointer-events: none; } +.quota-curve .qc-tip b { display: block; margin-bottom: 3px; font-weight: 600; font-variant-numeric: tabular-nums; } +.quota-curve .qc-tip div { display: flex; align-items: center; gap: 6px; line-height: 1.6; } +.quota-curve .qc-tip div span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.quota-curve .qc-tip i { width: 7px; height: 7px; border-radius: 2px; flex: none; } +.quota-curve .qc-tip em { margin-left: auto; padding-left: 10px; font-style: normal; font-variant-numeric: tabular-nums; } +.quota-head .qt-days { width: 64px; height: 24px; padding: 0 8px; border: 1px solid var(--line); border-radius: 7px; background: var(--card); color: var(--fg); font-size: 12px; outline: none; } +.quota-head .qt-days:focus { border-color: var(--accent); } .quota-curve .qc-axis { display: flex; justify-content: space-between; gap: 8px; margin-top: 3px; font-size: 10px; color: var(--muted); font-variant-numeric: tabular-nums; white-space: nowrap; } .quota-curve .qc-legend { display: flex; flex-wrap: wrap; gap: 3px 12px; margin-top: 5px; font-size: 10.5px; color: var(--muted); } /* a key never breaks inside: a long name ends in … rather than its % on a line of its own */ diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 143e6e80b..15aa5423d 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -16644,33 +16644,22 @@ function creditDays(daily, named) { } // windows left over time (#651), broken at each restart, dashed even burn; -// "2 days", "Cycle" (or an earlier one per account), or "Off" (ARNO); one -// pick turns every card, remembered, and the tray follows +// "2 days", any last N days ("7d", shangyuan0818 on X), "Cycle" (or an +// earlier one per account), or "Off" (ARNO); one pick turns every card, +// remembered, and the tray follows. N goes as far back as the readings +// are kept (quotaHistKept, 45 days). +const QUOTA_DAYS_MAX = 45; +const quotaDays = (r) => parseInt(r) || 0; +const quotaRangeOk = (r) => /^(off|cycle|[1-9]\d?d)$/.test(r) && quotaDays(r) <= QUOTA_DAYS_MAX; let quotaRange = "cycle"; -try { const v = localStorage.getItem("magpie.quotaRange"); if (v === "2d" || v === "off") quotaRange = v; } catch {} -const QUOTA_RANGES = [["off", "Off", "No curves on the cards"], ["2d", "2 days", "The last two days"], ["cycle", "Cycle", "The current cycle, from the window's start to its reset"]]; +try { const v = localStorage.getItem("magpie.quotaRange"); if (quotaRangeOk(v)) quotaRange = v; } catch {} +// a range's name: "Cycle", "2 days", "12 days" +const quotaRangeName = (r, n = quotaDays(r)) => n ? t(n === 1 ? "{n} day" : "{n} days", { n }) : t(r === "off" ? "Off" : "Cycle"); addEventListener("storage", (e) => { if (e.key !== "magpie.quotaRange") return; - const v = QUOTA_RANGES.some(([id]) => id === e.newValue) ? e.newValue : "cycle"; + const v = quotaRangeOk(e.newValue) ? e.newValue : "cycle"; if (v !== quotaRange) { quotaRange = v; renderQuotas(); } }); -// renderQuotaTrend: the allowances' head's pick of the curves' range, there -// once some account has readings to draw -function renderQuotaTrend() { - const b = $("#quotaTrend"); - if (!b) return; - b.hidden = !quotas?.some((q) => !q.error && (quotaLines(q).length || q.balanceTrend?.points?.length > 1)); - if (b.hidden) return; - const cur = QUOTA_RANGES.find(([id]) => id === quotaRange); - b.classList.toggle("set", quotaRange !== "off"); - b.replaceChildren(el("span", "", t("Trends: {range}", { range: t(cur[1]) })), svg(CHEV, 11, 1.6)); - b.title = t("What was left over time, under each account's meters"); - b.onclick = (e) => { - e.stopPropagation(); - if (b.classList.contains("open")) return closeProtoMenu(); - openProtoMenu(b, QUOTA_RANGES.map(([v, name, note]) => ({ v, name, note })), quotaRange, setQuotaRange, "Left over time", "sess-menu"); - }; -} function quotaHistOf(sub) { const user = (sub.user || "").toLowerCase(); @@ -16862,7 +16851,7 @@ function quotaEtaText(l, now) { : t("Runs out {when} at this pace", { when: quotaTimeText(Math.max(p.out, now + 60e3), now) }); } function quotaSpan(lines, range, now) { - if (range === "2d") return [now - 48 * 3600e3, now]; + if (quotaDays(range)) return [now - quotaDays(range) * 864e5, now]; let x0 = Infinity, x1 = now; for (const l of lines) { const c = quotaCycle(l, now); @@ -16985,8 +16974,9 @@ function quotaCurve(sub) { // at its end belongs to the next cycle, not this cycle's last figure. const shown = history?.shown || lines; drawQuotaPlot(g, shown, x0, Math.max(x0 + 1, x1), W, H, now); + box.hover = { x0, x1: Math.max(x0 + 1, x1), lines: shown.map((l, i) => ({ label: l.label, color: `var(--c${(i % 7) + 1})`, points: l.points, text: (p) => quotaLeftText(p.left) })) }; box.title = quotaCurveTitle(); - const r = picked ? t("Past cycle") : t(quotaRange === "2d" ? "2 days" : "Cycle"); + const r = picked ? t("Past cycle") : quotaRangeName(quotaRange); range.textContent = r; range.disabled = quotaRange !== "cycle" || !past.cycles.length; range.title = t("Choose a recorded cycle"); @@ -17020,8 +17010,11 @@ function quotaCurve(sub) { }; box.append(head, g, axis, legend); box.draw(); + curveHover(box, g, W, H); return box; } +// what a reading left, as exact as it was read: 73.46%, 100% +const quotaLeftText = (v) => +(+v).toFixed(2) + "%"; // curveZoom: a curve made larger on a click, or Enter, and back on the // next (TJHHHH on Discord); the page stays where it is function curveZoom(box, g) { @@ -17075,7 +17068,7 @@ function balanceCurve(sub) { if (tr.perDay > 0) legend.append(el("span", "qc-key bc-pace", t("about {amount} a day", { amount: balanceAmount(sub, tr.perDay) }))); box.draw = () => { const now = Date.now(); - let x0 = quotaRange === "2d" ? now - 48 * 3600e3 : pts[0].at, x1 = now; + let x0 = quotaDays(quotaRange) ? now - quotaDays(quotaRange) * 864e5 : pts[0].at, x1 = now; if (!(x0 < now)) x0 = now - 3600e3; // the dashes reach zero when it is no further off than what is shown if (out && out > now && out - now <= now - x0) x1 = out; @@ -17100,9 +17093,11 @@ function balanceCurve(sub) { pace.title = out ? new Date(out).toLocaleString(intlLang()) : ""; g.setAttribute("aria-label", t("Balance over time") + (out ? " · " + pace.textContent : "")); axis.replaceChildren(el("span", "", quotaTimeText(x0, now)), el("span", "", quotaTimeText(x1, now))); + box.hover = { x0, x1, lines: [{ label: t("Balance"), color: "var(--c1)", points: pts, text: (p) => balanceAmount(sub, p.v) }] }; }; box.append(head, g, axis, legend); box.draw(); + curveHover(box, g, W, H); return box; } function setQuotaRange(id) { diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 44bd1af9c..22ae8105e 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -4250,6 +4250,9 @@ const I18N = { "The last two days": "最近两天", "The current cycle, from the window's start to its reset": "当前周期:从窗口开始到重置", "Trends: {range}": "走势:{range}", + "Other number of days…": "其他天数…", + "Days back, 1 to {n}": "往前的天数,1 到 {n}", + "A number of days from 1 to {n}": "天数为 1 到 {n} 之间的整数", "No curves on the cards": "卡片上不画走势", "What was left over time, under each account's meters": "每个账号额度条下方的剩余额度走势", "{name}: {n} left, read {when}": "{name}:剩余 {n},读取于 {when}", @@ -9562,6 +9565,9 @@ const I18N = { "The last two days": "最近兩天", "The current cycle, from the window's start to its reset": "目前週期:從時段開始到重置", "Trends: {range}": "走勢:{range}", + "Other number of days…": "其他天數…", + "Days back, 1 to {n}": "往前的天數,1 到 {n}", + "A number of days from 1 to {n}": "天數為 1 到 {n} 之間的整數", "No curves on the cards": "卡片上不畫走勢", "What was left over time, under each account's meters": "每個帳號額度條下方的剩餘額度走勢", "{name}: {n} left, read {when}": "{name}:剩餘 {n},讀取於 {when}", @@ -14890,6 +14896,9 @@ const I18N = { "The last two days": "直近 2 日間", "The current cycle, from the window's start to its reset": "現在のサイクル(ウィンドウ開始からリセットまで)", "Trends: {range}": "推移:{range}", + "Other number of days…": "日数を指定…", + "Days back, 1 to {n}": "さかのぼる日数(1〜{n})", + "A number of days from 1 to {n}": "日数は 1〜{n} の整数です", "No curves on the cards": "カードに推移を表示しない", "What was left over time, under each account's meters": "各アカウントのメーターの下に残量の推移を表示します", "{name}: {n} left, read {when}": "{name}:残り {n}、{when} に取得", @@ -20227,6 +20236,9 @@ const I18N = { "The last two days": "Die letzten zwei Tage", "The current cycle, from the window's start to its reset": "Der aktuelle Zyklus, vom Beginn des Zeitfensters bis zum Zurücksetzen", "Trends: {range}": "Verlauf: {range}", + "Other number of days…": "Andere Anzahl Tage…", + "Days back, 1 to {n}": "Tage zurück, 1 bis {n}", + "A number of days from 1 to {n}": "Eine Anzahl Tage von 1 bis {n}", "No curves on the cards": "Keine Kurven auf den Karten", "What was left over time, under each account's meters": "Der Rest im Zeitverlauf, unter den Anzeigen jedes Kontos", "{name}: {n} left, read {when}": "{name}: {n} übrig, gelesen {when}", diff --git a/internal/gui/assets/plugins/usage/page.js b/internal/gui/assets/plugins/usage/page.js index 95a1fcf31..25fd2f69c 100644 --- a/internal/gui/assets/plugins/usage/page.js +++ b/internal/gui/assets/plugins/usage/page.js @@ -5492,3 +5492,105 @@ function packUsageNow(list) { for (const part of card.children) usagePack.observe(part); } } + +// The allowances' trend pick in the page's head, and what a curve under a +// card reads out on a hover; app.js draws the curves. +const QUOTA_RANGES = [["off", "Off", "No curves on the cards"], ["2d", "2 days", "The last two days"], ["cycle", "Cycle", "The current cycle, from the window's start to its reset"], ["7d", "7 days", ""], ["30d", "30 days", ""]]; +// renderQuotaTrend: the allowances' head's pick of the curves' range, there +// once some account has readings to draw +function renderQuotaTrend() { + const b = $("#quotaTrend"); + if (!b || b.nextElementSibling?.classList.contains("qt-days")) return; + b.hidden = !quotas?.some((q) => !q.error && (quotaLines(q).length || q.balanceTrend?.points?.length > 1)); + if (b.hidden) return; + b.classList.toggle("set", quotaRange !== "off"); + b.replaceChildren(el("span", "", t("Trends: {range}", { range: quotaRangeName(quotaRange) })), svg(CHEV, 11, 1.6)); + b.title = t("What was left over time, under each account's meters"); + b.onclick = (e) => { + e.stopPropagation(); + if (b.classList.contains("open")) return closeProtoMenu(); + const opts = QUOTA_RANGES.map(([v, name, note]) => ({ v, name, note })); + // a number of days typed before is listed beside the presets + if (!opts.some((o) => o.v === quotaRange)) opts.push({ v: quotaRange, name: quotaRangeName(quotaRange), literalName: true, note: "" }); + opts.push({ v: "days", name: "Other number of days…", note: "" }); + openProtoMenu(b, opts, quotaRange, (v) => v === "days" ? quotaDaysField(b) : setQuotaRange(v), "Left over time", "sess-menu"); + }; +} + +// quotaDaysField: the trend head's button as a field for a number of days, +// 1 to 45; Enter picks it, Escape or a bad number leaves the range as it was +function quotaDaysField(b) { + const i = input(quotaDays(quotaRange) ? String(quotaDays(quotaRange)) : "", "1–" + QUOTA_DAYS_MAX, "text"); + i.className = "rename-in qt-days"; + i.inputMode = "numeric"; + i.setAttribute("aria-label", t("Days back, 1 to {n}", { n: QUOTA_DAYS_MAX })); + let done = false; + const finish = (save) => { + if (done) return; + done = true; + const s = i.value.trim(), n = Number(s); + i.remove(); + b.hidden = false; + if (save && s && !(Number.isInteger(n) && n >= 1 && n <= QUOTA_DAYS_MAX)) status(t("A number of days from 1 to {n}", { n: QUOTA_DAYS_MAX }), "err"); + else if (save && s) setQuotaRange(n + "d"); + b.focus(NO_SCROLL); + }; + // the Enter is used up here: let through, it would press the button that + // focus goes back to and open its menu again + i.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter" || e.key === "Escape") { e.preventDefault(); finish(e.key === "Enter"); } }; + i.onblur = () => finish(true); + b.hidden = true; + b.after(i); + i.focus(NO_SCROLL); + i.select(); +} + +// curveHover: a curve's readings nearest the pointer, each line's with its +// figure and when it was read (shangyuan0818 on X), from what box.hover says +// was drawn last; a mouse's alone, a touch is the click that zooms +function curveHover(box, g, W, H) { + const tip = el("div", "qc-tip"); + tip.hidden = true; + const hot = sv("line", { y1: 0, y2: H, class: "qc-hot" }); + box.append(tip); + // the curve's own tooltip (what the dashes mean) waits while it is read + let title = null; + const hide = () => { + tip.hidden = true; + hot.remove(); + if (title != null && !box.title) box.title = title; + title = null; + }; + g.addEventListener("pointerleave", hide); + g.addEventListener("pointermove", (e) => { + const h = box.hover; + if (e.pointerType === "touch" || !h) return hide(); + const r = g.getBoundingClientRect(); + const at = h.x0 + ((e.clientX - r.left) / r.width) * (h.x1 - h.x0); + // each line's reading nearest the pointer, of those drawn + const near = h.lines.map((l) => { + let best = null; + for (const p of l.points) if (p.at >= h.x0 && p.at <= h.x1 && (!best || Math.abs(p.at - at) < Math.abs(best.at - at))) best = p; + return best && { l, p: best }; + }).filter(Boolean); + if (!near.length) return hide(); + const first = near.reduce((a, b) => Math.abs(b.p.at - at) < Math.abs(a.p.at - at) ? b : a); + const x = ((first.p.at - h.x0) / (h.x1 - h.x0)) * W; + hot.setAttribute("x1", x); + hot.setAttribute("x2", x); + if (!hot.isConnected) g.append(hot); + tip.replaceChildren(el("b", "", quotaCycleDate(first.p.at))); + for (const { l, p } of near) { + const row = el("div"), sw = el("i"); + sw.style.background = l.color; + row.append(sw, el("span", "", l.label), el("em", "", l.text(p))); + tip.append(row); + } + tip.hidden = false; + if (box.title) { title = box.title; box.removeAttribute("title"); } + // beside the pointer, on whichever side has room + const bx = box.getBoundingClientRect(), px = r.left - bx.left + (x / W) * r.width, w = tip.offsetWidth; + tip.style.left = Math.max(0, px + 12 + w > bx.width ? px - w - 12 : px + 12) + "px"; + tip.style.top = r.top - bx.top + "px"; + }); +} diff --git a/internal/gui/tests/quota-trend-days.test.cjs b/internal/gui/tests/quota-trend-days.test.cjs new file mode 100644 index 000000000..02f62f2d7 --- /dev/null +++ b/internal/gui/tests/quota-trend-days.test.cjs @@ -0,0 +1,180 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// The allowances' trend range takes any number of days back, not only the +// presets (shangyuan0818 on X): "Other number of days…" in the app's menu +// opens a small field in the head, 1 to 45 (what magpie keeps), Enter saves +// it, the head and every card name it, and it is remembered across a +// reload; a number out of range says so and keeps the range. Hovering a +// curve shows the exact reading nearest the pointer, every line's, with its +// time: the quota's left to two decimals, a balance as its card writes it. +// No click moves the page. Every language, both engines; the API is faked. +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 H = 3600e3; +const iso = (ms) => new Date(ms).toISOString(); +// the pointer on (x, y) until the tip shows: a card drawn again under a +// still pointer (the history read in) has no hover until it moves +async function hoverTip(page, tip, x, y) { + await page.mouse.move(x, y); + for (let i = 0; i < 40 && !(await tip.isVisible()); i++) await page.mouse.move(x + ((i + 1) % 2), y); + await tip.waitFor(); +} + +function fixtures(now) { + const rw = now + 3 * 24 * H; + const quotas = [ + { provider: "codex", name: "Codex", icon: "openai", plan: "Plus", user: "a@x.com", windows: [{ name: "Weekly", used: 30, resetsAt: iso(rw) }] }, + { provider: "deepseek", name: "DeepSeek", icon: "deepseek", windows: [], balance: "¥30.50", readAt: iso(now), + balanceTrend: { points: [[48, 50], [24, 40.125], [0, 30.5]].map(([h, v]) => ({ at: iso(now - h * H), amount: v })) } }, + ]; + const week = []; + for (let h = 20 * 24; h >= 0; h -= 6) week.push({ at: iso(now - h * H), left: +(70.456 + h / 9).toFixed(3), start: iso(rw - 168 * H), resetsAt: iso(rw) }); + return { quotas, history: [{ provider: "codex", user: "a@x.com", lines: [{ name: "Weekly", points: week }] }] }; +} + +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()); + const json = (body) => route.fulfill({ json: body }); + 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/quotas") return json(data.quotas); + if (url.pathname === "/api/usage/quotas/history/holds") return json([]); + if (url.pathname === "/api/usage/quotas/history") return json(data.history); + if (url.pathname === "/api/usage") return json({ calls: 0, input: 0, output: 0, cost: 0, agents: [], accounts: [], models: [], series: [], 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: "" }); } + }; +} + +const words = { + en: { trend: "Trends: ", other: "Other number of days…", days: (n) => n + " days", bad: "A number of days from 1 to 45", week: "Weekly", balance: "Balance" }, + zh: { trend: "走势:", other: "其他天数…", days: (n) => n + " 天", bad: "天数为 1 到 45 之间的整数", week: "每周", balance: "余额" }, + "zh-TW": { trend: "走勢:", other: "其他天數…", days: (n) => n + " 天", bad: "天數為 1 到 45 之間的整數", week: "每週", balance: "餘額" }, + ja: { trend: "推移:", other: "日数を指定…", days: (n) => n + " 日", bad: "日数は 1〜45 の整数です", week: "週", balance: "残高" }, + de: { trend: "Verlauf: ", other: "Andere Anzahl Tage…", days: (n) => n + " Tage", bad: "Eine Anzahl Tage von 1 bis 45", week: "Wöchentlich", balance: "Guthaben" }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const [lang, w] of Object.entries(words)) { + test(`${engine} ${lang}: the quota trend takes any number of days, and a hover reads the exact numbers`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const context = await browser.newContext({ viewport: { width: 440, height: 760 }, reducedMotion: "reduce" }); + const page = await context.newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const data = fixtures(Date.now()); + await page.route("**/*", serve(lang, data)); + await page.goto("http://magpie.test/?view=usage"); + const curve = page.locator('.subscription-card[data-key="codex"] .quota-curve').first(); + await curve.waitFor(); + const pick = page.locator("#quotaHead #quotaTrend"); + const scroll = () => page.locator("#view-usage").evaluate((v) => v.scrollTop); + const before = await scroll(); + + // the presets, then any number + await pick.click(); + const items = page.locator(".sess-menu .pm-item"); + const names = await items.allTextContents(); + assert.ok(names.some((n) => n.startsWith(w.days(7))) && names.some((n) => n.startsWith(w.days(30))), "7 and 30 days are offered: " + names); + await items.filter({ hasText: w.other }).click(); + const field = page.locator("#quotaHead input.qt-days"); + await field.waitFor(); + assert.ok(await pick.isHidden(), "the field stands where the button was"); + await field.fill("12"); + await field.press("Enter"); + await page.waitForFunction((s) => document.querySelector("#quotaTrend")?.textContent === s, w.trend + w.days(12)); + assert.equal(await field.count(), 0); + assert.equal(await page.evaluate(() => localStorage.getItem("magpie.quotaRange")), "12d"); + assert.equal(await curve.locator(".qc-range").textContent(), w.days(12), "the card names the range too"); + const axis12 = await curve.locator(".qc-axis span").first().textContent(); + + // the custom number is listed and checked; a bad number keeps it + await pick.click(); + const custom = items.filter({ hasText: w.days(12) }); + await items.first().waitFor(); + assert.equal(await custom.count(), 1, "the custom range is in the menu: " + await items.allTextContents()); + await items.filter({ hasText: w.other }).click(); + await field.waitFor(); + assert.equal(await field.inputValue(), "12", "the field starts at the current number"); + await field.fill("99"); + await field.press("Enter"); + await page.waitForFunction((s) => document.querySelector("#status")?.textContent === s, w.bad); + assert.equal(await page.evaluate(() => localStorage.getItem("magpie.quotaRange")), "12d", "a number out of range changes nothing"); + // Escape leaves it as it was + await pick.click(); + await items.filter({ hasText: w.other }).click(); + await field.fill("3"); + await field.press("Escape"); + assert.equal(await page.evaluate(() => localStorage.getItem("magpie.quotaRange")), "12d"); + assert.equal(await pick.textContent(), w.trend + w.days(12)); + + // a preset's span differs from 12 days' + await pick.click(); + await items.filter({ hasText: w.days(7) }).first().click(); + await page.waitForFunction((s) => document.querySelector("#quotaTrend")?.textContent === s, w.trend + w.days(7)); + assert.notEqual(await curve.locator(".qc-axis span").first().textContent(), axis12, "12 days reaches further back than 7"); + // and back to 12, kept across a reload + await pick.click(); + await items.filter({ hasText: w.other }).click(); + await field.fill("12"); + await field.press("Enter"); + await page.waitForFunction((s) => document.querySelector("#quotaTrend")?.textContent === s, w.trend + w.days(12)); + assert.equal(await scroll(), before, "no click moved the page"); + await page.reload(); + await curve.waitFor(); + assert.equal(await pick.textContent(), w.trend + w.days(12), "remembered across a reload"); + + // the hover: the reading nearest the pointer, exactly + const plot = curve.locator(".qc-plot"); + const box = await plot.boundingBox(); + const tip = curve.locator(".qc-tip"); + await hoverTip(page, tip, box.x + box.width - 2, box.y + box.height / 2); + const rows = await tip.locator("div").allTextContents(); + assert.deepEqual(rows, [w.week + "70.46%"], "the exact left at now, two decimals"); + assert.ok((await tip.locator("b").textContent()).trim(), "with its time"); + assert.equal(await curve.getAttribute("title"), null, "the curve's own tooltip waits while the tip shows"); + await hoverTip(page, tip, box.x + box.width / 2, box.y + box.height / 2); + const mid = await tip.locator("em").textContent(); + assert.match(mid, /^\d+(\.\d{1,2})?%$/); + assert.notEqual(mid, "70.46%", "the reading follows the pointer"); + await page.mouse.move(0, 0); + await tip.waitFor({ state: "hidden" }); + assert.ok(await curve.getAttribute("title"), "and comes back after"); + + const bal = page.locator(".subscription-card", { hasText: "DeepSeek" }).locator(".balance-curve"); + // wheeled into view, as a person would: the page puts back a scroll no one asked for + const vb = await page.locator("#view-usage").boundingBox(); + await page.mouse.move(vb.x + vb.width / 2, vb.y + 40); + for (let i = 0; i < 20 && (await bal.locator(".qc-plot").boundingBox()).y + 60 > vb.y + vb.height; i++) await page.mouse.wheel(0, 120); + // Chromium's wheel glides on: read the plot once it has stopped + let bbox = null; + for (let i = 0; i < 50; i++) { + const b = await bal.locator(".qc-plot").boundingBox(); + if (bbox && b.y === bbox.y) break; + bbox = b; + await page.waitForTimeout(100); + } + const btip = bal.locator(".qc-tip"); + await hoverTip(page, btip, bbox.x + 2, bbox.y + bbox.height / 2); + assert.equal(await btip.locator("span").textContent(), w.balance); + assert.match(await btip.locator("em").textContent(), /50(\.00)?/, "the oldest balance at the left end"); + assert.deepEqual(errors, []); + }); + } +}