Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

routing: a day of thousands of requests draws only the rows in sight, and its numbers are measured again on a new width only (#2524)

yetonea8224019afa3
diff --git a/internal/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.js
index 4c636d50b..6fdaf6646 100644
--- a/internal/gui/assets/plugins/routing/client.js
+++ b/internal/gui/assets/plugins/routing/client.js
@@ -283,7 +283,7 @@ function routingPage(part) {
const metaFit = () => { if (!metaFitting) metaFitting = requestAnimationFrame(() => {
metaFitting = 0;
if (colA.classList.contains("max760") || !reqs.offsetParent) return;
- const kept = [];
+ const kept = [], under = colA.classList.contains("meta-under");
for (let p = reqs; p; p = p.parentElement) if (p.scrollTop) kept.push([p, p.scrollTop]);
colA.classList.remove("meta-under");
const wraps = [...reqs.querySelectorAll(".rt-req .meta:not([hidden])")].some((m) => {
@@ -292,8 +292,13 @@ function routingPage(part) {
});
colA.classList.toggle("meta-under", wraps);
for (const [p, top] of kept) if (p.scrollTop !== top) p.scrollTop = top;
+ if (colA.classList.contains("meta-under") !== under) redrawList(); // the rows' heights changed
}); };
- new ResizeObserver(metaFit).observe(colA);
+ // only a new width can make the numbers wrap or fit: measured on its
+ // height too, the mark it sets made the rows taller and measured them
+ // again, flipping back and forth (#2524: 8 times in 8s, ~200ms each)
+ let metaW = -1;
+ new ResizeObserver(() => { const w = colA.clientWidth; if (w !== metaW) { metaW = w; metaFit(); } }).observe(colA);
const path = () => { const p = document.createElementNS(NS, "path"); wires.appendChild(p); return p; };
const setText = (e, s) => { if (e.textContent !== s) e.textContent = s; };
@@ -2625,58 +2630,202 @@ function routingPage(part) {
t("Each request an agent sends through magpie shows up here: who answered it, why, and each try."));
if (!day && days.length) p.append(" " + t("Earlier ones are kept by day, in the bar above."));
reqs.replaceChildren(p);
+ reqs.classList.remove("win");
+ listItems = [];
+ probes.clear();
reqRows.clear();
sessionRows.clear();
closedSessions.clear();
renderActs(rs);
return;
}
- const lang = document.documentElement.lang, ids = new Set();
- let redrawn = false; // a row made anew, or the rows moved: metaFit measures them again
- const rowEls = rs.map((r) => {
- const [said, how, tr] = outcome(r);
- const sel = String(pinned ? pinned.id === r.id : cur?.id === r.id);
- const ag = agentOf(r.agent);
- const meta = [];
- if (r.tries.length > 1) meta.push(t("{n} tries", { n: r.tries.length }));
- const metrics = requestMetrics(r, how);
- // all the row says, and its titles
- const title = reqTitle(r, how, tr);
- const sig = JSON.stringify([lang, said, how, title, r.time, r.agent, agentName(r.agent), ag?.icon, r.model, r.provider, tagKind(r), r.effort,
- tr?.effort, tr?.picked, tr?.fixed, tr?.fast, tr?.swapped && tr.done && tryOk(tr) ? [tr.model, tr.served] : 0, tr?.routed && tr.done && tryOk(tr) ? tr.served : 0, tr?.done && tryOk(tr) ? tr.upstream : 0, meta, metrics, routeCost(r)]);
- ids.add(r.id);
- let x = reqRows.get(r.id);
- if (!x || x.sig !== sig) {
- const row = x = { sig, b: reqRow(r, said, how, tr, ag, meta, metrics, title) };
- row.b.onclick = () => pick(row.r); // the request as it is when clicked
- reqRows.set(r.id, x);
- redrawn = true;
+ const ids = new Set(rs.map((r) => r.id));
+ for (const id of reqRows.keys()) if (!ids.has(id)) reqRows.delete(id);
+ // the requests, with their sessions' heads between them when grouped:
+ // a request's row is made only when it is drawn
+ listItems = bySession && rs.some((r) => r.session) ? groupedRows(rs, rs) : rs;
+ rowsMoved = false;
+ drawList();
+ // measuring the rows' lines forces a layout: only when a row was made
+ // anew or the rows moved (a resize measures them through the
+ // ResizeObserver)
+ if (rowsMoved) metaFit();
+ renderActs(rs);
+ }
+ // rowOf: a request's row, kept while what it says is the same
+ function rowOf(r) {
+ const lang = document.documentElement.lang;
+ const [said, how, tr] = outcome(r);
+ const sel = String(pinned ? pinned.id === r.id : cur?.id === r.id);
+ const ag = agentOf(r.agent);
+ const meta = [];
+ if (r.tries.length > 1) meta.push(t("{n} tries", { n: r.tries.length }));
+ const metrics = requestMetrics(r, how);
+ // all the row says, and its titles
+ const title = reqTitle(r, how, tr);
+ const sig = JSON.stringify([lang, said, how, title, r.time, r.agent, agentName(r.agent), ag?.icon, r.model, r.provider, tagKind(r), r.effort,
+ tr?.effort, tr?.picked, tr?.fixed, tr?.fast, tr?.swapped && tr.done && tryOk(tr) ? [tr.model, tr.served] : 0, tr?.routed && tr.done && tryOk(tr) ? tr.served : 0, tr?.done && tryOk(tr) ? tr.upstream : 0, meta, metrics, routeCost(r)]);
+ let x = reqRows.get(r.id);
+ if (!x || x.sig !== sig) {
+ const row = x = { sig, b: reqRow(r, said, how, tr, ag, meta, metrics, title) };
+ row.b.onclick = () => pick(row.r); // the request as it is when clicked
+ reqRows.set(r.id, x);
+ rowsMoved = true;
+ }
+ x.r = r;
+ if (x.b.getAttribute("aria-pressed") !== sel) x.b.setAttribute("aria-pressed", sel);
+ return x.b;
+ }
+ // A day of history is up to 2,000 requests, and a row is ~20 elements:
+ // all of them in the list, a day picked took the page 0.4–0.7s here and
+ // seconds on Windows, and the old rows stayed in while the new ones went
+ // in among them, twice the rows at once (#2524, UNscientific-9). A list
+ // that long draws only the rows in and near its sight, between two gaps
+ // as tall as the rows above and below; scrolled, it draws the next ones.
+ // A row's height is measured once it was drawn, and one not yet drawn is
+ // taken as tall as the average drawn.
+ //
+ // The columns are as wide as the widest of all the requests, drawn or
+ // not, as before: a row unlike any drawn — another time's shape, model,
+ // kind or numbers — is in the list too, with no height and unseen (a
+ // probe), so the grid sizes its columns by it. Digits are as wide as
+ // each other there (tabular-nums), so a probe stands for every row of
+ // its shape.
+ const WIN_MIN = 300;
+ let listItems = [], winKey = "", winAvg = 0, winSoon = 0, rowsMoved = false;
+ const heights = new Map(); // a request's id, or a session's head → its height
+ const gapAbove = el("div", "rt-gap"), gapBelow = el("div", "rt-gap");
+ for (const g of [gapAbove, gapBelow]) g.setAttribute("aria-hidden", "true");
+ const probes = new Map(), probeShapes = new WeakMap();
+ const isHead = (x) => x instanceof Element;
+ const itemKey = (x) => isHead(x) ? x : x.id;
+ const itemEl = (x) => isHead(x) ? x : rowOf(x);
+ const digits = (s) => String(s).replace(/\d/g, "0");
+ let clockFmt = null, clockLang = "";
+ const rowClock = (time) => {
+ if (clockLang !== intlLang()) { clockLang = intlLang(); clockFmt = new Intl.DateTimeFormat(clockLang, { hour: "2-digit", minute: "2-digit", second: "2-digit" }); }
+ return clockFmt.format(new Date(time));
+ };
+ // what decides a row's width in each column sized by its content: its
+ // time, what was asked for, its numbers
+ function shapes(r, key) {
+ const was = probeShapes.get(r);
+ if (was && was.key === key) return was.s;
+ const how = outcome(r)[1], meta = r.tries.length > 1 ? t("{n} tries", { n: r.tries.length }) : "";
+ const s = ["t" + digits(rowClock(r.time)), "a" + JSON.stringify([r.model, tagKind(r) ? kindName(tagKind(r)) : ""]),
+ "m" + digits(JSON.stringify([meta, requestMetrics(r, how).map((m) => [m[0], m[2]])]))];
+ probeShapes.set(r, { key, s });
+ return s;
+ }
+ function probesFor(rs) {
+ const key = document.documentElement.lang + "|" + visibleMetrics.join(), seen = new Set(), want = new Map();
+ for (const r of rs) {
+ const s = shapes(r, key);
+ if (s.every((x) => seen.has(x))) continue;
+ s.forEach((x) => seen.add(x));
+ const id = key + JSON.stringify(s);
+ if (!want.has(id)) want.set(id, r);
+ }
+ for (const id of probes.keys()) if (!want.has(id)) probes.delete(id);
+ return [...want].map(([id, r]) => {
+ let b = probes.get(id);
+ if (!b) {
+ const [said, how, tr] = outcome(r), meta = r.tries.length > 1 ? [t("{n} tries", { n: r.tries.length })] : [];
+ b = reqRow(r, said, how, tr, agentOf(r.agent), meta, requestMetrics(r, how), "");
+ b.classList.add("probe");
+ b.removeAttribute("title");
+ b.tabIndex = -1;
+ b.inert = true;
+ b.setAttribute("aria-hidden", "true");
+ probes.set(id, b);
}
- x.r = r;
- if (x.b.getAttribute("aria-pressed") !== sel) x.b.setAttribute("aria-pressed", sel);
- return x.b;
+ return b;
});
- for (const id of reqRows.keys()) if (!ids.has(id)) reqRows.delete(id);
- const els = bySession && rs.some((r) => r.session) ? groupedRows(rs, rowEls) : rowEls;
- // the rows moved only where they changed; the list scrolls on its own,
- // and WebKit, a row taken out for a moment, would send it back to its
- // top from under the row just picked
+ }
+ // placeRows puts the list's children in order, moving only those out of
+ // place: the list scrolls on its own, and WebKit, a row taken out for a
+ // moment, would send it back to its top from under the row just picked.
+ // A list made mostly anew (another day) is put in at once, not row by
+ // row among the old ones.
+ function placeRows(els) {
const kids = reqs.children;
- if (kids.length !== els.length || els.some((e, i) => kids[i] !== e)) {
- const listTop = reqs.scrollTop;
- els.forEach((e, i) => { if (kids[i] !== e) reqs.insertBefore(e, kids[i] || null); });
- while (kids.length > els.length) reqs.lastElementChild.remove();
- if (reqs.scrollTop !== listTop) reqs.scrollTop = listTop;
- redrawn = true;
+ if (kids.length === els.length && els.every((e, i) => kids[i] === e)) return;
+ rowsMoved = true;
+ const listTop = reqs.scrollTop;
+ let kept = 0;
+ for (const e of els) if (e.parentNode === reqs) kept++;
+ if (kept * 2 < els.length) reqs.replaceChildren(...els);
+ else {
+ let at = reqs.firstElementChild;
+ for (const e of els) {
+ if (e === at) { at = at.nextElementSibling; continue; }
+ reqs.insertBefore(e, at);
+ }
+ while (at) { const n = at.nextElementSibling; at.remove(); at = n; }
+ }
+ if (reqs.scrollTop !== listTop) reqs.scrollTop = listTop;
+ }
+ function drawList() {
+ const n = listItems.length;
+ if (n < WIN_MIN) {
+ reqs.classList.remove("win");
+ probes.clear();
+ return placeRows(listItems.map(itemEl));
+ }
+ reqs.classList.add("win");
+ // out of sight (another view, the window hidden) nothing has a height:
+ // drawn as last measured, and measured once in sight again
+ const live = !!reqs.offsetParent;
+ const listKey = [colA.className, reqs.clientWidth, document.documentElement.lang, visibleMetrics.join()].join("|");
+ if (live && listKey !== winKey) { winKey = listKey; heights.clear(); winAvg = 0; }
+ const pad = parseFloat(getComputedStyle(reqs).paddingTop) || 0;
+ // the first row in sight, and where: it stays there
+ const box = reqs.getBoundingClientRect();
+ let anchor = null, anchorAt = 0;
+ for (const e of reqs.children) {
+ if (e.classList.contains("rt-gap") || e.classList.contains("probe")) continue;
+ const r = e.getBoundingClientRect();
+ if (r.bottom > box.top) { anchor = e; anchorAt = r.top - box.top; break; }
+ }
+ const est = winAvg || 31, off = new Float64Array(n + 1);
+ const sum = () => { for (let i = 0; i < n; i++) off[i + 1] = off[i] + (heights.get(itemKey(listItems[i])) ?? est); };
+ sum();
+ const view = reqs.clientHeight, over = Math.max(view, 300), y = reqs.scrollTop - pad;
+ let i0 = 0, i1 = n;
+ while (i0 < n - 1 && off[i0 + 1] <= y - over) i0++;
+ for (let i = i0; i < n; i++) if (off[i] >= y + view + over) { i1 = i; break; }
+ const drawn = listItems.slice(i0, i1).map(itemEl);
+ gapAbove.style.height = off[i0] + "px";
+ gapBelow.style.height = off[n] - off[i1] + "px";
+ placeRows([gapAbove, ...drawn, gapBelow, ...probesFor(listItems.filter((x) => !isHead(x)))]);
+ if (!live) return;
+ // measured as drawn: each one's slot in the grid, its margins with it
+ drawn.forEach((e, i) => {
+ const s = getComputedStyle(e);
+ heights.set(itemKey(listItems[i0 + i]), e.getBoundingClientRect().height + parseFloat(s.marginTop) + parseFloat(s.marginBottom));
+ });
+ let total = 0;
+ for (const h of heights.values()) total += h;
+ winAvg = heights.size ? total / heights.size : 0;
+ sum();
+ const above = off[i0] + "px", below = off[n] - off[i1] + "px";
+ if (gapAbove.style.height !== above) gapAbove.style.height = above;
+ if (gapBelow.style.height !== below) gapBelow.style.height = below;
+ if (anchor?.parentNode === reqs) {
+ const moved = anchor.getBoundingClientRect().top - reqs.getBoundingClientRect().top - anchorAt;
+ if (Math.abs(moved) >= 0.5) reqs.scrollTop += moved;
}
- // measuring every row's line forces a layout: only when one changed
- // (a resize measures them through the ResizeObserver)
- if (redrawn) metaFit();
- renderActs(rs);
}
+ // scrolled or resized: the rows now in sight drawn, once a frame
+ const redrawList = () => {
+ if (winSoon || !reqs.classList.contains("win")) return;
+ winSoon = requestAnimationFrame(() => { winSoon = 0; if (reqs.classList.contains("win")) drawList(); });
+ };
+ reqs.addEventListener("scroll", redrawList, { passive: true });
+ new ResizeObserver(redrawList).observe(reqs);
function reqRow(r, said, how, tr, ag, meta, metrics, title) {
const b = el("button", "rt-req " + how);
- const when = el("span", "at", new Date(r.time).toLocaleTimeString(intlLang(), { hour: "2-digit", minute: "2-digit", second: "2-digit" }));
+ const when = el("span", "at", rowClock(r.time));
const asked = el("span", "asked");
const sw = el("i", "ag");
sw.style.setProperty("--agent", hueOf(r.agent));
diff --git a/internal/gui/assets/plugins/routing/routing.css b/internal/gui/assets/plugins/routing/routing.css
index f370fe313..d107f2721 100644
--- a/internal/gui/assets/plugins/routing/routing.css
+++ b/internal/gui/assets/plugins/routing/routing.css
@@ -227,6 +227,12 @@
.rt-reqs { padding: 4px; max-height: 420px; overflow-y: auto; display: grid; grid-template-columns: auto fit-content(32%) minmax(min(14em, 30%), 1fr) fit-content(40%); }
.rt-req { grid-column: 1 / -1; display: grid; grid-template-columns: subgrid; align-items: center; column-gap: 12px; padding: 6px 8px; font: inherit; font-size: 12px; text-align: left; color: var(--fg-2); background: none; border: 1px solid transparent; border-radius: 8px; cursor: pointer; }
.rt-req:hover { background: var(--card-2); }
+/* a long list draws only the rows near its sight, between gaps as tall as
+ the rest; a probe is a row unlike any drawn, there for the columns'
+ widths only (#2524) */
+.rt-reqs.win { overflow-anchor: none; }
+.rt-reqs .rt-gap { grid-column: 1 / -1; }
+.rt-req.probe { height: 0; padding-block: 0; border-block-width: 0; overflow: hidden; visibility: hidden; pointer-events: none; }
.rt-req[aria-pressed="true"] { background: var(--card-2); border-color: var(--line); color: var(--fg); }
.rt-req .at { font-variant-numeric: tabular-nums; color: var(--muted); }
.rt-req .asked { display: flex; align-items: center; gap: 6px; min-width: 0; }
diff --git a/internal/gui/tests/routing-day-window.test.cjs b/internal/gui/tests/routing-day-window.test.cjs
new file mode 100644
index 000000000..8f14d1e04
--- /dev/null
+++ b/internal/gui/tests/routing-day-window.test.cjs
@@ -0,0 +1,254 @@
+// Run with Node's test runner and Playwright on the module path; see README.md.
+// A day of history is up to 2,000 requests (#2524, UNscientific-9: a day of
+// 3,410 froze the window for seconds each time it was picked). The list
+// draws only the rows in and near its sight: picked, a day of 2,000 puts a
+// few dozen rows in the page, not 2,000, and scrolled, the list draws the
+// next ones, down to the day's first request. It looks as it did with all
+// of them in: its columns are as wide as the widest row of the day, drawn
+// or not, and stay so as it scrolls; a row scrolled to stays where it is
+// as the rows around it are drawn; a row picked far down is marked.
+// MAGPIE_ROUTING_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(process.env.MAGPIE_ROUTING_ASSETS || path.join(__dirname, "../assets"));
+const iso = (ms) => new Date(ms).toISOString();
+const acct = (n) => ({ id: `acct-${n}`, provider: `prov${n}`, name: `Provider ${n}`, who: `user${n}@example.com`, kind: "account", model: `model-${n}`, known: true, used: 10 * n, plan: "Pro" });
+const agentsOf = ["codex", "claude", "opencode", "kimi"];
+const N = 2000;
+const WIDE_MODEL = "claude-wide-model-name-2026", LAST_MODEL = "first-of-the-day";
+
+function req(id, t0) {
+ const order = [acct(id % 5), acct((id + 1) % 5)];
+ const tries = [{ id: order[0].id, model: order[0].model, start: iso(t0), done: true, ms: 300, status: 200, in: 1200, out: 300, cacheRead: 600 }];
+ return { id, seq: id, time: iso(t0), agent: agentsOf[id % agentsOf.length], model: order[0].model, provider: order[0].provider, order, tries, done: true, status: 200, ms: 400, tokens: 900, session: "s" + (id % 9), prompt: { tokens: 5000, counted: true, window: 200000, parts: [{ kind: "chat", tokens: 5000, items: [{ name: "turn", tag: "turns", n: 1, tokens: 5000 }] }] } };
+}
+// a day's requests, newest last as the history serves them; far from the
+// newest, one asks for a wide model and one has three tries and many
+// tokens, so the columns are wider than any row near the top needs
+function dayOf(d, base) {
+ const start = Date.parse(`2026-10-${d}T00:00:00Z`);
+ return Array.from({ length: N }, (_, i) => {
+ const r = req(base + i + 1, start + i * 20000);
+ r.model += `-d${d}`;
+ if (i === 0) r.model = LAST_MODEL;
+ if (i === 300) r.model = WIDE_MODEL;
+ if (i === 500) {
+ r.tries = [{ ...r.tries[0], status: 429, fail: "rate", again: true }, { ...r.tries[0], status: 429, fail: "rate", again: true }, r.tries[0]];
+ r.tokens = 123456789;
+ }
+ return r;
+ });
+}
+
+function serve(lang) {
+ const state = { agents: agentsOf.map((id) => ({ id, name: id[0].toUpperCase() + id.slice(1), path: `/test/${id}`, fields: [] })), profiles: [], settings: { lang, theme: "light" } };
+ const days = [{ day: "2026-10-16", requests: N }, { day: "2026-10-15", requests: N }];
+ const hist = { "2026-10-16": dayOf(16, 160000), "2026-10-15": dayOf(15, 150000) };
+ const live = [req(1, Date.now() - 500)];
+ return async (route) => {
+ const url = new URL(route.request().url());
+ const json = (data) => route.fulfill({ json: data }).catch(() => {});
+ 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(state);
+ if (url.pathname === "/api/plugins") return json({ plugins: [] });
+ if (url.pathname === "/api/gateway/trace") {
+ const wait = url.searchParams.get("wait");
+ // no request comes while a test runs: the live poll waits (each answer
+ // draws the page again, and would be counted with what is measured)
+ if (wait) await new Promise((r) => setTimeout(r, 60000).unref());
+ return json({ mine: true, now: new Date().toISOString(), seq: wait ? +url.searchParams.get("after") || 1 : 1, totals: { requests: 1, rerouted: 0, errors: 0 }, routes: wait ? [] : live });
+ }
+ if (url.pathname === "/api/gateway/history") {
+ const d = url.searchParams.get("day");
+ return json({ cut: false, days, routes: d ? hist[d] || [] : [] });
+ }
+ if (url.pathname === "/api/groups") return json({ models: [], groups: [], pools: [] });
+ if (url.pathname === "/api/providers") return json({ providers: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } });
+ 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)];
+ await route.fulfill({ body: await fs.readFile(file), contentType });
+ };
+}
+
+// what the reader sees of the list: the rows drawn (a probe is not one),
+// the columns' widths, and the first row in sight with where it is
+const look = (page) => page.evaluate(() => {
+ const list = document.querySelector(".rt-reqs"), box = list.getBoundingClientRect();
+ const rows = [...list.querySelectorAll(":scope > .rt-req:not(.probe)")];
+ const seen = [...list.children].find((e) => (e.matches(".rt-req:not(.probe)") || e.matches(".rt-session")) && e.getBoundingClientRect().bottom > box.top + 1);
+ return {
+ rows: rows.length,
+ cols: getComputedStyle(list).gridTemplateColumns,
+ models: rows.map((r) => r.querySelector(".m")?.textContent),
+ first: seen && { text: seen.textContent, at: Math.round(seen.getBoundingClientRect().top - box.top) },
+ top: list.scrollTop, height: list.scrollHeight, view: list.clientHeight,
+ };
+});
+const frames = (page, n = 4) => page.evaluate((n) => new Promise((r) => { const f = (i) => (i ? requestAnimationFrame(() => f(i - 1)) : r()); f(n); }), n);
+// scrolled as the reader scrolls, each step drawn before the next
+async function scrollTo(page, top) {
+ await page.evaluate((top) => { const l = document.querySelector(".rt-reqs"); l.scrollTop = top === "end" ? l.scrollHeight : top; }, top);
+ await frames(page);
+ await page.evaluate((top) => { const l = document.querySelector(".rt-reqs"); if (top === "end") l.scrollTop = l.scrollHeight; }, top);
+ await frames(page);
+}
+
+for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
+ for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
+ for (const width of [1280, 420]) {
+ test(`${engine} ${lang} ${width}px: a day of ${N} requests draws the rows in sight, looking as it did with all of them`, async (t) => {
+ const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
+ const page = await browser.newPage({ viewport: { width, height: 900 }, reducedMotion: "reduce" });
+ page.setDefaultTimeout(15000);
+ const errors = [];
+ page.on("pageerror", (e) => errors.push(e.message));
+ await page.route("**/*", serve(lang));
+ t.after(() => browser.close());
+ await page.goto("http://magpie.test/?view=routing");
+ await page.locator(".rt-req").first().waitFor();
+ // a day picked from its pill, or at a narrow width, from the menu
+ // the pills past the bar's width go under (#961); picked, the day's
+ // requests are in the list (each day's models are its own)
+ // (dispatched, as every click here: the bar sits below the fold,
+ // and the page keeps its scroll on a click)
+ const pickDay = async (i, d) => {
+ const pill = page.locator(".rt-days .rt-day:not(.rt-day-more)").nth(i);
+ if (await pill.isVisible()) await pill.dispatchEvent("click");
+ else {
+ const shown = await page.locator(".rt-days .rt-day:not(.rt-day-more)").evaluateAll((xs) => xs.filter((x) => !x.hidden).length);
+ await page.locator(".rt-days .rt-day-more").dispatchEvent("click");
+ await page.locator(".proto-menu .pm-item").nth(i - shown).dispatchEvent("click");
+ }
+ await page.waitForFunction((d) => [...document.querySelectorAll(".rt-reqs > .rt-req:not(.probe) .m")].some((m) => m.textContent.endsWith(`-d${d}`)), d);
+ await frames(page);
+ };
+ await pickDay(1, 16);
+
+ // a few dozen rows in the page, not the day's 2,000
+ let at = await look(page);
+ assert(at.rows > 5 && at.rows <= 150, `a day of ${N} put ${at.rows} rows in the list`);
+ assert(at.height > N * 20, `the list is ${at.height}px tall: not all ${N} rows can be scrolled to`);
+ const topCols = at.cols;
+
+ // the columns are the widest row's, drawn or not: the same far down,
+ // where the wide model and the three tries are, and the wide model
+ // is not cut there
+ // (the 301st request of the day is about 85% of the way down; from
+ // there, a list's height at a time, each drawn before the next)
+ await scrollTo(page, Math.round(at.height * 0.8));
+ for (let i = 0; i < 60; i++) {
+ at = await look(page);
+ if (at.models.includes(WIDE_MODEL)) break;
+ await scrollTo(page, at.top + at.view);
+ }
+ assert(at.models.includes(WIDE_MODEL), "the wide model's row was never drawn");
+ assert.equal(at.cols, topCols, "the columns changed width as the list scrolled");
+ if (width > 760) {
+ const cut = await page.evaluate((model) => {
+ const m = [...document.querySelectorAll(".rt-reqs > .rt-req:not(.probe) .m")].find((m) => m.textContent === model);
+ return m.scrollWidth > m.clientWidth + 1;
+ }, WIDE_MODEL);
+ assert.equal(cut, false, "the wide model is cut: its column is sized by the rows drawn only");
+ }
+
+ // a row scrolled to stays where it is while the rows around it are drawn
+ await scrollTo(page, Math.round(at.height / 2));
+ const before = (await look(page)).first;
+ await frames(page, 8);
+ const after = (await look(page)).first;
+ assert.deepEqual(after, before, "the list moved under the reader");
+
+ // scrolled to its foot: the day's first request, and picked there it is marked
+ await scrollTo(page, "end");
+ at = await look(page);
+ assert(at.models.includes(LAST_MODEL), `the day's first request is not at the list's foot: ${at.models.slice(-3)}`);
+ assert(at.top + at.view >= at.height - 2, "the list doesn't scroll to its foot");
+ const last = page.locator(".rt-reqs > .rt-req:not(.probe)").filter({ has: page.locator(".m", { hasText: LAST_MODEL }) });
+ await last.dispatchEvent("click");
+ await page.waitForFunction((model) => [...document.querySelectorAll(".rt-reqs > .rt-req:not(.probe)")].some((r) => r.querySelector(".m")?.textContent === model && r.getAttribute("aria-pressed") === "true"), LAST_MODEL);
+ assert.equal(await page.locator('.rt-reqs > .rt-req[aria-pressed="true"]').count(), 1);
+
+ // another day: its rows, as few
+ await pickDay(2, 15);
+ at = await look(page);
+ assert(at.rows > 5 && at.rows <= 150, `the next day put ${at.rows} rows in the list`);
+ assert.equal(at.cols, topCols, "another day of the same shapes changed the columns");
+
+ // by session: the heads among the rows, the last one reached at the foot
+ await page.locator(".rt-group-by button").nth(1).dispatchEvent("click");
+ await page.waitForFunction(() => document.querySelector(".rt-group-by button:nth-child(2)").getAttribute("aria-pressed") === "true");
+ await scrollTo(page, 0);
+ await page.waitForFunction(() => document.querySelector(".rt-reqs > .rt-session"));
+ await frames(page);
+ at = await look(page);
+ assert(at.rows <= 150, `grouped, ${at.rows} rows are in the list`);
+ await scrollTo(page, "end");
+ at = await look(page);
+ const foot = await page.evaluate(() => {
+ const list = document.querySelector(".rt-reqs"), box = list.getBoundingClientRect();
+ const last = [...list.children].filter((e) => e.matches(".rt-req:not(.probe), .rt-session")).pop();
+ return last && Math.round(box.bottom - last.getBoundingClientRect().bottom);
+ });
+ assert(foot >= 0 && foot < 40, `grouped, the list's last row is ${foot}px above its foot: the rows below it are not drawn`);
+ assert(at.top + at.view >= at.height - 2, "grouped, the list doesn't scroll to its foot");
+ assert.deepEqual(errors, []);
+ });
+ }
+ }
+}
+
+// Whether a request's numbers go under it is measured again when the list's
+// column gets a new width only (#2524: measured on every change of its
+// height too, a day of 3,410 was measured 8 times in 8s, ~200ms each, and
+// the mark it set changed the height it was measured on)
+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 list growing taller doesn't measure its rows' numbers again`, async (t) => {
+ const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
+ const page = await browser.newPage({ viewport: { width: 1800, height: 900 }, reducedMotion: "reduce" });
+ page.setDefaultTimeout(15000);
+ const errors = [];
+ page.on("pageerror", (e) => errors.push(e.message));
+ await page.route("**/*", serve(lang));
+ t.after(() => browser.close());
+ await page.goto("http://magpie.test/?view=routing");
+ await page.locator(".rt-req").first().waitFor();
+ await page.locator(".rt-days .rt-day:not(.rt-day-more)").nth(1).dispatchEvent("click");
+ await page.waitForFunction(() => [...document.querySelectorAll(".rt-reqs > .rt-req:not(.probe) .m")].some((m) => m.textContent.endsWith("-d16")));
+ await frames(page, 8);
+ // the list's column, wide enough for its numbers to be measured, and
+ // taller than the window already, so the page's own scrollbar is there
+ // and the heights below leave its width alone
+ await page.evaluate(() => { document.querySelector(".rt-reqs").parentElement.style.minHeight = "1100px"; });
+ await frames(page, 6);
+ const col = await page.evaluate(() => document.querySelector(".rt-reqs").parentElement.className);
+ assert(!/max760/.test(col), `the column is too narrow to measure in (${col})`);
+ // each measure reads where a row's numbers sit: count those reads
+ await page.evaluate(() => {
+ window.marks = 0;
+ const rect = Element.prototype.getBoundingClientRect;
+ Element.prototype.getBoundingClientRect = function () {
+ if (this.parentElement?.matches(".rt-req .meta")) window.marks++;
+ return rect.call(this);
+ };
+ });
+ for (const h of ["1200px", "1500px", "1300px"]) {
+ await page.evaluate((h) => { document.querySelector(".rt-reqs").parentElement.style.minHeight = h; }, h);
+ await frames(page);
+ }
+ assert.equal(await page.evaluate(() => window.marks), 0, "the column grew taller and its rows were measured again");
+ // a new width is measured (the column's own: the page's is capped)
+ await page.evaluate(() => { const c = document.querySelector(".rt-reqs").parentElement; c.style.width = c.clientWidth - 40 + "px"; });
+ await frames(page, 6);
+ assert(await page.evaluate(() => window.marks) > 0, "a new width was not measured");
+ assert.deepEqual(errors, []);
+ });
+ }
+}
diff --git a/internal/gui/tests/routing-sessions.test.cjs b/internal/gui/tests/routing-sessions.test.cjs
index de5994102..62d6d9d99 100644
--- a/internal/gui/tests/routing-sessions.test.cjs
+++ b/internal/gui/tests/routing-sessions.test.cjs
@@ -455,12 +455,25 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
await page.locator(".rt-group-by button").nth(1).click();
// openRoute loads the full day, then appends a row outside its 2,000-row page.
await page.evaluate(({ id, time }) => window.openRoute(id, time), extra);
- await page.locator(".rt-req").nth(2000).waitFor();
+ // the list draws the rows in sight only (#2524): the day's 2,001 are
+ // counted in its note, and a session far down is scrolled to
+ await page.waitForFunction(() => /2001/.test(document.querySelector(".rt-req-head .note")?.textContent || ""));
await page.evaluate(() => window.dispatchEvent(new Event("focus")));
await page.waitForFunction(() => [...document.querySelectorAll(".rt-session .nm")].some((e) => e.textContent === "Codex · Applied opened-chat"));
const group = (id) => page.locator(`button.rt-session:has(.nm[title$="${id}"])`);
- assert.equal(await group("chat-2000").locator(".nm").textContent(), "Codex · Applied chat-2000");
- assert.equal(await group(mixed ? "chat-801" : "chat-1").locator(".nm").textContent(), `Codex · Applied chat-${mixed ? 801 : 1}`);
+ const scrolledTo = async (id) => {
+ await page.evaluate(() => { document.querySelector(".rt-reqs").scrollTop = 0; });
+ // a list's height at a time, each drawn, down to its foot
+ for (let moved = true; moved && !await group(id).count();) {
+ moved = await page.evaluate(() => { const l = document.querySelector(".rt-reqs"), was = l.scrollTop; l.scrollTop += l.clientHeight; return l.scrollTop > was; });
+ await page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))));
+ }
+ return group(id);
+ };
+ assert.equal(await (await scrolledTo("chat-2000")).locator(".nm").textContent(), "Codex · Applied chat-2000");
+ assert.equal(await (await scrolledTo(mixed ? "chat-801" : "chat-1")).locator(".nm").textContent(), `Codex · Applied chat-${mixed ? 801 : 1}`);
+ await page.evaluate(() => { document.querySelector(".rt-reqs").scrollTop = 0; });
+ await page.waitForFunction(() => [...document.querySelectorAll(".rt-session .nm")].some((e) => e.textContent === "Codex · Applied opened-chat"));
assert.equal(await group("opened-chat").locator(".cost").textContent(), "≈$0.010");
const batches = titleRequests.filter((input) => input.day === day);
assert(batches.length > 0, "history refresh never ran");