gui: a card of many accounts is laid out once a render, not once an account (#5310)
fitQuota stacks each window's counts and gives side-by-side names one height. It ran group by group: clear the names' min-height, then read their offsetTop. Every read after a write lays the card out again, so one Usage render with N accounts in full laid the card out N times, O(N²). With 600 accounts at 520px wide and the names wrapping (a long window name), one render held WebKit's WebContent at 100% CPU: 1.7-2.3s of script and 10-13s to the second frame after it. Chromium took 1.2-1.4s. fitQuota now takes every group. It reads all the sizes first, then writes the classes and clears the heights. It reads each name's row and height in one pass, then sets the heights. packUsage's heights() passes the card's groups in one call; the ResizeObserver path already passed a set. Probe (600 accounts, all open, W=520, wrapped names), on mote: WebKit: 0.5s sync, 0.7s to two frames (was 1.7-2.3s, 10-13s) Chromium: 0.45s (was 1.2-1.4s) Wide layout, both engines: 0.3-0.4s before and after. Scrolling 600 accounts was smooth before and after (2 frames ~30ms). Test: quota-fit-batched.test.cjs counts the layouts forced in one render: a read of a layout getter while MutationObserver records are pending. The count must be the same at 160 accounts as at 40 (+4 room for a frame's observer). It also checks that every group was drawn, the names' heights were written, and each group was evened. Chromium and WebKit, en/zh/zh-TW/ja/de, 10/10 green. Broken by hand: the test pointed at HEAD's app.js (MAGPIE_FIT_ASSETS) is red 10/10: 243 forced layouts at 40 accounts, 963 at 160, both engines. Run (mote, load ~30; first at base40cfae5d3+ this change): - 161 GUI files that touch quota/usage/panel, both engines, every language they cover: 2832 tests, 34 red in 9 files. - Those 9 files again, on this change and on base40cfae5d3alone: 25 red with the change, 30 on base. Every red on the change is also red on base except provider-mask, which times out in a different language each run on both trees (#5109). - The reds on base are filed: codex-auto-reset webkit de (#4790), mobile-web (#3952, #5013), tray-cell-click (#5215), usage-fold 'most on one screen' (#4790, #3415), and panel-fold (#5796, filed now). - i18n-keys 'a plugin's words are its own' is red (#5327, #5332, #5426, #5482). - At the pushed head (this change on origin/mainc056b7c8c): TestCoreScriptBudget ok. quota-fit-batched 10/10, and usage-agents-hide, usage-compact-counts, usage-fold, usage-ledger and usage-ledger-search run beside it: 32 red, the same 32 as atc056b7c8calone (usage-agents-hide #2276 #3414, usage-ledger Requests #5048, usage-fold #4790 #3415). Not tried: the real app with 600 real accounts. The fixture's accounts are Claude windows with one long name. Another layer is not changed: the first layout after the rebuild, resetClock's Intl formatters, and building the DOM, ~45ms each at 600 accounts.
This commit is contained in:
@@ -16347,7 +16347,7 @@ function packUsage() {
|
||||
};
|
||||
const heights = () => {
|
||||
for (const c of cards) c.style.minHeight = "";
|
||||
for (const g of list.querySelectorAll(".quota-windows")) fitQuota(g);
|
||||
fitQuota([...list.querySelectorAll(".quota-windows")]);
|
||||
return cards.map((c) => c.getBoundingClientRect().height);
|
||||
};
|
||||
const columns = (n) => { list.style.gridTemplateColumns = `repeat(${n}, minmax(0, 1fr))`; };
|
||||
@@ -18375,20 +18375,31 @@ const quotaFit = new ResizeObserver((es) => {
|
||||
for (const { target } of es) quotaFitting.add(target);
|
||||
});
|
||||
function fitQuotas() {
|
||||
for (const g of quotaFitting) fitQuota(g);
|
||||
fitQuota([...quotaFitting]);
|
||||
quotaFitting.clear();
|
||||
}
|
||||
function fitQuota(g) {
|
||||
// fitQuota fits the groups of windows given, every one's sizes read before
|
||||
// any is changed: a read after a change lays the page out again, and a card
|
||||
// of hundreds of accounts, each group's names reset and then read, was laid
|
||||
// out once a group, in WebKit seconds a render at 600 (#5310).
|
||||
function fitQuota(groups) {
|
||||
const wide = (e) => [...e.children].reduce((w, c) => w + c.getBoundingClientRect().width, 0) + 4 * (e.children.length - 1);
|
||||
const wraps = [...g.querySelectorAll(".quota-labels")].some((l) => {
|
||||
const wraps = groups.map((g) => [...g.querySelectorAll(".quota-labels")].some((l) => {
|
||||
const [name, n] = l.children;
|
||||
return name.getBoundingClientRect().width + 6 + wide(n) > l.clientWidth;
|
||||
}));
|
||||
const labels = groups.map((g) => [...g.querySelectorAll(":scope > .quota > .quota-labels")]);
|
||||
groups.forEach((g, i) => {
|
||||
g.classList.toggle("stacked", wraps[i]);
|
||||
for (const l of labels[i]) l.style.minHeight = "";
|
||||
});
|
||||
// each name's row and height, then the tallest of each row's to each
|
||||
const read = labels.map((ls) => ls.map((l) => [l.offsetTop, l.getBoundingClientRect().height]));
|
||||
labels.forEach((ls, i) => {
|
||||
const top = {};
|
||||
for (const [y, h] of read[i]) top[y] = Math.max(top[y] || 0, h);
|
||||
ls.forEach((l, j) => { const [y, h] = read[i][j]; if (top[y] > h + 0.5) l.style.minHeight = top[y] + "px"; });
|
||||
});
|
||||
g.classList.toggle("stacked", wraps);
|
||||
const ls = g.querySelectorAll(":scope > .quota > .quota-labels"), top = {}, h = (l) => l.getBoundingClientRect().height;
|
||||
for (const l of ls) l.style.minHeight = "";
|
||||
for (const l of ls) top[l.offsetTop] = Math.max(top[l.offsetTop] || 0, h(l));
|
||||
for (const l of ls) if (top[l.offsetTop] > h(l) + 0.5) l.style.minHeight = top[l.offsetTop] + "px";
|
||||
}
|
||||
|
||||
// balanceRow: what is left, a line per amount, the first the one that
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// A card of many accounts is drawn again without laying the page out once
|
||||
// an account (#5310). fitQuota stacks each window's count and gives the
|
||||
// names beside each other one height; it read each group's names after
|
||||
// resetting them, and every such read laid out the whole card again: at
|
||||
// 600 accounts in full, names wrapped, a render took WebKit seconds and
|
||||
// held the WebContent process at 100% CPU. Every group's sizes are read
|
||||
// before any is changed now. This counts the reads of a layout made after
|
||||
// a write a render has made (a forced layout), in both engines and every
|
||||
// language, and holds the count to the same at 40 accounts as at 160.
|
||||
// MAGPIE_FIT_ASSETS points the page at an older asset tree, to watch this
|
||||
// go red there.
|
||||
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(__dirname, process.env.MAGPIE_FIT_ASSETS || "../assets");
|
||||
const at = (ms) => new Date(Date.now() + ms).toISOString();
|
||||
const quotasOf = (n) => Array.from({ length: n }, (_, i) => ({
|
||||
provider: "claude", name: "Claude", icon: "claudecode-color", user: `user${i}@example.com`,
|
||||
windows: [
|
||||
{ name: "5 hours", used: (i * 7) % 100, resetsAt: at(36e5 * ((i % 5) + 1)) },
|
||||
// wraps beside the short one at this width: the names get a height
|
||||
{ name: "7 days of every Opus and Sonnet model together", used: (i * 13) % 100, resetsAt: at(864e5 * ((i % 6) + 1)) },
|
||||
],
|
||||
}));
|
||||
|
||||
function serve(lang, quotas) {
|
||||
const settings = { lang, theme: "light", currency: "usd" };
|
||||
return async (r) => {
|
||||
const url = new URL(r.request().url());
|
||||
const json = (data) => r.fulfill({ json: data });
|
||||
if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
|
||||
if (url.pathname === "/wails/runtime.js") return r.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/quotas/history") return json([]);
|
||||
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 r.fulfill({ body: await fs.readFile(file), contentType }); } catch { await r.fulfill({ status: 404, body: "" }); }
|
||||
};
|
||||
}
|
||||
|
||||
// every account in full, none folded away; and a count of the reads of a
|
||||
// layout made after the page changed (a node added, a style or class
|
||||
// written): the observer's records are taken in each read, so a read with
|
||||
// any waiting is one that lays the page out again
|
||||
const watch = () => {
|
||||
try {
|
||||
localStorage.setItem("magpie.usageOpen", JSON.stringify(["claude"]));
|
||||
localStorage.setItem("magpie.usageAcctsAll", JSON.stringify(["claude"]));
|
||||
} catch {}
|
||||
const w = (window.__fit = { on: false, forced: 0, heights: 0 });
|
||||
const mo = new MutationObserver(() => {});
|
||||
mo.observe(document, { subtree: true, childList: true, attributes: true, attributeFilter: ["style", "class"] });
|
||||
const take = () => {
|
||||
const rs = mo.takeRecords();
|
||||
if (w.on) w.heights += rs.filter((r) => r.attributeName === "style" && r.target.classList?.contains("quota-labels")).length;
|
||||
return rs.length;
|
||||
};
|
||||
w.take = take;
|
||||
const read = () => { if (take() && w.on) w.forced++; };
|
||||
for (const name of ["offsetTop", "offsetHeight", "offsetWidth", "clientWidth", "clientHeight"]) {
|
||||
const proto = name.startsWith("offset") ? HTMLElement.prototype : Element.prototype;
|
||||
const d = Object.getOwnPropertyDescriptor(proto, name);
|
||||
Object.defineProperty(proto, name, { ...d, get() { read(); return d.get.call(this); } });
|
||||
}
|
||||
const rect = Element.prototype.getBoundingClientRect;
|
||||
Element.prototype.getBoundingClientRect = function () { read(); return rect.call(this); };
|
||||
};
|
||||
|
||||
// the forced layouts of one render of the Usage page's cards, with the
|
||||
// frame after it that fits what its observer saw
|
||||
async function forcedLayouts(browser, lang, n) {
|
||||
const context = await browser.newContext({ viewport: { width: 520, height: 800 }, reducedMotion: "reduce" });
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(30000);
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.addInitScript(watch);
|
||||
await page.route("**/*", serve(lang, quotasOf(n)));
|
||||
await page.goto("http://magpie.test/?view=usage&tab=usage");
|
||||
await page.waitForFunction((n) => document.querySelectorAll("#subscriptionUsage .quota-windows:not(.brief)").length >= n, n);
|
||||
const seen = await page.evaluate(async () => {
|
||||
const w = window.__fit;
|
||||
await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));
|
||||
w.take();
|
||||
w.on = true; w.forced = 0; w.heights = 0;
|
||||
renderQuotas(true);
|
||||
await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));
|
||||
w.take();
|
||||
w.on = false;
|
||||
const groups = [...document.querySelectorAll("#subscriptionUsage .quota-windows")];
|
||||
return {
|
||||
forced: w.forced, heights: w.heights,
|
||||
groups: groups.length,
|
||||
stacked: groups.filter((g) => g.classList.contains("stacked")).length,
|
||||
evened: document.querySelectorAll("#subscriptionUsage .quota-labels[style*='min-height']").length,
|
||||
};
|
||||
});
|
||||
await context.close();
|
||||
assert.deepEqual(errors, []);
|
||||
return seen;
|
||||
}
|
||||
|
||||
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}: a card of many accounts is drawn again in no more layouts at 160 than at 40`, async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
const few = await forcedLayouts(browser, lang, 40);
|
||||
const many = await forcedLayouts(browser, lang, 160);
|
||||
// what the count is about happened: every account's windows drawn,
|
||||
// the names' heights written, in both renders
|
||||
assert.equal(few.groups, 40);
|
||||
assert.equal(many.groups, 160);
|
||||
assert.ok(few.heights >= 40 && many.heights >= 160, `names' heights written: ${few.heights}, ${many.heights}`);
|
||||
// the names wrapped and were given one height, as at any count
|
||||
assert.equal(few.evened, 40);
|
||||
assert.equal(many.evened, 160);
|
||||
assert.ok(few.forced > 0, "a render lays the card out");
|
||||
// a frame's observer can land on either side of the count's end: room
|
||||
// for that, none for a layout an account
|
||||
assert.ok(many.forced <= few.forced + 4, `forced layouts: ${few.forced} at 40 accounts, ${many.forced} at 160`);
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user