Files
magpie/internal/gui/tests/menu-scroll.test.cjs
T
yetone b9f790d37b plugins: panels in magpie's pages, a page that replaces a built-in one, titles in the window's language, and a look that matches
P5 of the plugin runtime (docs/subsystems/plugin-runtime.md):

- Panels (magpie.panels): a plugin draws a frame into a slot of a
  built-in page (a provider's editor, Settings, Usage); magpie.context
  says where it is, and the frame is as tall as what it draws.
- A page can replace a built-in one (magpie.page.replaces); show() opens
  it in that page's place, and the sidebar row goes to it.
- page.titles and a panel's titles name it in the window's language
  ({"zh": …}); a malformed map is dropped, the title kept
  (TestWindowTitles).
- main's #2501 already names wails:// in the policy of a page in the
  desktop window (through ownWindow), which is why the usage page drew as
  bare HTML from v0.1.1259. TestPluginPageLoadsItsFilesInTheWindow loads
  a page through ownWindow in a real WKWebView, which Playwright on http
  can't; the subsystem page says how.
- The bridge adds magpie's look for what a page leaves unstyled, every
  rule in :where() so any rule of the page's wins, and the theme's
  colours as --magpie-* variables.

One commit: the panels, the replacing pages and the titles share hunks
in page.go, pluginpage.go, pluginpages.js and the docs, and couldn't be
split cleanly.

Run:
- Full: this series (P5, the Plugins dot, the probe test, P6, and a
  built-ins-on commit since dropped for main's own 5a2414acd) was run
  together, at load 200-660.
  At the pushed tree, 88dfab2d3 on origin/main 5380114da (rebased
  from 210bc2b77, no conflicts; its GUI assets and tests are the same
  bytes as the tree the GUI runs below used, diff -rq): gofmt clean,
  vet darwin/linux nogui/windows ok, TestCoreScriptBudget ok
  (1,446,845 of 1,447,000). go test -timeout 45m ./... at load
  193-278: 62 packages ok, red in TestMainWindowCorners (#1936) and
  TestPluginStreamLargeReplies JSON_fast (client timeout; alone 1 of
  3 red here, 0 of 3 on 5380114da side by side at load ~280; the
  series doesn't touch the stream path; #2551 reopened with the
  output, taken). Two earlier runs at this tree are discarded: one
  stopped when the disk filled, one when another session's go clean
  -cache emptied the build cache mid-run. The whole GUI suite at
  this tree was not finished (the disk filled); the files the series
  reaches ran (1318 tests, 124 red), and the 39 red files ran again
  at concurrency 1 on both trees: here 148 ok 120 red, origin/main
  135 ok 127 red. Both sides' reds are page.goto/launch timeouts
  under load (66 here, 71 there) and the same assertions:
  title-bar-tools' and settings-proxy-auth's "access control checks"
  on a cut-off /api/providers read (#2740, taken next), sidebar's
  "the list unrolls" and WebKit "#prefs pressed darkens" (#2684;
  alone, 1 red here, 3 on main), side-toggle (#2732); plugin-move
  red on main only. Six files again one by one on both trees:
  plugin-actions red 1 of 6 here, a 5s goto of ?view=plugins at load
  260; plugin-clash red on both; plugin-own-icon, plugin-gateway,
  plugin-checkin ok on both; settings-proxy-auth ok here, 3 red on
  main.
  At 976c9893a (on origin/main 6f950653f): go test -timeout 45m ./...
  red only in TestMainWindowCorners (#1936, the window's process
  killed at its deadline) and TestSetAnswersWhileDevinAndProvidersHang
  (#1375, 3 of 3 alone). The whole GUI suite, both engines: 10834
  tests, 237 red in 73 files, 184 of them a 180s browser launch. Those
  73 files run again at concurrency 2: 52 green, among them every
  plugin-* and agent-* file and plugin-actions; the 21 still red were
  run at origin/main f191d6423 and are red there too: codex-predictions
  (#2624), lightweight (#2638), segs-glide (#2683), usage-agents-hide
  (#2276), provider-advanced-fold (#2552), routing-bodies (#2559),
  routing-model-rest and rest-try-now (#2115, #2564), routing-keys-fold
  (#1612), routing-wb-restricted (#1905), routing-request-metrics
  (#2571), quota-count-wrap and quota-name-translated (#2228), s3-sync
  (#2448), usage-checkin (#2549), usage-ledger-abort (#2700),
  tencent-access-key (#2733), usage-range (#2734); side-toggle's WebKit
  motion red 1 of 3 on main, 0 of 3 here (#2732); usage-fold green alone.
  Rebased onto origin/main 717b69f78 (60725faa1, no conflicts): gofmt
  clean, vet darwin/linux nogui/windows ok; go test -timeout 45m ./...
  red in TestSetAnswersWhileDevinAndProvidersHang (#1375) and agent and
  gateway at the 45m alarm with tests still moving at load 400+, both ok
  alone (1173s, 1167s); 105 GUI files the series reaches (plugin*,
  sidebar*, side-*, settings*, title*, header*, agent-*): 1322 tests,
  23 red, run alone 214 of 218 ok, the 4 left in sidebar and
  sidebar-overlay-scrollbar (WebKit), red on 717b69f78 too (#2684,
  #1863). The whole GUI suite was not run again after the rebase.
- plugin-panels' tall panel (body{margin:0}) measured 220, not 180,
  after the look above gave an unstyled body 20px of padding; the
  fixture now sets padding:0 too, as a page that wants none would.
  plugin-panels ok in chromium and webkit after.
- gofmt -l clean; go vet darwin, linux (-tags nogui) and windows ok.
- GUI: plugin-page and plugin-panels in chromium and webkit, en zh zh-TW
  ja de, wide and narrow, ok.
- Broken by hand, each red then green: titled() in pluginpages.js
  (the "draws in its frame" test), the wails:// scheme in pagePolicy
  (the WKWebView test, before the rebase onto #2501), titles' parsing
  (TestWindowTitles).
- Real use: the published @magpie-community/page-usage 0.1.1 in a
  sandbox magpie window, its tiles styled.
2026-10-18 07:13:09 +08:00

189 lines
10 KiB
JavaScript

// Run with Node's test runner and Playwright on the module path; see README.md.
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 date = "2026-09-28";
const usage = Array.from({ length: 40 }, (_, i) => ({
agent: "fixture", cwd: "/projects/project-" + String(i + 1).padStart(2, "0"),
model: "model-" + String(i + 1).padStart(2, "0"), input: 40000 - i * 500,
output: 1000, cache_read: 0, cache_write: 0, cost: 1, priced: true,
}));
const sessions = usage.map((u, i) => ({
...u, id: String(i), title: "Session " + (i + 1), name: "Fixture",
last: date + "T08:00:00Z", start: date + "T07:00:00Z", models: [u], unpriced: 0,
}));
const state = {
agents: [{ id: "fixture", name: "Fixture", path: "/test/config.toml", wired: true, fields: [{
key: "model", label: "model", value: "model-01",
options: usage.map(u => ({ value: u.model, label: u.model, ref: u.model })),
}] }],
profiles: [], settings: { lang: "en", theme: "light" },
};
async function serve(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/sessions/progress") return json({ indexing: false });
if (url.pathname === "/api/sessions") return json({ sessions, dirs: ["/test/sessions"] });
if (url.pathname === "/api/sessions/stats") return json({ from: date, to: date, days: [{ date, usage, active: [] }], agents: { fixture: "Fixture" } });
if (url.pathname === "/api/sessions/overview") return json({ count: sessions.length, days: [sessions.length], top: { tokens: [], cost: [], active: [] } });
if (url.pathname === "/api/update" || url.pathname === "/api/drift") return json({});
if (url.pathname === "/api/agents/cli") return json({ agents: {}, pending: false });
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname === "/api/gateway/trace") return json({ mine: false, now: date, totals: { requests: 0, rerouted: 0, errors: 0 } });
if (url.pathname === "/api/plugins/updates") return json({ waiting: [] });
if (url.pathname === "/api/usage/quotas" || url.pathname === "/api/usage/quotas/history" || url.pathname === "/api/agents/install") return json([]);
if (url.pathname === "/api/whatsnew") return json({});
if (url.pathname === "/api/upstream") return json({ vendors: [], providers: {} });
// the sidebar's plugin pages, and plugin panels in magpie's pages: none
if (url.pathname === "/api/plugin-pages" || url.pathname === "/api/plugin-panels") return json([]);
// the sidebar's gateway line, when no page has read the providers
if (url.pathname === "/api/providers") return json({ providers: [], gateway: { url: "http://127.0.0.1:3425", running: true } });
assert(!url.pathname.startsWith("/api/"), "Unexpected API: " + url.pathname);
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 });
}
async function scrolled(page, selector) {
await page.waitForFunction(selector => {
const box = document.querySelector(selector);
return !box || box.hidden || box.scrollTop > 0;
}, selector);
const box = page.locator(selector);
assert(await box.isVisible(), "scrolling must leave the dropdown open");
assert(await box.evaluate(e => e.scrollTop > 0), "the dropdown must actually scroll");
}
async function scrollMenu(page, selector, gesture) {
const box = page.locator(selector);
assert(await box.evaluate(e => e.scrollHeight > e.clientHeight), "the fixture must overflow");
// the menu's opening come to rest first: a click on its scrollbar's track
// while it still moved landed nowhere, now and then (both engines)
await page.evaluate(() => Promise.all(document.getAnimations().map(a => a.finished.catch(() => {}))));
const r = await box.boundingBox();
if (gesture === "wheel") {
await page.mouse.move(r.x + r.width / 2, r.y + r.height / 2);
await page.mouse.wheel(0, 240);
} else if (gesture === "track") {
await page.mouse.click(r.x + r.width - 6, r.y + r.height - 25);
} else {
await page.mouse.move(r.x + r.width - 6, r.y + 20);
await page.mouse.down();
await page.mouse.move(r.x + r.width - 6, r.y + 200, { steps: 10 });
await page.mouse.up();
}
await scrolled(page, selector);
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": scrollable dropdowns", async t => {
assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium", ignoreDefaultArgs: ["--hide-scrollbars"] }));
const context = await browser.newContext({ viewport: { width: 1100, height: 800 }, reducedMotion: "reduce" });
const page = await context.newPage();
page.setDefaultTimeout(5000);
const errors = [];
page.on("pageerror", e => errors.push(e.message));
await page.route("**/*", serve);
await page.addInitScript(() => localStorage.setItem("magpie.usageTab", "sessions"));
await context.tracing.start({ screenshots: true, snapshots: true });
t.after(async () => {
try {
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 + ".png") });
await context.tracing.stop({ path: path.join(process.env.ARTIFACT_DIR, engine + ".zip") });
} else await context.tracing.stop();
} finally { await browser.close(); }
});
async function reset() {
await page.goto("http://magpie.test/?view=usage");
await page.locator("#sessFolder:not([hidden])").waitFor();
assert.equal(await page.title(), "magpie");
assert.equal(await page.locator("#sessList .sess-item").count(), 40);
// Always-visible scrollbars make track/thumb input independent of OS preferences.
await page.addStyleTag({ content: `
.sess-menu, #list { animation: none !important; scrollbar-width: auto; scrollbar-gutter: stable; }
:is(.sess-menu, #list)::-webkit-scrollbar { width: 14px; }
:is(.sess-menu, #list)::-webkit-scrollbar-thumb { background: #888; }
:is(.sess-menu, #list)::-webkit-scrollbar-track { background: #eee; }
` });
await page.evaluate(async () => {
await document.fonts.ready;
await Promise.all(document.getAnimations().map(a => a.finished.catch(() => {})));
});
}
for (const filter of ["sessFolder", "sessModel"]) {
for (const gesture of ["wheel", "track", "drag"]) {
await t.test(filter + ": " + gesture, async () => {
await reset();
await page.locator("#" + filter).click();
await scrollMenu(page, ".sess-menu", gesture);
await page.keyboard.press("Escape");
assert.equal(await page.locator(".sess-menu").count(), 0);
assert(await page.locator("#" + filter).evaluate(e => e === document.activeElement));
});
}
await t.test(filter + ": keyboard scroll and selection", async () => {
await reset();
await page.locator("#" + filter).click();
await page.keyboard.press("ArrowUp");
await scrolled(page, ".sess-menu");
assert(await page.locator(".sess-menu .pm-item").last().evaluate(e => e === document.activeElement));
await page.keyboard.press("Enter");
assert.equal(await page.locator(".sess-menu").count(), 0);
assert.match(await page.locator("#" + filter).innerText(), /(?:project|model)-40/);
assert.equal(await page.locator("#sessList .sess-item").count(), 1);
assert.equal(await page.locator("#sessList .name").innerText(), "Session 40");
});
}
await t.test("outside click, page scroll, resize and reopen", async () => {
await reset();
const anchor = page.locator("#sessFolder");
for (const dismiss of ["outside", "page scroll", "resize"]) {
await reset();
await anchor.click();
await page.locator(".sess-menu").waitFor();
if (dismiss === "outside") { const bar = await page.locator("#sessionsPane .sess-tools").boundingBox(); await page.mouse.click(bar.x + bar.width - 6, bar.y + bar.height / 2); }
else if (dismiss === "page scroll") {
await page.mouse.move(1000, 650);
await page.mouse.wheel(0, 200);
} else await page.setViewportSize({ width: 1101, height: 800 });
await page.locator(".sess-menu").waitFor({ state: "detached" });
}
await anchor.click();
await scrollMenu(page, ".sess-menu", "wheel");
});
await t.test("main model picker keeps scrolling", async () => {
await reset();
await page.locator('#nav [data-view="agents"]').click();
for (const gesture of ["wheel", "track", "drag"]) {
await page.locator('#agents [data-key="model"]').click();
await scrollMenu(page, "#list", gesture);
await page.locator("#q").press("Escape");
assert(await page.locator("#pop").isHidden());
}
});
await t.test("main model picker closes on a second click", async () => {
const anchor = page.locator('#agents [data-key="model"]');
await anchor.click();
assert(await page.locator("#pop").isVisible());
await anchor.click();
assert(await page.locator("#pop").isHidden());
await anchor.click();
assert(await page.locator("#pop").isVisible(), "a third click opens it again");
await page.locator("#q").press("Escape");
});
assert.deepEqual(errors, [], "page runtime errors");
});
}