Files
magpie/internal/gui/tests/plugin-page.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

298 lines
20 KiB
JavaScript

// Run with Node's test runner and Playwright on the module path; see README.md.
// A community plugin's own page in the window (pluginpages.js, P4): the
// example plugin (testdata/page-plugin) gets a tab in the sidebar's
// Plugins group and draws in a frame sandboxed to scripts, with the
// window's theme, its own options and the read it declared. The frame
// can't reach magpie's API: its policy stops the fetch, and with the
// policy gone the request it would send carries Origin: null, which
// apiFramed turns away (TestPluginPageNoAPI). A read it didn't declare is
// refused, and a message from another frame is nothing. A page that
// throws shows "This page stopped working" with Try again. The Plugins
// page says what a page may read before it is on. Every language, both
// engines, a narrow window. The API is faked here; the server's side is
// pluginpage_test.go.
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 example = path.resolve(__dirname, "../testdata/page-plugin/page");
const bridge = path.resolve(__dirname, "../pagebridge.js");
const GLANCE = "a".repeat(32), PROBE = "b".repeat(32), OPEN = "c".repeat(32), BROKEN = "d".repeat(32);
const entry = (tok, name, title, reads, file = "index.html") => ({
spec: "/x/" + name, name, key: "plugin-" + name, title, reads,
url: `/_magpie/plugin/${tok}/${file}`, icon: name === "glance" ? `/_magpie/plugin/${tok}/icon.svg` : "",
});
// the example's title by language (magpie.page.titles); none in German,
// which reads its title
const TITLES = { zh: "用量速览", "zh-TW": "用量速覽", ja: "使用量の概要" };
const pages = [
{ ...entry(GLANCE, "glance", "Usage glance", ["usage:summary"]), titles: TITLES },
entry(PROBE, "probe", "Probe", []),
entry(OPEN, "open", "Probe without a policy", []),
entry(BROKEN, "broken", "Broken", []),
];
// what pluginpage.go's pagePolicy sends, for this host: the page's folder
// under each scheme the window is served on
const policy = (tok) => {
const dir = `magpie.test/_magpie/plugin/${tok}/`;
const own = `wails://${dir} http://${dir} https://${dir}`;
return [
"sandbox allow-scripts", "default-src 'none'", `script-src ${own}`, `style-src ${own} 'unsafe-inline'`,
`img-src ${own} data:`, `font-src ${own}`, `media-src ${own}`, "connect-src 'none'", "frame-src 'none'",
"worker-src 'none'", "object-src 'none'", "form-action 'none'", "base-uri 'none'", "frame-ancestors 'self'",
].join("; ");
};
// a page that tries every way out it has, and tells the window what came
// of each (its message has no magpie:1, so the window's bridge ignores it)
const PROBE_HTML = `<!doctype html><meta charset="utf-8"><script src="_magpie/bridge.js"></script><script src="probe.js"></script><style>.own { border-radius: 2px; }</style><h1>probe</h1><p id="p">probe</p><button id="b">b</button><button class="own">o</button>`;
const PROBE_JS = `(async () => {
const out = {};
await magpie.ready;
try { const r = await fetch("/api/state?probe=1"); out.fetch = "status " + r.status; } catch (e) { out.fetch = "refused"; }
try { out.storage = typeof localStorage.length; } catch (e) { out.storage = "refused"; }
try { out.cookie = document.cookie; } catch (e) { out.cookie = "refused"; }
try { out.top = String(parent.document.title); } catch (e) { out.top = "refused"; }
try { await magpie.read("usage:summary"); out.read = "given"; } catch (e) { out.read = e.message; }
try { await magpie.read("providers:list"); out.read2 = "given"; } catch (e) { out.read2 = e.message; }
// what the page left unstyled is magpie's; what it styled is its own
const cs = (q) => getComputedStyle(document.querySelector(q));
out.look = { bg: cs("html").backgroundColor, fg: cs("body").color, font: cs("body").fontFamily, h1: cs("h1").fontSize, button: cs("#b").borderRadius, own: cs(".own").borderRadius };
parent.postMessage({ probe: out }, "*");
})();`;
const BROKEN_HTML = `<!doctype html><meta charset="utf-8"><script src="_magpie/bridge.js"></script><script src="app.js"></script><p id="ok">drawn</p>`;
function server(lang, seen, plugins) {
return async (route) => {
const req = route.request();
const url = new URL(req.url());
const json = (data) => route.fulfill({ json: data });
if (url.searchParams.get("probe")) {
seen.api.push(await req.allHeaders());
return route.fulfill({ status: 403, body: "" });
}
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:${JSON.stringify(lang)},theme:"light",web:false};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } });
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true }, plugins: [] });
if (url.pathname === "/api/groups") return json({ groups: [], pools: [] });
if (url.pathname === "/api/plugin-pages") return json(pages);
if (url.pathname === "/api/plugin-pages/read") {
const b = req.postDataJSON();
seen.reads.push(b);
return json({ period: "today", calls: 12, errors: 0, input: 1000, output: 234, cost: 0.5, models: [] });
}
if (url.pathname === "/api/plugin-pages/options") {
const b = req.postDataJSON();
if (b.options) { seen.options.push(b); seen.saved = b.options; }
return json(seen.saved || {});
}
if (url.pathname === "/api/plugins") return json(plugins);
if (url.pathname === "/api/plugins/market") return json({ listings: [], state: plugins });
if (url.pathname === "/api/plugins/listings") return json({ listings: [] });
if (url.pathname.startsWith("/api/")) return json({});
const m = url.pathname.match(/^\/_magpie\/plugin\/([0-9a-f]{32})\/(.+)$/);
if (m) {
const [, tok, rel] = m;
const headers = { "X-Content-Type-Options": "nosniff", "Referrer-Policy": "no-referrer", "Cache-Control": "no-cache" };
if (tok !== OPEN) headers["Content-Security-Policy"] = policy(tok);
const type = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml" }[path.extname(rel)];
let body;
if (rel === "_magpie/bridge.js") body = await fs.readFile(bridge);
else if (tok === GLANCE) body = await fs.readFile(path.join(example, rel)).catch(() => null);
else if ((tok === PROBE || tok === OPEN) && rel === "index.html") body = PROBE_HTML;
else if ((tok === PROBE || tok === OPEN) && rel === "probe.js") body = PROBE_JS;
else if (tok === BROKEN && rel === "index.html") body = BROKEN_HTML;
else if (tok === BROKEN && rel === "app.js") body = seen.broken ? "throw new Error('fixture: the page broke')" : "1";
if (body == null) return route.fulfill({ status: 404, body: "" });
return route.fulfill({ status: 200, headers: { ...headers, "Content-Type": type }, body });
}
if (url.host !== "magpie.test") return route.fulfill({ status: 404, body: "" });
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)];
try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }
};
}
const plugins = { bun: true, bunVersion: "1.3.0", plugins: [
{ spec: "/x/magpie-usage-glance", providers: [], moved: [], inMagpieOnly: true, page: { title: "Usage glance", reads: ["usage:summary", "providers:list"] } },
{ spec: "/x/quiet-page", off: true, providers: [], moved: [], inMagpieOnly: true, page: { title: "Quiet", reads: [] } },
] };
const frameOf = (page, tok) => page.frames().find((f) => f.url().includes(tok));
async function frameReady(page, tok) {
await page.waitForFunction((tok) => [...document.querySelectorAll("iframe.plugin-frame")].some((f) => f.src.includes(tok)), tok);
for (let i = 0; i < 100 && !frameOf(page, tok); i++) await page.waitForTimeout(50);
return frameOf(page, tok);
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(`${engine}: a plugin's page draws in its frame, shut in`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
for (const width of [1100, 420]) {
const where = `${engine} ${lang} ${width}`;
const context = await browser.newContext({ viewport: { width, height: 700 }, reducedMotion: "reduce" });
const page = await context.newPage();
page.setDefaultTimeout(8000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
const seen = { api: [], reads: [], options: [] };
await page.route("**/*", server(lang, seen, plugins));
await page.goto("http://magpie.test/");
// the sidebar's Plugins group, after the built-in pages
const head = page.locator("#nav .nav-gl[data-plugin-pages]");
await head.waitFor({ state: "attached" });
assert.equal(await head.textContent(), await page.evaluate(() => t("Plugins")), where);
const tabs = page.locator("#nav button[data-plugin-page]");
assert.equal(await tabs.count(), 4, where);
assert.equal(await page.evaluate(() => { const h = document.querySelector("#nav .nav-gl[data-plugin-pages]"); return [...h.parentElement.children].indexOf(h) > [...h.parentElement.querySelectorAll("button[data-view='plugins']")].map((b) => [...b.parentElement.children].indexOf(b))[0]; }), true, `${where}: after the built-in pages`);
assert.equal(await tabs.first().locator("img.nav-ic").getAttribute("src"), `/_magpie/plugin/${GLANCE}/icon.svg`, where);
// titled in the window's language, else by its title
assert.equal(await tabs.first().locator("span").textContent(), TITLES[lang] || "Usage glance", `${where}: the tab's title`);
if (lang === "de") {
// a new language retitles the tab, and back
await page.evaluate(() => setLocale("ja"));
await page.waitForFunction(() => document.querySelector("#nav button[data-plugin-page] span").textContent === "使用量の概要");
await page.evaluate(() => setLocale("de"));
await page.waitForFunction(() => document.querySelector("#nav button[data-plugin-page] span").textContent === "Usage glance");
}
// no frame until the page is looked at
assert.equal(await page.locator("iframe.plugin-frame").count(), 0, `${where}: nothing loaded unseen`);
// the example: its declared read, the theme, its options
await page.evaluate(() => show("plugin-glance"));
const glance = await frameReady(page, GLANCE);
assert.equal(await page.locator("#view-plugin-glance iframe").getAttribute("sandbox"), "allow-scripts", where);
await glance.waitForFunction(() => document.getElementById("cost").textContent === "$0.50");
assert.equal(await glance.locator("#calls").textContent(), "12 calls, 1234 tokens", where);
assert.deepEqual(seen.reads.map((r) => [r.spec, r.read]), [["/x/glance", "usage:summary"]], where);
assert.equal(await glance.evaluate(() => document.documentElement.lang), lang, `${where}: the window's language`);
assert.equal(await glance.evaluate(() => document.documentElement.dataset.theme), "light", where);
await page.evaluate(() => { document.documentElement.dataset.theme = "dark"; });
await glance.waitForFunction(() => document.documentElement.dataset.theme === "dark");
assert.ok((await glance.evaluate(() => document.documentElement.style.getPropertyValue("--magpie-bg"))).length > 0, `${where}: the tokens`);
await glance.locator("#hide").click();
await glance.waitForFunction(() => document.getElementById("cost").textContent === "");
assert.deepEqual(seen.options.map((o) => [o.spec, o.options.hideCost]), [["/x/glance", true]], `${where}: its own options`);
// the frame fits the window
assert.ok(await page.evaluate(() => { const v = document.querySelector("#view-plugin-glance"); const f = v.querySelector("iframe"); return f.getBoundingClientRect().width <= v.clientWidth + 1 && v.scrollWidth <= v.clientWidth + 1 && f.getBoundingClientRect().height > 200; }), `${where}: fits`);
if (lang === "en" && width === 1100) {
// every way out of the frame is shut; a read it didn't declare
// is refused before it reaches the server
const got = page.evaluate(() => new Promise((res) => addEventListener("message", (e) => { if (e.data?.probe) res(e.data.probe); })));
await page.evaluate(() => show("plugin-probe"));
const probe = await got;
assert.equal(probe.fetch, "refused", `${where}: the policy stops a fetch of /api`);
assert.equal(probe.storage, "refused", `${where}: no storage`);
assert.equal(probe.cookie, "refused", `${where}: no cookie`);
assert.equal(probe.top, "refused", `${where}: no reach into the window`);
assert.equal(probe.read, "Probe doesn't ask to read usage:summary", where);
assert.equal(probe.read2, "Probe doesn't ask to read providers:list", where);
assert.equal(seen.api.length, 0, `${where}: nothing reached /api`);
assert.equal(seen.reads.length, 1, `${where}: an undeclared read never reached the server`);
// a page with no stylesheet of its own reads as part of the window
const win = await page.evaluate(() => {
const d = document.createElement("div");
d.style.cssText = "background: var(--bg); color: var(--fg)";
document.body.append(d);
const c = getComputedStyle(d);
const r = { bg: c.backgroundColor, fg: c.color };
d.remove();
return r;
});
assert.equal(probe.look.bg, win.bg, `${where}: the window's background`);
assert.equal(probe.look.fg, win.fg, `${where}: the window's text colour`);
assert.match(probe.look.font, /apple-system|SF Pro|system-ui/, `${where}: the window's font, not a serif`);
assert.equal(probe.look.h1, "20px", `${where}: magpie's heading`);
assert.equal(probe.look.button, "6px", `${where}: magpie's button`);
assert.equal(probe.look.own, "2px", `${where}: the page's own rule wins`);
// with the policy gone, what the frame's fetch would send is what
// apiFramed turns away
const got2 = page.evaluate(() => new Promise((res) => addEventListener("message", (e) => { if (e.data?.probe) res(e.data.probe); })));
await page.evaluate(() => show("plugin-open"));
const open = await got2;
assert.equal(open.fetch.startsWith("status") || open.fetch === "refused", true, where);
assert.equal(seen.api.length, 1, `${where}: the fetch went out`);
assert.equal(seen.api[0].origin, "null", `${where}: as Origin: null`);
assert.ok(!seen.api[0].cookie, `${where}: without a cookie`);
// a message from another frame naming a page is nothing
const before = seen.reads.length;
await page.evaluate(() => {
const f = document.createElement("iframe");
f.srcdoc = `<script>parent.postMessage({magpie:1,id:1,method:"read",params:{name:"usage:summary"}},"*")<\/script>`;
document.body.append(f);
});
await page.waitForTimeout(300);
assert.equal(seen.reads.length, before, `${where}: another frame's read is not answered`);
// a page that throws shows the kernel's broken state, and Try again
// draws it once its code works
seen.broken = true;
await page.evaluate(() => show("plugin-broken"));
const card = page.locator("#view-plugin-broken .slot-error");
await card.waitFor();
assert.equal(await card.locator(".name").textContent(), "This page stopped working", where);
// the frame's own script's error is muted to it ("Script error."):
// the window says the page hit one
assert.equal(await card.locator(".sub").textContent(), "The page hit an error", where);
seen.broken = false;
await card.locator(".slot-again").click();
const fixed = await frameReady(page, BROKEN);
await fixed.locator("#ok").waitFor();
assert.equal(await card.count(), 0, `${where}: the card gone`);
}
// the broken page's own throw, in its frame, is the only error
assert.deepEqual(errors.filter((e) => e !== "fixture: the page broke"), [], where);
await context.close();
}
}
});
test(`${engine}: Plugins says what a page may read before it is on`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
for (const width of [980, 420]) {
const where = `${engine} ${lang} ${width}`;
const page = await (await browser.newContext({ viewport: { width, height: 820 } })).newPage();
page.setDefaultTimeout(5000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", server(lang, { api: [], reads: [], options: [] }, plugins));
await page.goto("http://magpie.test/?view=plugins");
const view = page.locator("#view-plugins");
const installed = await page.evaluate(() => t("Installed"));
await page.locator(":is(.lib-tabs .opt, .nav-s):visible", { hasText: installed }).first().click();
const row = (name) => view.locator(".pm-row").filter({ has: page.locator(".name", { hasText: name }) });
const glance = row("magpie-usage-glance");
await glance.waitFor();
const tr = (k, v) => page.evaluate(([k, v]) => t(k, v), [k, v]);
assert.deepEqual((await glance.locator(".pm-chip.kind").allInnerTexts()).map((x) => x.trim()), [await tr("Page")], where);
const reads = [await tr("your usage totals, by model"), await tr("your providers' names")].join(await tr(", "));
assert.equal((await glance.locator(".pm-page").innerText()).trim(), await tr("Adds a page to the sidebar, which can read {reads}", { reads }), where);
if (lang !== "en") assert.ok(!(await glance.locator(".pm-page").innerText()).includes("Adds a page"), `${where}: translated`);
// one switched off still says it
const quiet = row("quiet-page");
assert.equal((await quiet.locator(".pm-page").innerText()).trim(), await tr("Adds a page to the sidebar, which reads nothing of magpie's"), where);
assert.ok(await view.evaluate((v) => v.scrollWidth <= v.clientWidth + 1), `${where}: fits`);
// nothing drawn with a coloured left border
const borders = await view.locator(".pm-row *").evaluateAll((els) => els.filter((e) => { const s = getComputedStyle(e); return parseFloat(s.borderLeftWidth) > 0 && s.borderLeftStyle !== "none" && parseFloat(s.borderRightWidth) === 0; }).length);
assert.equal(borders, 0, where);
assert.deepEqual(errors, [], where);
await page.context().close();
}
}
});
}