P1 of docs/subsystems/plugin-runtime.md. P0 (3ccbe6bc1) gave built-in plugins a manifest, plugins.yml and a switch; their pages were still app.js's own code. Now the window has a kernel a plugin draws its page through, and the Gateway page moved into plugins/gateway to prove it. What changed: - internal/gui/assets/kernel.js (new): window.magpie. A plugin registers with magpie.plugin(id, setup); ctx.slots.add("page", part) puts its markup where index.html's <template data-slot="page"> is. The shell calls its hooks through magpie.call, behind an error boundary: a hook that throws, or whose promise fails, is logged and its page shows "This page stopped working", what broke and Try again, while every other page goes on. ctx.ui is the kit (button, switch, the app menu, a settings row) and ui.form draws a plugin's settings from their schema. ctx.config / onConfig carry the settings, from boot.js before the first paint and from Plugins › Built-in after. - internal/pluginrt/schema.go (new): a plugin's settings are a Go struct (Manifest.Settings); SchemaOf makes the JSON Schema the form is drawn from, and Validate is what SetConfig (config.go) takes into plugins.yml. Compose drops a hand-edited value the schema refuses. - plugins/gateway: the Gateway page as a plugin, Essential and in use while a gateway key is there. One setting, callsPage (10/20/50/100, 20 by default). Its client is plugins/gateway/{keys.js,client.js}, moved out of app.js (and caller-keys.js) unchanged in behaviour. - internal/gui: builtins.go takes POST {id, config} beside {id, on} and lists each plugin's schema and config; boot.js carries pluginConfig; /plugins/<id>/… files are served. Plugins › Built-in draws a plugin's settings rows under its switch. - Docs: plugin-runtime.md has "The window's kernel (P1)"; gui-shell.md, subsystems/README.md and tests/README.md updated. What was run: - go test ./... (sandbox HOME, pinned caches): all packages ok; gofmt -l clean; go vet on darwin, GOOS=linux -tags nogui and GOOS=windows. - New tests: TestSchemaOf, TestValidate, TestSetConfig, TestBuiltinConfig, TestBuiltinClientsLoaded; plugin-kernel.test.cjs (a page that throws breaks only itself and Try again draws it, at 1100 and 420 in en, zh, zh-TW, ja, de; callsPage from boot.js and from Plugins › Built-in), both engines. - Broken by hand, each turned its test red: the boundary's catch removed; Try again not putting the page's markup back; the Gateway page's onConfig not re-reading callsPage; boot.js's pluginConfig ignored; SetConfig skipping Validate. - The full GUI suite in Chromium and WebKit (node --test *.test.cjs). One red was this change's own. providers-fetching-retry lifts providersWhileFetching out of app.js, which now asks providersPage, and the lift lacked it. The test now lifts that too, and gains "a poll under the Gateway page, a plugin's page that reads with Providers, reads". That case goes red with providersPage dropped from the poll's guard. - The reds that were on origin/maina75de4c21too are fixed in their own commits after this one. Two of them came from P0's Built-in tab: nav-sub-unroll and plugin-check-github-limit.
227 lines
16 KiB
JavaScript
227 lines
16 KiB
JavaScript
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||
// Plugins › Built-in (Lxxyx on X: too much to look through): magpie's
|
||
// built-in plugins (internal/pluginrt, plugins/), each with a switch kept in
|
||
// plugins.yml. Off, a plugin's parts leave the window: its page leaves the
|
||
// nav — the sidebar's and the header's — and an address kept for it opens
|
||
// Agents, its Settings tab goes. One in use can't be switched off: its
|
||
// switch is on and disabled and its row says what uses it, in the page's
|
||
// language. Switched on, a page's tab is back at once. A plugins.yml that
|
||
// doesn't parse says so and no switch moves. The tab is first on the
|
||
// Plugins page, with no search field. Every language, both layouts and a
|
||
// narrow window; no backend, the API is faked here.
|
||
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");
|
||
|
||
// as plugins/*'s manifests say them, in pluginrt.Registered's order (by id)
|
||
const PLUGINS = [
|
||
{ id: "gateway", name: "Gateway page", sub: "The gateway's state and keys, how to connect a client, its models and recent calls", one: "1 gateway key", many: "{n} gateway keys" },
|
||
{ id: "groups", name: "Routing groups", sub: "Several models agents pick as one: each request goes to the right one, and to the next when one fails", one: "1 group in use", many: "{n} groups in use" },
|
||
{ id: "library", name: "Library", sub: "Instructions, MCP servers, skills and hooks, kept once and given to every agent", one: "1 item given to agents", many: "{n} items given to agents" },
|
||
{ id: "otel", name: "Observability", sub: "Send each request's traces and metrics to an OpenTelemetry collector, such as Langfuse", one: "Sending to a collector", many: "Sending to a collector" },
|
||
{ id: "sessions", name: "Sessions", sub: "Your agents' past conversations: read, search, resume and export them", one: "Recording gateway conversations", many: "Recording gateway conversations" },
|
||
{ id: "warmups", name: "Warm-up and check-in", sub: "Start a subscription's usage window at a time you pick, and claim vendors' daily check-in credits", one: "1 warm-up or check-in on", many: "{n} warm-ups and check-ins on" },
|
||
];
|
||
// a new install's (the Essentials preset): all off but the Gateway page,
|
||
// which is essential, and two routing groups the user made
|
||
const START = { gateway: [true, 0], groups: [false, 2], library: [false, 0], otel: [false, 0], sessions: [false, 0], warmups: [false, 0] };
|
||
|
||
// the Gateway page's settings, as pluginrt.SchemaOf makes them
|
||
const GATEWAY_SCHEMA = {
|
||
type: "object",
|
||
properties: { callsPage: { type: "integer", title: "Recent calls at a time", description: "How many of the gateway's recent calls the page shows, and how many more each Show more adds", enum: [10, 20, 50, 100], default: 20 } },
|
||
"x-order": ["callsPage"],
|
||
};
|
||
|
||
function builtins(st, broken, config) {
|
||
return PLUGINS.map((p) => {
|
||
const [chosen, inUse] = st[p.id];
|
||
const on = chosen || inUse > 0;
|
||
const f = { id: p.id, name: p.name, sub: p.sub, on, chosen, source: inUse > 0 && !chosen ? "in use" : "preset", state: on ? "active" : "off", inUse, use: inUse === 1 ? p.one : inUse > 1 ? p.many : undefined, broken };
|
||
if (p.id === "gateway") Object.assign(f, { schema: GATEWAY_SCHEMA, config });
|
||
return f;
|
||
});
|
||
}
|
||
|
||
function server(lang, posts, broken) {
|
||
const st = structuredClone(START);
|
||
const config = { callsPage: 20 };
|
||
const list = () => builtins(st, broken, config);
|
||
const cur = () => ({
|
||
theme: "light", lang, tray: "panel", currency: "usd", textSize: 100, redactWords: [],
|
||
codexWarmup: "", claudeWarmup: "", codexWarmAt: "", claudeWarmAt: "",
|
||
version: "0.1.400", dir: "/config/home/.config/magpie", gateway: "http://127.0.0.1:3425",
|
||
proxyNow: "none", proxySource: "none", visionModels: [], imageGenModels: [], workbuddyCheckins: [], lanURLs: [],
|
||
fx: { rate: 7.2, at: new Date().toISOString(), stale: false },
|
||
builtins: list(),
|
||
});
|
||
return async (route) => {
|
||
const req = route.request(), url = new URL(req.url());
|
||
const json = (data) => route.fulfill({ json: data });
|
||
if (url.pathname === "/boot.js") {
|
||
const off = list().filter((f) => !f.on).map((f) => f.id);
|
||
return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:${JSON.stringify(lang)},theme:"light",featuresOff:${JSON.stringify(off)}};` });
|
||
}
|
||
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: cur(), fx: cur().fx });
|
||
if (url.pathname === "/api/plugins/builtin") {
|
||
if (req.method() !== "POST") return json(list());
|
||
const { id, on, config: change } = req.postDataJSON();
|
||
if (change) {
|
||
posts.push([id, change]);
|
||
if (broken || ![10, 20, 50, 100].includes(change.callsPage)) return route.fulfill({ status: 400, json: { error: "callsPage: not one of [10 20 50 100]" } });
|
||
Object.assign(config, change);
|
||
return json(list());
|
||
}
|
||
posts.push([id, on]);
|
||
if (broken || (!on && st[id][1] > 0)) return route.fulfill({ status: 400, json: { error: "in use" } });
|
||
st[id][0] = on;
|
||
return json(list());
|
||
}
|
||
if (url.pathname === "/api/settings") return json(cur());
|
||
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true }, plugins: [] });
|
||
if (url.pathname === "/api/plugins") return json({ bun: true, bunVersion: "1.4.2", plugins: [], picker: false, movable: [] });
|
||
if (url.pathname === "/api/plugins/listings") return json({ listings: [] });
|
||
if (url.pathname === "/api/plugins/github") return json({ repos: [] });
|
||
if (url.pathname === "/api/usage/quotas") return json([]);
|
||
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
|
||
if (url.pathname === "/api/window/fit") return route.fulfill({ status: 204 });
|
||
if (url.pathname.startsWith("/api/")) return json({});
|
||
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: "" }); }
|
||
};
|
||
}
|
||
|
||
// the pages' tabs shown, the page shown
|
||
const tabs = (page) => page.evaluate(() => [...document.querySelectorAll("#nav button[data-view]")].filter((b) => !b.hidden && b.offsetParent && getComputedStyle(b).display !== "none").map((b) => b.dataset.view));
|
||
const viewShown = (page) => page.evaluate(() => [...document.querySelectorAll("main.view")].filter((v) => !v.hidden).map((v) => v.id));
|
||
const KEPT = ["agents", "providers", "routing", "gateway", "usage", "plugins"];
|
||
const rowsOf = (page) => page.evaluate(() => [...document.querySelectorAll("#builtinList .feat-row")].map((r) => {
|
||
const b = r.querySelector('[role="switch"]');
|
||
return { id: r.dataset.id, name: r.querySelector(".name").textContent, on: b.getAttribute("aria-checked"), disabled: b.disabled, why: r.querySelector(".feat-why")?.textContent || "" };
|
||
}));
|
||
|
||
// the Plugins page's tabs: the sidebar's, from 1024 points, or the page's
|
||
// own strip
|
||
const pluginTabs = (page, side) => page.locator(side ? ".nav-sub:not(.leaving) .nav-s" : "#view-plugins .lib-tabs .opt");
|
||
async function builtinTab(page, side) {
|
||
await pluginTabs(page, side).first().click();
|
||
await page.waitForSelector("#builtinList .feat-row");
|
||
}
|
||
|
||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||
test(`${engine}: Plugins › Built-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"]) {
|
||
// the sidebar from 1024 points, the header's tabs under it, and narrow
|
||
for (const width of [1100, 800, 420]) {
|
||
const where = `${engine} ${lang} ${width}`;
|
||
const context = await browser.newContext({ viewport: { width, height: 700 }, reducedMotion: "reduce" });
|
||
const page = await context.newPage();
|
||
page.setDefaultTimeout(5000);
|
||
const errors = [], posts = [];
|
||
page.on("pageerror", (e) => errors.push(e.message));
|
||
await page.route("**/*", server(lang, posts));
|
||
await page.goto("http://magpie.test/?view=sessions");
|
||
await page.waitForSelector("#nav button.on");
|
||
const side = await page.evaluate(() => document.body.classList.contains("side-nav"));
|
||
assert.equal(side, width >= 1024, `${where}: the layout`);
|
||
if (width >= 800) assert.deepEqual(await tabs(page), KEPT, `${where}: Sessions' and Library's tabs gone`);
|
||
// an address kept for a page switched off opens Agents
|
||
assert.deepEqual(await viewShown(page), ["view-agents"], `${where}: ?view=sessions`);
|
||
// Settings has no Features tab of its own, and Observability's is off
|
||
assert.equal(await page.locator("#setTab-features").count(), 0, `${where}: no Settings › Features`);
|
||
assert.ok(await page.locator("#setTab-otel").isHidden(), `${where}: Observability's tab, off`);
|
||
|
||
await page.goto("http://magpie.test/?view=plugins");
|
||
await pluginTabs(page, side).first().waitFor();
|
||
// Built-in first, in the page's language
|
||
const first = (await pluginTabs(page, side).first().textContent()).trim();
|
||
assert.equal(first, await page.evaluate(() => t("Built-in")), where);
|
||
if (lang !== "en") assert.notEqual(first, "Built-in", `${where}: Built-in translated`);
|
||
await builtinTab(page, side);
|
||
assert.ok(await page.locator("#view-plugins .pm-find").isHidden(), `${where}: no search on Built-in`);
|
||
const rows = await rowsOf(page);
|
||
const want = await page.evaluate((ps) => ps.map((p) => ({ id: p.id, name: t(p.name) })), PLUGINS);
|
||
assert.deepEqual(rows.map((r) => ({ id: r.id, name: r.name })), want, `${where}: a row each, by the table`);
|
||
// the groups in use: on, can't be switched off, saying why
|
||
const g = rows.find((r) => r.id === "groups");
|
||
assert.deepEqual([g.on, g.disabled], ["true", true], `${where}: in use, locked`);
|
||
assert.equal(g.why, await page.evaluate(() => t("{n} groups in use", { n: 2 })), where);
|
||
if (lang !== "en") assert.notEqual(g.why, "2 groups in use", `${where}: why translated`);
|
||
const gw = rows.find((r) => r.id === "gateway");
|
||
assert.deepEqual([gw.on, gw.disabled], ["true", false], `${where}: the Gateway page, on`);
|
||
for (const r of rows.filter((r) => r.id !== "groups" && r.id !== "gateway")) assert.deepEqual([r.on, r.disabled, r.why], ["false", false, ""], `${where}: ${r.id}`);
|
||
await page.locator('#builtinList [data-id="groups"] [role="switch"]').click({ force: true });
|
||
await page.waitForTimeout(100);
|
||
assert.deepEqual(posts, [], `${where}: a locked switch posts nothing`);
|
||
// nothing wider than the window
|
||
assert.ok(await page.evaluate(() => { const v = document.querySelector("#view-plugins"); return v.scrollWidth <= v.clientWidth + 1; }), `${where}: fits`);
|
||
|
||
// the Gateway page's setting, under its row, from its schema: in
|
||
// the page's language, its value in the app's menu, saved as picked
|
||
const set = page.locator('#builtinList .feat-set[data-of="gateway"][data-setting="callsPage"]');
|
||
assert.equal(await set.locator(".name").textContent(), await page.evaluate(() => t("Recent calls at a time")), where);
|
||
if (lang !== "en") assert.notEqual(await set.locator(".name").textContent(), "Recent calls at a time", `${where}: translated`);
|
||
assert.equal(await page.evaluate(() => document.querySelector('#builtinList .feat-set').previousElementSibling.dataset.id), "gateway", `${where}: under its row`);
|
||
assert.equal((await set.locator(".proto.pick").textContent()).trim(), "20", where);
|
||
await set.locator(".proto.pick").click();
|
||
await page.locator(".proto-menu .pm-item", { hasText: "50" }).click();
|
||
await page.waitForFunction(() => document.querySelector('#builtinList .feat-set .proto.pick')?.textContent.trim() === "50");
|
||
assert.deepEqual(posts, [["gateway", { callsPage: 50 }]], `${where}: posted`);
|
||
assert.equal(await page.evaluate(() => document.querySelectorAll(".proto-menu").length), 0, `${where}: the menu closed`);
|
||
posts.length = 0;
|
||
assert.ok(await page.evaluate(() => { const v = document.querySelector("#view-plugins"); return v.scrollWidth <= v.clientWidth + 1; }), `${where}: the setting fits`);
|
||
|
||
// Library switched on: its tab is back at once, the page stays
|
||
await page.locator('#builtinList [data-id="library"] [role="switch"]').click();
|
||
await page.waitForSelector('#builtinList [data-id="library"] [aria-checked="true"]');
|
||
assert.deepEqual(posts, [["library", true]], where);
|
||
if (width >= 800) assert.deepEqual(await tabs(page), ["agents", "library", ...KEPT.slice(1)], `${where}: Library back`);
|
||
assert.deepEqual(await viewShown(page), ["view-plugins"], `${where}: Plugins stays`);
|
||
// and Observability: its Settings tab is back
|
||
await page.locator('#builtinList [data-id="otel"] [role="switch"]').click();
|
||
await page.waitForSelector('#builtinList [data-id="otel"] [aria-checked="true"]');
|
||
assert.ok(await page.locator("#setTab-otel").evaluate((b) => getComputedStyle(b).display !== "none"), `${where}: Observability back`);
|
||
// Discover brings the search back
|
||
await pluginTabs(page, side).nth(1).click();
|
||
assert.ok(await page.locator("#view-plugins .pm-find").isVisible(), `${where}: search on Discover`);
|
||
assert.deepEqual(errors, [], where);
|
||
await context.close();
|
||
}
|
||
}
|
||
});
|
||
|
||
test(`${engine}: Plugins › Built-in, plugins.yml broken`, 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"]) {
|
||
const where = `${engine} ${lang}`;
|
||
const context = await browser.newContext({ viewport: { width: 420, height: 700 }, reducedMotion: "reduce" });
|
||
const page = await context.newPage();
|
||
page.setDefaultTimeout(5000);
|
||
const errors = [], posts = [];
|
||
page.on("pageerror", (e) => errors.push(e.message));
|
||
await page.route("**/*", server(lang, posts, "/config/plugins.yml doesn't parse: yaml: line 2"));
|
||
await page.goto("http://magpie.test/?view=plugins");
|
||
await builtinTab(page, false);
|
||
const say = await page.locator("#builtinList .feat-say.warn").textContent();
|
||
assert.ok(say.includes("yaml: line 2"), `${where}: says the error`);
|
||
if (lang !== "en") assert.ok(!say.startsWith("plugins.yml can't be read"), `${where}: translated`);
|
||
for (const r of await rowsOf(page)) assert.equal(r.disabled, true, `${where}: ${r.id} can't be switched`);
|
||
await page.locator('#builtinList [data-id="library"] [role="switch"]').click({ force: true });
|
||
await page.waitForTimeout(100);
|
||
assert.deepEqual(posts, [], `${where}: no switch posts`);
|
||
assert.deepEqual(errors, [], where);
|
||
await context.close();
|
||
}
|
||
});
|
||
}
|