gui: Usage cards keep their place as they come in (liuzhengdong99 on X)

liuzhengdong99 on X: 用量界面每张卡片取数的时间不一致,导致卡片渲染时高度一直
跳动——滑到上面看某张卡片,视图会被拽回下面. The allowance cards come in
at different times: each vendor's read (the page asks again every 1.5s
while X-Magpie-Reading says a read is under way), then the curves'
history. Every answer redraws the cards (renderQuotas), and packUsage
grows the ones above the card being read. Nothing kept that card in
place: the view's scroll guard (keepInView) only knew elements by node,
and the cards are new nodes on each draw, so the browser's anchoring was
the only thing holding them. It anchored on nodes that were being
replaced, and the reader ended up dragged down.

Fix:
- The Overview keeps the card being read in place: the highest card (or
  part of the page under the cards) that starts in sight, found again by
  its data-key after a redraw (keepInView's new `only` mode with pinnedAt),
  and followed after every packUsage (followPin). The browser's own
  anchoring stays on while nothing is kept: at the page's top, on
  another tab, and while the cards are dragged or moved by keys (unpin,
  so a dropped card lands where its slot showed).
- Placeholders from the last known height: each card's height drawn in
  full is kept by its key (localStorage magpie.usageCardTall, 1s
  debounce, 200 keys at most). A card still waiting on its read or its
  curve (usageWaiting: quotasReading, the new flag loadQuotas sets, or
  no history answer yet) is packed and held at least that tall, in the
  column count the cards were last whole in at that width. On the next
  start, no card in sight moves.
- loadQuotaHist counts its first answer even when it is empty, so a
  user with no history isn't left waiting (found by usage-pack: the
  cards held their first packing at 560px).

No new animation, nothing scrolls the page on its own (click-scroll
passes), and the layout is unchanged once the cards are in.

Run (mica, Playwright 1.62.0, Chromium + WebKit):
- usage-cards-steady.test.cjs (new): 20 tests, all 5 languages, 1100px
  and 420px. On the old assets (MAGPIE_ASSETS) it was red 8 of 8 in en
  and ja. With the hold disabled, the second visit goes red.
- At ee079814b + this change (then rebased onto 1c29e2c7d, which changes
  only app.css, redact.css and a new contrast test; script budgets
  measured again, unchanged): go test ./internal/gui/ (budgets included),
  gofmt, and usage-pack, usage-cards-steady, usage-drag, usage-arrange,
  click-scroll and i18n-keys: go ok (300s), 64 of 64 GUI tests pass.
