gui: Routing and Usage keep the reader's place when wheeled as they open, heard late or never (issennknight)
issennknight on Discord (macOS 13.7.8, v0.1.1902), afterf92db4cdd: "路由 用量 页面 刚点开并滚动页面时会抖动复位". Two causes, both in the window's own scroll guard, which every page takes: 1. A load landing under the wheel (show()'s back on the page's first reads, loadProvidersNow's put-back after render) called backToReader with the place last heard of. The page hears of a scroll a frame or more late (WebKit scrolls off the main thread; a loaded Mac), so each load took the reader's last steps back and stopped their coast. backAfterLoad now keeps a view that has gone on the way the reader's own scrolls go (readerWay, set from each of theirs) as theirs, and puts back only a move against it (a redraw's clamp). 2. On macOS 13's WebKit (16.6) the page never hears the wheel. Every gesture's first scrolls were put back until three the same way made a run (puttingBack): a shake at the start of each gesture, a page just opened included. The first run given back is now remembered (localStorage magpie.unheardWheels, for the next start too); from then on a scroll at rest waits 120ms before it is put back (waitsBack), and a second the same way within 80ms, the page's height unchanged between them, is the reader's at once (code's two scrolls in a row, 100ms apart in view-wheel-unheard, are both put back). A lone scroll (a redraw's, code's) is still put back, 120ms later; one under a click's hold at once, as before. What the wait puts back is recorded as an at-once put-back is, so a wheel heard later than the wait (a loaded machine) still gives it back (givesBack). Not changed: the browser's scroll anchoring. It lowers scrollTop as data comes in above with what's on the screen still; the test tells that from a put-back (view up and what was under the pointer going down with it). Nothing between v0.1.1902 and425a61322touched this guard (68 commits; none in backToReader, readerScrolls, readerLeaves, puttingBack or overflow-anchor), and no view has smooth scrolling. Size budgets: app.js 1,313,704, the core 1,532,830 (main's plus 1,969), both the guard's own, with no room added. Tests: - New view-open-wheel.test.cjs: Usage and Routing, opened and opened again, the first data held until the wheel is going; the page told of each scroll 80ms late (late) or never (unheard, a capture listener stopping the wheel, learned on the Agents page first); every frame's place and every write moving a view up are recorded. en, zh, zh-TW, ja, de; 420 and 1000 wide; Chromium and WebKit. 162/162 on this tree (mote). - Broken by hand: on the base's assets (425a61322) 117/162 red: late Routing 31, late Usage 4 (210 to 180 under the wheel), unheard all 80 ("nothing put the view back up": 30, 30, 30 put back each gesture). With backAfterLoad but no waitsBack, the unheard half was 80/80 red the same way; with waitsBack but readerAt unset taken as no move, red too (found by logging each write's stack), fixed to 0 as backToReader reads it. - click-scroll.test.cjs: new subtest, a wheel heard 250ms late with the unheard wheels learned still scrolls the view. Red in both engines (Windows, 2 of 2 runs) with the wait's put-back not recorded, 24/24 green with it (3 of 3). Found from the whole suite's first run: under WSL's load, click-scroll's late-heard wheel subtest went red in webkit, which learned the unheard wheels from a run put back. - Also tried and dropped: .view { overflow-anchor: none }. It only silenced a scrollTop-only check; anchoring moves nothing on screen. - TestCoreScriptBudget ok (mote); gofmt -l clean. - After the rebase onto2f5548371: TestCoreScriptBudget and the app.js budget ok (mote); view-open-wheel, view-wheel-unheard, click-scroll on mote under another session's suite (load 16 to 35): 192/192 once, and 1 of 80 unheard subtests red once (#4132: under load the driver's second wheel comes after waitsBack's 120ms). - Rebased ontoc3462d5fe(main's GUI changes: context.js, i18n.js, the Codex auto-reset title; none in the scroll guard). app.js budget ok (mote). TestCoreScriptBudget is red by 670 bytes atc3462d5feitself (1,531,531 > 1,530,861, #4133, taken by another session); this commit adds its own 1,969 to both, so the core stays 670 over, not more. The four scroll files on WSL: chromium all green; Linux WebKit red in click-scroll, view-wheel-unheard and view-wheel-after-click as at2f5548371, and 7 of 80 view-open-wheel unheard subtests (a first gesture's put-backs before the run is learned, the #4132 class). On mote at load 81 (another session's full GUI suite) 14 of 113 red, mostly 5s click timeouts; not counted as a run. - Whole GUI suite at this tree, WSL magpie-desktop (mote had another session's suite): 14,519 tests, 14,263 pass, 256 red. Every red file is named on #4120 / #4121 (Linux reds at main) or was run alone at2f5548371and is red there the same: routing-rule-models, recent-calls-more, searcher-pick, usage-ledger-chart, list-sort (#4131), click-scroll's late-heard wheel, inner-scroll-contain, view-wheel-after-click and view-wheel-unheard in WebKit on Linux (base 9 to 10 red, this tree 4 to 9). Recorded on #4120. - Tried and dropped: a check in waitsBack's timer for a view gone on further untold. It took a code scroll whose event was still pending under load as the reader's (view-wheel-unheard webkit red on mote). Not tried: a real macOS 13 WebKit 16.6 (none here). The unheard case is an emulation (wheels stopped before the page), the same one view-wheel-unheard and view-wheel-after-redraw use. The first gesture of a fresh install on macOS 13 still shakes once, until the run is seen.
This commit is contained in:
@@ -413,6 +413,8 @@ covers it in both engines, every language and a narrow window.
|
||||
- Every user-visible string has zh, zh-TW, ja and de translations with the same placeholders. `gui-zh-tw.test.cjs`, `gui-ja.test.cjs` and `gui-de.test.cjs` fail on a missing one; `gui-zh-tw.test.cjs` also fails on a zh-TW string with a Simplified character left in it.
|
||||
- A click never moves the page. Code scrolls a view only with the reader's event in hand (`scrollOnPurpose`); `click-scroll.test.cjs` guards this. A click is taken where the reader left the view: a scroll not theirs made just before it, whose scroll event the browser sends only at the next frame, after the click, is put back first (`backToReader` in the click guard, #1554). What was clicked is held where it was (`hold`); a view at its top when clicked stays at its top, and what comes in above the control moves it down instead (#2134, `update-auto.test.cjs`), as long as it moves less than half its own height and so stays under the pointer. When what the click does leaves the page shorter under it (a list emptied), the view keeps room at its foot for it to stay (`.view-room`), room that goes as the reader scrolls back. A control under what it unrolls (`data-unrolls`, "Show 7 more") goes down with what it opens: what's held is the part it is in, so the rows open downwards. Anything larger above it, as the stage a day picked on Routing brings in above the bar, is scrolled past, and the control stays where it was clicked (`routing-days-fit.test.cjs`, `routing-failed-open.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.
|
||||
- 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`.
|
||||
- There are no native `<select>` elements and no colored left-border stripes. State is shown with a dot or a swatch.
|
||||
|
||||
@@ -5986,7 +5986,7 @@ async function loadProvidersNow() {
|
||||
if (!providers.providers.length && editing === null && !providers.fileError) adding = true;
|
||||
if (providersPage(view)) {
|
||||
magpie.call(view, "render", was);
|
||||
backToReader($("#view-" + view));
|
||||
backAfterLoad($("#view-" + view));
|
||||
} else renderProviders();
|
||||
renderArchive();
|
||||
providersWhileFetching();
|
||||
@@ -22871,6 +22871,25 @@ function puttingBack(v, from, h) {
|
||||
if (mine.length < 3 && !(run?.v === v && run.d === d && at - run.at < 1000)) return;
|
||||
run = { v, d, at }; putBack = putBack.filter((p) => !mine.includes(p)); flings();
|
||||
for (const p of mine) v.scrollTop += p.by;
|
||||
if (!deaf) { deaf = true; try { localStorage.setItem("magpie.unheardWheels", "1"); } catch {} }
|
||||
}
|
||||
// Seen once (a run given back, kept for the next start), a scroll at rest
|
||||
// waits a moment before it is put back, and one more the same way within
|
||||
// 80ms (a frame or few: code's two scrolls come further apart), nothing laid
|
||||
// out anew between them, is the reader's: a gesture
|
||||
// starts without three put back first. What it puts back is kept, as at
|
||||
// once, for a wheel heard late to give back (issennknight, macOS 13: Routing and
|
||||
// Usage shook as they were opened and wheeled)
|
||||
let deaf = false;
|
||||
try { deaf = localStorage.getItem("magpie.unheardWheels") === "1"; } catch {}
|
||||
const waits = new WeakMap();
|
||||
function waitsBack(v) {
|
||||
const d = Math.sign(Math.round(v.scrollTop - (readerAt.get(v) ?? 0))), w = waits.get(v);
|
||||
if (!d) return false;
|
||||
clearTimeout(w?.t); waits.delete(v);
|
||||
if (w?.d === d && w.h === v.scrollHeight && performance.now() - w.at < 80) { readerWay.set(v, d); readerLeaves(v); flings(); return true; }
|
||||
waits.set(v, { d, h: v.scrollHeight, at: performance.now(), t: setTimeout(() => { waits.delete(v); if (performance.now() >= purposeUntil && held?.v !== v) { const from = v.scrollTop; backToReader(v); puttingBack(v, from, false); } }, 120) });
|
||||
return true;
|
||||
}
|
||||
// Given back is what was put back after the reader's input was made (its
|
||||
// timeStamp is when it was made, not when the page was told) and went the
|
||||
@@ -23019,6 +23038,15 @@ function backToReader(v) {
|
||||
if (r.bottom > b.bottom || r.top < b.top) { readerScrolls(1000); guardUntil = purposeUntil; f.scrollIntoView({ block: "nearest" }); }
|
||||
}
|
||||
}
|
||||
// A load come in puts the view back where the reader left it, a redraw
|
||||
// having pulled it up; under a wheel the place last heard is late, and a
|
||||
// move the way the reader goes (readerWay) is theirs (gui-shell.md)
|
||||
const readerWay = new WeakMap();
|
||||
function backAfterLoad(v) {
|
||||
const at = readerAt.get(v);
|
||||
if (!v.hidden && (barDrag === v || performance.now() < purposeUntil && at != null && readerWay.get(v) === Math.sign(Math.round(v.scrollTop - at)))) readerLeaves(v);
|
||||
else backToReader(v);
|
||||
}
|
||||
// Where an element is on the screen in its view. What's held is the element
|
||||
// clicked or, once it's gone or hidden (drawn again), the nearest still
|
||||
// there of its neighbours, its parents and theirs; one moving as it plays
|
||||
@@ -23210,7 +23238,11 @@ for (const v of document.querySelectorAll(".view")) {
|
||||
v.addEventListener("scroll", () => {
|
||||
if (v.hidden) return;
|
||||
if (panning?.v === v) readerScrolls(250);
|
||||
if (performance.now() < purposeUntil || barDrag === v) { fitRoom(v); readerLeaves(v); scrolledFrom.set(v, document.activeElement); return; }
|
||||
if (performance.now() < purposeUntil || barDrag === v) {
|
||||
const by = v.scrollTop - (readerAt.get(v) ?? v.scrollTop);
|
||||
if (Math.abs(by) >= 1) readerWay.set(v, Math.sign(by));
|
||||
fitRoom(v); readerLeaves(v); scrolledFrom.set(v, document.activeElement); return;
|
||||
}
|
||||
const from = v.scrollTop;
|
||||
// a click's hold takes what a redraw moved; a scroll with the page laid
|
||||
// out as the hold left it is put back as at rest, so the reader's run
|
||||
@@ -23218,6 +23250,7 @@ for (const v of document.querySelectorAll(".view")) {
|
||||
// wheeled through, held still for 4s)
|
||||
const h = held?.v === v && redrawn(held);
|
||||
if (held?.v === v) hold(held);
|
||||
else if (deaf && waitsBack(v)) return;
|
||||
else backToReader(v);
|
||||
puttingBack(v, from, h);
|
||||
}, { passive: true });
|
||||
@@ -23270,7 +23303,7 @@ async function show(v) {
|
||||
navSubs();
|
||||
for (const id of ["agents", "providers", "plugins", "settings", ...magpie.pages()]) $("#view-" + id).hidden = v !== id;
|
||||
// back to where the reader was in it, and again once it has what it loads
|
||||
const back = () => backToReader($("#view-" + v));
|
||||
const back = () => backAfterLoad($("#view-" + v));
|
||||
requestAnimationFrame(back);
|
||||
closePicker();
|
||||
closeAgentModels();
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -290,7 +290,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
const heard = (fn, e) => { try { fn(e); } finally { window.__wheelsHeard++; } };
|
||||
window.addEventListener = function (type, fn, o) {
|
||||
if (type !== "wheel") return add.call(this, type, fn, o);
|
||||
return add.call(this, type, (e) => (window.__lateWheel ? setTimeout(() => heard(fn, e), 60) : heard(fn, e)), o);
|
||||
return add.call(this, type, (e) => (window.__lateWheel ? setTimeout(() => heard(fn, e), window.__lateBy || 60) : heard(fn, e)), o);
|
||||
};
|
||||
});
|
||||
await reset();
|
||||
@@ -331,6 +331,27 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
await page.evaluate(() => { window.__lateWheel = false; });
|
||||
});
|
||||
|
||||
// A window that has learned of wheels it never hears (macOS 13, or a run
|
||||
// put back on a loaded machine) waits 120ms before it puts a scroll back
|
||||
// (waitsBack). A wheel heard later still than that gives back what was
|
||||
// put back, as it does at once.
|
||||
await t.test("a wheel heard after the wait for unheard wheels is still the reader's", async () => {
|
||||
await reset();
|
||||
await page.evaluate(() => localStorage.setItem("magpie.unheardWheels", "1"));
|
||||
await reset();
|
||||
await page.locator(view).evaluate((v) => { const s = document.createElement("div"); s.style.cssText = "flex:none;height:1600px"; v.append(s); });
|
||||
await page.evaluate(() => { window.__lateWheel = true; window.__lateBy = 250; });
|
||||
const box = await page.locator(view).boundingBox();
|
||||
await page.mouse.move(box.x + box.width / 2, box.y + 60);
|
||||
const scrollTop = () => page.locator(view).evaluate((v) => v.scrollTop);
|
||||
const was = await scrollTop(), n = await page.evaluate(() => window.__wheelsHeard);
|
||||
await page.mouse.wheel(0, 300);
|
||||
await page.waitForFunction((n) => window.__wheelsHeard > n, n);
|
||||
await page.waitForFunction(() => performance.now() >= purposeUntil);
|
||||
assert((await scrollTop()) > was + 100, "the wheel heard 250ms late must scroll the view");
|
||||
await page.evaluate(() => { window.__lateWheel = false; window.__lateBy = 0; localStorage.removeItem("magpie.unheardWheels"); });
|
||||
});
|
||||
|
||||
assert.deepEqual(errors, [], "page runtime errors");
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// issennknight on Discord (after f92db4cdd): the Routing and Usage pages,
|
||||
// scrolled as soon as they were opened, shook and snapped back. Each page
|
||||
// puts the view back where the reader left it once what it loads comes in
|
||||
// (show()'s back, and the providers' reload drawing a page they show): a
|
||||
// redraw may have pulled it up. That ran while the reader was scrolling it
|
||||
// too, with the place last heard of, and the page hears of a scroll late
|
||||
// (WebKit scrolls on its own thread; a loaded Mac tells the page frames
|
||||
// later), so each load that landed under the wheel took the reader's last
|
||||
// steps back and stopped their coast. And on macOS 13 (WebKit 16.6, where
|
||||
// issennknight is), the page never hears the wheel at all: every gesture's
|
||||
// first scrolls were put back until three made a run, a shake as the page
|
||||
// was opened and wheeled. Here the first data waits until the wheel is
|
||||
// going, the page hears of each scroll 80ms late, or never (learned on the
|
||||
// page before, as a real window learns it); the view never goes back up
|
||||
// under a wheel going down, in the frames painted nor by a write the frames
|
||||
// can't show. Both pages, opened and opened again, every language, narrow
|
||||
// and wide, Chromium and WebKit. The browser's scroll anchoring (the view
|
||||
// up as data comes in above, what's on the screen still) is not a put-back.
|
||||
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 = process.env.MAGPIE_OPEN_WHEEL_ASSETS || path.resolve(__dirname, "../assets");
|
||||
const now = new Date();
|
||||
const day = [now.getFullYear(), now.getMonth() + 1, now.getDate()].map((n) => String(n).padStart(2, "0")).join("-");
|
||||
const at = (i) => new Date(now.getTime() - (i + 1) * 60e3).toISOString();
|
||||
const who = { id: "fixture-key", provider: "fixture", name: "Fixture", who: "key-1", kind: "key", model: "model-a", routing: "", used: 0 };
|
||||
const routes = Array.from({ length: 12 }, (_, i) => ({ id: 100 - i, seq: 100 - i, time: at(i), agent: "fixture", model: "model-a", provider: "fixture", order: [who],
|
||||
tries: [{ id: who.id, model: "model-a", start: at(i), done: true, status: 200, ms: 1200 }], done: true, status: 200, ms: 1200, tokens: 3000 }));
|
||||
const AGENTS = Array.from({ length: 14 }, (_, i) => ({ id: "a" + i, name: "Agent " + i, path: "/t/a" + i + ".json", icon: "generic", wired: true,
|
||||
fields: [{ key: "model", label: "model", value: "m", options: [{ value: "m", label: "M", ref: "a/m" }] }] }));
|
||||
const U = (id) => ({ id, name: id, calls: 10, errors: 0, input: 1000, output: 500, cache_read: 0, cache_write: 0, cost: 0.1 });
|
||||
const USAGE = { calls: 140, errors: 0, input: 14000, output: 7000, reasoning: 0, unpriced: 0, cost: 1.4, bucket: "day",
|
||||
series: Array.from({ length: 7 }, (_, i) => ({ label: "d" + i, time: at(i * 1440), calls: 20, input: 2000, output: 1000, cost: 0.2 })),
|
||||
agents: Array.from({ length: 10 }, (_, i) => U("agent" + i)), models: Array.from({ length: 12 }, (_, i) => U("model" + i)), path: "" };
|
||||
const QUOTAS = Array.from({ length: 4 }, (_, i) => ({ provider: "p" + i, name: "Vendor " + i, user: "u" + i + "@x.test", plan: "Pro",
|
||||
windows: [{ name: "5h", used: 20 + i, resets: new Date(now.getTime() + 3600e3).toISOString() }, { name: "Week", used: 40, resets: new Date(now.getTime() + 86400e3).toISOString() }] }));
|
||||
|
||||
// The first reads a page makes when it opens wait for open(): the reader
|
||||
// wheels before they land
|
||||
function server(lang, gate) {
|
||||
return async (route) => {
|
||||
const url = new URL(route.request().url());
|
||||
const json = async (data, slow) => { if (slow && gate.on) await gate.wait; return route.fulfill({ json: data }); };
|
||||
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: AGENTS, profiles: [], settings: { lang, theme: "light", guideHidden: true } });
|
||||
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } }, true);
|
||||
if (url.pathname === "/api/gateway/trace") {
|
||||
if (url.searchParams.get("wait")) {
|
||||
await new Promise((ok) => setTimeout(ok, 700));
|
||||
const k = gate.traceSeq = (gate.traceSeq || 1) + 1;
|
||||
if (k > 8) return new Promise(() => {});
|
||||
const r = { ...routes[0], id: 100 + k, seq: 100 + k, time: new Date().toISOString() };
|
||||
return route.fulfill({ json: { mine: true, now: new Date().toISOString(), seq: k, totals: { requests: routes.length + k, rerouted: 0, errors: 0 }, routes: [r] } });
|
||||
}
|
||||
return json({ mine: true, now: now.toISOString(), seq: 1, totals: { requests: routes.length, rerouted: 0, errors: 0 }, routes }, true);
|
||||
}
|
||||
if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [{ day, requests: routes.length }], routes: [] }, true);
|
||||
if (url.pathname === "/api/usage/quotas") {
|
||||
if (gate.on) await gate.wait;
|
||||
const n = gate.quotaReads = (gate.quotaReads || 0) + 1;
|
||||
const q = QUOTAS.map((x, i) => ({ ...x, windows: x.windows.map((w) => ({ ...w, used: w.used + n })) }));
|
||||
return route.fulfill({ json: q, headers: { "X-Magpie-Reading": n < 6 ? "1" : "0", "Access-Control-Expose-Headers": "X-Magpie-Reading" } });
|
||||
}
|
||||
if (url.pathname === "/api/usage") return json(USAGE, true);
|
||||
if (url.pathname === "/api/groups") return json({ groups: [], models: [] }, true);
|
||||
if (url.pathname === "/api/plugins") return json({ plugins: [] });
|
||||
if (url.pathname === "/api/agents/cli") return json({ agents: {}, pending: false });
|
||||
if (url.pathname === "/api/window/fit") return route.fulfill({ status: 204 });
|
||||
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).catch(() => ""), contentType });
|
||||
};
|
||||
}
|
||||
|
||||
// the page told of a view's scroll late, as WebKit tells it under load: the
|
||||
// view is already where the wheel took it, the page still thinks it where
|
||||
// it last heard
|
||||
const LATE = `addEventListener("scroll", (e) => {
|
||||
const v = e.target;
|
||||
if (!e.isTrusted || !(v instanceof Element) || !v.classList.contains("view")) return;
|
||||
e.stopImmediatePropagation();
|
||||
setTimeout(() => v.dispatchEvent(new Event("scroll")), 80);
|
||||
}, { capture: true });`;
|
||||
// macOS 13's WebKit (16.6) scrolls a view under a wheel it never tells the
|
||||
// page of: a capture listener before app.js's stops each one, as
|
||||
// view-wheel-unheard does
|
||||
const DEAF = `addEventListener("wheel", (e) => e.stopImmediatePropagation(), { capture: true, passive: true });`;
|
||||
// every time code moves a view up, by how much: the put-backs the frames
|
||||
// can't show (one put back before the frame is painted is a step lost)
|
||||
const UPS = `{
|
||||
const d = Object.getOwnPropertyDescriptor(Element.prototype, "scrollTop");
|
||||
window.ups = [];
|
||||
Object.defineProperty(Element.prototype, "scrollTop", { get: d.get, configurable: true, set(y) {
|
||||
if (this.classList?.contains("view") && !this.hidden) window.ups.push(d.get.call(this) - y);
|
||||
d.set.call(this, y);
|
||||
} });
|
||||
}`;
|
||||
// MAGPIE_OPEN_WHEEL_HEARD=late or unheard runs only that half
|
||||
const HEARD = process.env.MAGPIE_OPEN_WHEEL_HEARD ? [process.env.MAGPIE_OPEN_WHEEL_HEARD] : ["late", "unheard"];
|
||||
const LANGS = ["en", "zh", "zh-TW", "ja", "de"];
|
||||
|
||||
for (const engine of ["chromium", "webkit"]) {
|
||||
test(engine + ": a page scrolled as it opens keeps the reader's place when its data lands", { timeout: 900000 }, async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit : chromium).launch();
|
||||
t.after(() => browser.close());
|
||||
for (const heard of HEARD) for (const lang of LANGS) for (const width of [420, 1000]) for (const name of ["usage", "routing"]) for (const visit of ["opened", "opened again"]) {
|
||||
await t.test(`${name}, ${visit}, wheels ${heard}, ${lang}, ${width}px`, async () => {
|
||||
const ctx = await browser.newContext({ viewport: { width, height: 600 }, reducedMotion: "reduce" });
|
||||
t.after(() => ctx.close());
|
||||
const p = await ctx.newPage();
|
||||
p.setDefaultTimeout(8000);
|
||||
const errors = [];
|
||||
p.on("pageerror", (e) => { if (!/^ResizeObserver loop/.test(e.message)) errors.push(e.message); });
|
||||
await p.addInitScript(heard === "late" ? LATE : DEAF);
|
||||
await p.addInitScript(UPS);
|
||||
const gate = { on: false };
|
||||
await p.route("**/*", server(lang, gate));
|
||||
await p.goto("http://magpie.test/?view=agents");
|
||||
await p.locator("#view-agents .ag-lead").first().waitFor();
|
||||
await p.waitForTimeout(500);
|
||||
// unheard: the window learns it on the page before, as the reader's
|
||||
// first scroll there teaches it (and it is kept for the next start)
|
||||
if (heard === "unheard") {
|
||||
const a = await p.locator("#view-agents").boundingBox();
|
||||
await p.mouse.move(a.x + a.width / 2, a.y + a.height / 2);
|
||||
for (let i = 0; i < 8; i++) { await p.mouse.wheel(0, 30); await p.waitForTimeout(16); }
|
||||
await p.waitForTimeout(400);
|
||||
assert.equal(await p.evaluate(() => localStorage.getItem("magpie.unheardWheels")), "1", "wheels the page never heard are learned");
|
||||
}
|
||||
const view = p.locator("#view-" + name);
|
||||
// opened again: what it drew the first time is there while it reads again
|
||||
if (visit === "opened again") {
|
||||
await p.locator(`#nav button[data-view="${name}"]`).click();
|
||||
await p.waitForTimeout(1000);
|
||||
await p.locator('#nav button[data-view="agents"]').click();
|
||||
await p.waitForTimeout(300);
|
||||
}
|
||||
let release;
|
||||
gate.wait = new Promise((ok) => { release = ok; });
|
||||
gate.on = true;
|
||||
await p.locator(`#nav button[data-view="${name}"]`).click();
|
||||
await view.waitFor();
|
||||
await p.waitForTimeout(150);
|
||||
// every frame's place, and how far what was under the pointer the
|
||||
// frame before has moved on the screen since
|
||||
const r = await view.boundingBox();
|
||||
const x = r.x + r.width / 2, y = r.y + r.height * 0.6;
|
||||
await view.evaluate((v, [x, y]) => {
|
||||
window.tops = []; window.downs = [];
|
||||
let was = null;
|
||||
const tick = () => {
|
||||
window.tops.push(v.scrollTop);
|
||||
const now = was?.[0].isConnected ? was[0].getBoundingClientRect().top : null;
|
||||
window.downs.push(now == null ? 0 : now - was[1]);
|
||||
const n = document.elementFromPoint(x, y);
|
||||
was = n && v.contains(n) ? [n, n.getBoundingClientRect().top] : null;
|
||||
requestAnimationFrame(tick);
|
||||
};
|
||||
requestAnimationFrame(tick);
|
||||
}, [x, y]);
|
||||
await p.mouse.move(x, y);
|
||||
await p.evaluate(() => { window.ups = []; });
|
||||
for (let i = 0; i < 30; i++) {
|
||||
await p.mouse.wheel(0, 30);
|
||||
await p.waitForTimeout(16);
|
||||
if (i === 6) { gate.on = false; release(); } // the data lands under the wheel
|
||||
}
|
||||
await p.waitForTimeout(1500);
|
||||
const [tops, downs, ups] = await p.evaluate(() => [window.tops, window.downs, window.ups]);
|
||||
// back is the view going up with what was under the pointer going
|
||||
// down with it: not the browser's anchoring (the view up, what's on
|
||||
// screen still), nor a part above growing (what's on screen down,
|
||||
// the view where it was)
|
||||
const back = tops.findIndex((y, i) => i && y < tops[i - 1] - 1 && downs[i] > 1);
|
||||
assert.equal(back, -1, `the view went back up under a wheel going down, ${tops[back - 1]} to ${tops[back]} (frame ${back}): ${tops.map(Math.round).join(" ")}`);
|
||||
// a step of the wheel put back (a redraw's few pixels kept in
|
||||
// place by the browser's anchoring are not one)
|
||||
assert.deepEqual(ups.filter((by) => by > 20).map(Math.round), [], "nothing put the view back up under the wheel: " + tops.map(Math.round).join(" "));
|
||||
assert.ok(tops[tops.length - 1] > 100, "the wheel scrolled the page: " + tops.map(Math.round).join(" "));
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user