diff --git a/docs/subsystems/plugin-runtime.md b/docs/subsystems/plugin-runtime.md index 5bb09ab58..168faa264 100644 --- a/docs/subsystems/plugin-runtime.md +++ b/docs/subsystems/plugin-runtime.md @@ -13,7 +13,7 @@ Sessions, Library, Routing and Usage), and P3 (the gateway's extension points: the observer, with OTel export as its first plugin; the router strategy, with the routings besides Smart and the user's groups; and the middleware point, with the JS gateway middleware and privacy masking; -the tool point, with web search; and the budget point, with key limits). OpenCode plugins (npm packages in +the tool point, with web search; and the budget point, with key limits), P4 (community plugins at each of those points) and P5 (community panels in magpie's own pages, and a plugin's page in a built-in's place). OpenCode plugins (npm packages in the plugin host) are a different thing; see [provider and plugin ownership](provider-plugins.md) and [gateway middleware](gateway-middleware.md). @@ -263,6 +263,73 @@ still means off; a page is its own plugin's to turn on and off. `plugins/middleware` is now "JS gateway plugins". Apply registers the chain and `usage.Observe(middleware.Points())`; off, no JS middleware, strategy or `onUsage` runs, and a pool routed by a JS strategy is its listed order. `InUse` is unchanged. ([`middleware.go`](../../plugins/middleware/middleware.go)) +## P5: panels in magpie's own pages, and pages that replace one + +P5 lets a community plugin into the pages magpie draws itself, not only a +page of its own. Both come from package.json and are read by +`plugin.Window` ([`page.go`](../../internal/plugin/page.go)); neither +starts a Bun host. + +- **Panels.** `magpie.panels: [{slot, file, title}]`, at most 8 a plugin + (`maxPanels`), each `slot` one of `plugin.PanelSlots`: `agents` (the end + of the Agents page), `usage` (the end of Usage's Overview), `settings` (a + Plugins tab in Settings, shown only while a panel is in it, in the tab + strip and in the sidebar of a wide window) and `provider` (each saved + provider's editor, told `{provider: {id, name}}`). `file` is an .html in + the plugin's folder (`plugin.FileIn`). `GET /api/plugin-panels` lists an + on plugin's panels in plugins.json order, each with a token of its own + (`pageToken(spec + "\x00panel\x00" + i)`), served under the same policy + as a page ([`pluginpage.go`](../../internal/gui/pluginpage.go)). A + panel's frame is sandboxed to `allow-scripts` like a page's, and shares + its plugin's reads (`magpie.permissions`) and options through the same + `/api/plugin-pages/read` and `/options`. The bridge + ([`pagebridge.js`](../../internal/gui/pagebridge.js)) gives it + `magpie.context` and posts its height (`size`), which the window holds + to 0..2400px. A panel that throws, or doesn't say hello in 10s, is + replaced by its own card ("{name} stopped working", Try again); the page + around it and the panels beside it go on. The size watch's own + "ResizeObserver loop" notice, which WebKit gives a sandboxed page as a + bare "Script error.", is not a throw. +- **Titles and look.** `magpie.page.titles` and a panel's `titles`, an + object of language code to title (`plugin.titles`: trimmed, empty ones + and a non-object dropped), name the tab and the panel's heading in the + window's language, `zh-TW` falling back to `zh` and anything else to + `title` (`titled` in [`pluginpages.js`](../../internal/gui/assets/pluginpages.js), + redrawn when `` changes). The bridge prepends a stylesheet of + `:where()` rules, of no weight, for the font, colours, headings, buttons, + fields and tables, so a page with no stylesheet reads as the window's + and any rule of the page's wins. Tests: `TestWindowTitles`, + `plugin-page.test.cjs`. +- **The policy's scheme.** The desktop window serves on `wails://localhost` + (macOS, Linux), and a sandboxed frame has an opaque origin, so a CSP + source without a scheme matches only http(s) there. `ownWindow` puts the + native scheme on the request's context and `pagePolicy` names the folder + under it (#2501); the web keeps a scheme-less source. + `TestPluginPageWindowPolicy` checks the policy, and + `TestPluginPageLoadsItsFilesInTheWindow` loads a page through + `ownWindow` in a real WKWebView; Playwright, on http, can't see it. +- **Slots.** A page names a slot with `
No calls today
+ + diff --git a/internal/gui/testdata/panel-plugin/ui/spend.js b/internal/gui/testdata/panel-plugin/ui/spend.js new file mode 100644 index 000000000..f98c481dd --- /dev/null +++ b/internal/gui/testdata/panel-plugin/ui/spend.js @@ -0,0 +1,13 @@ +// A panel at the end of the Usage page: today's three most used models, +// from the usage:summary read its package declares. +(async () => { + await magpie.ready; + const s = await magpie.read("usage:summary", { period: "today" }); + const top = document.getElementById("top"); + for (const m of s.models.slice(0, 3)) { + const li = document.createElement("li"); + li.textContent = `${m.model}: ${m.calls} calls`; + top.append(li); + } + document.getElementById("none").hidden = s.models.length > 0; +})(); diff --git a/internal/gui/testdata/panel-plugin/ui/style.css b/internal/gui/testdata/panel-plugin/ui/style.css new file mode 100644 index 000000000..be2b0057f --- /dev/null +++ b/internal/gui/testdata/panel-plugin/ui/style.css @@ -0,0 +1,7 @@ +html, body { background: transparent; } +body { margin: 0; padding: 10px 12px; font: 13px/1.5 var(--magpie-font, system-ui); color: var(--magpie-fg); } +p { margin: 0 0 4px; } +.muted { color: var(--magpie-muted); } +textarea { box-sizing: border-box; width: 100%; min-height: 56px; font: inherit; color: inherit; background: var(--magpie-card); border: 1px solid var(--magpie-line); border-radius: 6px; padding: 6px 8px; resize: vertical; } +button { font: inherit; color: var(--magpie-accent); background: none; border: 0; padding: 0; cursor: pointer; } +ol { margin: 0; padding-left: 18px; } diff --git a/internal/gui/tests/menu-scroll.test.cjs b/internal/gui/tests/menu-scroll.test.cjs index fa999e424..d3af86b24 100644 --- a/internal/gui/tests/menu-scroll.test.cjs +++ b/internal/gui/tests/menu-scroll.test.cjs @@ -42,8 +42,8 @@ async function serve(route) { 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: none - if (url.pathname === "/api/plugin-pages") return json([]); + // 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); diff --git a/internal/gui/tests/plugin-page.test.cjs b/internal/gui/tests/plugin-page.test.cjs index af2c37d73..7ba9b6640 100644 --- a/internal/gui/tests/plugin-page.test.cjs +++ b/internal/gui/tests/plugin-page.test.cjs @@ -26,16 +26,21 @@ 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"]), + { ...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 +// 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 own = `magpie.test/_magpie/plugin/${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'", @@ -45,7 +50,7 @@ const policy = (tok) => { // 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 = `probe
`; +const PROBE_HTML = `probe
`; const PROBE_JS = `(async () => { const out = {}; await magpie.ready; @@ -55,6 +60,9 @@ const PROBE_JS = `(async () => { 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 = `drawn
`; @@ -147,6 +155,15 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", 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`); @@ -182,6 +199,22 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", 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 diff --git a/internal/gui/tests/plugin-panels.test.cjs b/internal/gui/tests/plugin-panels.test.cjs new file mode 100644 index 000000000..192ed8b42 --- /dev/null +++ b/internal/gui/tests/plugin-panels.test.cjs @@ -0,0 +1,286 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A community plugin's panels in magpie's own pages (pluginpages.js, P5): +// the example plugin (testdata/panel-plugin) adds a note to each +// provider's editor, told which provider it is in, the top models at the +// end of Usage, and its settings on Settings' Plugins tab, a tab there +// only while a plugin's panel is. A panel on the Agents page draws as +// tall as it says. Each is a frame sandboxed to scripts. One that throws +// says so in its own place, with Try again, and the page around it goes +// on. A page that replaces a built-in page takes its tab's place, and a +// way to the built-in page opens it. The Plugins page says where a +// plugin's panels go and what they may read, and which page a page +// replaces. Every language, both engines, a narrow window. The API is +// faked here; the server's side is pluginpanel_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/panel-plugin/ui"); +const bridge = path.resolve(__dirname, "../pagebridge.js"); + +const NOTES = "1".repeat(32), SPEND = "2".repeat(32), SETS = "3".repeat(32), TALL = "4".repeat(32), BROKEN = "5".repeat(32), LIB = "6".repeat(32); +const panel = (tok, i, slot, title, file, name = "magpie-provider-notes", reads = ["usage:summary"]) => ({ + spec: "/x/" + name, name, key: `plugin-${name.replace("magpie-", "")}-${i}`, slot, title, reads, url: `/_magpie/plugin/${tok}/${file}`, +}); +const allPanels = [ + panel(NOTES, 0, "provider", "Notes", "notes.html"), + panel(SPEND, 1, "usage", "Top models today", "spend.html"), + panel(SETS, 2, "settings", "Provider notes", "settings.html"), + panel(TALL, 0, "agents", "Tall", "tall.html", "tall", []), + panel(BROKEN, 0, "agents", "Broken", "broken.html", "broken", []), +]; +const pages = [{ spec: "/x/my-library", name: "my-library", key: "plugin-my-library", title: "My library", replaces: "library", reads: [], url: `/_magpie/plugin/${LIB}/index.html` }]; + +const TALL_HTML = `drawn
`; +const LIB_HTML = `my library
`; + +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 })); + +function server(lang, seen, 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/plugin-pages") return json(opts.pages); + if (url.pathname === "/api/plugin-panels") return json(opts.panels); + if (url.pathname === "/api/plugin-pages/read") { + seen.reads.push(req.postDataJSON()); + return json({ period: "today", calls: 12, models: [{ model: "gpt-5", calls: 9 }, { model: "glm-5", calls: 3 }] }); + } + 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(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 [, tok, rel] = m; + const type = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css" }[path.extname(rel)]; + let body; + if (rel === "_magpie/bridge.js") body = await fs.readFile(bridge); + else if ([NOTES, SPEND, SETS].includes(tok)) body = await fs.readFile(path.join(example, rel)).catch(() => null); + else if (tok === TALL && rel === "tall.html") body = TALL_HTML; + else if (tok === BROKEN && rel === "broken.html") body = BROKEN_HTML; + else if (tok === BROKEN && rel === "app.js") body = seen.broken ? "throw new Error('fixture: the panel broke')" : "1"; + else if (tok === LIB && rel === "index.html") body = LIB_HTML; + if (body == null) return route.fulfill({ status: 404, body: "" }); + 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 frameOf = (page, tok) => page.frames().find((f) => f.url().includes(tok)); +async function frameReady(page, tok) { + await page.waitForFunction((tok) => [...document.querySelectorAll("iframe.plugin-panel-frame, 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); +} +const fits = (page, sel) => page.evaluate((sel) => { const v = document.querySelector(sel); return v.scrollWidth <= v.clientWidth + 1; }, sel); + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(`${engine}: a plugin's panels draw in magpie's own pages, 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: 760 }, reducedMotion: "reduce" }); + const page = await context.newPage(); + page.setDefaultTimeout(8000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const seen = { reads: [], options: [], broken: lang === "en" && width === 1100 }; + await page.route("**/*", server(lang, seen, { panels: allPanels, pages })); + await page.goto("http://magpie.test/"); + const tr = (k, v) => page.evaluate(([k, v]) => t(k, v), [k, v]); + + // the Agents page: a panel as tall as it draws, in a frame sandboxed to scripts + const tall = page.locator('#view-agents .plugin-slot[data-slot="agents"] .plugin-panel[data-panel="plugin-tall-0"]'); + await tall.waitFor(); + const tf = tall.locator("iframe"); + assert.equal(await tf.getAttribute("sandbox"), "allow-scripts", where); + await page.waitForFunction(() => Math.round(document.querySelector('.plugin-panel[data-panel="plugin-tall-0"] iframe').getBoundingClientRect().height) === 180); + assert.equal((await tall.locator(".row-head .label").textContent()), "Tall", where); + assert.ok(await fits(page, "#view-agents"), `${where}: Agents fits`); + + // the size watch's own "ResizeObserver loop" notice is no error of + // the panel's, named or (WebKit, sandboxed) a bare "Script error." + // while the watch has just run: the panel stays + if (lang === "en" && width === 1100) { + const tallFrame = await frameReady(page, TALL); + await tallFrame.evaluate(() => new Promise((done) => { + dispatchEvent(new ErrorEvent("error", { message: "ResizeObserver loop completed with undelivered notifications.", cancelable: true })); + // a real loop: the watch is told of a new size, and an observer + // told in the same turn changes it again; the browser's notice + // comes after every observer of the turn has run + const box = document.getElementById("box"); + box.style.height = "181px"; + let first = true; + new ResizeObserver(() => { + if (first) { first = false; box.style.height = "182px"; setTimeout(done, 100); } + }).observe(document.documentElement); + })); + await page.waitForTimeout(100); + assert.equal(await tall.locator(".plugin-panel-broke").count(), 0, `${where}: a size notice broke the panel`); + assert.equal(await tall.locator("iframe").count(), 1, where); + } + + if (seen.broken) { + // a panel that throws says so in its own place; the one beside it goes on + const broke = page.locator('.plugin-panel[data-panel="plugin-broken-0"] .plugin-panel-broke'); + await broke.waitFor(); + assert.equal(await broke.locator("b").textContent(), await tr("{name} stopped working", { name: "Broken" }), where); + assert.equal(await broke.locator(".note").textContent(), await tr("The page hit an error"), where); + assert.equal(await tall.locator("iframe").count(), 1, `${where}: the other panel stays`); + seen.broken = false; + // by the keyboard: WebKit's Playwright calls a button low in a + // scrolled view outside the viewport after scrolling it in + await broke.locator("button").focus(); + await page.keyboard.press("Enter"); + const fixed = await frameReady(page, BROKEN); + await fixed.locator("#ok").waitFor(); + assert.equal(await broke.count(), 0, `${where}: the card gone`); + } + + // the end of Usage: what it declared it reads + await page.evaluate(() => show("usage")); + const spend = await frameReady(page, SPEND); + await spend.waitForFunction(() => document.querySelectorAll("#top li").length === 2); + assert.equal(await spend.locator("#top li").first().textContent(), "gpt-5: 9 calls", where); + assert.ok(seen.reads.some((r) => r.spec === "/x/magpie-provider-notes" && r.read === "usage:summary"), where); + assert.equal(await spend.evaluate(() => document.documentElement.lang), lang, `${where}: the window's language`); + assert.ok(await fits(page, "#view-usage"), `${where}: Usage fits`); + // Usage hides its own headings while a period loads, not a panel's + const spendHead = page.locator('#view-usage .plugin-panel:has(iframe[src*="' + SPEND + '"]) > .row-head'); + await page.waitForFunction(() => !document.querySelector("#view-usage .loading, #view-usage[aria-busy=true]")); + assert.ok(await spendHead.isVisible(), `${where}: the panel's heading shows`); + + // a provider's editor: the note panel knows which provider it is in + await page.evaluate(() => show("providers")); + await page.waitForFunction(() => providers?.providers?.length === 1); + await page.evaluate(() => openModal(renderEditor(providers.providers[0]))); + const notes = await frameReady(page, NOTES); + assert.equal(await page.locator('#modal .plugin-slot[data-slot="provider"] iframe').getAttribute("sandbox"), "allow-scripts", where); + await notes.waitForFunction(() => window.magpie.context?.provider?.id === "openai"); + assert.equal(await notes.evaluate(() => magpie.context.provider.name), "OpenAI", where); + await notes.locator("#note").fill("work account"); + await notes.locator("#saved").filter({ hasText: "Saved" }).waitFor(); + assert.deepEqual(seen.options.at(-1), { spec: "/x/magpie-provider-notes", options: { notes: { openai: "work account" } } }, `${where}: its own options`); + assert.ok(await page.evaluate(() => { const m = document.querySelector("#modal .plugin-slot"); return m.getBoundingClientRect().right <= innerWidth + 1; }), `${where}: the editor fits`); + // a new provider's editor has no provider to tell: no panel + await page.evaluate(() => openModal(renderEditor(null))); + assert.equal(await page.locator('#modal .plugin-slot[data-slot="provider"]').count(), 0, `${where}: none for a new one`); + await page.evaluate(() => closeModal()); + + // Settings: the Plugins tab, with the plugin's settings + await page.evaluate(() => show("settings")); + // its tab, in the tab strip or (a wide window) the sidebar + const plug = await tr("Plugins"); + const tab = page.locator(":is(#setTabs button, .nav-sub .nav-s):visible", { hasText: plug }); + await tab.first().waitFor(); + assert.equal((await tab.first().textContent()).trim(), plug, where); + await tab.first().click(); + const sets = await frameReady(page, SETS); + // drawn when the window opened, before the note was written + await sets.locator("#count").filter({ hasText: /^\d+ notes?$/ }).waitFor(); + await page.waitForTimeout(1100); // options are set once a second at most + await sets.locator("#clear").click(); + await sets.locator("#count").filter({ hasText: "0 notes" }).waitFor(); + assert.deepEqual(seen.options.at(-1).options.notes, {}, `${where}: cleared`); + assert.ok(await page.locator("#setPage-plugins").isVisible(), where); + assert.ok(await fits(page, "#view-settings"), `${where}: Settings fits`); + + // a page that replaces Library: its tab in Library's place, and + // Library opens it + const lib = page.locator('#nav button[data-view="library"]:not([data-plugin-page])'); + assert.equal(await lib.getAttribute("data-replaced"), "plugin-my-library", where); + assert.equal(await lib.isVisible(), false, `${where}: the built-in steps aside`); + assert.equal(await page.evaluate(() => document.querySelector('#nav button[data-view="library"]').nextElementSibling?.dataset.view), "plugin-my-library", `${where}: in its place`); + assert.equal(await page.locator("#nav .nav-gl[data-plugin-pages]").count(), 0, `${where}: no Plugins group for a page in a built-in's place`); + await page.evaluate(() => show("library")); + await page.waitForFunction(() => view === "plugin-my-library"); + const mine = await frameReady(page, LIB); + await mine.locator("#mine").waitFor(); + + // the broken panel's own throw, in its frame, is the only error + assert.deepEqual(errors.filter((e) => e !== "fixture: the panel broke"), [], where); + await context.close(); + } + } + }); + + test(`${engine}: with no plugin's settings, Settings has no Plugins tab`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width: 980, height: 700 } })).newPage(); + page.setDefaultTimeout(5000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", server("en", { reads: [], options: [] }, { panels: allPanels.filter((p) => p.slot !== "settings"), pages: [] })); + await page.goto("http://magpie.test/?view=settings"); + await page.locator('.plugin-panel[data-panel="plugin-tall-0"]').waitFor({ state: "attached" }); + assert.equal(await page.locator("#setTab-plugins").isVisible(), false); + assert.equal(await page.locator(".nav-sub .nav-s", { hasText: "Plugins" }).count(), 0, "not in the sidebar"); + // the address of the tab opens the first there + await page.evaluate(() => setSetTab("plugins", false)); + assert.equal(await page.evaluate(() => setShown), "general"); + // Library is Library + assert.equal(await page.locator('#nav button[data-view="library"]').getAttribute("data-replaced"), null); + assert.deepEqual(errors, []); + await page.context().close(); + }); + + test(`${engine}: Plugins says where panels go and what a page replaces`, 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-provider-notes", providers: [], moved: [], inMagpieOnly: true, panels: [{ slot: "provider", title: "Notes" }, { slot: "usage", title: "Top models today" }, { slot: "settings", title: "Provider notes" }], panelReads: ["usage:summary"] }, + { spec: "/x/my-library", providers: [], moved: [], inMagpieOnly: true, page: { title: "My library", replaces: "library", reads: [] } }, + ] }; + 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, { reads: [], options: [] }, { panels: [], 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 row = (name) => view.locator(".pm-row").filter({ has: page.locator(".name", { hasText: name }) }); + const tr = (k, v) => page.evaluate(([k, v]) => t(k, v), [k, v]); + const notes = row("magpie-provider-notes"); + await notes.waitFor(); + assert.deepEqual((await notes.locator(".pm-chip.kind").allInnerTexts()).map((x) => x.trim()), [await tr("Panels")], where); + const where2 = [await tr("each provider's editor"), await tr("the Usage page"), await tr("Settings")].join(await tr(", ")); + assert.equal((await notes.locator(".pm-page").innerText()).trim(), await tr("Adds panels to {where}, which can read {reads}", { where: where2, reads: await tr("your usage totals, by model") }), where); + const lib = row("my-library"); + assert.equal((await lib.locator(".pm-page").innerText()).trim(), await tr("Takes the place of the {page} page, and reads nothing of magpie's", { page: await tr("Library") }), where); + if (lang !== "en") assert.ok(!(await notes.locator(".pm-page").innerText()).includes("Adds panels"), `${where}: translated`); + assert.ok(await view.evaluate((v) => v.scrollWidth <= v.clientWidth + 1), `${where}: fits`); + assert.deepEqual(errors, [], where); + await page.context().close(); + } + } + }); +} diff --git a/internal/plugin/agent.go b/internal/plugin/agent.go index 5899681e8..07cf78a64 100644 --- a/internal/plugin/agent.go +++ b/internal/plugin/agent.go @@ -42,15 +42,15 @@ func Agent(target string) (file string, only bool) { } // InMagpieOnly is whether everything a plugin at target has runs in -// magpie's own process, its gateway middleware, its agent and its page, -// so the host has nothing of it to load. +// magpie's own process, its gateway middleware, its agent and what it adds +// to the window, so the host has nothing of it to load. func InMagpieOnly(target string) bool { if Gateway(target) != "" { return false } mw, mwOnly := Middleware(target) ag, agOnly := Agent(target) - pg, pgOnly := WindowPage(target) + pg, pgOnly := Window(target) if mw == "" && ag == "" && pg == nil { return false } diff --git a/internal/plugin/page.go b/internal/plugin/page.go index a61e0122a..0be430294 100644 --- a/internal/plugin/page.go +++ b/internal/plugin/page.go @@ -9,27 +9,91 @@ import ( "strings" ) -// PageSpec is the page a plugin adds to magpie's window: package.json's -// magpie.page, and the reads magpie.permissions asks for. +// WindowSpec is what a plugin adds to magpie's window: its page +// (package.json's magpie.page), its panels in magpie's own pages +// (magpie.panels), and the reads magpie.permissions asks for, which its +// page and its panels share. +type WindowSpec struct { + Page *PageSpec // nil when it adds no page of its own + Panels []PanelSpec + // Reads are the reads it asked for that magpie has (PageReads), in + // the order asked. + Reads []string +} + +// PageSpec is a plugin's own page in magpie's window. type PageSpec struct { Title string // "" when it names none - Icon string // a file in the page's folder, relative to it, or "" - File string // the page's HTML, inside the plugin's folder - Dir string // the folder the page's files are served from: File's - // Reads are the reads the page asked for that magpie has (PageReads), - // in the order asked. - Reads []string + // Titles are its title in other languages, by the window's language + // ("zh", "zh-TW", "ja", "de"): magpie.page.titles + Titles map[string]string + Icon string // a file in the page's folder, relative to it, or "" + File string // the page's HTML, inside the plugin's folder + Dir string // the folder the page's files are served from: File's + // Replaces is the built-in page (one of Replaceable) whose place in + // the sidebar the page takes while its plugin is on, or "". + Replaces string +} + +// PanelSpec is a panel a plugin adds to one of magpie's own pages: a +// part of that page, drawn by the plugin's HTML in a frame of its own. +type PanelSpec struct { + Slot string // one of PanelSlots + Title string // "" when it names none + Titles map[string]string + File string // the panel's HTML, inside the plugin's folder + Dir string // the folder the panel's files are served from: File's } // PageReads are the reads a plugin's page can be granted, each in // magpie.permissions. None of them carries a secret. var PageReads = []string{"usage:summary", "providers:list"} -// WindowPage is the page a plugin at target adds to magpie's window, or nil: -// package.json's magpie.page {title, file, icon}. A file outside the -// plugin's folder is no page. only is whether it is nothing else: no -// OpenCode plugin for the host to load (no main, no exports). -func WindowPage(target string) (p *PageSpec, only bool) { +// PanelSlots are the places in magpie's own pages a plugin's panel can +// go: under the Agents page's list, at the end of the Usage page, on +// Settings' Plugins tab, and in a provider's editor (which tells the +// panel the provider's id and name). +var PanelSlots = []string{"agents", "usage", "settings", "provider"} + +// Replaceable are the built-in pages a plugin's page can take the place +// of: the pages that are built-in plugins of their own. +var Replaceable = []string{"sessions", "library", "routing", "usage"} + +// titles are a page's or a panel's titles by language, without the empty +// ones, or nil: magpie.page.titles {"zh": "…"}. title stays a string +// beside them, so a magpie that knows no titles still reads the package, +// and titles that aren't an object of strings leave the page as it was. +func titles(raw json.RawMessage) map[string]string { + var m map[string]any + if json.Unmarshal(raw, &m) != nil { + return nil + } + var out map[string]string + for k, x := range m { + v, _ := x.(string) + k, v = strings.TrimSpace(k), strings.TrimSpace(v) + if k == "" || v == "" || len(k) > 16 || len(out) == 16 { + continue + } + if out == nil { + out = map[string]string{} + } + out[k] = v + } + return out +} + +// maxPanels is how many panels one plugin adds, at most. +const maxPanels = 8 + +// Window is what a plugin at target adds to magpie's window, or nil when +// it adds nothing: package.json's magpie.page {title, file, icon, +// replaces} and magpie.panels [{slot, file, title}]. A file outside the +// plugin's folder, or not .html, is no page or panel; a panel in a slot +// magpie doesn't have is left out, and so is a replaces of a page that +// can't be replaced. only is whether it is nothing else: no OpenCode +// plugin for the host to load (no main, no exports). +func Window(target string) (w *WindowSpec, only bool) { st, err := os.Stat(target) if err != nil || !st.IsDir() { return nil, false @@ -38,39 +102,75 @@ func WindowPage(target string) (p *PageSpec, only bool) { if err != nil { return nil, false } + type part struct { + Title string `json:"title"` + Titles json.RawMessage `json:"titles"` + File string `json:"file"` + Icon string `json:"icon"` + Slot string `json:"slot"` + Replaces string `json:"replaces"` + } var pkg struct { Main string `json:"main"` Exports json.RawMessage `json:"exports"` Magpie struct { - Page *struct { - Title string `json:"title"` - File string `json:"file"` - Icon string `json:"icon"` - } `json:"page"` + Page *part `json:"page"` + Panels []part `json:"panels"` Permissions []string `json:"permissions"` } `json:"magpie"` } - if json.Unmarshal(b, &pkg) != nil || pkg.Magpie.Page == nil { + if json.Unmarshal(b, &pkg) != nil { return nil, false } - pg := pkg.Magpie.Page - file, ok := inside(target, pg.File) - if !ok || !strings.HasSuffix(strings.ToLower(file), ".html") { - return nil, false - } - p = &PageSpec{Title: strings.TrimSpace(pg.Title), File: file, Dir: filepath.Dir(file)} - // the icon is served with the page, so it sits in the page's folder - if icon, ok := inside(target, pg.Icon); ok { - if rel, err := filepath.Rel(p.Dir, icon); err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) { - p.Icon = filepath.ToSlash(rel) + w = &WindowSpec{} + if pg := pkg.Magpie.Page; pg != nil { + if file, ok := htmlInside(target, pg.File); ok { + p := &PageSpec{Title: strings.TrimSpace(pg.Title), Titles: titles(pg.Titles), File: file, Dir: filepath.Dir(file)} + // the icon is served with the page, so it sits in the page's folder + if icon, ok := inside(target, pg.Icon); ok { + if rel, err := filepath.Rel(p.Dir, icon); err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) { + p.Icon = filepath.ToSlash(rel) + } + } + if r := strings.TrimSpace(pg.Replaces); slices.Contains(Replaceable, r) { + p.Replaces = r + } + w.Page = p } } + for _, pn := range pkg.Magpie.Panels { + if len(w.Panels) == maxPanels { + break + } + slot := strings.TrimSpace(pn.Slot) + file, ok := htmlInside(target, pn.File) + if !ok || !slices.Contains(PanelSlots, slot) { + continue + } + w.Panels = append(w.Panels, PanelSpec{Slot: slot, Title: strings.TrimSpace(pn.Title), Titles: titles(pn.Titles), File: file, Dir: filepath.Dir(file)}) + } + if w.Page == nil && len(w.Panels) == 0 { + return nil, false + } for _, r := range pkg.Magpie.Permissions { - if slices.Contains(PageReads, r) && !slices.Contains(p.Reads, r) { - p.Reads = append(p.Reads, r) + if slices.Contains(PageReads, r) && !slices.Contains(w.Reads, r) { + w.Reads = append(w.Reads, r) } } - return p, pkg.Main == "" && len(pkg.Exports) == 0 + return w, pkg.Main == "" && len(pkg.Exports) == 0 +} + +// htmlInside is rel joined to dir, if that stays inside dir and is an +// .html file. +func htmlInside(dir, rel string) (string, bool) { + file, ok := inside(dir, rel) + if !ok || !strings.HasSuffix(strings.ToLower(file), ".html") { + return "", false + } + if st, err := os.Stat(file); err != nil || st.IsDir() { + return "", false + } + return file, true } // inside is rel joined to dir, if that stays inside dir: no "..", no @@ -99,10 +199,10 @@ func inside(dir, rel string) (string, bool) { return full, true } -// PageFile is the file at rel among a page's files, if it is one: inside -// the page's folder, and a file. -func (p *PageSpec) PageFile(rel string) (string, bool) { - f, ok := inside(p.Dir, rel) +// FileIn is the file at rel among the files served from dir (a page's +// or a panel's folder), if it is one: inside dir, and a file. +func FileIn(dir, rel string) (string, bool) { + f, ok := inside(dir, rel) if !ok { return "", false } @@ -112,8 +212,8 @@ func (p *PageSpec) PageFile(rel string) (string, bool) { return f, true } -// SetPageOptions sets the options of a plugin from its page. One whose -// page is all it has is never loaded by the host, so the host goes on as +// SetPageOptions sets the options of a plugin from its page or a panel. +// One whose page and panels are all it has is never loaded by the host, so the host goes on as // it was; any other is SetOptions, which starts the host again for it. func SetPageOptions(spec string, opts map[string]any) error { t := Target(spec) @@ -123,7 +223,7 @@ func SetPageOptions(spec string, opts map[string]any) error { if ag, _ := Agent(t); ag != "" { return SetOptions(spec, opts) } - if p, only := WindowPage(t); p == nil || !only { + if w, only := Window(t); w == nil || !only { return SetOptions(spec, opts) } listMu.Lock() diff --git a/internal/plugin/page_test.go b/internal/plugin/page_test.go index a3d96ed77..f07233916 100644 --- a/internal/plugin/page_test.go +++ b/internal/plugin/page_test.go @@ -32,17 +32,18 @@ func TestWindowPageStaysInside(t *testing.T) { return d } good := mk("good", `{"name":"good","magpie":{"page":{"title":"Good","file":"page/index.html","icon":"page/index.html"},"permissions":["usage:summary","secrets:all","usage:summary"]}}`) - p, only := WindowPage(good) - if p == nil || !only || p.Title != "Good" || p.Icon != "index.html" { - t.Fatalf("good: %+v only=%v", p, only) + w, only := Window(good) + if w == nil || w.Page == nil || !only || w.Page.Title != "Good" || w.Page.Icon != "index.html" { + t.Fatalf("good: %+v only=%v", w, only) } - if !slices.Equal(p.Reads, []string{"usage:summary"}) { - t.Errorf("reads %v, want only the one magpie has, once", p.Reads) + p := w.Page + if !slices.Equal(w.Reads, []string{"usage:summary"}) { + t.Errorf("reads %v, want only the one magpie has, once", w.Reads) } if !InMagpieOnly(good) || notPlugin(good) != nil { t.Errorf("a page-only plugin: InMagpieOnly %v, notPlugin %v", InMagpieOnly(good), notPlugin(good)) } - if _, only := WindowPage(mk("main", `{"name":"m","main":"index.js","magpie":{"page":{"file":"page/index.html"}}}`)); only { + if _, only := Window(mk("main", `{"name":"m","main":"index.js","magpie":{"page":{"file":"page/index.html"}}}`)); only { t.Error("a plugin with a main is more than its page") } link := mk("link", `{"name":"l","magpie":{"page":{"file":"page/out.html"}}}`) @@ -55,17 +56,120 @@ func TestWindowPageStaysInside(t *testing.T) { "notml": `{"name":"n","magpie":{"page":{"file":"package.json"}}}`, "none": `{"name":"x","magpie":{"page":{"file":"page/missing.html"}}}`, } { - if p, _ := WindowPage(mk(name, pkg)); p != nil { - t.Errorf("%s: %+v is a page", name, p) + if w, _ := Window(mk(name, pkg)); w != nil { + t.Errorf("%s: %+v is a page", name, w) } } - if p, _ := WindowPage(link); p != nil { - t.Errorf("a symbolic link out of the folder: %+v is a page", p) + if w, _ := Window(link); w != nil { + t.Errorf("a symbolic link out of the folder: %+v is a page", w) } - if f, ok := p.PageFile("../package.json"); ok { - t.Errorf("PageFile served %s", f) + if f, ok := FileIn(p.Dir, "../package.json"); ok { + t.Errorf("FileIn served %s", f) } - if f, ok := p.PageFile("index.html"); !ok || filepath.Base(f) != "index.html" { - t.Errorf("PageFile(index.html) = %s %v", f, ok) + if f, ok := FileIn(p.Dir, "index.html"); !ok || filepath.Base(f) != "index.html" { + t.Errorf("FileIn(index.html) = %s %v", f, ok) + } +} + +// A plugin's panels (magpie.panels) go only where magpie has a slot, each +// an .html inside the plugin's folder, at most maxPanels of them; a page +// replaces only a built-in page that can be replaced. A plugin that is +// only panels is a window plugin all the same: in magpie only, and a +// plugin. +func TestWindowPanels(t *testing.T) { + root := t.TempDir() + if err := os.WriteFile(filepath.Join(root, "secret.html"), []byte("secret
"), 0o644); err != nil { + t.Fatal(err) + } + d := filepath.Join(root, "p") + if err := os.MkdirAll(filepath.Join(d, "ui"), 0o755); err != nil { + t.Fatal(err) + } + for _, f := range []string{"ui/usage.html", "ui/prov.html", "ui/page.html"} { + if err := os.WriteFile(filepath.Join(d, filepath.FromSlash(f)), []byte("hi
"), 0o644); err != nil { + t.Fatal(err) + } + } + write := func(pkg string) { + t.Helper() + if err := os.WriteFile(filepath.Join(d, "package.json"), []byte(pkg), 0o644); err != nil { + t.Fatal(err) + } + } + write(`{"name":"p","magpie":{"panels":[ + {"slot":"usage","file":"ui/usage.html","title":"Spend"}, + {"slot":"provider","file":"ui/prov.html"}, + {"slot":"nowhere","file":"ui/usage.html"}, + {"slot":"usage","file":"../secret.html"}, + {"slot":"usage","file":"ui/missing.html"}, + {"slot":"agents","file":"package.json"} + ],"permissions":["providers:list"]}}`) + w, only := Window(d) + if w == nil || !only || w.Page != nil { + t.Fatalf("panels only: %+v only=%v", w, only) + } + var got []string + for _, p := range w.Panels { + got = append(got, p.Slot+":"+p.Title+":"+filepath.Base(p.File)) + } + if want := []string{"usage:Spend:usage.html", "provider::prov.html"}; !slices.Equal(got, want) { + t.Errorf("panels %v, want %v", got, want) + } + if !slices.Equal(w.Reads, []string{"providers:list"}) { + t.Errorf("reads %v", w.Reads) + } + if !InMagpieOnly(d) || notPlugin(d) != nil { + t.Errorf("a panels-only plugin: InMagpieOnly %v, notPlugin %v", InMagpieOnly(d), notPlugin(d)) + } + + many := `{"slot":"usage","file":"ui/usage.html"}` + for range maxPanels { + many += `,{"slot":"usage","file":"ui/usage.html"}` + } + write(`{"name":"p","magpie":{"panels":[` + many + `]}}`) + if w, _ := Window(d); w == nil || len(w.Panels) != maxPanels { + t.Errorf("%+v kept, want %d panels at most", w, maxPanels) + } + + for replaces, want := range map[string]string{"usage": "usage", "sessions": "sessions", "agents": "", "settings": "", "plugins": "", "": ""} { + write(`{"name":"p","magpie":{"page":{"file":"ui/page.html","replaces":"` + replaces + `"}}}`) + w, _ := Window(d) + if w == nil || w.Page == nil || w.Page.Replaces != want { + t.Errorf("replaces %q: %+v, want %q", replaces, w, want) + } + } +} + +// A page's and a panel's titles by language (magpie.page.titles) are kept +// trimmed, without the empty ones; titles that aren't an object of strings +// leave the page as it was, with its title. +func TestWindowTitles(t *testing.T) { + d := t.TempDir() + if err := os.WriteFile(filepath.Join(d, "index.html"), []byte("hi
"), 0o644); err != nil { + t.Fatal(err) + } + write := func(titles string) *WindowSpec { + t.Helper() + pkg := `{"name":"p","magpie":{"page":{"title":"Glance","file":"index.html","titles":` + titles + `}, + "panels":[{"slot":"usage","file":"index.html","title":"Spend","titles":` + titles + `}]}}` + if err := os.WriteFile(filepath.Join(d, "package.json"), []byte(pkg), 0o644); err != nil { + t.Fatal(err) + } + w, _ := Window(d) + if w == nil || w.Page == nil || len(w.Panels) != 1 || w.Page.Title != "Glance" || w.Panels[0].Title != "Spend" { + t.Fatalf("titles %s: %+v", titles, w) + } + return w + } + w := write(`{" zh ":" 速览 ","ja":"","de":7,"":"x"}`) + for _, m := range []map[string]string{w.Page.Titles, w.Panels[0].Titles} { + if len(m) != 1 || m["zh"] != "速览" { + t.Errorf("titles %v, want only zh 速览", m) + } + } + for _, bad := range []string{`"速览"`, `["速览"]`, `null`} { + if w := write(bad); w.Page.Titles != nil || w.Panels[0].Titles != nil { + t.Errorf("titles %s: %v %v", bad, w.Page.Titles, w.Panels[0].Titles) + } } } diff --git a/internal/plugin/store.go b/internal/plugin/store.go index 6f551be2c..28f660f8a 100644 --- a/internal/plugin/store.go +++ b/internal/plugin/store.go @@ -472,7 +472,7 @@ func notPlugin(target string) error { if f, _ := Agent(target); f != "" { return nil } - if p, _ := WindowPage(target); p != nil { + if w, _ := Window(target); w != nil { return nil } var pkg struct { diff --git a/site/public/docs/ja/plugins.html b/site/public/docs/ja/plugins.html index f30c33f8f..495347b78 100644 --- a/site/public/docs/ja/plugins.html +++ b/site/public/docs/ja/plugins.html @@ -808,7 +808,10 @@ claude mcp add --transport http magpie-tools http://127.0.0.1:3425/mcp/magpie/to "name": "magpie-usage-glance", "version": "0.1.0", "magpie": { - "page": { "title": "Usage glance", "file": "page/index.html", "icon": "page/icon.svg" }, + "page": { + "title": "Usage glance", "file": "page/index.html", "icon": "page/icon.svg", + "titles": { "zh": "用量速览", "ja": "使用量の概要" } + }, "permissions": ["usage:summary"] } } @@ -831,7 +834,8 @@ document.getElementById("calls").textContent = `${s.calls const opts = await magpie.options.get() // this plugin's own options await magpie.options.set({ ...opts, hideCost: true })プラグインページの行には、オンにする前からページと読めるものが表示されます。page.file と page.icon はプラグイン内のパスです。ページのファイルは file のフォルダにあるものだけで、外を指すパスやリンクは配信されません。1 つのパッケージがページとプロバイダ、ミドルウェア、エージェントを兼ねることもできます。ページだけのプラグインはプラグインホストを起動しません。
プラグインページの行には、オンにする前からページと読めるものが表示されます。page.file と page.icon はプラグイン内のパスです。ページのファイルは file のフォルダにあるものだけで、外を指すパスやリンクは配信されません。1 つのパッケージがページとプロバイダ、ミドルウェア、エージェントを兼ねることもできます。ページだけのプラグインはプラグインホストを起動しません。page.titles(パネルでは titles)は、言語コード(zh、zh-TW、ja、de)ごとのタブ名です。ほかの言語では title を使います。
ページがスタイルを付けていないところは、最初から magpie の見た目になります。bridge がフォント、色、見出し、ボタン、入力欄、表のスタイルシートを重みなし(:where())で加えるので、ページ自身のルールが常に勝ちます。自分のスタイルでは --magpie-* 変数を使うとウィンドウに揃います。
| フィールド / 呼び出し | 返すもの |
|---|
slot | パネルが入る場所 | magpie.context |
|---|---|---|
agents | 「エージェント」ページの末尾 | {} |
usage | 使用量の「概要」の末尾 | {} |
settings | 設定の「プラグイン」タブ(プラグインがそこにパネルを置いているときだけ表示) | {} |
provider | 保存した各プロバイダーの編集画面 | { provider: { id, name } } |
パネルは 1 つのプラグインにつき 8 個まで。パネルの高さは <html> に合わせて決まる(最大 2400px)ので、ページ自身に高さを任せ、html や body に固定の高さを付けないでください。パネルがエラーを出すか 10 秒以内に応答しないと、その場所に「{name} は動作を停止しました」と「再試行」が表示されます。周りのページと隣のパネルはそのまま動き続けます。
ページは magpie 自身のページの代わりになれます。magpie.page に "replaces" を加え、sessions、library、routing、usage のどれかを指定します。そのタブが組み込みページのあった場所に入り、そのページへのリンクはプラグインのページを開きます。2 つのプラグインが同じページを指定したときは、プラグイン一覧で先にあるほうが代わりになり、もう一方は独立したページになります。プラグインをオフにすると、組み込みページが元どおりに戻ります。
"page": { "title": "My library", "file": "page/index.html", "replaces": "library" }+
magpie は pi のパッケージも動かします。pi.registerProvider でプロバイダを登録する pi 拡張は、何も変えずに pi と同じように magpie で動き、ほかのプラグインと同じ方法で追加できます(magpie plugin add pi-antigravity)。
The Plugins page shows the page, and what it may read, on the plugin’s row before it is turned on. page.file and page.icon are paths inside the plugin. The page’s files are what sits in file’s folder; a path out of it, or a link that leads out, isn’t served. A package can be a page and a provider, middleware or an agent too. A plugin that is only a page doesn’t start the plugin host.
The Plugins page shows the page, and what it may read, on the plugin’s row before it is turned on. page.file and page.icon are paths inside the plugin. The page’s files are what sits in file’s folder; a path out of it, or a link that leads out, isn’t served. A package can be a page and a provider, middleware or an agent too. A plugin that is only a page doesn’t start the plugin host. page.titles (and a panel’s titles) names the tab in other languages, by language code (zh, zh-TW, ja, de); title is used for any other.
What the page leaves unstyled already looks like magpie: the bridge adds a stylesheet for the font, colours, headings, buttons, fields and tables, with no weight (:where()), so any rule of the page’s own wins. Use the --magpie-* variables to match the window in your own styles.
| Field / call | What it gives |
|---|
slot | Where the panel goes | magpie.context |
|---|---|---|
agents | The end of the Agents page | {} |
usage | The end of Usage’s Overview | {} |
settings | A Plugins tab in Settings, there only while a plugin has a panel in it | {} |
provider | Each saved provider’s editor | { provider: { id, name } } |
A plugin has at most 8 panels. A panel’s height follows its <html> (up to 2400px), so let the page size itself and don’t give html or body a fixed height. A panel that throws, or doesn’t answer in 10 seconds, shows {name} stopped working with Try again in its own place; the page around it and the panels beside it go on.
A page can take the place of one of magpie’s own: add "replaces" to magpie.page, one of sessions, library, routing or usage. Its tab then stands where the built-in’s was, and links to that page open the plugin’s. When two plugins ask for the same page, the first in the Plugins list takes it and the other is a page of its own. Turn the plugin off and the built-in page is back as it was.
"page": { "title": "My library", "file": "page/index.html", "replaces": "library" }+
magpie also runs pi’s packages. A pi extension that registers a provider with pi.registerProvider works in magpie as it does in pi, with nothing to change, and is added like any plugin (magpie plugin add pi-antigravity).
插件打开之前,插件页面就会在它的那一行显示这个页面和它能读什么。page.file 和 page.icon 是插件里面的路径;页面的文件就是 file 所在文件夹里的文件,指向外面的路径或链接不会被提供。一个包可以同时是页面、供应商、中间件或 agent。只有页面的插件不会启动插件宿主。
插件打开之前,插件页面就会在它的那一行显示这个页面和它能读什么。page.file 和 page.icon 是插件里面的路径;页面的文件就是 file 所在文件夹里的文件,指向外面的路径或链接不会被提供。一个包可以同时是页面、供应商、中间件或 agent。只有页面的插件不会启动插件宿主。page.titles(以及面板的 titles)按语言代码(zh、zh-TW、ja、de)给出其他语言里的标签名,其余语言用 title。
页面没写样式的地方本来就是 magpie 的样子:bridge 会加一份样式表,管字体、颜色、标题、按钮、输入框和表格,权重为零(:where()),页面自己的任何规则都会盖过它。自己写样式时,用 --magpie-* 变量和窗口保持一致。
| 字段 / 调用 | 给出什么 |
|---|
slot | 面板放在哪里 | magpie.context |
|---|---|---|
agents | 「Agent」页面的末尾 | {} |
usage | 用量「概览」的末尾 | {} |
settings | 设置里的「插件」标签页,有插件在这里放了面板时才出现 | {} |
provider | 每个已保存 Provider 的编辑页 | { provider: { id, name } } |
一个插件最多 8 个面板。面板的高度跟随它的 <html>(最高 2400px),所以让页面自己决定高度,不要给 html 或 body 固定高度。面板出错,或 10 秒内没有应答,就在它自己的位置显示「{name} 已停止工作」和「重试」;所在的页面和旁边的面板照常运行。
页面可以替代 magpie 自己的某个页面:在 magpie.page 里加上 "replaces",取 sessions、library、routing 或 usage 之一。它的标签就出现在内置页面原来的位置,指向那个页面的链接都会打开插件的页面。两个插件要替代同一个页面时,插件列表里排在前面的那个替代,另一个作为独立页面。关掉插件,内置页面就原样回来。
"page": { "title": "My library", "file": "page/index.html", "replaces": "library" }+
magpie 也运行 pi 的扩展包。用 pi.registerProvider 注册了供应商的 pi 扩展,在 magpie 里和在 pi 里一样工作,不用改任何东西,添加方式和其他插件相同(magpie plugin add pi-antigravity)。