Files
magpie/internal/gui/tests/plugin-actions.test.cjs
T
yetone d783df46cb plugin: a plugin's page adds items to a provider's and an agent's row menu (P6)
package.json's magpie.actions: [{id, menu, title, titles}] puts items in
the row menus magpie draws, after its own: a provider row's (right-click)
and an agent row's (its handle, or right-click). Picking one opens the
plugin's page and posts it {event: "action", data: {id, provider|agent:
{id, name}}}, nothing else of the row; the bridge's magpie.onAction(fn)
gets it, and an action picked before fn was given waits for it.

- plugin.Window reads them (page.go): menu one of ActionMenus (provider,
  agent; a session's menu is left out, its title is user content), id
  ^[a-z0-9][a-z0-9-]{0,39}$, an id given twice is the first's, 8 at most,
  none for a plugin with no page.
- /api/plugin-pages carries them on the page; a missing title is the
  page's, in each language (pluginpage.go).
- pluginpages.js: magpie.actions(menu, context) gives the row menu's
  items; openRowMenu draws a plugin's name as written (literal), not
  through t().
- The Plugins page says which menus a plugin adds to (actionsLine),
  translated in zh, zh-TW, ja and de.
- Docs: plugin-runtime.md's P6 section and verification; the site's
  plugin docs (en, zh, ja) gain "Items in magpie's menus".
- The core's budget (TestCoreScriptBudget) is not raised (#2710): with
  P6 the core came to 1,447,648 bytes, 648 over. pluginpages.js's header
  now says P5's and P6's part in one paragraph and points to
  plugin-runtime.md, which says it in full, and plugins.js's panels and
  actions lines share whereLine: 1,446,845, 155 under.

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.
- gofmt -l clean; go vet darwin, linux (-tags nogui) and windows ok;
  TestCoreScriptBudget ok.
- go test -run 'TestWindowActions|TestPluginPageActions' ok: duplicate,
  malformed and session-menu ids dropped, 12 actions kept to 8, none
  without a page, an off plugin's not served.
- plugin-actions.test.cjs: chromium and webkit, en zh zh-TW ja de, at
  1100 and 420: no page adds nothing; the agent menu ends with Hide then
  the plugin's item; the provider menu's item is in the window's
  language; a pick opens the page, which gets exactly {id, provider|
  agent: {id, name}} once, in one frame, though it calls onAction 400ms
  late. The Plugins row says which menus.
- Broken by hand, each red then restored: the bridge not holding an
  action picked before onAction (the late-registering fixture), the
  provider's whole row posted in place of {id, name} (the exact-data
  check), any id and any menu accepted (TestWindowActions).
- Neighbours in both engines: plugin-page, agent-cli-missing,
  agent-disconnect, group-bulk-remove, model-test-why and provider-find
  ok; plugin-panels red before P5's fixture fix (padding, in that
  commit), ok after.
- Real use: a dev build (-tags dev) in a sandbox HOME with a
  local plugin of two actions; WebKit on its dev UI picked "Inspect
  agent" on Claude Code and "Inspect provider" on a local provider, and
  the page logged {"id":"about-agent","agent":{"id":"claude","name":
  "Claude Code"}} then {"id":"about-provider","provider":{"id":
  "local-try","name":"Local Try"}}, one frame. Not clicked in the
  WKWebView window itself; the frame's loading there is
  TestPluginPageLoadsItsFilesInTheWindow's.
2026-10-18 07:13:12 +08:00

171 lines
11 KiB
JavaScript