- Every usage-*, quota-*, view-*, account-arrange, click-scroll,
  i18n-keys and gui-de/ja/zh-TW file (151 files), run before the empty-history fix and the last
  rebase, head vs origin/main.
  No red at head is new. The reds that are also on base: account-arrange
  (#6010), quota-count-wrap (#3404), quota-curve (#6789),
  quota-refresh-order (#6180), quota-credits (#6807), usage-ledger
  (#5048, #6003), routing-* (#7016), gui-ja (#7144),
  view-trackpad-coast (#4724), view-wheel-unheard (#5158), plus the
  whole-suite reds in #6975 and #6934. usage-pack and usage-drag went
  red at head along the way and are fixed here.

Not tried: the real app (WebKitGTK on Linux, WebView2 on Windows,
WKWebView on macOS) and the full GUI suite.
This commit is contained in:
yetone
2026-11-19 13:01:23 +08:00
parent 1c29e2c7dd
commit 1c9c359f9d
6 changed files with 299 additions and 14 deletions
+1
View File
@@ -770,6 +770,7 @@ covers it in both engines, every language and a narrow window.
- A page scrolled a screen down shows Scroll to top and Scroll to bottom (emo172, #1090): a small capsule of two chevron buttons at the open page's lower right, in its right margin when a wide window leaves one, else over its corner; above Providers' sticky Add buttons. It goes again near the page's top and over a dialog, and, over the corner, at the page's foot, where the last row can't scroll out from under it, unless it has the pointer or focus. It is placed again on a scroll, a resize, a page shown or hidden, and whenever the open page or one of its own children changes size (a `ResizeObserver`, so a Routing group opened or closed moves it off the editor with no scroll, Jiabubu; see `view-ends-relayout.test.cjs`). It never changes the page's height, which the guard below measures. A press is the reader's scroll (`scrollOnPurpose`, then `arrived` once the page stands still), smooth unless motion is reduced; Scroll to bottom is `aria-disabled` at the foot. Each button's name and tooltip are in every language. The code is [`scrollends.js`](../../internal/gui/assets/scrollends.js), imported on the window's first scroll so the core doesn't carry it; the tray panel has none. Home and End scroll a page as before. See `view-ends.test.cjs`.
- A scroll not the reader's is put back, so every way the reader scrolls has to count as theirs: the wheel and a trackpad's coast after the lift (WebKit on the Mac plays the coast itself and the page hears its scrolls with no wheel for each, so the wheel starts the same chain a touch fling does, `flings`/`flingUntil`: each scroll keeps the next one the reader's till it rests, and a click ends it; issenn on Discord, `view-trackpad-coast.test.cjs`), a wheel or coast the page is never told of (macOS 13's WebKit, Safari 16.6's, scrolled a view under wheels it never dispatched, so every scroll was put back and only the bar's drag moved the page: three scrolls put back the same way within a second are taken as the reader's run and given back, and so is each one after it that goes on the same way within a second of the last, so a wheel turned slowly or on a loaded Mac loses no step; a scroll by code is one, not a run, and two at rest are still put back; issenn on Discord, `view-wheel-unheard.test.cjs`. Under a click's 4s hold the same holds: only a put-back that comes with the page redrawn since the hold last held (`redrawn`: the view's height or where the first held parts sit moved from `h.lay`) is the hold's and never counts toward a run, so a profile opened on the Agents page and wheeled through at once scrolls, issennknight on Discord, `view-wheel-after-click.test.cjs`. The parts `h.lay` measures are those still in the page that scroll with it: a part drawn again since (the Usage page's tabs, the agents' list under an agent opened or closed) is a redraw once, not at every scroll, and a sticky one (Settings' tabs at a narrow width) is left out, as it sits still while the page scrolls; `view-wheel-after-redraw.test.cjs`), a touch and its fling, the keys, a drag, the scrollbar's own drag (`barDrag`, #1089) and the middle button's autoscroll (`panning`, 多喝热水 on Discord). Chromium and WebView2 give the autoscroll a press of button 1 and then no event of the reader's while it scrolls; from that press the view follows it till Chromium ends it, on the next press (which reaches the page only as a pointerup), a key (a keyup), or the lift after the mouse moved while held. A field the guard brings back into view after putting a scroll back is one focused since the reader last scrolled that view, not one they scrolled away from (`scrolledFrom`): the middle press focuses the button under it. See `view-middle-autoscroll.test.cjs`.
- A load that lands puts the view back where the reader left it (`show`'s `back` on the page's first reads, the Providers pages' reload after `render`): what it drew may have pulled the view up, the browser clamping it to a page shorter for a moment. While the reader scrolls, the place last heard is late (the page hears of a scroll a frame or more after it, WebKit scrolling on its own thread), and putting it back took their last steps and stopped their coast each time a load landed under the wheel, so Routing and Usage, scrolled as they opened, shook and snapped back (issennknight on Discord, macOS 13). `backAfterLoad` keeps a view that has gone on the way the reader's own scrolls go (`readerWay`, set from each scroll of theirs) as theirs, and puts back only a move against it, which is a redraw's clamp. The browser's scroll anchoring stays on: as data comes in above, it lowers `scrollTop` with what's on the screen still, which the reader never sees, so the test tells a put-back (the view up, what was under the pointer going down with it) from that.
- The Usage page's allowance cards come in at different times (each vendor's read while `X-Magpie-Reading` asks again, then the curves' history), and a card drawn above the one being read used to push it down the screen (liuzhengdong99 on X). Overview keeps the card being read in place (`keepInView(..., true)` in `plugins/usage/page.js`: the highest card, or part of the page under them, starting in sight; found again by its `data-key` once `renderQuotas` draws the cards anew, and followed after every `packUsage`). Such a view leaves the browser's own anchoring on while it keeps nothing (at its top, on another tab, and while the cards are dragged or moved by keys: `unpin`, so a card lands where its slot showed). Each card's height drawn in full is kept by its key (`usageTall`, localStorage `magpie.usageCardTall`), and a card still waiting on its read or its curve (`usageWaiting`; the history's first answer ends the wait, an empty one too, `loadQuotaHist`) is packed at least that tall, and packed in the number of columns they were last drawn whole in at that width (`usageTall["#" + most]`), since the heights kept are that layout's; so on the next start the cards fill in without the page moving. See `usage-cards-steady.test.cjs`.
- Where the window's WebKit scrolls under wheels it never tells the page of (macOS 13's, 16.6), each gesture's first scrolls were put back until three the same way made a run (`puttingBack`), a shake at the start of every gesture, the first on a page just opened included. The first run given back is remembered (`deaf`, kept in localStorage as `magpie.unheardWheels` for the next start); from then on a scroll at rest waits 120ms before it is put back (`waitsBack`), and one more the same way within 80ms (a frame or a few; code's two scrolls in a row come further apart and are both put back, `view-wheel-unheard.test.cjs`), with the page's height the same (no redraw between them), makes it the reader's at once. A lone scroll (a redraw's, code's) is still put back, 120ms later; one under a click's hold is put back at once as before. See `view-open-wheel.test.cjs`, which starts the wheel before the first data, tells the page of each scroll 80ms late or never, and counts every write that moves the view up under the wheel. What the wait puts back is recorded as an at-once put-back is, so a wheel heard later than 120ms still gives it back (`givesBack`).
- Typing never moves the page either. A textarea that grows with its text (the Library's `autosize` in plugins/library/client.js: a set's text, an agent's own text, a skill's description, a subagent's fields) is measured at height auto with what holds it kept at its height, so the page never goes short for a moment: a page gone short has its view's scroll clamped by the browser at every input, an input method's every composing step included, and the guard's putting it back pulled a textarea taller than the view to one of its edges (#2636, `library-ime-scroll.test.cjs`).
- A box that scrolls inside a page keeps the wheel at its ends: wheeled past its top or foot, the page stays where it was (碳碳双键 on Discord, Requests' list on Usage). `holds` in app.js marks every box between the pointer and its `.view` that scrolls vertically and overflows (`.holds`), on `pointerover` and on each wheel, and app.css gives `.holds` `overscroll-behavior-y: contain` (the Mac's bounce stays, on the box). It is not one CSS rule for every box because Chromium (WebView2, magpie web) holds the wheel in a box told to contain even when it doesn't overflow, and in one that scrolls only sideways, so a short list or a wide table would stop the page. `.holds` is under `:where()`, so a rule that passes the wheel on still does (`.mchips` in a short window, #833). The page itself (`.view`) and the document chain as before. An engine with no `overscroll-behavior` (Safari 15, macOS 12's WebKit until Safari is updated; Safari 16+, WebKitGTK and Chromium have it) gets the same from `compat.js`: a wheel over a `.holds` box at its end in the wheel's direction is cancelled, so there the Mac's bounce at the box's end is lost. A guard in `inner-scroll-contain.test.cjs` builds every rule in every stylesheet under assets that scrolls a box vertically from its own selector, fills it and points at it, and fails naming the file and selector of one that doesn't hold the wheel (a rule that sets `overscroll-behavior` back to auto, or a box `holds` doesn't reach). See `inner-scroll-contain.test.cjs`.
+32 -10
View File
@@ -16160,6 +16160,9 @@ function quotasOpened() {
// A load is never swallowed by a lesser one on its way. A stale answer
// (X-Magpie-Reading) is asked again every 1.5s, 30s at most (#959).
let quotasLoading = null, quotasLater = 0, quotasTries = 0;
// accounts the gateway is reading yet (X-Magpie-Reading, asked again):
// their cards keep the room they had (usageWaiting in page.js)
let quotasReading = false;
let quotaRefreshVersion = 0;
const quotaRefreshVersions = new Map();
function loadQuotas(asked, again) {
@@ -16190,6 +16193,7 @@ function loadQuotas(asked, again) {
}, () => { quotas = quotas || []; quotasKept = reading = false; })
.finally(() => {
if (quotasLoading === p) quotasLoading = null;
quotasReading = reading && quotasTries < 20;
if (!same) renderQuotas(true);
if (view === "usage") loadUpstream();
globalThis.markBalances?.();
@@ -16203,13 +16207,14 @@ function loadQuotas(asked, again) {
}
// loadQuotaHist reads the allowances' history for the curves, and draws
// them again only when it differs from what is drawn. Of two reads on
// their way, the later asked is the one that stands.
// them again only when it differs from what is drawn, or on its first
// answer, an empty one too (the cards stop waiting on it: usageWaiting).
// Of two reads on their way, the later asked is the one that stands.
let quotaHistSeq = 0, quotaHistV = 0;
function loadQuotaHist() {
const seq = ++quotaHistSeq;
return api("usage/quotas/history?days=45").then((h) => {
if (seq !== quotaHistSeq || !h || JSON.stringify(h) === JSON.stringify(quotaHist)) return;
if (seq !== quotaHistSeq || !h || quotaHistV && JSON.stringify(h) === JSON.stringify(quotaHist)) return;
quotaHist = h; quotaHistV++;
if (quotas) renderQuotas(true);
}, () => {});
@@ -16701,6 +16706,7 @@ function usageHandle(sub, card) {
usageArranging = false;
if (usageRenderPending) { usageRenderPending = false; renderQuotas(); }
}, usageLayout);
if (usageArranging) unpin($("#view-usage"));
};
return b;
}
@@ -16720,6 +16726,7 @@ async function moveUsage(key, to) {
const prev = state.settings;
const order = [...keys, ...(prev.usageOrder || []).filter((k) => !keys.includes(k))];
state.settings = { ...prev, usageOrder: order };
unpin($("#view-usage"));
renderQuotas();
try {
const s = await api("usage/arrange", { order });
@@ -23105,10 +23112,13 @@ const scrolledFrom = new WeakMap();
// to keep in place (keepInView, the Routing page's lists under parts that
// redraw on their own): then it is where that part is on screen as the
// reader leaves it, and the view follows it (scroll anchoring WebKit lacked).
const pinOf = new Map(), pinAt = new WeakMap();
function keepInView(v, part) {
// A view whose part comes and goes (`only`, the Usage page's cards) leaves
// the browser's own anchoring on while it keeps none.
const pinOf = new Map(), pinAt = new WeakMap(), pinOnly = new WeakSet();
function keepInView(v, part, only) {
pinOf.set(v, part);
v.style.overflowAnchor = "none"; // the browser's own would anchor on another part, and fight this
if (only) pinOnly.add(v);
else v.style.overflowAnchor = "none"; // the browser's own would anchor on another part, and fight this
pinSizes.observe(v);
for (const c of v.children) pinSizes.observe(c);
}
@@ -23116,17 +23126,29 @@ function readerLeaves(v) {
readerAt.set(v, v.scrollTop);
// a view at its top stays at its top: nothing in it is kept in place
const p = pinOf.has(v) && v.scrollTop >= 1 ? pinOf.get(v)() : null;
pinAt.set(v, p ? [p, onScreen(p, v)] : null);
pinAt.set(v, p ? [p, onScreen(p, v), p.parentElement] : null);
if (pinOnly.has(v)) v.style.overflowAnchor = p ? "none" : "";
}
// the cards the reader moves stay where they put them: none is kept in place
// till the reader scrolls again (keepInView's part is none while arranging),
// the browser's own anchoring back as it is with none
function unpin(v) {
pinAt.delete(v);
v.style.overflowAnchor = "";
}
function pinnedAt(v) {
const a = pinAt.get(v);
// a part drawn again (a card by its data-key) is found again in its box
if (a && !a[0].isConnected && a[0].dataset.key) a[0] = a[2].querySelector(`:scope>[data-key="${CSS.escape(a[0].dataset.key)}"]`) || a[0];
return a && a[0].isConnected && a[0].offsetParent ? v.scrollTop + onScreen(a[0], v) - a[1] : null;
}
// laid out, not yet painted: a view with a part kept in place follows it
// as soon as what's above it has changed size, before the reader sees it
const pinSizes = new ResizeObserver(() => {
for (const v of pinOf.keys()) if (!v.hidden && held?.v !== v && performance.now() >= purposeUntil) backToReader(v);
});
// (followPin; a part redrawn or moved with nothing changing size calls it)
function followPin(v) {
if (pinOf.has(v) && (!pinOnly.has(v) || pinAt.get(v)) && !v.hidden && held?.v !== v && performance.now() >= purposeUntil) backToReader(v);
}
const pinSizes = new ResizeObserver(() => { for (const v of pinOf.keys()) followPin(v); });
function backToReader(v) {
if (v.hidden) return;
const pinned = pinnedAt(v);
+77 -2
View File
@@ -805,6 +805,30 @@ function fitChartLabels() {
}
new ResizeObserver(fitChartLabels).observe($("#view-usage"));
// The allowances' cards come in at different times, each vendor's read
// and the curves' history apart, and each one drawn grows the page above
// what's below it (liuzhengdong99 on X: 滑到上面看某张卡片,视图会被拽回下面).
// The Overview keeps where the reader is on what they read: the card, or
// the part of the page under the cards, nearest the view's top, found again
// by its data-key once the cards are drawn anew (keepInView in app.js). At
// the page's top, while the cards are arranged by hand (unpin in app.js),
// or on another tab, nothing is kept and the browser's own anchoring is
// left as it was.
keepInView($("#view-usage"), () => {
const v = $("#view-usage"), pane = $("#usagePane");
if (pane.hidden || !pane.offsetParent || usageArranging) return null;
// the highest that starts in sight, else the one cut by the view's top
const top = v.getBoundingClientRect().top, foot = top + v.clientHeight;
let best = null, at = Infinity, cut = null;
for (const n of [...$("#subscriptionUsage").children, ...[...pane.children].filter((c) => c.id !== "subscriptionUsage")]) {
if (!n.offsetParent) continue;
const r = n.getBoundingClientRect();
if (r.bottom <= top + 1 || !r.height || r.top >= foot) continue;
if (r.top >= top - 0.5) { if (r.top < at) { at = r.top; best = n; } } else if (!cut || r.top > cut.getBoundingClientRect().top) cut = n;
}
return best || cut;
}, true);
// The Overview's lists — Agents, Models, Accounts, Gateway keys — each fold
// away under their heading (#2378: 日常看账号维度较多,都要拉到最底下), and
// stay folded across a reload (magpie.usageFolded, the folded ones' names).
@@ -5693,6 +5717,46 @@ function cardsShownFor(p) {
// that ends highest (#860), as tall as what it holds (jen_celeus on X).
const USAGE_MIN = 260, USAGE_GAP = 7;
let usagePacked = null, usagePackFrame = 0;
// usageTall: each card's height as last drawn in full, by its key, kept
// for the next start (magpie.usageCardTall). A card still
// waiting on its read or its curve (usageWaiting) is packed and
// held at least that tall, so the cards come in without the page around
// them moving (liuzhengdong99 on X: 先按固定高度占位、数据回来再填内容).
let usageTall = {}, usageTallSave = 0;
try { usageTall = JSON.parse(localStorage.getItem("magpie.usageCardTall") || "{}") || {}; } catch {}
for (const k in usageTall) if (!(usageTall[k] > 0)) delete usageTall[k];
// still to come for a card: an account the gateway is reading yet
// (X-Magpie-Reading, asked again), or its curve before the history's
// first answer (quotasReading, quotaHistV in app.js; history that never
// comes leaves the card as tall as it was)
function usageWaiting(k) {
const subs = (quotas || []).filter((q) => q.provider === k);
return quotasReading && subs.some((q) => q.error) || !quotaHistV && quotaRange !== "off" && subs.some((q) => !q.error && q.windows?.length);
}
function usageWaits(cards, hs) {
const held = cards.map(() => false);
let moved = false;
cards.forEach((c, i) => {
const k = c.dataset.key, was = usageTall[k];
if (!k) return;
if (usageWaiting(k)) {
if (was > hs[i]) { hs[i] = was; held[i] = true; }
} else if (was !== Math.ceil(hs[i])) {
usageTall[k] = Math.ceil(hs[i]);
moved = true;
}
});
if (moved) usageTallKeep();
return held;
}
function usageTallKeep() {
if (!usageTallSave) usageTallSave = setTimeout(() => {
usageTallSave = 0;
const keys = Object.keys(usageTall);
for (const k of keys.slice(0, Math.max(0, keys.length - 200))) delete usageTall[k];
try { localStorage.setItem("magpie.usageCardTall", JSON.stringify(usageTall)); } catch {}
}, 1000);
}
function packUsage() {
const list = $("#subscriptionUsage");
if (usagePackFrame) { cancelAnimationFrame(usagePackFrame); usagePackFrame = 0; }
@@ -5716,10 +5780,13 @@ function packUsage() {
const empty = ends.reduce((s, e) => s + tall - (e - USAGE_GAP), 0) * (width - (n - 1) * USAGE_GAP) / n;
return { n, at, tall, empty };
};
let held = [];
const heights = () => {
for (const c of cards) c.style.minHeight = "";
fitQuota([...list.querySelectorAll(".quota-windows")]);
return foldedHeights(cards, cards.map((c) => c.getBoundingClientRect().height));
const hs = cards.map((c) => c.getBoundingClientRect().height);
held = usageWaits(cards, hs);
return foldedHeights(cards, hs);
};
const columns = (n) => { list.style.gridTemplateColumns = `repeat(${n}, minmax(0, 1fr))`; };
let best;
@@ -5729,7 +5796,11 @@ function packUsage() {
} else {
list.classList.remove("packed");
for (const c of cards) c.style.gridArea = "";
// while cards are still to come, the columns they were last seen
// whole in ("#" + how many fit): the heights kept are that width's
const waits = cards.some((c) => usageWaiting(c.dataset.key)), kept = usageTall["#" + most];
for (let n = most; n >= Math.max(1, most - 1); n--) {
if (waits && kept && n !== kept && kept >= most - 1 && kept <= most) continue;
columns(n);
const p = place(n, heights());
if (!best) best = p;
@@ -5740,13 +5811,17 @@ function packUsage() {
best = place(best.n, heights());
}
usagePacked = { most, keys, n: best.n };
if (!held.some(Boolean) && !cards.some((c) => usageWaiting(c.dataset.key)) && usageTall["#" + most] !== best.n) { usageTall["#" + most] = best.n; usageTallKeep(); }
list.classList.add("packed");
best.at.forEach(([c, top, h], i) => {
const area = `${top + 1} / ${c + 1} / span ${Math.max(1, h)} / span 1`;
if (cards[i].style.gridArea !== area) cards[i].style.gridArea = area;
const min = cards[i].dataset.folded ? h + "px" : "";
const min = cards[i].dataset.folded || held[i] ? h + "px" : "";
if (cards[i].style.minHeight !== min) cards[i].style.minHeight = min;
});
// the cards drawn anew or moved to another column: the one being read
// stays where it was on the screen
followPin($("#view-usage"));
}
// foldedHeights: a folded card as tall as the tallest folded one of one
// account, or whole rows of it, so folded cards line up in a grid; an
File diff suppressed because one or more lines are too long
+8
View File
@@ -1211,6 +1211,14 @@ at least 5em, at 420 wide the long names are shortened while no bar is under
5em and nothing runs past its card, and wide again the names are whole; in
Chromium and WebKit, English and Chinese.
`usage-cards-steady.test.cjs` opens Usage › Overview with eight allowance
cards, most still being read (`X-Magpie-Reading`), wheels down and back up
to a card in the middle, then lets the reads and the curves' history in
400ms apart. The card being read must not move a pixel in any frame;
opened again with the heights known, no card in sight may move. All five
languages, 1100px and 420px, Chromium and WebKit; the API is faked.
`MAGPIE_ASSETS` selects older assets for the failing comparison.
`usage-sessions-agents-fit.test.cjs` checks Usage › Sessions with 15 agents
(#929): the agent filter is a menu button like the model and folder ones, no
segment per agent; at 860 and 560 wide nothing scrolls sideways and the three
@@ -0,0 +1,179 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// The Usage page's allowance cards come in at different times (liuzhengdong99
// on X: 用量界面每张卡片取数的时间不一致,导致卡片渲染时高度一直跳动——滑到
// 上面看某张卡片,视图会被拽回下面). The reader wheels up to a card while the
// page is still reading: the vendors' answers land a few at a time (the page
// asks again while X-Magpie-Reading says a read is under way) and the curves'
// history after them. The card being read (the highest starting in sight)
// stays where it is on the screen through every frame. Opened again, with
// the cards' heights known from before, no card in sight moves at all: a
// card waiting on its read or its curve keeps the room it had.
// MAGPIE_ASSETS can point at older assets.
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 H = 3600e3, iso = (ms) => new Date(ms).toISOString();
// eight accounts' cards; the n-th read has the first 3 + 2n read, the rest
// still failing as a read cut short does, and the curves' history comes last
const NAMES = ["Claude Code", "Codex", "Kimi", "GLM", "MiniMax", "Copilot", "Gemini", "Qwen"];
function cards(now, read) {
return NAMES.map((name, i) => {
const q = { provider: "p" + i, name, icon: "openai", plan: "Pro", readAt: iso(now - 60e3) };
if (i >= read) return { ...q, windows: [], error: "Get \"https://api.example.com/usage\": context deadline exceeded" };
const windows = [{ name: "5 hours", used: 10 + i * 7, resetsAt: iso(now + 2 * H) }, { name: "Weekly", used: 5 + i * 3, resetsAt: iso(now + 50 * H) }];
if (i % 3 === 0) windows.push({ name: "Monthly", used: 30, resetsAt: iso(now + 400 * H) });
return { ...q, windows };
});
}
function history(now) {
return NAMES.map((_, i) => ({
provider: "p" + i, user: "",
lines: [{ name: "5 hours", points: Array.from({ length: 8 }, (_, k) => ({ at: iso(now - (8 - k) * 20 * 60e3), left: 100 - k * 5 - i, start: iso(now - 3 * H), resetsAt: iso(now + 2 * H) })) }],
}));
}
function serve(lang, st) {
const settings = { theme: "light", lang, quotaLeft: false, currency: "usd" };
return async (route) => {
const url = new URL(route.request().url());
const json = (body, headers) => route.fulfill({ json: body, headers });
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") {
// a read held till the test lets the next answer go
const n = st.reads++;
if (n > 0) await st.gate(n);
const read = Math.min(NAMES.length, 3 + 2 * n);
return json(cards(st.now, read), read < NAMES.length ? { "X-Magpie-Reading": "1" } : {});
}
if (url.pathname === "/api/usage/quotas/history") { await st.gate("history"); return json(history(st.now)); }
if (url.pathname === "/api/usage") {
// the local figures under the cards, so the page scrolls
const series = Array.from({ length: 7 }, (_, i) => ({ label: "d" + i, time: iso(st.now - (6 - i) * 24 * H), calls: 10 + i, input: 100, output: 200, cache_read: 0, cache_write: 0, cost: 0.1 }));
const agents = Array.from({ length: 12 }, (_, i) => ({ id: "a" + i, name: "Agent " + i, calls: 10 + i, input: 100, output: 200, cost: 0.1 }));
const models = Array.from({ length: 12 }, (_, i) => ({ id: "m" + i, calls: 10 + i, input: 100, output: 200, cost: 0.1 }));
return json({ calls: 100, errors: 0, input: 1000, output: 2000, reasoning: 0, unpriced: 0, cost: 1, bucket: "day", series, agents, models, keys: [], path: "" });
}
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: "" }); }
};
}
// where each card is on the screen, every frame, until stopWatch()
const WATCH = () => {
const seen = [];
let on = true;
const v = document.querySelector("#view-usage");
const tick = () => {
const top = v.getBoundingClientRect().top, at = {};
for (const c of document.querySelectorAll("#subscriptionUsage > [data-key]")) at[c.dataset.key] = Math.round((c.getBoundingClientRect().top - top) * 2) / 2;
seen.push(at);
if (on) requestAnimationFrame(tick);
};
requestAnimationFrame(tick);
window.stopWatch = () => { on = false; return seen; };
};
// the cards in sight, by where they are from the view's top
const IN_SIGHT = () => {
const v = document.querySelector("#view-usage"), b = v.getBoundingClientRect(), at = {};
for (const c of document.querySelectorAll("#subscriptionUsage > [data-key]")) {
const r = c.getBoundingClientRect();
if (r.top >= b.top && r.top < b.top + v.clientHeight) at[c.dataset.key] = r.top - b.top;
}
return at;
};
const LANGS = ["en", "zh", "zh-TW", "ja", "de"];
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of LANGS) {
for (const width of [1100, 420]) {
test(`${engine} ${lang} ${width}px: a card read while the others come in stays where it is`, 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: 700 }, reducedMotion: "no-preference" });
page.setDefaultTimeout(8000);
page.setDefaultNavigationTimeout(60000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
const held = new Map();
const st = {
now: Date.now(), reads: 0,
open: new Set(),
gate: (k) => st.open.has(k) ? null : new Promise((r) => held.set(k, [...held.get(k) || [], r])),
};
const release = async (k) => {
for (let i = 0; i < 100 && !held.has(k); i++) await page.waitForTimeout(30);
assert.ok(held.has(k), "the page asked for " + k);
st.open.add(k);
for (const r of held.get(k)) r();
held.delete(k);
};
t.after(() => { for (const rs of held.values()) for (const r of rs) r(); });
await page.addInitScript(() => { localStorage.setItem("magpie.navLayout", "top"); localStorage.setItem("magpie.usageTab", "usage"); });
await page.route("**/*", serve(lang, st));
const view = page.locator("#view-usage");
const key = width > 600 ? "p5" : "p4";
const top = () => page.evaluate((k) => {
const v = document.querySelector("#view-usage"), c = document.querySelector(`#subscriptionUsage > [data-key="${k}"]`);
return c.getBoundingClientRect().top - v.getBoundingClientRect().top;
}, key);
// opened, read a few at a time while the reader goes down the page
// and back up to a card in the middle; then the rest come in
const visit = async () => {
st.reads = 0; st.open.clear();
await page.goto("http://magpie.test/?view=usage");
await page.locator('#subscriptionUsage > [data-key="p7"]').waitFor();
await page.locator("#usageModels .row").first().waitFor();
const box = await view.boundingBox();
await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
for (let i = 0; i < 30 && await page.evaluate(() => { const v = document.querySelector("#view-usage"); return v.scrollTop + v.clientHeight < v.scrollHeight - 2; }); i++) {
await page.mouse.wheel(0, 200);
await page.waitForTimeout(40);
}
for (let i = 0; i < 60 && await top() < 60; i++) {
await page.mouse.wheel(0, -60);
await page.waitForTimeout(40);
}
await page.waitForTimeout(500);
const sight = await page.evaluate(IN_SIGHT);
assert.ok(Object.keys(sight).length, "a card is in sight");
await page.evaluate(WATCH);
for (const k of [1, 2, 3, "history"]) {
await release(k);
await page.waitForTimeout(400);
}
await page.locator(`#subscriptionUsage > [data-key="p7"] .quota-curve`).waitFor();
await page.waitForTimeout(400);
const seen = await page.evaluate(() => window.stopWatch());
// each card in sight: where it went, frame by frame
return Object.fromEntries(Object.entries(sight).map(([k, at]) => [k, [at, [...new Set(seen.map((s) => s[k]).filter((y) => y == null || Math.abs(y - at) > 1))]]]));
};
// the first time: the card the reader is on, the highest starting
// in sight, stays
const first = await visit();
const [read] = Object.entries(first).sort((a, b) => a[1][0] - b[1][0]);
assert.deepEqual(read[1][1], [], `${read[0]} was at ${read[1][0]}px from the view's top; it went to ${read[1][1].join(", ")}`);
// opened again, every card's height known: none in sight moves
await page.waitForTimeout(1200); // the heights kept (a second after)
const again = await visit();
for (const [k, [at, moved]] of Object.entries(again)) assert.deepEqual(moved, [], `opened again, ${k} was at ${at}px from the view's top; it went to ${moved.join(", ")}`);
assert.deepEqual(errors, []);
});
}
}
}