diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 1ad9cd8c4..8ef51268e 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -7836,9 +7836,41 @@ addEventListener("keydown", (e) => { if (e.key === "Tab" || (!typing && SCROLL_KEYS.has(e.key))) readerScrolls(400); }, true); const readerAt = new WeakMap(); +// Where the reader is is a number, the view's scrollTop, unless the view +// names a part of itself to keep in place (keepInView): a part under others +// that redraw on their own (the Routing page's groups, under the live stage +// and lists), which the number alone lets slide as what's above it grows or +// shrinks. Then where the reader is is where that part is on the screen, +// taken as the reader leaves it (a scroll of theirs, a click held), and the +// view follows it wherever the parts above take it: scroll anchoring, which +// WebKit lacked and which putting the number back undid. +const pinOf = new Map(), pinAt = new WeakMap(); +function keepInView(v, part) { + pinOf.set(v, part); + 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); +} +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); +} +function pinnedAt(v) { + const a = pinAt.get(v); + 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); +}); function backToReader(v) { if (v.hidden) return; - const want = Math.min(readerAt.get(v) || 0, Math.max(0, v.scrollHeight - v.clientHeight)); + const pinned = pinnedAt(v); + const want = Math.max(0, Math.min(pinned ?? readerAt.get(v) ?? 0, v.scrollHeight - v.clientHeight)); + if (pinned != null) readerAt.set(v, want); if (Math.abs(v.scrollTop - want) < 1) return; v.scrollTop = want; // a field focused out of sight still comes into view, no further than needed @@ -7899,7 +7931,7 @@ function hold(h) { v.scrollTop = want; } fitRoom(v); - readerAt.set(v, v.scrollTop); + readerLeaves(v); } let holding = false; // one frame loop, whatever the clicks // A part that grows or shrinks as it plays (the agents' scroll unrolling @@ -7932,7 +7964,7 @@ addEventListener("click", (e) => { for (const v of document.querySelectorAll(".view")) { v.addEventListener("scroll", () => { if (v.hidden) return; - if (performance.now() < purposeUntil) { fitRoom(v); readerAt.set(v, v.scrollTop); } + if (performance.now() < purposeUntil) { fitRoom(v); readerLeaves(v); } else if (held?.v === v) hold(held); else backToReader(v); }, { passive: true }); diff --git a/internal/gui/assets/routing.js b/internal/gui/assets/routing.js index 8f2812a29..150619270 100644 --- a/internal/gui/assets/routing.js +++ b/internal/gui/assets/routing.js @@ -1177,7 +1177,20 @@ row.title = w.id; out.push(row); } - acts.replaceChildren(...out); + patch(acts, out); + } + + // patch puts a list's new rows in, keeping each old one that is the same + // (and has no button, whose handler is the new one's): the accounts list + // emptied and filled again each second (its countdowns) had WebKit scroll + // the page, a frame at a time, as if the list had been shorter + function patch(box, rows) { + const old = [...box.children]; + const same = (r, o) => o && !r.querySelector("button") && r.isEqualNode(o); + if (old.length === rows.length && rows.every((r, i) => same(r, old[i]))) return; + rows = rows.map((r, i) => (same(r, old[i]) ? old[i] : r)); + rows.forEach((r, i) => { if (box.children[i] !== r) box.insertBefore(r, box.children[i] || null); }); + while (box.children.length > rows.length) box.lastElementChild.remove(); } function renderAll() { render(); renderLog(); renderHist(); } @@ -2099,6 +2112,22 @@ window.addEventListener("focus", () => { if (shown()) loadGroups(); }); loadGroups(); + // ---------- where the reader is, as requests come ---------- + // Every request redraws what is above the routing groups: the stage gains + // or loses a row, the story a line, the lists theirs. The view kept its + // scrollTop, so all of it pushed the groups down or pulled them up under + // the reader, a group being edited too (Jerell.OvO on Discord). The view + // keeps a part of itself where it is on the screen instead (keepInView in + // app.js): the groups, while they are in the upper half of the view or a + // field in them has the focus, else the lists, while they are; with + // neither (the stage in sight at the top), the view stays as it is. + const rv = $("#view-routing"); + keepInView(rv, () => { + const mid = rv.getBoundingClientRect().top + rv.clientHeight / 2; + if (gsec.contains(document.activeElement) && gsec.offsetParent) return gsec; + return [gsec, hist].find((p) => p.offsetParent && p.getBoundingClientRect().top <= mid) || null; + }); + // ---------- the tray panel's Routing tab ---------- // The gateway's latest requests, as they come, from the same trace the // page above plays: who sent each, the model asked for, the provider and diff --git a/internal/gui/tests/README.md b/internal/gui/tests/README.md index 165473324..ae20bf69b 100644 --- a/internal/gui/tests/README.md +++ b/internal/gui/tests/README.md @@ -35,6 +35,13 @@ under the model's dated name and ones naming none: only the first is marked gpt-6-sol ยท served gpt-6-luna" in its story, in English and Chinese, and the click that picks it leaves the page where it is. +`routing-steady.test.cjs` scrolls the Routing page down to its routing groups, +opens one in its editor and types into its name, then streams six requests in +from the trace (new agents and accounts on the stage, failures and retries in +the story, the lists growing): the groups and the editor stay where they are +on the screen on every layout and scroll, the view's scrollTop moving by just +what grew above them, and the field keeps its focus and what was typed. + `balance-fix.test.cjs` opens a custom provider whose balance token sits beside new-api's `/api/usage/token` (and a new one with a token and no Balance URL): the editor says so, one click moves it to `/api/user/self` @@ -132,7 +139,7 @@ projects. With Node.js and Playwright available: ```sh -node --test internal/gui/tests/menu-scroll.test.cjs internal/gui/tests/click-scroll.test.cjs internal/gui/tests/panel-fold.test.cjs internal/gui/tests/panel-routing.test.cjs internal/gui/tests/gateway-fold.test.cjs internal/gui/tests/routing-kind.test.cjs internal/gui/tests/balance-fix.test.cjs internal/gui/tests/cli-update.test.cjs internal/gui/tests/login-import.test.cjs internal/gui/tests/agy-launch.test.cjs internal/gui/tests/currency.test.cjs internal/gui/tests/usage-ledger.test.cjs internal/gui/tests/update-check.test.cjs +node --test internal/gui/tests/menu-scroll.test.cjs internal/gui/tests/click-scroll.test.cjs internal/gui/tests/panel-fold.test.cjs internal/gui/tests/panel-routing.test.cjs internal/gui/tests/gateway-fold.test.cjs internal/gui/tests/routing-kind.test.cjs internal/gui/tests/balance-fix.test.cjs internal/gui/tests/cli-update.test.cjs internal/gui/tests/login-import.test.cjs internal/gui/tests/agy-launch.test.cjs internal/gui/tests/currency.test.cjs internal/gui/tests/usage-ledger.test.cjs internal/gui/tests/update-check.test.cjs internal/gui/tests/routing-steady.test.cjs ``` If Playwright is installed outside the repository, set `NODE_PATH` to the diff --git a/internal/gui/tests/routing-steady.test.cjs b/internal/gui/tests/routing-steady.test.cjs new file mode 100644 index 000000000..d9d2e28aa --- /dev/null +++ b/internal/gui/tests/routing-steady.test.cjs @@ -0,0 +1,179 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Requests coming in never move the Routing page (Jerell.OvO on Discord +// #general: as the request log refreshed, the page kept scrolling up, so +// the routing groups further down could not be read or edited). With the +// view scrolled down to the groups and one open in its editor, a name being +// typed, new requests stream in from the trace โ€” new agents and accounts on +// the stage, a failure and a retry in the story, the list growing โ€” and the +// groups stay where they are on the screen, the view's scrollTop with them, +// and the field keeps its focus and what was typed. +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 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"]; + +// a request: from an agent, weighing some accounts, answered by the last +// of them after the others failed (more tries, a longer story) +function req(id, agent, ids, fails) { + const t0 = now.getTime() - (200 - id) * 1000; + const order = ids.map(acct); + const tries = order.slice(0, fails + 1).map((w, i) => ({ + id: w.id, model: w.model, start: iso(t0 + i * 100), done: true, ms: 800, + ...(i < fails ? { status: 429, fail: "rate", again: true, error: "rate limited, try again later" } : { status: 200 }), + })); + return { id, seq: id, time: iso(t0), agent, model: order[0].model, provider: order[0].provider, order, tries, done: true, status: 200, ms: 900 + fails * 800, tokens: 1500 }; +} +const first = [req(100, "codex", [1], 0), req(101, "codex", [1, 2], 0)]; +const later = [ + req(102, "claude", [3, 4, 5], 2), + req(103, "opencode", [6, 1, 2, 3], 3), + req(104, "kimi", [7, 8], 1), + req(105, "codex", [1, 2, 3, 4, 5, 6], 4), + req(106, "claude", [2], 0), + req(107, "opencode", [8, 7, 6, 5, 4], 3), +]; + +const models = [1, 2, 3].map((n) => ({ id: `prov${n}/model-${n}`, name: `model-${n}`, providerName: `Provider ${n}`, icon: "generic" })); +const groups = { + models, + groups: [ + { id: "opus-anywhere", name: "Opus anywhere", members: [models[0].id, models[1].id], routing: "", ready: true }, + { id: "cheap", name: "Cheap", members: [models[2].id], routing: "order", ready: true }, + ], + pools: [1, 2, 3].map((n) => ({ provider: `prov${n}`, name: `Provider ${n}`, kind: "account", who: ["a", "b"], routing: "", affinity: "" })), +}; + +function serve(feed) { + const state = { agents: agentsOf.map((id) => ({ id, name: id[0].toUpperCase() + id.slice(1), path: `/test/${id}`, fields: [] })), profiles: [], settings: { lang: "en", theme: "light" } }; + return async (route) => { + const url = new URL(route.request().url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: 'window.bootPrefs = {lang:"en",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/gateway/trace") { + const trace = (routes) => json({ mine: true, now: new Date().toISOString(), seq: routes.length ? routes[routes.length - 1].seq : Number(url.searchParams.get("after")), totals: { requests: 0, rerouted: 0, errors: 0 }, routes }); + if (!url.searchParams.get("wait")) return trace(first); + // the long poll: answered when the test feeds a request + const r = await new Promise((res) => { feed.next = res; }); + return trace([r]); + } + 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: [], 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 }); + }; +} + +const view = "#view-routing"; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(`${engine}: requests coming in leave the routing groups where they are`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const context = await browser.newContext({ viewport: { width: 1100, height: 760 } }); + const page = await context.newPage(); + page.setDefaultTimeout(5000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const feed = { next: null }; + await page.route("**/*", serve(feed)); + t.after(async () => { + if (process.env.ARTIFACT_DIR) { + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-steady.png`) }); + } + feed.next?.(req(999, "codex", [1], 0)); + await browser.close(); + }); + await page.goto("http://magpie.test/?view=routing"); + await page.locator(".rt-req").nth(first.length - 1).waitFor(); + await page.locator(".rt-group").first().waitFor(); + await page.waitForTimeout(2000); // the first request's play + + // down to the groups with the wheel (the view moves only for the + // reader), the second group in the middle of the view; then the first + // opened in its editor and a name typed into it + const dy = await page.locator(view).evaluate((v) => { + const g = [...document.querySelectorAll(".rt-group")].pop(); + return Math.round(g.getBoundingClientRect().top - v.getBoundingClientRect().top - v.clientHeight / 2); + }); + await page.mouse.move(550, 400); + await page.mouse.wheel(0, dy); + await page.waitForTimeout(400); + const scrolled = await page.locator(view).evaluate((v) => v.scrollTop); + assert(scrolled > 200, `the view must be scrolled down to the groups (${scrolled})`); + await page.locator(".rt-group").first().locator("button", { hasText: "Edit" }).click(); + const name = page.locator(".rt-gedit input").first(); + await name.click(); + await name.press("End"); + await page.keyboard.type(" and more"); + const typed = await name.inputValue(); + assert.equal(typed, "Opus anywhere and more"); + await page.waitForTimeout(300); + + // where things are: on the screen, and the groups' place in the page + // (which moves as what's above them grows or shrinks) + const where = () => page.evaluate((sel) => { + const v = document.querySelector(sel), vt = v.getBoundingClientRect().top; + const top = (e) => e.getBoundingClientRect().top - vt; + const gsec = document.querySelector(".rt-gsec"); + return { + scrollTop: v.scrollTop, + inPage: gsec.getBoundingClientRect().top - vt + v.scrollTop, + onScreen: { head: top(gsec), editor: top(document.querySelector(".rt-gedit")), group: top([...document.querySelectorAll(".rt-group")].pop()) }, + }; + }, view); + const before = await where(); + + // every layout and every scroll while they come, after the page has + // had its say (these observers and listeners come after the page's): + // what the reader could see, not only where it ends + await page.evaluate((sel) => { + // (to a pixel and a half: WebKit scrolls by whole pixels, the + // parts above are laid out in fractions of one) + const v = document.querySelector(sel), ed = () => document.querySelector(".rt-gedit").getBoundingClientRect().top; + const want = ed(); + window.__moves = []; + const look = (why) => { const at = ed(); if (Math.abs(at - want) > 1.5) window.__moves.push(`${why}: the editor at ${at}, not ${want}`); }; + window.__ro = new ResizeObserver(() => look("layout")); + for (const e of [v, ...v.children, ...document.querySelector("#rtMore").children]) window.__ro.observe(e); + v.addEventListener("scroll", () => look("scroll")); + }, view); + for (const r of later) { + for (let i = 0; i < 50 && !feed.next; i++) await page.waitForTimeout(50); + const next = feed.next; + feed.next = null; + next(r); + await page.waitForTimeout(900); + } + await page.waitForTimeout(2500); // the plays end, the countdowns tick + assert.equal(await page.locator(".rt-req").count(), first.length + later.length, "every request must be listed"); + const moves = await page.evaluate(() => { window.__ro.disconnect(); return window.__moves; }); + const after = await where(); + + // what's above the groups did change: new agents and accounts on the + // stage, a longer story, more rows in the lists + assert(Math.abs(after.inPage - before.inPage) > 50, `the part above the groups must have changed (${before.inPage} โ†’ ${after.inPage})`); + // and the groups stayed where they were on the screen, the view + // scrolling by just what grew above them, on every frame + for (const k of Object.keys(before.onScreen)) assert(Math.abs(after.onScreen[k] - before.onScreen[k]) <= 1.5, `the ${k} moved: ${JSON.stringify([before, after])}`); + assert(Math.abs((after.scrollTop - before.scrollTop) - (after.inPage - before.inPage)) < 2, `scrollTop must follow the groups: ${JSON.stringify([before, after])}`); + assert.deepEqual(moves, [], "the page moved while the requests came"); + // the field kept its focus and what was typed, and goes on taking it + assert.equal(await name.evaluate((e) => e === document.activeElement), true, "the field lost its focus"); + assert.equal(await name.inputValue(), typed); + await page.keyboard.type("!"); + assert.equal(await name.inputValue(), typed + "!"); + assert.deepEqual(errors, []); + }); +}