// Run with Node's test runner and Playwright on the module path; see README.md.
// A community plugin's actions (magpie.actions, pluginpages.js, P6): items
// its page adds to a provider's and an agent's row menu, after magpie's
// own, named in the plugin's words in the window's language. Picking one
// opens the plugin's page and tells it the action and that row's id and
// name, and nothing else of it; a page that gives magpie.onAction late
// still gets every action picked before. A page with no action adds
// nothing to a menu. The Plugins page says which menus a plugin adds to.
// Every language, both engines, a narrow window. The API is faked here;
// the server's side is TestWindowActions and 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 bridge = path.resolve(__dirname, "../pagebridge.js");
const TOK = "7".repeat(32);
const withActions = [{
spec: "/x/magpie-row-tools", name: "magpie-row-tools", key: "plugin-row-tools", title: "Row tools", titles: { zh: "行工具" }, reads: [],
url: `/_magpie/plugin/${TOK}/index.html`,
actions: [
{ id: "check", menu: "provider", title: "Check balance", titles: { zh: "查余额", "zh-TW": "查餘額", ja: "残高を確認", de: "Guthaben prüfen" } },
{ id: "logs", menu: "agent", title: "Row tools", titles: { zh: "行工具" } },
],
}];
// the page gives its handler late: what was picked before waits for it
const HTML = `<!doctype html><meta charset="utf-8"><script src="_magpie/bridge.js"></script><ol id="got"></ol><script src="app.js"></script>`;
const JS = `setTimeout(() => magpie.onAction((a) => { const li = document.createElement("li"); li.textContent = JSON.stringify(a); document.getElementById("got").append(li); }), 400);`;
const providerList = [{ id: "openai", name: "OpenAI", icon: "generic", host: "api.openai.com", chat: "https://api.openai.com/v1", models: [] }]
.map((p) => ({ responses: "", anthropic: "", agents: [], fallback: [], headers: {}, key: { set: false }, keyList: [], ready: true, ...p }));
const agents = [{ id: "codex", name: "Codex", icon: "generic", path: "/fixture/codex", fields: [{ key: "model", label: "model", value: "gpt-5.4", options: [{ value: "gpt-5.4", label: "gpt-5.4" }] }] }];
function server(lang, opts) {
return async (route) => {
const req = route.request();
const url = new URL(req.url());
const json = (data) => route.fulfill({ json: data });
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: providerList, presets: [], excluded: [], gateway: { running: true, window: true }, plugins: [] });
if (url.pathname === "/api/groups") return json({ groups: [], pools: [] });
if (url.pathname === "/api/agents/cli") return json({ agents: {}, pending: false });
if (url.pathname === "/api/usage/quotas") return json([]);
if (url.pathname === "/api/plugin-pages") return json(opts.pages);
if (url.pathname === "/api/plugin-panels") return json([]);
if (url.pathname === "/api/plugins") return json(opts.plugins || { plugins: [] });
if (url.pathname === "/api/plugins/market") return json({ listings: [], state: opts.plugins || { 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 rel = m[2];
const body = rel === "_magpie/bridge.js" ? await fs.readFile(bridge) : rel === "index.html" ? HTML : rel === "app.js" ? JS : null;
if (body == null) return route.fulfill({ status: 404, body: "" });
const type = { ".html": "text/html", ".js": "text/javascript" }[path.extname(rel)];
return route.fulfill({ status: 200, headers: { "Content-Security-Policy": "sandbox allow-scripts; connect-src 'none'", "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 want = { en: "Check balance", zh: "查余额", "zh-TW": "查餘額", ja: "残高を確認", de: "Guthaben prüfen" };
const got = async (page) => {
const f = page.frames().find((x) => x.url().includes(TOK));
if (!f) return [];
return (await f.locator("#got li").allInnerTexts().catch(() => [])).map((x) => JSON.parse(x));
};
const menuNames = (page) => page.locator(".pop.row-menu .rm-item .rm-name").allInnerTexts();
const closeMenu = async (page) => { await page.keyboard.press("Escape"); await page.locator(".pop.row-menu").waitFor({ state: "detached" }); };
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(`${engine}: a plugin's actions in the row menus open its page and tell it the row`, 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}`;
for (const pages of [[], withActions]) {
const context = await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" });
const page = await context.newPage();
page.setDefaultTimeout(8000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", server(lang, { pages }));
await page.goto("http://magpie.test/");
// the agent's menu: magpie's own items, then the plugin's
await page.locator('.row.agent[data-id="codex"] .ag-handle').click();
await page.locator(".pop.row-menu").waitFor();
const own = await page.evaluate(() => t("Hide"));
const agentItems = await menuNames(page);
if (!pages.length) {
assert.equal(agentItems.at(-1), own, `${where}: no plugin, nothing added`);
await closeMenu(page);
await context.close();
continue;
}
const logs = lang.startsWith("zh") ? "行工具" : "Row tools"; // zh-TW takes zh's
assert.deepEqual(agentItems.slice(-2), [own, logs], `${where}: agent menu`);
assert.equal(await page.locator(".pop.row-menu .rm-sep").count() >= 1, true, where);
await closeMenu(page);
// the provider's menu: its item in the window's language
await page.evaluate(() => show("providers"));
const row = page.locator('#providers > .row.provider[data-id="openai"]');
await row.locator(".name").click({ button: "right" });
await page.locator(".pop.row-menu").waitFor();
const pvItems = await menuNames(page);
assert.equal(pvItems.at(-1), want[lang], `${where}: provider menu`);
assert.ok(await page.locator(".pop.row-menu").evaluate((m) => m.getBoundingClientRect().right <= innerWidth + 1), `${where}: menu fits`);
await page.locator(".pop.row-menu .rm-item", { hasText: want[lang] }).click();
await page.waitForFunction(() => view === "plugin-row-tools");
await page.waitForFunction(() => document.querySelector("#view-plugin-row-tools iframe.plugin-frame"));
for (let i = 0; i < 100 && (await got(page)).length < 1; i++) await page.waitForTimeout(50);
assert.deepEqual(await got(page), [{ id: "check", provider: { id: "openai", name: "OpenAI" } }], `${where}: told the row, and only its id and name`);
// picked again with the page open: told again, nothing drawn anew
await page.evaluate(() => show("agents"));
await page.locator('.row.agent[data-id="codex"] .ag-handle').click();
await page.locator(".pop.row-menu .rm-item", { hasText: logs }).click();
await page.waitForFunction(() => view === "plugin-row-tools");
for (let i = 0; i < 100 && (await got(page)).length < 2; i++) await page.waitForTimeout(50);
assert.deepEqual((await got(page))[1], { id: "logs", agent: { id: "codex", name: "Codex" } }, `${where}: agent action`);
assert.equal(await page.locator("#view-plugin-row-tools iframe.plugin-frame").count(), 1, where);
assert.deepEqual(errors, [], where);
await context.close();
}
}
}
});
test(`${engine}: Plugins says which menus a plugin adds to`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const plugins = { bun: true, bunVersion: "1.3.0", plugins: [
{ spec: "/x/magpie-row-tools", providers: [], moved: [], inMagpieOnly: true, page: { title: "Row tools", reads: [] }, actions: [{ menu: "provider", title: "Check balance" }, { menu: "agent", title: "Row tools" }] },
] };
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, { pages: [], 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 tr = (k, v) => page.evaluate(([k, v]) => t(k, v), [k, v]);
const row = view.locator(".pm-row").filter({ has: page.locator(".name", { hasText: "magpie-row-tools" }) });
await row.waitFor();
const lines = (await row.locator(".pm-page").allInnerTexts()).map((x) => x.trim());
const menus = [await tr("providers' menus"), await tr("agents' menus")].join(await tr(", "));
assert.deepEqual(lines, [await tr("Adds a page to the sidebar, which reads nothing of magpie's"), await tr("Adds items to {where}, which open its page", { where: menus })], where);
if (lang !== "en") assert.ok(!lines[1].includes("Adds items"), `${where}: translated`);
assert.ok(await view.evaluate((v) => v.scrollWidth <= v.clientWidth + 1), `${where}: fits`);
assert.deepEqual(errors, [], where);
await page.context().close();
}
}
});
}