diff --git a/internal/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.js index f637535aa..f03a02ffc 100644 --- a/internal/gui/assets/plugins/routing/client.js +++ b/internal/gui/assets/plugins/routing/client.js @@ -330,7 +330,7 @@ function routingPage(part) { }).observe(node); byWidth(box, { max560: (w) => w <= 560 }); byWidth(list, { max460: (w) => w <= 460, max560: (w) => w <= 560 }); - byWidth(more, { max520: (w) => w <= 520, min1150: (w) => w >= 1150 }); + byWidth(more, { max520: (w) => w <= 520 }); for (const col of [colA, colB]) byWidth(col, { max440: (w) => w <= 440, max760: (w) => w <= 760 }); // A request's numbers on a line of their own, under where it went, where // they no longer fit their column on one line (#2288): a list of about @@ -340,6 +340,10 @@ function routingPage(part) { // the frame is drawn: measured under, they can fit their column's share // and still wrap beside a wide model, and the row would flip each frame. // The rows are shorter on one line, so what scrolls keeps its place. + const metaWraps = () => [...reqs.querySelectorAll(".rt-req .meta:not([hidden])")].some((m) => { + const k = m.children; + return k.length > 1 && k[k.length - 1].getBoundingClientRect().top - k[0].getBoundingClientRect().top > 2; + }); let metaFitting = 0; const metaFit = () => { if (!metaFitting) metaFitting = requestAnimationFrame(() => { metaFitting = 0; @@ -349,10 +353,7 @@ function routingPage(part) { colA.classList.remove("meta-under"); inMetaFit = true; fitCols(); // the rows' columns for the layout measured, not the one before - const wraps = [...reqs.querySelectorAll(".rt-req .meta:not([hidden])")].some((m) => { - const k = m.children; - return k.length > 1 && k[k.length - 1].getBoundingClientRect().top - k[0].getBoundingClientRect().top > 2; - }); + const wraps = metaWraps(); colA.classList.toggle("meta-under", wraps); fitCols(); inMetaFit = false; @@ -365,6 +366,40 @@ function routingPage(part) { // Out of sight (0 wide) is no new width: back, nothing is measured (#4652) let metaW = -1; new ResizeObserver(() => { const w = colA.clientWidth; if (w && w !== metaW) { metaW = w; metaFit(); } }).observe(colA); + // The accounts beside the requests (min1150) only where the requests + // still keep each on one line there: put beside by the page's width + // alone (1150px), a page kept to 1200px left the requests ~850px, and a + // wider window showed each request on two lines where a narrower one, + // the accounts under the requests, showed it on one (normalcoder_ on X). + // Tried beside and measured before the frame is drawn, as metaFit does; + // again when the page's width or the rows' shapes change. + let sideFitting = 0; + const sideFit = () => { if (!sideFitting) sideFitting = requestAnimationFrame(() => { + sideFitting = 0; + const w = more.clientWidth; + if (!w) return; // out of sight: the layout it had (#4652) + const was = more.classList.contains("min1150"); + let side = w >= 1150; + if (side && reqs.offsetParent && !hist.classList.contains("solo") && reqs.querySelector(".rt-req")) { + const narrow = colA.classList.contains("max760"), under = colA.classList.contains("meta-under"), kept = []; + for (let p = reqs; p; p = p.parentElement) if (p.scrollTop) kept.push([p, p.scrollTop]); + more.classList.add("min1150"); + inMetaFit = true; + colA.classList.toggle("max760", colA.clientWidth <= 760); + colA.classList.remove("meta-under"); + fitCols(); + side = !colA.classList.contains("max760") && !metaWraps(); + colA.classList.toggle("max760", narrow); + colA.classList.toggle("meta-under", under); + more.classList.toggle("min1150", was); + fitCols(); + inMetaFit = false; + for (const [p, top] of kept) if (p.scrollTop !== top) p.scrollTop = top; + } + if (side !== was) more.classList.toggle("min1150", side); + }); }; + let sideW = -1; + new ResizeObserver(() => { const w = more.clientWidth; if (w && w !== sideW) { sideW = w; sideFit(); } }).observe(more); const path = () => { const p = document.createElementNS(NS, "path"); wires.appendChild(p); return p; }; const setText = (e, s) => { if (e.textContent !== s) e.textContent = s; }; @@ -4432,7 +4467,7 @@ function routingPage(part) { reqs.style.setProperty("--rt-cols", px.join(" ")); } redrawList(); // the rows' heights measured in the columns before are dropped (listKey) - if (!inMetaFit) metaFit(); // new columns, not metaFit's own: whether the numbers fit asked again + if (!inMetaFit) { metaFit(); sideFit(); } // new columns, not metaFit's own: whether the numbers fit asked again }; // told a frame later: the rows taking their columns can move the list's // scrollbar and with it the probes, which within the observer's own turn @@ -4457,12 +4492,20 @@ function routingPage(part) { 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 }) : ""; + // a request in flight's numbers too (60 B, ≈ tokens, ago): measured + // without them, its column was as wide as no numbers, and they were + // drawn past the list's edge, cut off (normalcoder_ on X) 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]])]))]; + "m" + digits(JSON.stringify([meta, requestMetrics(r, how).map((m) => [m[0], m[2]]), liveParts(probeOf(r)).map((p) => p[0])]))]; probeShapes.set(r, { key, s }); return s; } // fillSizer: a probe of each shape the rows have, in the sizer + // probeOf: a request in flight measured as quiet for 59 min, the widest + // its "ago" says in the hour: measured as it was then ("3 s ago"), the + // row's numbers wrapped a line once it said "13 s ago", between two of + // the gateway's answers, and stayed two lines at any width + const probeOf = (r) => r.done || !r.contentAt ? r : { ...r, contentAt: Date.now() - 3540e3 }; function fillSizer(rs) { const key = document.documentElement.lang + "|" + visibleMetrics.join(), seen = new Set(), want = new Map(); for (const r of rs) { @@ -4477,7 +4520,7 @@ function routingPage(part) { let p = probes.get(id); if (!p) { const [said, how, tr] = outcome(r), meta = r.tries.length > 1 ? [t("{n} tries", { n: r.tries.length })] : []; - const b = reqRow(r, said, how, tr, agentOf(r.agent), meta, requestMetrics(r, how), ""); + const b = reqRow(probeOf(r), said, how, tr, agentOf(r.agent), meta, requestMetrics(r, how), ""); p = el("div", b.className.replace(/^rt-req /, "rt-probe ") + " probe"); // not a row to anything that asks for one p.append(...b.childNodes); probes.set(id, p); diff --git a/internal/gui/assets/plugins/routing/routing.css b/internal/gui/assets/plugins/routing/routing.css index ba5dbeeec..9251a10f8 100644 --- a/internal/gui/assets/plugins/routing/routing.css +++ b/internal/gui/assets/plugins/routing/routing.css @@ -310,7 +310,10 @@ body.side-nav #view-groups:not(.rt-gfrom) .rt-gback { display: none; } few accounts'. Only where the requests' column still keeps each request on one line (wider than 760px, see below): narrower, one column of one-line requests reads better than two with each request on three - (#860, huoranxuanyuan). Where the page is 1150px wide or more. Kept to + (#860, huoranxuanyuan). Where the page is 1150px wide or more and the + requests, tried beside, keep their numbers on one line (sideFit in + client.js: normalcoder_ on X saw a wider window put each request on two + lines where a narrower one kept it on one). Kept to 28%, no more than 360px: in a page kept to 1200px the accounts had room to spare while the requests' models were cut (#1926, hibaliqya-yonma) */ :where(.rt-more.min1150) .rt-cols { grid-template-columns: minmax(0, 1fr) clamp(260px, 28%, 360px); } diff --git a/internal/gui/tests/routing-rows-widths.test.cjs b/internal/gui/tests/routing-rows-widths.test.cjs new file mode 100644 index 000000000..8790ad4c5 --- /dev/null +++ b/internal/gui/tests/routing-rows-widths.test.cjs @@ -0,0 +1,147 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// The Routing page's requests at every window width (normalcoder_ on X, +// v0.1.4053): +// - a request still answering got its numbers (60 B, ≈ tokens, ago) after +// the list's columns were measured, so they sat past the list's right +// edge, cut off, in a column measured with none; +// - made wider, the Accounts and keys moved beside the requests and took a +// third of the page from them, so a wide window showed each request on +// more lines than a narrower one. +// Each row stays inside the list at every width, from wide to narrow and +// back, by request and by session; no metric is shown at one width and gone +// at a wider one, and a row is never taller in a wider window. Chromium and +// WebKit, the desktop window and the browser page, en and zh. +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, "../assets"); +const now = new Date(); +const at = (i) => new Date(now.getTime() - (i + 1) * 60e3).toISOString(); +const acct = (n, who) => ({ id: "antigravity:" + n, provider: "antigravity", name: "Antigravity", who, plan: "Google AI Pro", kind: "account", model: "gemini-3.8-flash", known: true, used: 10 + n, icon: "generic", routing: "speed" }); +const seats = [acct(1, "racooseoordssoiacl@example.com"), acct(2, "cecitimcmmarnicdosserenaos@example.com")]; +const usage = [{ provider: "antigravity", model: "gemini-3.8-flash", in: 1000, out: 400, cache_read: 3000, cache_write: 1000 }]; +const done = (i) => ({ id: 100 - i, seq: 100 - i, time: at(i), agent: "codex", session: "chat-" + (i % 2), model: "antigravity/gemini-3.8-flash", provider: "antigravity", + effort: "medium", order: seats, done: true, status: 200, ms: 12345, ttft: 2345, tokens: 135400, out: 400, usage, priced: true, cost: 0.0123, + tries: [{ id: seats[0].id, model: "gemini-3.8-flash", effort: "medium", start: at(i), done: true, status: 200, ms: 12345, ttft: 2345 }] }); +// the reporter's: answering, its first bytes not come yet when the list is +// first drawn +const live = (extra) => ({ id: 200, seq: 200, time: now.toISOString(), agent: "codex", session: "chat-live", model: "antigravity/gemini-3.8-flash", provider: "antigravity", + effort: "medium", order: seats, done: false, tries: [{ id: seats[0].id, model: "gemini-3.8-flash", effort: "medium", start: now.toISOString() }], ...extra }); + +function serve(lang, web, feed) { + return async (r) => { + const url = new URL(r.request().url()); + const json = (d) => r.fulfill({ json: d }); + if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:${web}};` }); + if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [{ id: "codex", name: "Codex", path: "/t", fields: [] }], profiles: [], settings: { lang, theme: "light" } }); + if (url.pathname === "/api/gateway/trace") { + const routes = url.searchParams.has("wait") ? await new Promise((resolve) => { feed.next = resolve; }) : feed.routes; + return json({ mine: true, now: new Date().toISOString(), seq: feed.seq, totals: { requests: feed.routes.length, rerouted: 0, errors: 0 }, routes }); + } + if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] }); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } }); + 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 r.fulfill({ body: await fs.readFile(file).catch(() => ""), contentType }); + }; +} + +// each row: what of it is past its own box or the list's (cut off), the +// metrics wholly in sight, and its height +const measure = (page) => page.evaluate(() => { + const list = document.querySelector(".rt-reqs"), lb = list.getBoundingClientRect(); + return [...list.querySelectorAll(".rt-req, button.rt-session")].map((row) => { + const rb = row.getBoundingClientRect(), edge = Math.min(rb.right, lb.right - parseFloat(getComputedStyle(list).paddingRight)); + const out = [...row.querySelectorAll(".at, .asked, .to, .meta > *, .nm, .summary, .summary > *, .cost")].filter((e) => { + const b = e.getBoundingClientRect(); + return b.width && (b.right > edge + 1 || b.left < rb.left - 1); + }).map((e) => `${e.className} "${e.textContent.slice(0, 16)}" ${Math.round(e.getBoundingClientRect().right - edge)}px past`); + const shown = [...row.querySelectorAll(".rt-metric")].filter((e) => { + const b = e.getBoundingClientRect(); + return b.width && b.left >= lb.left - 1 && b.right <= lb.right + 1; + }).map((e) => e.className.replace("rt-metric ", "")); + return { key: row.classList.contains("rt-session") ? "session " + row.textContent.slice(0, 12) : "request " + row.querySelector(".at").textContent, out, shown, height: Math.round(rb.height) }; + }); +}); + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh"]) { + test(`${engine} ${lang}: every request row fits its list at every width, and a wider window shows no less`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + // the reporter's list, the request in flight alone in it, and one + // with finished requests too + for (const [web, lone] of [[false, true], [false, false], [true, false]]) { + const feed = { seq: 100, routes: [live({}), ...(lone ? [] : Array.from({ length: 6 }, (_, i) => done(i)))] }; + const page = await browser.newPage({ viewport: { width: 1000, height: 1000 }, reducedMotion: "reduce" }); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, web, feed)); + await page.goto("http://magpie.test/?view=routing"); + await page.locator(".rt-req").nth(feed.routes.length - 1).waitFor(); + // its first bytes come in: the numbers a request in flight shows + for (let i = 0; i < 100 && !feed.next; i++) await page.waitForTimeout(20); + assert(feed.next, "live poll started"); + feed.seq = 101; + feed.next([live({ seq: 101, bytes: 60, estTok: 1234, contentAt: Date.now() - 3000 })]); + await page.locator(".rt-req .recv").first().waitFor(); + const settle = () => page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(() => setTimeout(r, 150))))); + const widths = []; + for (let w = 2000; w >= 520; w -= 60) widths.push(w); + for (const by of ["request", "session"]) { + if (by === "session") { + await page.locator(".rt-group-by button").nth(1).click(); + await page.locator("button.rt-session").first().waitFor(); + } + // narrowed, then widened again: the same width shows the same + const seen = new Map(); + for (const w of [...widths, ...widths.slice().reverse()]) { + await page.setViewportSize({ width: w, height: 1000 }); + await settle(); + const rows = await measure(page); + // the page's own width: the window's sidebar comes in at its + // own width, and takes from the page + rows.page = await page.locator("#rtMore").evaluate((e) => Math.round(e.getBoundingClientRect().width)); + const where = `${web ? "web" : "desktop"}${lone ? " alone" : ""} by ${by} at ${w}px`; + for (const row of rows) assert.deepEqual(row.out, [], `${where}: ${row.key} inside the list`); + if (seen.has(w)) assert.deepEqual(rows.map((r) => r.shown), seen.get(w).map((r) => r.shown), `${where}: the same metrics narrowed to it and widened back`); + seen.set(w, rows); + } + // wider never shows less: every metric in sight at one width is in + // sight at each wider one, and no row takes more lines + const asc = [...seen.keys()].sort((a, b) => seen.get(a).page - seen.get(b).page || a - b); + for (let i = 1; i < asc.length; i++) { + const narrow = seen.get(asc[i - 1]), wide = seen.get(asc[i]); + if (wide.page === narrow.page) continue; + assert.equal(wide.length, narrow.length); + narrow.forEach((row, j) => { + const at = `${web ? "web" : "desktop"} by ${by}, ${row.key}, a page of ${narrow.page}px → ${wide.page}px (window ${asc[i - 1]} → ${asc[i]})`; + for (const m of row.shown) assert(wide[j].shown.includes(m), `${at}: ${m} still shown (${wide[j].shown})`); + assert(wide[j].height <= row.height + 1, `${at}: no taller (${row.height} → ${wide[j].height})`); + }); + } + // every metric picked, in the live row's numbers too, is shown at + // the narrowest width + const least = seen.get(asc[0]); + if (!lone) { + const doneRow = least.find((r) => r.key.startsWith("request") && r.shown.includes("duration")); + assert(doneRow, "a finished request's row"); + assert.deepEqual(doneRow.shown, ["duration", "ttft", "tokens", "cache-hit", "speed", "cost-metric"]); + } + assert(least.some((r) => r.shown.filter((m) => m === "recv").length === 3), `the request in flight's numbers: ${JSON.stringify(least.map((r) => r.shown))}`); + } + assert.deepEqual(errors, [], "no page error"); + feed.next?.([]); + await page.close(); + } + }); + } +}