From b9f790d37b8ac582f4fa90ff6b45af49a5aaacf9 Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 16 Oct 2026 18:13:44 +0800 Subject: [PATCH] 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 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- docs/subsystems/plugin-runtime.md | 75 ++++- internal/cli/plugins_cli.go | 43 ++- internal/gui/assets/app.css | 12 + internal/gui/assets/app.js | 12 +- internal/gui/assets/i18n.js | 40 +++ internal/gui/assets/index.html | 5 + internal/gui/assets/kernel.js | 2 + internal/gui/assets/pluginpages.js | 174 ++++++++++- internal/gui/assets/plugins.js | 38 ++- internal/gui/assets/plugins/usage/client.js | 1 + internal/gui/assets/plugins/usage/page.js | 4 +- internal/gui/pagebridge.js | 79 ++++- internal/gui/pluginpage.go | 159 +++++++--- internal/gui/pluginpage_webkit_darwin_test.go | 84 +++++ internal/gui/pluginpanel_test.go | 177 +++++++++++ internal/gui/plugins.go | 33 +- .../gui/testdata/panel-plugin/package.json | 13 + .../gui/testdata/panel-plugin/ui/notes.html | 13 + .../gui/testdata/panel-plugin/ui/notes.js | 19 ++ .../testdata/panel-plugin/ui/settings.html | 13 + .../gui/testdata/panel-plugin/ui/settings.js | 15 + .../gui/testdata/panel-plugin/ui/spend.html | 13 + .../gui/testdata/panel-plugin/ui/spend.js | 13 + .../gui/testdata/panel-plugin/ui/style.css | 7 + internal/gui/tests/menu-scroll.test.cjs | 4 +- internal/gui/tests/plugin-page.test.cjs | 41 ++- internal/gui/tests/plugin-panels.test.cjs | 286 ++++++++++++++++++ internal/plugin/agent.go | 6 +- internal/plugin/page.go | 178 ++++++++--- internal/plugin/page_test.go | 132 +++++++- internal/plugin/store.go | 2 +- site/public/docs/ja/plugins.html | 40 ++- site/public/docs/plugins.html | 40 ++- site/public/docs/zh/plugins.html | 40 ++- 34 files changed, 1659 insertions(+), 154 deletions(-) create mode 100644 internal/gui/pluginpage_webkit_darwin_test.go create mode 100644 internal/gui/pluginpanel_test.go create mode 100644 internal/gui/testdata/panel-plugin/package.json create mode 100644 internal/gui/testdata/panel-plugin/ui/notes.html create mode 100644 internal/gui/testdata/panel-plugin/ui/notes.js create mode 100644 internal/gui/testdata/panel-plugin/ui/settings.html create mode 100644 internal/gui/testdata/panel-plugin/ui/settings.js create mode 100644 internal/gui/testdata/panel-plugin/ui/spend.html create mode 100644 internal/gui/testdata/panel-plugin/ui/spend.js create mode 100644 internal/gui/testdata/panel-plugin/ui/style.css create mode 100644 internal/gui/tests/plugin-panels.test.cjs 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 ` @@ -412,6 +414,9 @@
+
+ +
diff --git a/internal/gui/assets/kernel.js b/internal/gui/assets/kernel.js index 6f92d7ce9..32755c2dc 100644 --- a/internal/gui/assets/kernel.js +++ b/internal/gui/assets/kernel.js @@ -48,6 +48,7 @@ main.hidden = true; main.dataset.feature = p.id; main.innerHTML = part.html || ""; + window.magpie?.fillSlots?.(main); const anchor = document.querySelector('template[data-slot="page"]'); if (anchor) anchor.before(main); else document.body.append(main); @@ -94,6 +95,7 @@ page.broken = null; page.mounted = false; page.main.innerHTML = page.part.html || ""; + window.magpie?.fillSlots?.(page.main); window.translateStatic?.(); if (hook !== "mount") run(page, "mount", [page.main]); run(page, hook, args); diff --git a/internal/gui/assets/pluginpages.js b/internal/gui/assets/pluginpages.js index 7c88dd050..eed6ba724 100644 --- a/internal/gui/assets/pluginpages.js +++ b/internal/gui/assets/pluginpages.js @@ -9,12 +9,29 @@ // (magpie.permissions), which /api/plugin-pages/read checks again. // A page that throws, or never says hello, shows the kernel's "This // page stopped working" with its Try again. +// +// A plugin's panels (magpie.panels, P5) are parts of magpie's own pages, +// each in a frame shut in the same way, answered the same way: a slot is +// a
in a page's markup, or one +// app.js draws through magpie.slot(name, context) (a provider's editor, +// which tells its panels the provider). A panel is as tall as what it +// draws (its "size"), and one that breaks says so in its own place, with +// Try again, and nothing else on the page goes. +// +// A page that replaces a built-in page (magpie.page.replaces) takes its +// tab's place in the sidebar, and a way to the built-in page (a link, an +// address kept, show) opens the plugin's instead. (() => { if (mode !== "window") return; // how long a page has to say hello before it is taken as broken const HELLO_MS = 10e3; const pages = new Map(); // key → { entry, frame, hello, timer } + const panels = new Map(); // frame → { entry, frame, context, hello, timer, body } + let panelList = []; // /api/plugin-panels: every panel of a plugin on let ctx = null; + // a built-in page → the plugin's page in its place (magpie.page.replaces) + let replaced = new Map(); + magpie.replacing = (v) => replaced.get(v) || v; magpie.plugin("plugin-pages", (c) => { ctx = c; }); const TOKENS = ["bg", "card", "fg", "fg-2", "muted", "faint", "line", "accent", "accent-soft", "accent-fg", "green", "red", "amber", "font", "code"]; @@ -32,13 +49,21 @@ // the theme or the language changed: every page open is told function pushTheme() { const data = theme(); - for (const p of pages.values()) if (p.hello) post(p.frame?.contentWindow, { event: "theme", data }); + for (const p of [...pages.values(), ...panels.values()]) if (p.hello) post(p.frame?.contentWindow, { event: "theme", data }); } new MutationObserver(pushTheme).observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme", "lang", "class", "style"] }); matchMedia("(prefers-color-scheme: dark)").addEventListener?.("change", pushTheme); function broke(key, why) { ctx?.broke(key, new Error(why)); } + // a page's or a panel's title in the window's language: its titles + // (magpie.page.titles, {"zh": "…"}) by the language, then by its first + // part (zh for zh-TW), else its title + function titled(e) { + const m = e.titles || {}; + return m[locale] || m[locale.split("-")[0]] || e.title; + } + // the page's frame, made the first time the page is opened (and again // after Try again): a plugin's page costs nothing until it is looked at function open(key) { @@ -53,14 +78,14 @@ f.setAttribute("sandbox", "allow-scripts"); f.setAttribute("referrerpolicy", "no-referrer"); f.setAttribute("allow", ""); - f.title = p.entry.title; + f.title = titled(p.entry); f.src = p.entry.url; p.frame = f; p.hello = false; p.ready = new Promise((resolve, reject) => { p.said = resolve; clearTimeout(p.timer); - p.timer = setTimeout(() => { if (!p.hello) reject(new Error(t("{name}'s page didn't answer", { name: p.entry.title }))); }, HELLO_MS); + p.timer = setTimeout(() => { if (!p.hello) reject(new Error(t("{name}'s page didn't answer", { name: titled(p.entry) }))); }, HELLO_MS); }); main.replaceChildren(f); return p.ready; @@ -73,7 +98,8 @@ p.hello = true; clearTimeout(p.timer); p.said?.(); - return theme(); + // a panel is told where it is: the provider whose editor it is in + return { ...theme(), context: p.context || {} }; case "theme": return theme(); case "options.get": @@ -87,7 +113,7 @@ const name = String(m.params?.name || ""); // what its package didn't declare is refused here, and again by // the server - if (!e.reads.includes(name)) throw new Error(t("{name} doesn't ask to read {what}", { name: e.title, what: name })); + if (!e.reads.includes(name)) throw new Error(t("{name} doesn't ask to read {what}", { name: titled(e), what: name })); return api("plugin-pages/read", { spec: e.spec, read: name, params: m.params?.params || {} }); } } @@ -99,11 +125,24 @@ // or one that names a page, is nothing let key = "", p = null; for (const [k, x] of pages) if (x.frame && ev.source === x.frame.contentWindow) { key = k; p = x; break; } + if (!p) { + for (const [f, x] of panels) { + if (!f.isConnected) { panels.delete(f); clearTimeout(x.timer); continue; } + if (ev.source === f.contentWindow) { p = x; break; } + } + } if (!p) return; const m = ev.data; if (!m || typeof m !== "object" || m.magpie !== 1 || typeof m.method !== "string") return; if (m.method === "error") { - broke(key, String(m.params?.message || t("The page hit an error"))); + const why = String(m.params?.message || t("The page hit an error")); + if (p.context) panelBroke(p, why); else broke(key, why); + return; + } + // a panel is as tall as what it draws; a page fills its view + if (m.method === "size") { + const h = Number(m.params?.height); + if (p.context && Number.isFinite(h)) p.frame.style.height = Math.min(Math.max(Math.ceil(h), 0), PANEL_MAX) + "px"; return; } const src = ev.source; @@ -133,12 +172,13 @@ s.setAttribute("aria-hidden", "true"); b.append(s); } - b.append(el("span", "", e.title)); + b.append(el("span", "", titled(e))); b.onclick = () => { show(e.key); b.blur(); }; return b; } async function load() { + loadPanels(); let list; try { list = await api("plugin-pages"); } catch { return; } // an answer that isn't a list is not known: the tabs drawn stay @@ -148,6 +188,10 @@ // a page whose plugin went off, or away: its tab goes, and the window // leaves it if it was open for (const b of nav.querySelectorAll("button[data-plugin-page]")) if (!keys.has(b.dataset.view)) b.remove(); + // a built-in page replaced by a plugin's that went is back in its place + const replacing = new Map(list.filter((e) => e.replaces).map((e) => [e.replaces, e.key])); + for (const b of nav.querySelectorAll("button[data-replaced]")) if (!replacing.has(b.dataset.view)) b.removeAttribute("data-replaced"); + replaced = replacing; for (const [k, p] of pages) { if (keys.has(k)) continue; p.frame?.remove(); @@ -156,8 +200,9 @@ if (view === k) show("plugins"); } let head = nav.querySelector(".nav-gl[data-plugin-pages]"); - if (!list.length) { head?.remove(); return; } - if (!head) { + const own = list.filter((e) => !e.replaces); + if (!own.length) head?.remove(); + if (!head && own.length) { head = el("span", "nav-gl", t("Plugins")); head.dataset.pluginPages = ""; head.dataset.en = "Plugins"; @@ -170,7 +215,7 @@ if (!p) { p = { entry: e }; pages.set(e.key, p); - ctx.slots.add("page", { key: e.key, title: e.title, html: "", mount(main) { main.classList.add("plugin-page"); p.frame = null; }, open: () => open(e.key) }); + ctx.slots.add("page", { key: e.key, title: titled(e), html: "", mount(main) { main.classList.add("plugin-page"); p.frame = null; }, open: () => open(e.key) }); } else if (p.entry.url !== e.url || p.gone) { p.frame?.remove(); p.frame = null; @@ -178,13 +223,25 @@ p.gone = false; p.entry = e; const part = magpie.page(e.key); - if (part) part.title = e.title; + if (part) part.title = titled(e); let b = nav.querySelector(`button[data-plugin-page][data-view="${e.key}"]`); if (!b) b = tab(e); + else b.querySelector("span").textContent = titled(e); b.classList.toggle("on", view === e.key); + // in the place of the built-in page it replaces, which steps aside + // (and the reader on it is taken to the plugin's); else in the + // Plugins group + const built = e.replaces && nav.querySelector(`button[data-view="${e.replaces}"]:not([data-plugin-page])`); + if (built) { + built.dataset.replaced = e.key; + built.after(b); + if (view === e.replaces) show(e.key); + continue; + } at.after(b); at = b; } + navSubs(); // a reload of a plugin's page, or the one the window was left on, // comes back to it once its tab is there if (view === "agents" && !opened) { @@ -195,6 +252,101 @@ } } let opened = false; + + // ---- panels ---- + + // how tall a panel can be, so one that says it is endless isn't + const PANEL_MAX = 2400; + + function panelBroke(p, why) { + if (p.broken) return; + p.broken = true; + clearTimeout(p.timer); + panels.delete(p.frame); + const card = el("div", "plugin-panel-broke"); + card.setAttribute("role", "alert"); + card.append(el("b", "", t("{name} stopped working", { name: titled(p.entry) })), el("span", "note", why)); + const again = el("button", "text", t("Try again")); + again.type = "button"; + again.onclick = () => panelFrame(p.entry, p.context, p.body); + card.append(again); + p.body.replaceChildren(card); + console.error(`[magpie] ${p.entry.name}: panel ${p.entry.key}: ${why}`); + } + + // a panel's frame in body, told context once it says hello + function panelFrame(e, context, body) { + const f = document.createElement("iframe"); + f.className = "plugin-frame plugin-panel-frame"; + f.setAttribute("sandbox", "allow-scripts"); + f.setAttribute("referrerpolicy", "no-referrer"); + f.setAttribute("allow", ""); + f.title = titled(e); + f.src = e.url; + const p = { entry: e, frame: f, context, body, hello: false, broken: false }; + p.timer = setTimeout(() => { if (!p.hello) panelBroke(p, t("{name}'s page didn't answer", { name: titled(e) })); }, HELLO_MS); + panels.set(f, p); + body.replaceChildren(f); + } + + // fill a slot with the panels of its name: drawn again only when they + // changed, so a panel already open goes on as it is + function fill(box) { + const name = box.dataset.slot; + const list = panelList.filter((e) => e.slot === name); + const sig = list.map((e) => e.key + " " + e.url + " " + titled(e)).join("|"); + if (box.dataset.sig === sig && box.childElementCount === list.length) return; + box.dataset.sig = sig; + const context = box.pluginContext || {}; + const parts = list.map((e) => { + const sec = el("section", "plugin-panel"); + sec.dataset.panel = e.key; + const head = el("div", "row-head"); + head.append(el("span", "label", titled(e))); + if (titled(e) !== e.name) head.append(el("span", "note", e.name)); + const body = el("div", "plugin-panel-body"); + sec.append(head, body); + panelFrame(e, context, body); + return sec; + }); + box.replaceChildren(...parts); + box.hidden = !parts.length; + // Settings' Plugins tab comes or goes with its panels, in the sidebar too + if (name === "settings" && typeof setSetTab === "function") { setSetTab(setTab); navSubs(); } + } + + // a slot app.js draws, with what its panels are told (a provider's + // editor: { provider: { id, name } }) + magpie.slot = (name, context) => { + const box = document.createElement("div"); + box.className = "plugin-slot"; + box.dataset.slot = name; + box.pluginContext = context || {}; + box.hidden = true; + fill(box); + return box; + }; + + // a page's markup written after the panels came (a built-in page + // registered late, or put back by Try again): its slots filled now + magpie.fillSlots = (root) => { for (const box of root.querySelectorAll(".plugin-slot[data-slot]")) fill(box); }; + + async function loadPanels() { + let list; + try { list = await api("plugin-panels"); } catch { return; } + // an answer that isn't a list is not known: the panels drawn stay + if (!Array.isArray(list)) return; + panelList = list; + for (const box of document.querySelectorAll(".plugin-slot[data-slot]")) fill(box); + } + window.loadPluginPages = load; load(); + // a new language: the tabs and the panels' heads are titled in it + let lang = document.documentElement.lang; + new MutationObserver(() => { + if (document.documentElement.lang === lang) return; + lang = document.documentElement.lang; + load(); + }).observe(document.documentElement, { attributes: true, attributeFilter: ["lang"] }); })(); diff --git a/internal/gui/assets/plugins.js b/internal/gui/assets/plugins.js index e522a84c3..a127cc112 100644 --- a/internal/gui/assets/plugins.js +++ b/internal/gui/assets/plugins.js @@ -117,13 +117,15 @@ // an agent ("ag") is one magpie has no wiring of its own for, which it // then connects as it does its own; tools ("tl") are given to every // agent through magpie's plugin tools MCP server; a page ("pg") is a - // page of its own in the window's sidebar (pluginpages.js) + // page of its own in the window's sidebar (pluginpages.js); panels + // ("pn") are its parts in magpie's own pages const KINDS = { pv: [PLUG, "Provider", "Signs in to a subscription and serves its models"], mw: [PIPE, "Middleware", "Runs in magpie's gateway on the requests your agents send and on the replies"], ag: [TERM, "Agent", "Adds an agent magpie has no setup of its own for: pick its model on the Agents page and it goes through magpie"], tl: [TOOL, "Tools", "Gives every agent tools of its own, through magpie's MCP server"], pg: [PAGE, "Page", "Adds a page of its own to the sidebar. It runs shut off from the rest of magpie and can read only what its row lists"], + pn: [PAGE, "Panels", "Adds panels to magpie's own pages. They run shut off from the rest of magpie and can read only what its row lists"], }; const kindOf = (l) => ({ middleware: "mw", agent: "ag", tools: "tl", page: "pg" })[l.kind] || "pv"; function kindChip(kind) { @@ -1131,6 +1133,7 @@ const toolsOnly = !!e.tools?.length && !e.providers?.length; if (e.tools?.length) nm.append(kindChip("tl")); if (e.page) nm.append(kindChip("pg")); + if (e.panels?.length) nm.append(kindChip("pn")); if (e.providers?.length || !(e.gatewayOnly || e.middlewareOnly || e.inMagpieOnly || toolsOnly || (mw && !e.isMiddleware) || (ag && !e.isAgent))) nm.append(kindChip("pv")); who.append(nm); const subs = subsOf(pkg); @@ -1162,8 +1165,8 @@ else if (!x.signedIn && subs.some((y) => y.signedIn)) s.title = t("{name} is a subscription of its own; {other} works without it", { name: x.name, other: subs.find((y) => y.signedIn).name }); sub.append(s); } - } else if ((mw || ag || gw || e.isGateway || toolsOnly || e.page && e.inMagpieOnly) && !e.providers.length) { - // only middleware, a request hook, an agent, tools or a page: its own line says what it does + } else if ((mw || ag || gw || e.isGateway || toolsOnly || (e.page || e.panels?.length) && e.inMagpieOnly) && !e.providers.length) { + // only middleware, a request hook, an agent, tools, a page or panels: its own line says what it does } else if (clashes.length && !e.providers.length) { // its own line below says whose it is } else if (e.providers.length) sub.textContent = t("Signs in to {names}", { names: e.providers.join(t(", ")) }); @@ -1180,10 +1183,11 @@ if (e.tools?.length && !e.off && !ask) who.append(toolsLine(e.tools)); // off too: what its page may read is said before it is turned on if (e.page && !ask) who.append(pageLine(e.page)); + if (e.panels?.length && !ask) who.append(panelsLine(e.panels, e.panelReads)); if ((mw || e.isGateway) && !e.off && !ask && editing?.pkg === pkg) who.append(optionsEditor(e)); // the plugin's own picture (package.json's magpie.icon) before its // first provider's, which a plugin of several gives each its own (#1775) - r.append(logo(l?.icon || l?.npm?.icon || e.icon || subs[0]?.icon || ag?.icon, false, e.middlewareOnly ? "mw" : e.inMagpieOnly && e.isAgent && !e.isMiddleware ? "ag" : e.inMagpieOnly && e.page && !e.isAgent && !e.isMiddleware ? "pg" : toolsOnly && !e.page && !mw && !ag ? "tl" : ""), who); + r.append(logo(l?.icon || l?.npm?.icon || e.icon || subs[0]?.icon || ag?.icon, false, e.middlewareOnly ? "mw" : e.inMagpieOnly && e.isAgent && !e.isMiddleware ? "ag" : e.inMagpieOnly && (e.page || e.panels?.length) && !e.isAgent && !e.isMiddleware ? "pg" : toolsOnly && !e.page && !mw && !ag ? "tl" : ""), who); const val = el("div", "val"); const b = busy.get(pkg) || busy.get(e.spec); // npm's newer version, or a git one's repository at a newer commit @@ -1360,12 +1364,32 @@ // what a plugin's page may read of magpie's: what its package.json's // magpie.permissions declares, each a read with no secret in it const READS = { "usage:summary": "your usage totals, by model", "providers:list": "your providers' names" }; + const PAGES = { sessions: "Sessions", library: "Library", routing: "Routing", usage: "Usage" }; function pageLine(p) { const d = el("div", "sub pm-mw pm-page"); const reads = (p.reads || []).map((r) => t(READS[r] || r)); - d.textContent = d.title = reads.length - ? t("Adds a page to the sidebar, which can read {reads}", { reads: reads.join(t(", ")) }) - : t("Adds a page to the sidebar, which reads nothing of magpie's"); + const page = p.replaces && t(PAGES[p.replaces] || p.replaces); + d.textContent = d.title = page + ? reads.length + ? t("Takes the place of the {page} page, and can read {reads}", { page, reads: reads.join(t(", ")) }) + : t("Takes the place of the {page} page, and reads nothing of magpie's", { page }) + : reads.length + ? t("Adds a page to the sidebar, which can read {reads}", { reads: reads.join(t(", ")) }) + : t("Adds a page to the sidebar, which reads nothing of magpie's"); + return d; + } + + // where a plugin's panels go in magpie's own pages (magpie.panels), and + // what they may read + const SLOTS = { agents: "the Agents page", usage: "the Usage page", settings: "Settings", provider: "each provider's editor" }; + function panelsLine(panels, panelReads) { + const d = el("div", "sub pm-mw pm-page"); + const where = [...new Set(panels.map((x) => x.slot))].map((s) => t(SLOTS[s] || s)).join(t(", ")); + const reads = (panelReads || []).map((r) => t(READS[r] || r)); + d.textContent = reads.length + ? t("Adds panels to {where}, which can read {reads}", { where, reads: reads.join(t(", ")) }) + : t("Adds panels to {where}, which read nothing of magpie's", { where }); + d.title = panels.map((x) => x.title).filter(Boolean).join("\n") || d.textContent; return d; } diff --git a/internal/gui/assets/plugins/usage/client.js b/internal/gui/assets/plugins/usage/client.js index ddbd2245f..777df5643 100644 --- a/internal/gui/assets/plugins/usage/client.js +++ b/internal/gui/assets/plugins/usage/client.js @@ -50,6 +50,7 @@ magpie.plugin("usage", (ctx) => {

+
-

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.

What the page can ask

@@ -849,6 +853,38 @@ document.getElementById("calls").textContent = `${s.calls
  • An error the page doesn’t catch shows This page stopped working in its place, with Try again. Its own scripts’ errors reach it as “Script error.”, so look in the window’s console for the rest.
  • +

    Panels in magpie’s own pages

    +

    A plugin can also put panels into the pages magpie draws itself. Each one is a small page of its own in the plugin’s folder, with the same bridge, reads, options and sandbox as a page. It sits in a card under a heading with its title, as tall as it draws.

    +
    + package.json + +
    {
    +  "name": "magpie-provider-notes",
    +  "version": "0.1.0",
    +  "magpie": {
    +    "panels": [
    +      { "slot": "provider", "file": "ui/notes.html", "title": "Notes" },
    +      { "slot": "usage", "file": "ui/spend.html", "title": "Top models today" }
    +    ],
    +    "permissions": ["usage:summary"]
    +  }
    +}
    +
    +
    Field / callWhat it gives
    + + + + + +
    slotWhere the panel goesmagpie.context
    agentsThe end of the Agents page{}
    usageThe end of Usage’s Overview{}
    settingsA Plugins tab in Settings, there only while a plugin has a panel in it{}
    providerEach 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.

    +

    Taking a built-in page’s place

    +

    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.

    +
    + package.json + +
    "page": { "title": "My library", "file": "page/index.html", "replaces": "library" }
    +

    pi packages

    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).