Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
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
yetoneb9f790d37b8a
diff --git a/docs/subsystems/plugin-runtime.md b/docs/subsystems/plugin-runtime.mdindex 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'sextension points: the observer, with OTel export as its first plugin; therouter strategy, with the routings besides Smart and the user's groups; andthe 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 inthe 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 `<html lang>` 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 `<div class="plugin-slot"+ data-slot="…" hidden>` in its markup, or app.js draws one with+ `magpie.slot(name, context)` ([`pluginpages.js`](../../internal/gui/assets/pluginpages.js)).+ A slot is filled when the panels come, again only when they changed (a+ panel open goes on as it is), and when the kernel writes a page's markup+ afterwards (`magpie.fillSlots`, from `add` and Try again).+- **Replacing a page.** `magpie.page.replaces`, one of `plugin.Replaceable`+ (`sessions`, `library`, `routing`, `usage`), puts the plugin's page in+ the built-in's place in the sidebar: the built-in's button is hidden+ (`data-replaced`) and `show()` of it opens the plugin's page+ (`magpie.replacing`). The first on plugin in plugins.json's order takes+ a page; another asking for the same is a page of its own. The built-in+ page is still there, and comes back when the plugin is off.+- **The Plugins page** says, on the row, where a plugin's panels go and+ what they read, and which page it takes the place of (`panelsLine`,+ `pageLine` in [`plugins.js`](../../internal/gui/assets/plugins.js)),+ with a Panels chip.++Tests: `TestWindowPanels`, `TestPluginPanelsServedShutIn`,+`TestPluginPanelsReadWhatTheyDeclared`, `TestPluginPageReplacesFirstWins`,+`plugin-panels.test.cjs`. Example: `internal/gui/testdata/panel-plugin`.+## Source of truth and composingWhat a plugin runs with is composed field by field (`Compose`), each value@@ -374,5 +441,11 @@ remembering its layer (`Source`):on; `TestMaskingOnAndOff`, `TestMaskedQueryFailsClosed` and`TestMiddlewareOnAndOff` turn them off: masking asked for is a 503 andthe vendor gets nothing, middleware off sends the request as it came).+- P5: `go test ./internal/plugin/ -run TestWindowPanels`,+ `go test ./internal/gui/ -run 'TestPluginPanels|TestPluginPageReplaces'`+ and `plugin-panels.test.cjs` (every slot, a broken panel and Try again,+ the size watch's loop notice, a replaced Library, the Settings tab+ coming and going) in Chromium and WebKit, every language, 1100 and 420+ points (the Plugins page's rows at 980 and 420).- By hand, under a sandbox HOME: `magpie plugin builtin`, `magpie pluginbuiltin on groups`, `magpie plugin dump`, and a plugins.yml broken by hand.diff --git a/internal/cli/plugins_cli.go b/internal/cli/plugins_cli.goindex d7d37313d..64e40dfdb 100644--- a/internal/cli/plugins_cli.go+++ b/internal/cli/plugins_cli.go@@ -240,8 +240,13 @@ func listPlugins(ctx context.Context, asJSON bool) error {if ts := toolsLine(toolNames[e.Spec]); ts != "" {fmt.Printf(" %s %s\n", muted.Render("tools"), ts)}- if pg, _ := plugin.WindowPage(plugin.Target(e.Spec)); pg != nil {- fmt.Printf(" %s %s\n", muted.Render("page"), pageLine(pg))+ if w, _ := plugin.Window(plugin.Target(e.Spec)); w != nil {+ if w.Page != nil {+ fmt.Printf(" %s %s\n", muted.Render("page"), pageLine(w, w.Page))+ }+ if len(w.Panels) > 0 {+ fmt.Printf(" %s %s\n", muted.Render("panels"), panelsLine(w))+ }}for _, p := range ps {if p.Spec != e.Spec {@@ -616,11 +621,33 @@ func toolsLine(names map[string]string) string {return strings.Join(out, ", ")}-// pageLine is a plugin's page: its title and what it may read of magpie's.-func pageLine(pg *plugin.PageSpec) string {- reads := "reads nothing"- if len(pg.Reads) > 0 {- reads = "reads " + strings.Join(pg.Reads, ", ")+// pageLine is a plugin's page: its title, the built-in page it takes the+// place of, and what it may read of magpie's.+func pageLine(w *plugin.WindowSpec, pg *plugin.PageSpec) string {+ s := pg.Title+ if pg.Replaces != "" {+ s += " " + muted.Render("in place of "+pg.Replaces)+ }+ return s + " " + muted.Render("("+readsText(w.Reads)+")")+}++// panelsLine is the panels a plugin adds to magpie's own pages: the page+// each is in, and what they may read of magpie's.+func panelsLine(w *plugin.WindowSpec) string {+ var at []string+ for _, p := range w.Panels {+ s := p.Slot+ if p.Title != "" {+ s = p.Title + " on " + p.Slot+ }+ at = append(at, s)+ }+ return strings.Join(at, ", ") + " " + muted.Render("("+readsText(w.Reads)+")")+}++func readsText(reads []string) string {+ if len(reads) == 0 {+ return "reads nothing"}- return pg.Title + " " + muted.Render("("+reads+")")+ return "reads " + strings.Join(reads, ", ")}diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.cssindex 443a12305..0cc917123 100644--- a/internal/gui/assets/app.css+++ b/internal/gui/assets/app.css@@ -3192,6 +3192,18 @@ body:not(.side-nav) #view-settings .set-head.stuck::before { box-shadow: 0 1px 0.view.plugin-page { padding: 0; }.plugin-frame { flex: 1; display: block; width: 100%; min-height: 240px; border: 0; background: transparent; }.view.plugin-page > .slot-error { margin: 0 12px; }+/* a plugin's panels in magpie's own pages (P5): each a card, as tall as+ what its frame draws, under its title */+.plugin-slot { display: flex; flex-direction: column; gap: 12px; margin-top: 16px; }+.plugin-slot[hidden] { display: none; }+.plugin-panel > .row-head { display: flex; align-items: baseline; gap: 8px; margin-bottom: 6px; }+.plugin-panel > .row-head .note { color: var(--muted); font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; }+.plugin-panel-body { border: 1px solid var(--line); border-radius: 10px; background: var(--card); overflow: hidden; }+.plugin-panel-frame { flex: none; min-height: 0; height: 48px; }+.plugin-panel-broke { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 10px; padding: 12px 14px; }+.plugin-panel-broke .note { flex: 1 1 200px; color: var(--muted); overflow-wrap: anywhere; }+/* a built-in page a plugin's page replaces steps aside in the sidebar */+#nav button[data-replaced] { display: none !important; }img.nav-ic { border-radius: 3px; object-fit: contain; }.row.pref { min-height: 50px; padding: 8px 12px 8px 14px; gap: 14px; }.row.pref .who { flex: 1 1 auto; }diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.jsindex 25471e3d2..36ecfeb9a 100644--- a/internal/gui/assets/app.js+++ b/internal/gui/assets/app.js@@ -9734,6 +9734,8 @@ function drawEditor(p, presetID) {};saveBtn.onclick = save;bar.append(cancel, saveBtn);+ // a plugin's panels for a provider (magpie.panels' provider), told which+ if (p) { const slot = magpie.slot?.("provider", { provider: { id: p.id, name: p.name || p.id } }); if (slot) ed.append(slot); }ed.append(bar);setTimeout(() => (isNew ? (custom || another ? name : endpoint || vertexProject || key) : null)?.focus(), 0);return ed;@@ -18787,7 +18789,7 @@ function tabKeys(tabs, sel) {// tab. A click on a tab, like every click, leaves the page where it is: the// tabs at the top stay where they were and the part comes in under them.// Picked in the sidebar, a part opens at its top (navSubs).-const SET_TABS = ["general", "usage", "network", "models", "privacy", "otel", "sync", "about"];+const SET_TABS = ["general", "usage", "network", "models", "privacy", "otel", "sync", "plugins", "about"];let setTab = "general";try { const k = localStorage.getItem("magpie.settingsTab"); if (SET_TABS.includes(k)) setTab = k; } catch {}let setShown = setTab; // the part shown: the one picked, or the first there@@ -18807,7 +18809,9 @@ function setSetTab(tab, remember) {setTab = tab;try { localStorage.setItem("magpie.settingsTab", tab); } catch {}}- for (const id of SET_TABS) $("#setTab-" + id).hidden = featureHides($("#setTab-" + id)) || !partShows($("#setPage-" + id));+ // Plugins is there while a plugin's panel is (magpie.panels' settings)+ for (const id of SET_TABS) $("#setTab-" + id).hidden = featureHides($("#setTab-" + id)) || !partShows($("#setPage-" + id))+ || (id === "plugins" && !$("#setPage-plugins .plugin-panel"));if (!SET_TABS.includes(tab) || $("#setTab-" + tab).hidden) tab = SET_TABS.find((id) => !$("#setTab-" + id).hidden) || "general";for (const id of SET_TABS) {const b = $("#setTab-" + id), on = id === tab;@@ -22560,6 +22564,8 @@ for (const v of document.querySelectorAll(".view")) {}async function show(v) {+ // a built-in page a plugin's page replaces (magpie.page.replaces) opens that+ v = magpie.replacing?.(v) || v;// a page gateway mode leaves out (a link to it, an address kept) opens Providersif (gatewayMode && GATEWAY_HIDES.includes(v)) v = "providers";// and one a built-in plugin switched off has, Agents@@ -23125,7 +23131,7 @@ function navSubs() {// a group none of whose pages shows (gateway mode's) leaves out its namefor (const gl of nav.querySelectorAll(".nav-gl")) {let any = false;- for (let n = gl.nextElementSibling; n && !n.matches(".nav-gl"); n = n.nextElementSibling) if (n.dataset.view && !n.hidden) any = true;+ for (let n = gl.nextElementSibling; n && !n.matches(".nav-gl"); n = n.nextElementSibling) if (n.dataset.view && !n.hidden && !n.dataset.replaced) any = true;gl.hidden = !any;}const side = sideNav();diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.jsindex 72d22f456..719ce4a87 100644--- a/internal/gui/assets/i18n.js+++ b/internal/gui/assets/i18n.js@@ -830,7 +830,17 @@ const I18N = {"your providers' names": "你的服务商名称","Adds a page to the sidebar, which can read {reads}": "为侧边栏添加一个页面,可读取{reads}","Adds a page to the sidebar, which reads nothing of magpie's": "为侧边栏添加一个页面,不读取 magpie 的任何内容",+ "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": "在 magpie 自己的页面中添加面板。面板与 magpie 的其他部分隔离运行,只能读取其条目列出的内容",+ "Takes the place of the {page} page, and can read {reads}": "取代「{page}」页面,可以读取{reads}",+ "Takes the place of the {page} page, and reads nothing of magpie's": "取代「{page}」页面,不读取 magpie 的任何内容",+ "Adds panels to {where}, which can read {reads}": "在{where}中添加面板,可以读取{reads}",+ "Adds panels to {where}, which read nothing of magpie's": "在{where}中添加面板,不读取 magpie 的任何内容",+ "the Agents page": "「Agent」页面",+ "the Usage page": "「用量」页面",+ "each provider's editor": "每个服务商的编辑页","{name}'s page didn't answer": "{name} 的页面没有响应",+ "{name} stopped working": "{name} 已停止工作","A page's options are an object": "页面的选项须是一个对象","{name} doesn't ask to read {what}": "{name} 没有声明读取 {what}","No such call: {what}": "没有这个调用:{what}",@@ -4532,7 +4542,17 @@ const I18N = {"your providers' names": "你的供應商名稱","Adds a page to the sidebar, which can read {reads}": "為側邊欄加入一個頁面,可讀取{reads}","Adds a page to the sidebar, which reads nothing of magpie's": "為側邊欄加入一個頁面,不讀取 magpie 的任何內容",+ "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": "在 magpie 自己的頁面中加入面板。面板與 magpie 的其他部分隔離執行,只能讀取其項目列出的內容",+ "Takes the place of the {page} page, and can read {reads}": "取代「{page}」頁面,可以讀取{reads}",+ "Takes the place of the {page} page, and reads nothing of magpie's": "取代「{page}」頁面,不讀取 magpie 的任何內容",+ "Adds panels to {where}, which can read {reads}": "在{where}中加入面板,可以讀取{reads}",+ "Adds panels to {where}, which read nothing of magpie's": "在{where}中加入面板,不讀取 magpie 的任何內容",+ "the Agents page": "「Agent」頁面",+ "the Usage page": "「用量」頁面",+ "each provider's editor": "每個服務商的編輯頁","{name}'s page didn't answer": "{name} 的頁面沒有回應",+ "{name} stopped working": "{name} 已停止運作","A page's options are an object": "頁面的選項須是一個物件","{name} doesn't ask to read {what}": "{name} 沒有宣告讀取 {what}","No such call: {what}": "沒有這個呼叫:{what}",@@ -8206,7 +8226,17 @@ const I18N = {"your providers' names": "プロバイダの名前","Adds a page to the sidebar, which can read {reads}": "サイドバーにページを追加します。読み取れるもの:{reads}","Adds a page to the sidebar, which reads nothing of magpie's": "サイドバーにページを追加します。magpie のものは何も読み取りません",+ "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": "magpie 自身のページにパネルを追加します。パネルは magpie のほかの部分から切り離されて動作し、この行に挙げたものしか読み取れません",+ "Takes the place of the {page} page, and can read {reads}": "「{page}」ページの代わりになります。{reads}を読み取れます",+ "Takes the place of the {page} page, and reads nothing of magpie's": "「{page}」ページの代わりになります。magpie のものは何も読み取りません",+ "Adds panels to {where}, which can read {reads}": "{where}にパネルを追加します。{reads}を読み取れます",+ "Adds panels to {where}, which read nothing of magpie's": "{where}にパネルを追加します。magpie のものは何も読み取りません",+ "the Agents page": "「エージェント」ページ",+ "the Usage page": "「使用量」ページ",+ "each provider's editor": "各プロバイダーの編集画面","{name}'s page didn't answer": "{name} のページが応答しませんでした",+ "{name} stopped working": "{name} は動作を停止しました","A page's options are an object": "ページのオプションはオブジェクトです","{name} doesn't ask to read {what}": "{name} は {what} の読み取りを宣言していません","No such call: {what}": "そのような呼び出しはありません:{what}",@@ -11894,7 +11924,17 @@ const I18N = {"your providers' names": "die Namen deiner Anbieter","Adds a page to the sidebar, which can read {reads}": "Fügt der Seitenleiste eine Seite hinzu, die {reads} lesen kann","Adds a page to the sidebar, which reads nothing of magpie's": "Fügt der Seitenleiste eine Seite hinzu, die nichts von magpie liest",+ "Panels": "Bereiche",+ "Adds panels to magpie's own pages. They run shut off from the rest of magpie and can read only what its row lists": "Fügt magpies eigenen Seiten Bereiche hinzu. Sie laufen abgeschottet vom Rest von magpie und können nur lesen, was ihre Zeile aufführt",+ "Takes the place of the {page} page, and can read {reads}": "Ersetzt die Seite „{page}“ und kann {reads} lesen",+ "Takes the place of the {page} page, and reads nothing of magpie's": "Ersetzt die Seite „{page}“ und liest nichts von magpie",+ "Adds panels to {where}, which can read {reads}": "Fügt {where} Bereiche hinzu, die {reads} lesen können",+ "Adds panels to {where}, which read nothing of magpie's": "Fügt {where} Bereiche hinzu, die nichts von magpie lesen",+ "the Agents page": "der Seite „Agenten“",+ "the Usage page": "der Seite „Nutzung“",+ "each provider's editor": "dem Editor jedes Anbieters","{name}'s page didn't answer": "Die Seite von {name} hat nicht geantwortet",+ "{name} stopped working": "{name} funktioniert nicht mehr","A page's options are an object": "Die Optionen einer Seite sind ein Objekt","{name} doesn't ask to read {what}": "{name} fragt nicht danach, {what} zu lesen","No such call: {what}": "Kein solcher Aufruf: {what}",diff --git a/internal/gui/assets/index.html b/internal/gui/assets/index.htmlindex a5b5f984d..8e1a6c1bc 100644--- a/internal/gui/assets/index.html+++ b/internal/gui/assets/index.html@@ -100,6 +100,7 @@<section class="panel-quota" id="panelQuota" hidden></section><section class="panel-routing" id="panelRouting" data-feature="routing" hidden></section><section class="panel-usage" id="panelUsage" hidden></section>+ <div class="plugin-slot" data-slot="agents" hidden></div></main><main class="view" id="view-providers" hidden>@@ -138,6 +139,7 @@<button type="button" role="tab" id="setTab-privacy" data-set="privacy" aria-controls="setPage-privacy" data-t>Privacy</button><button type="button" role="tab" id="setTab-otel" data-set="otel" aria-controls="setPage-otel" data-feature="otel" data-t>Observability</button><button type="button" role="tab" id="setTab-sync" data-set="sync" aria-controls="setPage-sync" data-t>Sync and backup</button>+ <button type="button" role="tab" id="setTab-plugins" data-set="plugins" aria-controls="setPage-plugins" data-t hidden>Plugins</button><button type="button" role="tab" id="setTab-about" data-set="about" aria-controls="setPage-about" data-t>About</button></div><input class="sess-filter set-q" id="setQ" type="search" spellcheck="false" autocomplete="off" placeholder="Find a setting" aria-label="Find a setting" data-tp></div><p class="set-none" id="setNone" role="status" hidden></p>@@ -412,6 +414,9 @@<section class="set-page" id="setPage-sync" role="tabpanel" aria-labelledby="setTab-sync"><div class="list prefs" id="syncList"></div></section>+ <section class="set-page" id="setPage-plugins" role="tabpanel" aria-labelledby="setTab-plugins">+ <div class="plugin-slot" data-slot="settings" hidden></div>+ </section><section class="set-page" id="setPage-about" role="tabpanel" aria-labelledby="setTab-about"><div class="list prefs" id="about"></div></section>diff --git a/internal/gui/assets/kernel.js b/internal/gui/assets/kernel.jsindex 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.jsindex 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 <div class="plugin-slot" data-slot="…"> 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 brokenconst 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 onlet 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 toldfunction 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 atfunction 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 nothinglet 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 openfor (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 thereif (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.jsindex 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 pagesconst 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 onif (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 itconst 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.jsindex 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) => {<div class="row-head" id="usageKeysHead" hidden><button class="fold" type="button" data-fold="keys" aria-expanded="true" aria-controls="usageKeys"><span class="label" data-t>Gateway keys</span></button></div><div class="list" id="usageKeys" hidden></div><p class="usage-note" id="usageNote"></p>+ <div class="plugin-slot" data-slot="usage" hidden></div></div><div class="usage-pane" id="ledgerPane" hidden><div class="sess-tools">diff --git a/internal/gui/assets/plugins/usage/page.js b/internal/gui/assets/plugins/usage/page.jsindex ff62d9b15..19f0d414c 100644--- a/internal/gui/assets/plugins/usage/page.js+++ b/internal/gui/assets/plugins/usage/page.js@@ -206,7 +206,7 @@ function renderUsageLoading() {for (const id of ["usageAgents", "usageAgentsHid", "usageModels", "usageKeys"]) $("#" + id).hidden = true;// the allowances' head is renderQuotas' alone: the quotas it heads are// still there while the period loads (#809, Hu9956: 用量界面红框这行会延迟几秒才会出现)- for (const h of $$("#view-usage .row-head:not(#quotaHead)")) h.hidden = true;+ for (const h of $$("#view-usage .row-head:not(#quotaHead, .plugin-panel > .row-head)")) h.hidden = true;$("#usageNote").textContent = "";}@@ -384,7 +384,7 @@ function renderUsage() {$("#chart").hidden = empty;for (const id of ["usageAgents", "usageModels"]) $("#" + id).hidden = empty;if (empty) $("#usageAgentsHid").hidden = true;- for (const h of $$("#view-usage .row-head:not(#quotaHead)")) h.hidden = empty;+ for (const h of $$("#view-usage .row-head:not(#quotaHead, .plugin-panel > .row-head)")) h.hidden = empty;$("#usageKeysHead").hidden = $("#usageKeys").hidden = empty || !u.callerKeys?.length;// each subscription account's share, by the account that answered (#557)$("#usageAccountsHead").hidden = $("#usageAccounts").hidden = empty || !u.accounts?.length;diff --git a/internal/gui/pagebridge.js b/internal/gui/pagebridge.jsindex d36cf9c1d..a04aa1d4e 100644--- a/internal/gui/pagebridge.js+++ b/internal/gui/pagebridge.js@@ -10,6 +10,17 @@// await magpie.options.set(o) sets them, and answers with them// await magpie.read(name, p) a read its package.json's// magpie.permissions declares+// magpie.context where a panel is (P5): { provider: {+// id, name } } in a provider's editor,+// else {}; set once magpie.ready is+//+// A panel (magpie.panels) is as tall as what it draws: the window is told+// its height as it changes.+//+// What the page leaves unstyled takes magpie's look: the bridge adds a+// stylesheet of no weight (:where()) for the font, colours, headings,+// buttons, fields and tables, and the theme's colours are the page's+// --magpie-<token> variables.//// The page can't reach the network or magpie's API itself: everything goes// through the window, which answers only what the package declared. An@@ -55,10 +66,21 @@// a script's error reaches a sandboxed page only as "Script error." (its// files are another origin's to it); the window then says "The page hit// an error" in the reader's language, and the console has the rest- addEventListener("error", (e) => report(e.error || (e.message === "Script error." ? "" : e.message)));+ //+ // The size watch below can be told its own "ResizeObserver loop+ // completed with undelivered notifications" when the window resizes the+ // frame in the same frame of drawing; that is no error of the page's,+ // and WebKit hands it to a sandboxed page as a bare "Script error." with+ // no file, so one that comes while the watch has just run is let go+ let measuring = false;+ addEventListener("error", (e) => {+ if (/ResizeObserver loop/.test(e.message) || (measuring && !e.error && !e.filename)) { e.preventDefault(); return; }+ report(e.error || (e.message === "Script error." ? "" : e.message));+ });addEventListener("unhandledrejection", (e) => report(e.reason));const api = {theme: null,+ context: {},onTheme(fn) { themed.push(fn); },options: {get: () => call("options.get"),@@ -66,6 +88,59 @@},read: (name, params) => call("read", { name, params }),};- api.ready = call("hello").then((theme) => { api.theme = theme; paint(theme); return theme; });+ api.ready = call("hello").then(({ context, ...theme }) => {+ api.theme = theme;+ api.context = context || {};+ paint(theme);+ return theme;+ });+ // how tall the page draws, for a panel's frame; a page's frame fills its+ // view, and the window doesn't heed it there+ let told = -1;+ const size = () => {+ const h = Math.ceil(document.documentElement.getBoundingClientRect().height);+ if (h === told) return;+ told = h;+ parent.postMessage({ magpie: 1, method: "size", params: { height: h } }, "*");+ };+ const watch = () => {+ new ResizeObserver(() => {+ if (!measuring) { measuring = true; setTimeout(() => { measuring = false; }); }+ size();+ }).observe(document.documentElement);+ size();+ };+ if (document.readyState === "loading") addEventListener("DOMContentLoaded", watch); else watch();+ // magpie's look for what the page leaves unstyled: its font, colours,+ // headings, buttons, fields and tables, so a page with no stylesheet of+ // its own reads as part of the window, not a browser's default sheet.+ // Every rule is :where(), of no weight: any rule of the page's wins.+ const base = document.createElement("style");+ base.dataset.magpie = "base";+ base.textContent = `+:where(html) { background: var(--magpie-bg, Canvas); color: var(--magpie-fg, CanvasText); font: 13px/1.45 var(--magpie-font, -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif); -webkit-font-smoothing: antialiased; }+:where(body) { margin: 0; padding: 20px 24px; }+:where(h1, h2, h3, h4) { font-weight: 600; margin: 0 0 8px; letter-spacing: -.01em; }+:where(h1) { font-size: 20px; } :where(h2) { font-size: 15px; } :where(h3, h4) { font-size: 13px; }+:where(p) { margin: 0 0 8px; }+:where(small, .muted) { color: var(--magpie-muted, GrayText); }+:where(a) { color: var(--magpie-accent, LinkText); text-decoration: none; }+:where(a:hover) { text-decoration: underline; }+:where(button, input, textarea, select) { font: inherit; color: inherit; }+:where(button) { background: var(--magpie-card, ButtonFace); border: 1px solid var(--magpie-line, ButtonBorder); border-radius: 6px; padding: 3px 10px; }+:where(button:hover:not(:disabled)) { border-color: var(--magpie-muted, ButtonBorder); }+:where(button[aria-pressed="true"], button[aria-selected="true"]) { background: var(--magpie-accent-soft, Highlight); border-color: transparent; color: var(--magpie-accent, HighlightText); }+:where(button:disabled) { opacity: .5; }+:where(input, textarea, select) { background: var(--magpie-card, Field); border: 1px solid var(--magpie-line, ButtonBorder); border-radius: 6px; padding: 4px 8px; }+:where(:focus-visible) { outline: 2px solid var(--magpie-accent, Highlight); outline-offset: 1px; }+:where(table) { border-collapse: collapse; width: 100%; }+:where(th) { text-align: left; font-weight: 500; font-size: 12px; color: var(--magpie-muted, GrayText); }+:where(th, td) { padding: 6px 8px; border-bottom: 1px solid var(--magpie-line, ButtonBorder); }+:where(code, kbd, pre) { font-family: var(--magpie-code, ui-monospace, Menlo, monospace); font-size: 12px; }+:where(pre) { background: var(--magpie-card, Canvas); border: 1px solid var(--magpie-line, ButtonBorder); border-radius: 8px; padding: 8px 10px; overflow: auto; }+:where(hr) { border: 0; border-top: 1px solid var(--magpie-line, ButtonBorder); margin: 12px 0; }+:where(::selection) { background: var(--magpie-accent-soft, Highlight); }+`;+ (document.head || document.documentElement).prepend(base);window.magpie = api;})();diff --git a/internal/gui/pluginpage.go b/internal/gui/pluginpage.goindex 92891cbcd..fb682c03c 100644--- a/internal/gui/pluginpage.go+++ b/internal/gui/pluginpage.go@@ -13,6 +13,7 @@ import ("os""path/filepath""slices"+ "strconv""strings""sync""time"@@ -24,7 +25,9 @@ import (// A community plugin's own page in magpie's window (P4 of// docs/subsystems/plugin-runtime.md): package.json's magpie.page, shown in-// a sandboxed frame (pluginpages.js). Its files are served under+// a sandboxed frame (pluginpages.js), and its panels in magpie's own pages+// (magpie.panels, P5), each in a frame of its own shut in the same way.+// Their files are served under// pluginPagePrefix and a token only this run of magpie hands out, with a// policy that lets the page load nothing but its own files and reach// nothing over the network; it has no way to magpie's /api (apiFramed),@@ -61,31 +64,52 @@ func pageToken(spec string) string {// pluginPage is a plugin's page, of a plugin that is on.type pluginPage struct {- Spec string `json:"spec"`- Name string `json:"name"` // its package's- Key string `json:"key"` // the window's page key- Title string `json:"title"` // the page's, or the package's short name- URL string `json:"url"` // the page, under pluginPagePrefix- Icon string `json:"icon,omitempty"`- Reads []string `json:"reads"` // what it may read, of plugin.PageReads- token string- spec *plugin.PageSpec+ Spec string `json:"spec"`+ Name string `json:"name"` // its package's+ Key string `json:"key"` // the window's page key+ Title string `json:"title"` // the page's, or the package's short name+ // Titles are its title by the window's language (plugin.PageSpec)+ Titles map[string]string `json:"titles,omitempty"`+ URL string `json:"url"` // the page, under pluginPagePrefix+ Icon string `json:"icon,omitempty"`+ // Replaces is the built-in page whose place it takes: the first+ // plugin's in plugins.json's order to ask for it+ Replaces string `json:"replaces,omitempty"`+ Reads []string `json:"reads"` // what it may read, of plugin.PageReads+ token string+ dir string+}++// pluginPanel is a panel a plugin that is on adds to one of magpie's own+// pages (plugin.PanelSlots).+type pluginPanel struct {+ Spec string `json:"spec"`+ Name string `json:"name"` // its package's+ Key string `json:"key"` // the panel's, among every plugin's+ Slot string `json:"slot"` // the page it is in+ Title string `json:"title"` // the panel's, or the package's short name+ Titles map[string]string `json:"titles,omitempty"`+ URL string `json:"url"` // the panel, under pluginPagePrefix+ Reads []string `json:"reads"` // what it may read, of plugin.PageReads+ token string+ dir string}// pageKeyChars are what a window page's key can't havevar pageKeyChars = strings.NewReplacer("@", "", "/", "-", ".", "-", "_", "-", " ", "-")-// pluginPages are the pages of the plugins that are on, in plugins.json's-// order. A plugin switched off has none: its files aren't served.-func pluginPages() []pluginPage {- var out []pluginPage+// windowParts are the pages and the panels of the plugins that are on, in+// plugins.json's order. A plugin switched off has none: its files aren't+// served.+func windowParts() (pages []pluginPage, panels []pluginPanel) {seen := map[string]bool{}+ replaced := map[string]bool{}for _, e := range plugin.Load().Plugins {if e.Off {continue}- spec, _ := plugin.WindowPage(plugin.Target(e.Spec))- if spec == nil {+ w, _ := plugin.Window(plugin.Target(e.Spec))+ if w == nil {continue}name := plugin.PackageName(e.Spec)@@ -100,31 +124,62 @@ func pluginPages() []pluginPage {key = fmt.Sprintf("%s-%d", k, n)}seen[key] = true- tok := pageToken(e.Spec)- rel, _ := filepath.Rel(spec.Dir, spec.File)- p := pluginPage{Spec: e.Spec, Name: name, Key: key, Title: spec.Title, Reads: spec.Reads, token: tok, spec: spec,- URL: pluginPagePrefix + tok + "/" + filepath.ToSlash(rel)}- if p.Title == "" {- p.Title = plugin.ShortName(name)+ reads := w.Reads+ if reads == nil {+ reads = []string{}}- if p.Reads == nil {- p.Reads = []string{}+ if spec := w.Page; spec != nil {+ tok := pageToken(e.Spec)+ rel, _ := filepath.Rel(spec.Dir, spec.File)+ p := pluginPage{Spec: e.Spec, Name: name, Key: key, Title: spec.Title, Titles: spec.Titles, Reads: reads, token: tok, dir: spec.Dir,+ URL: pluginPagePrefix + tok + "/" + filepath.ToSlash(rel)}+ if p.Title == "" {+ p.Title = plugin.ShortName(name)+ }+ if spec.Icon != "" {+ p.Icon = pluginPagePrefix + tok + "/" + spec.Icon+ }+ if r := spec.Replaces; r != "" && !replaced[r] {+ replaced[r] = true+ p.Replaces = r+ }+ pages = append(pages, p)}- if spec.Icon != "" {- p.Icon = pluginPagePrefix + tok + "/" + spec.Icon+ for i, spec := range w.Panels {+ tok := pageToken(e.Spec + "\x00panel\x00" + strconv.Itoa(i))+ rel, _ := filepath.Rel(spec.Dir, spec.File)+ p := pluginPanel{Spec: e.Spec, Name: name, Key: fmt.Sprintf("%s-%d", key, i), Slot: spec.Slot, Title: spec.Title, Titles: spec.Titles, Reads: reads,+ token: tok, dir: spec.Dir, URL: pluginPagePrefix + tok + "/" + filepath.ToSlash(rel)}+ if p.Title == "" {+ p.Title = plugin.ShortName(name)+ }+ panels = append(panels, p)}- out = append(out, p)}- return out+ return pages, panels+}++// pluginPages are the pages of the plugins that are on.+func pluginPages() []pluginPage {+ pages, _ := windowParts()+ return pages}-func pageOf(spec string) (pluginPage, bool) {- for _, p := range pluginPages() {+// windowOf is a plugin that is on and adds a page or a panel to the+// window: its package's name and the reads it declared.+func windowOf(spec string) (name string, reads []string, ok bool) {+ pages, panels := windowParts()+ for _, p := range pages {if p.Spec == spec {- return p, true+ return p.Name, p.Reads, true}}- return pluginPage{}, false+ for _, p := range panels {+ if p.Spec == spec {+ return p.Name, p.Reads, true+ }+ }+ return "", nil, false}// pagePolicy is what a plugin's page may load and reach: its own files,@@ -173,14 +228,20 @@ func servePluginPage(rw http.ResponseWriter, r *http.Request) {http.NotFound(rw, r)return}- var page *pluginPage- for _, p := range pluginPages() {+ // the page's or the panel's folder, by its token+ dir := ""+ pages, panels := windowParts()+ for _, p := range pages {+ if hmac.Equal([]byte(p.token), []byte(tok)) {+ dir = p.dir+ }+ }+ for _, p := range panels {if hmac.Equal([]byte(p.token), []byte(tok)) {- page = &p- break+ dir = p.dir}}- if page == nil {+ if dir == "" {http.NotFound(rw, r)return}@@ -197,7 +258,7 @@ func servePluginPage(rw http.ResponseWriter, r *http.Request) {http.ServeContent(rw, r, "bridge.js", time.Time{}, strings.NewReader(string(pageBridgeJS)))return}- file, ok := page.spec.PageFile(rel)+ file, ok := plugin.FileIn(dir, rel)if !ok {http.NotFound(rw, r)return@@ -246,8 +307,15 @@ func pluginPageRoutes(mux *http.ServeMux) {}writeJSON(rw, out)})- // what a page asked the window to read: only what its package- // declared, and never a secret+ mux.HandleFunc("GET /api/plugin-panels", func(rw http.ResponseWriter, r *http.Request) {+ _, out := windowParts()+ if out == nil {+ out = []pluginPanel{}+ }+ writeJSON(rw, out)+ })+ // what a page or a panel asked the window to read: only what its+ // package declared, and never a secretmux.HandleFunc("POST /api/plugin-pages/read", func(rw http.ResponseWriter, r *http.Request) {var in struct {Spec string `json:"spec"`@@ -258,15 +326,15 @@ func pluginPageRoutes(mux *http.ServeMux) {fail(rw, err)return}- p, ok := pageOf(in.Spec)+ name, reads, ok := windowOf(in.Spec)if !ok {fail(rw, errors.New("no plugin page "+in.Spec))return}- if !slices.Contains(p.Reads, in.Read) {+ if !slices.Contains(reads, in.Read) {rw.Header().Set("Content-Type", "application/json")rw.WriteHeader(http.StatusForbidden)- _ = json.NewEncoder(rw).Encode(map[string]string{"error": fmt.Sprintf("%s's package doesn't ask to read %q", p.Name, in.Read)})+ _ = json.NewEncoder(rw).Encode(map[string]string{"error": fmt.Sprintf("%s's package doesn't ask to read %q", name, in.Read)})return}v, err := pageRead(in.Read, in.Params)@@ -276,7 +344,8 @@ func pluginPageRoutes(mux *http.ServeMux) {}writeJSON(rw, v)})- // a page's own options, as plugins.json keeps them: no other plugin's+ // a page's or a panel's own options, as plugins.json keeps them: no+ // other plugin'smux.HandleFunc("POST /api/plugin-pages/options", func(rw http.ResponseWriter, r *http.Request) {var in struct {Spec string `json:"spec"`@@ -286,7 +355,7 @@ func pluginPageRoutes(mux *http.ServeMux) {fail(rw, err)return}- if _, ok := pageOf(in.Spec); !ok {+ if _, _, ok := windowOf(in.Spec); !ok {fail(rw, errors.New("no plugin page "+in.Spec))return}diff --git a/internal/gui/pluginpage_webkit_darwin_test.go b/internal/gui/pluginpage_webkit_darwin_test.gonew file mode 100644index 000000000..d98af7647--- /dev/null+++ b/internal/gui/pluginpage_webkit_darwin_test.go@@ -0,0 +1,84 @@+//go:build darwin && cgo && !nogui++package gui++import (+ "fmt"+ "net/http"+ "os"+ "strings"+ "testing"+ "time"++ "github.com/wailsapp/wails/v3/pkg/application"+ "github.com/wailsapp/wails/v3/pkg/events"+)++// A plugin's page in the real window: WKWebView serves it on wails://, not+// the http:// Playwright tests on, and its sandboxed frame has an origin of+// its own. Under pagePolicy, served as the app serves it (ownWindow names+// the scheme), its stylesheet and its scripts load there.+func TestPluginPageLoadsItsFilesInTheWindow(t *testing.T) {+ out, err := runAppKit(t, 30*time.Second, []string{"MAGPIE_TEST_PLUGIN_PAGE=1"})+ if err != nil || !strings.Contains(string(out), "plugin page: styled script") {+ t.Fatalf("plugin page: %v\n%s", err, out)+ }+}++func init() {+ if os.Getenv("MAGPIE_TEST_PLUGIN_PAGE") != "1" {+ return+ }+ const tok = "0123456789abcdef0123456789abcdef"+ seen := make(chan string, 1)+ app := application.New(application.Options{+ Name: "magpie plugin page regression",+ Mac: application.MacOptions{ActivationPolicy: application.ActivationPolicyProhibited},+ Assets: application.AssetOptions{Handler: ownWindow(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/seen":+ select {+ case seen <- r.URL.Query().Get("what"):+ default:+ }+ case "/":+ w.Header().Set("Content-Type", "text/html")+ fmt.Fprint(w, `<iframe sandbox="allow-scripts" src="`+pluginPagePrefix+tok+`/index.html"></iframe>+<script>addEventListener("message", (e) => fetch("/seen?what=" + encodeURIComponent(e.data)));+setTimeout(() => fetch("/seen?what=nothing"), 8000);</script>`)+ default:+ rel, ok := strings.CutPrefix(r.URL.Path, pluginPagePrefix+tok+"/")+ if !ok {+ http.NotFound(w, r)+ return+ }+ w.Header().Set("Content-Security-Policy", pagePolicy(r, tok))+ switch rel {+ case "index.html":+ w.Header().Set("Content-Type", "text/html")+ fmt.Fprint(w, `<!doctype html><link rel="stylesheet" href="style.css"><h1>x</h1><script src="app.js"></script>`)+ case "style.css":+ w.Header().Set("Content-Type", "text/css")+ fmt.Fprint(w, `h1 { color: rgb(1, 2, 3); }`)+ case "app.js":+ w.Header().Set("Content-Type", "text/javascript")+ fmt.Fprint(w, `addEventListener("load", () => parent.postMessage(+ (getComputedStyle(document.querySelector("h1")).color === "rgb(1, 2, 3)" ? "styled" : "unstyled") + " script", "*"));`)+ default:+ http.NotFound(w, r)+ }+ }+ }))},+ })+ app.Event.OnApplicationEvent(events.Common.ApplicationStarted, func(*application.ApplicationEvent) {+ app.Window.NewWithOptions(application.WebviewWindowOptions{Name: "main", Width: 300, Height: 200, URL: "/"})+ })+ go func() {+ fmt.Println("plugin page: " + <-seen)+ app.Quit()+ }()+ if err := app.Run(); err != nil {+ panic(err)+ }+ os.Exit(0)+}diff --git a/internal/gui/pluginpanel_test.go b/internal/gui/pluginpanel_test.gonew file mode 100644index 000000000..c3bf4d6c9--- /dev/null+++ b/internal/gui/pluginpanel_test.go@@ -0,0 +1,177 @@+package gui++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/yetone/magpie/internal/settings"+)++// copyTree copies a testdata folder to to.+func copyTree(t *testing.T, from, to string) {+ t.Helper()+ err := filepath.WalkDir(from, func(p string, d os.DirEntry, err error) error {+ if err != nil {+ return err+ }+ rel, _ := filepath.Rel(from, p)+ if d.IsDir() {+ return os.MkdirAll(filepath.Join(to, rel), 0o755)+ }+ b, err := os.ReadFile(p)+ if err != nil {+ return err+ }+ return os.WriteFile(filepath.Join(to, rel), b, 0o644)+ })+ if err != nil {+ t.Fatal(err)+ }+}++// panelPlugins writes plugins.json with the example panel plugin+// (testdata/panel-plugin), on and a copy switched off, and two copies of+// the example page plugin that each ask to replace Usage; it answers+// their specs in that order.+func panelPlugins(t *testing.T) (on, off, first, second string) {+ t.Helper()+ h := t.TempDir()+ t.Setenv("HOME", h)+ t.Setenv("USERPROFILE", h)+ t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))+ t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache"))+ t.Setenv("XDG_DATA_HOME", filepath.Join(h, ".local", "share"))+ t.Setenv("MAGPIE_BUN", "")+ t.Setenv("PATH", "")+ on, off = filepath.Join(h, "src", "notes"), filepath.Join(h, "src", "notes-off")+ first, second = filepath.Join(h, "src", "usage-a"), filepath.Join(h, "src", "usage-b")+ copyTree(t, "testdata/panel-plugin", on)+ copyTree(t, "testdata/panel-plugin", off)+ for i, dir := range []string{first, second} {+ copyTree(t, "testdata/page-plugin", dir)+ pkg := `{"name":"usage-` + string(rune('a'+i)) + `","version":"0.1.0","magpie":{"page":{"title":"Usage ` + string(rune('A'+i)) + `","file":"page/index.html","replaces":"usage"},"permissions":["usage:summary"]}}`+ if err := os.WriteFile(filepath.Join(dir, "package.json"), []byte(pkg), 0o644); err != nil {+ t.Fatal(err)+ }+ }+ if err := os.WriteFile(filepath.Join(h, "secret.txt"), []byte("SECRET"), 0o644); err != nil {+ t.Fatal(err)+ }+ if err := os.MkdirAll(settings.Dir(), 0o755); err != nil {+ t.Fatal(err)+ }+ b, _ := json.Marshal(map[string]any{"plugins": []map[string]any{{"spec": on}, {"spec": off, "off": true}, {"spec": first}, {"spec": second}}})+ if err := os.WriteFile(filepath.Join(settings.Dir(), "plugins.json"), b, 0o644); err != nil {+ t.Fatal(err)+ }+ return on, off, first, second+}++// A plugin's panels are listed with the page each goes in, and each is+// served by a token of its own, shut in as a page is: to its own folder,+// off the network, and none of a plugin switched off.+func TestPluginPanelsServedShutIn(t *testing.T) {+ on, off, _, _ := panelPlugins(t)+ h := pageMux()+ var panels []pluginPanel+ w := do(h, httptest.NewRequest("GET", "/api/plugin-panels", nil))+ if err := json.Unmarshal(w.Body.Bytes(), &panels); err != nil || len(panels) != 3 {+ t.Fatalf("panels: %s %v", w.Body, err)+ }+ want := []struct{ slot, title, key string }{+ {"provider", "Notes", "plugin-magpie-provider-notes-0"},+ {"usage", "Top models today", "plugin-magpie-provider-notes-1"},+ {"settings", "Provider notes", "plugin-magpie-provider-notes-2"},+ }+ toks := map[string]bool{}+ for i, p := range panels {+ if p.Spec != on || p.Slot != want[i].slot || p.Title != want[i].title || p.Key != want[i].key || len(p.Reads) != 1 || p.Reads[0] != "usage:summary" {+ t.Errorf("panel %d: %+v", i, p)+ }+ tok := strings.Split(strings.TrimPrefix(p.URL, pluginPagePrefix), "/")[0]+ if toks[tok] || tok == pageToken(on) {+ t.Errorf("panel %d shares a token: %s", i, tok)+ }+ toks[tok] = true+ r := httptest.NewRequest("GET", p.URL, nil)+ r.Host = "127.0.0.1:3437"+ w := do(h, r)+ if w.Code != 200 || !strings.Contains(w.Body.String(), "<html") {+ t.Fatalf("panel %d: %d %s", i, w.Code, w.Body)+ }+ csp := w.Header().Get("Content-Security-Policy")+ for _, want := range []string{"sandbox allow-scripts", "connect-src 'none'", "script-src 127.0.0.1:3437" + pluginPagePrefix + tok + "/;"} {+ if !strings.Contains(csp, want) {+ t.Errorf("panel %d: policy %q has no %q", i, csp, want)+ }+ }+ if strings.Contains(csp, "allow-same-origin") {+ t.Errorf("panel %d: policy %q lets it out", i, csp)+ }+ for _, path := range []string{pluginPagePrefix + tok + "/../package.json", pluginPagePrefix + tok + "/../../secret.txt"} {+ r := httptest.NewRequest("GET", "/", nil)+ r.URL.Path = path+ w := httptest.NewRecorder()+ servePluginPage(w, r)+ if w.Code == 200 || strings.Contains(w.Body.String(), "SECRET") || strings.Contains(w.Body.String(), `"name"`) {+ t.Errorf("%s: %d %s", path, w.Code, w.Body)+ }+ }+ }+ // the switched-off copy's panels, by the token they would have+ r := httptest.NewRequest("GET", "/", nil)+ r.URL.Path = pluginPagePrefix + pageToken(off+"\x00panel\x000") + "/notes.html"+ w = httptest.NewRecorder()+ servePluginPage(w, r)+ if w.Code == 200 {+ t.Errorf("a plugin switched off's panel: %d", w.Code)+ }+}++// A panels-only plugin reads what it declared and nothing else, through+// the same endpoint as a page, and sets its own options.+func TestPluginPanelsReadWhatTheyDeclared(t *testing.T) {+ on, off, _, _ := panelPlugins(t)+ h := pageMux()+ post := func(path, body string) *httptest.ResponseRecorder {+ r := httptest.NewRequest("POST", path, strings.NewReader(body))+ r.Header.Set("Content-Type", "application/json")+ return do(h, r)+ }+ spec, _ := json.Marshal(on)+ if w := post("/api/plugin-pages/read", `{"spec":`+string(spec)+`,"read":"providers:list"}`); w.Code != http.StatusForbidden {+ t.Errorf("an undeclared read: %d %s", w.Code, w.Body)+ }+ if w := post("/api/plugin-pages/read", `{"spec":`+string(spec)+`,"read":"usage:summary"}`); w.Code != 200 {+ t.Errorf("a declared read: %d %s", w.Code, w.Body)+ }+ offSpec, _ := json.Marshal(off)+ if w := post("/api/plugin-pages/read", `{"spec":`+string(offSpec)+`,"read":"usage:summary"}`); w.Code == 200 {+ t.Errorf("a plugin switched off read: %d", w.Code)+ }+ if w := post("/api/plugin-pages/options", `{"spec":`+string(spec)+`,"options":{"notes":{"openai":"work"}}}`); w.Code != 200 || !strings.Contains(w.Body.String(), `"openai":"work"`) {+ t.Errorf("options set: %d %s", w.Code, w.Body)+ }+}++// Two plugins asking to replace one built-in page: the first in+// plugins.json's order takes its place, the other is a page of its own.+func TestPluginPageReplacesFirstWins(t *testing.T) {+ _, _, first, second := panelPlugins(t)+ var pages []pluginPage+ w := do(pageMux(), httptest.NewRequest("GET", "/api/plugin-pages", nil))+ if err := json.Unmarshal(w.Body.Bytes(), &pages); err != nil || len(pages) != 2 {+ t.Fatalf("pages: %s %v", w.Body, err)+ }+ if pages[0].Spec != first || pages[0].Replaces != "usage" {+ t.Errorf("the first: %+v", pages[0])+ }+ if pages[1].Spec != second || pages[1].Replaces != "" {+ t.Errorf("the second: %+v", pages[1])+ }+}diff --git a/internal/gui/plugins.go b/internal/gui/plugins.goindex 2d358e12e..8f1093854 100644--- a/internal/gui/plugins.go+++ b/internal/gui/plugins.go@@ -141,6 +141,11 @@ type pluginEntryJSON struct {// switched off too: what the row shows before it is turned on, with// what the page may read of magpie'sPage *pluginPageInfoJSON `json:"page,omitempty"`+ // Panels are the panels it adds to magpie's own pages+ // (magpie.panels), said of one switched off too, and PanelReads what+ // they may read of magpie's+ Panels []pluginPanelInfoJSON `json:"panels,omitempty"`+ PanelReads []string `json:"panelReads,omitempty"`// Clashes are the providers it signs in to that another plugin signs// in to as well (a plugin of the user's own beside a third party's):// the host runs one plugin for each, and the row says which, with a@@ -161,8 +166,15 @@ type pluginToolJSON struct {// pluginPageInfoJSON is a plugin's page as its row says it.type pluginPageInfoJSON struct {- Title string `json:"title,omitempty"`- Reads []string `json:"reads"`+ Title string `json:"title,omitempty"`+ Replaces string `json:"replaces,omitempty"` // the built-in page it takes the place of+ Reads []string `json:"reads"`+}++// pluginPanelInfoJSON is a panel a plugin adds, as its row says it.+type pluginPanelInfoJSON struct {+ Slot string `json:"slot"`+ Title string `json:"title,omitempty"`}// pluginClashJSON is a provider two plugins sign in to, as a row says it.@@ -293,10 +305,19 @@ func pluginsState(ctx context.Context, w Windows) pluginsJSON {j.Agent = pluginAgentOf(e.Spec, agentErrs)}}- if pg, _ := plugin.WindowPage(plugin.Target(e.Spec)); pg != nil {- j.Page = &pluginPageInfoJSON{Title: pg.Title, Reads: pg.Reads}- if j.Page.Reads == nil {- j.Page.Reads = []string{}+ if w, _ := plugin.Window(plugin.Target(e.Spec)); w != nil {+ reads := w.Reads+ if reads == nil {+ reads = []string{}+ }+ if w.Page != nil {+ j.Page = &pluginPageInfoJSON{Title: w.Page.Title, Replaces: w.Page.Replaces, Reads: reads}+ }+ for _, p := range w.Panels {+ j.Panels = append(j.Panels, pluginPanelInfoJSON{Slot: p.Slot, Title: p.Title})+ }+ if len(w.Panels) > 0 {+ j.PanelReads = reads}j.InMagpieOnly = plugin.InMagpieOnly(plugin.Target(e.Spec))}diff --git a/internal/gui/testdata/panel-plugin/package.json b/internal/gui/testdata/panel-plugin/package.jsonnew file mode 100644index 000000000..ac9d8f735--- /dev/null+++ b/internal/gui/testdata/panel-plugin/package.json@@ -0,0 +1,13 @@+{+ "name": "magpie-provider-notes",+ "version": "0.1.0",+ "description": "An example of a plugin's panels in magpie's own pages: a note in each provider's editor, the top models on Usage, and its settings",+ "magpie": {+ "panels": [+ { "slot": "provider", "title": "Notes", "file": "ui/notes.html" },+ { "slot": "usage", "title": "Top models today", "file": "ui/spend.html" },+ { "slot": "settings", "title": "Provider notes", "file": "ui/settings.html" }+ ],+ "permissions": ["usage:summary"]+ }+}diff --git a/internal/gui/testdata/panel-plugin/ui/notes.html b/internal/gui/testdata/panel-plugin/ui/notes.htmlnew file mode 100644index 000000000..c59998a53--- /dev/null+++ b/internal/gui/testdata/panel-plugin/ui/notes.html@@ -0,0 +1,13 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<link rel="stylesheet" href="style.css">+<script src="_magpie/bridge.js"></script>+<script src="notes.js" defer></script>+</head>+<body>+<textarea id="note" aria-label="Note" placeholder="A note of your own about this provider"></textarea>+<p class="muted" id="saved"></p>+</body>+</html>diff --git a/internal/gui/testdata/panel-plugin/ui/notes.js b/internal/gui/testdata/panel-plugin/ui/notes.jsnew file mode 100644index 000000000..3f8e77c0e--- /dev/null+++ b/internal/gui/testdata/panel-plugin/ui/notes.js@@ -0,0 +1,19 @@+// A panel in each provider's editor: magpie.context.provider says which+// provider it is in, and the note is kept in the plugin's own options.+(async () => {+ await magpie.ready;+ const id = magpie.context.provider.id;+ let opts = await magpie.options.get();+ const box = document.getElementById("note");+ box.value = opts.notes?.[id] || "";+ let timer = 0;+ // options are set once a second at most: the last keystroke's, a+ // little after it+ box.oninput = () => {+ clearTimeout(timer);+ timer = setTimeout(async () => {+ opts = await magpie.options.set({ ...opts, notes: { ...opts.notes, [id]: box.value } });+ document.getElementById("saved").textContent = "Saved";+ }, 1200);+ };+})();diff --git a/internal/gui/testdata/panel-plugin/ui/settings.html b/internal/gui/testdata/panel-plugin/ui/settings.htmlnew file mode 100644index 000000000..29e616d3c--- /dev/null+++ b/internal/gui/testdata/panel-plugin/ui/settings.html@@ -0,0 +1,13 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<link rel="stylesheet" href="style.css">+<script src="_magpie/bridge.js"></script>+<script src="settings.js" defer></script>+</head>+<body>+<p id="count"></p>+<button type="button" id="clear">Clear every note</button>+</body>+</html>diff --git a/internal/gui/testdata/panel-plugin/ui/settings.js b/internal/gui/testdata/panel-plugin/ui/settings.jsnew file mode 100644index 000000000..9cb49f124--- /dev/null+++ b/internal/gui/testdata/panel-plugin/ui/settings.js@@ -0,0 +1,15 @@+// A panel on Settings' Plugins tab: how many notes there are, and a way to+// clear them.+(async () => {+ await magpie.ready;+ let opts = await magpie.options.get();+ const paint = () => {+ const n = Object.values(opts.notes || {}).filter(Boolean).length;+ document.getElementById("count").textContent = n === 1 ? "1 note" : `${n} notes`;+ };+ paint();+ document.getElementById("clear").onclick = async () => {+ opts = await magpie.options.set({ ...opts, notes: {} });+ paint();+ };+})();diff --git a/internal/gui/testdata/panel-plugin/ui/spend.html b/internal/gui/testdata/panel-plugin/ui/spend.htmlnew file mode 100644index 000000000..35ec5f172--- /dev/null+++ b/internal/gui/testdata/panel-plugin/ui/spend.html@@ -0,0 +1,13 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<link rel="stylesheet" href="style.css">+<script src="_magpie/bridge.js"></script>+<script src="spend.js" defer></script>+</head>+<body>+<ol id="top"></ol>+<p class="muted" id="none" hidden>No calls today</p>+</body>+</html>diff --git a/internal/gui/testdata/panel-plugin/ui/spend.js b/internal/gui/testdata/panel-plugin/ui/spend.jsnew file mode 100644index 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.cssnew file mode 100644index 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.cjsindex 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 providersif (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.cjsindex 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 onconst 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 = `<!doctype html><meta charset="utf-8"><script src="_magpie/bridge.js"></script><script src="probe.js"></script><p id="p">probe</p>`;+const PROBE_HTML = `<!doctype html><meta charset="utf-8"><script src="_magpie/bridge.js"></script><script src="probe.js"></script><style>.own { border-radius: 2px; }</style><h1>probe</h1><p id="p">probe</p><button id="b">b</button><button class="own">o</button>`;const PROBE_JS = `(async () => {const out = {};await magpie.ready;@@ -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 = `<!doctype html><meta charset="utf-8"><script src="_magpie/bridge.js"></script><script src="app.js"></script><p id="ok">drawn</p>`;@@ -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 atassert.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 awaydiff --git a/internal/gui/tests/plugin-panels.test.cjs b/internal/gui/tests/plugin-panels.test.cjsnew file mode 100644index 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 = `<!doctype html><meta charset="utf-8"><style>body{margin:0;padding:0}</style><script src="_magpie/bridge.js"></script><div id="box" style="height:180px">tall</div>`;+const BROKEN_HTML = `<!doctype html><meta charset="utf-8"><script src="_magpie/bridge.js"></script><script src="app.js"></script><p id="ok">drawn</p>`;+const LIB_HTML = `<!doctype html><meta charset="utf-8"><script src="_magpie/bridge.js"></script><p id="mine">my library</p>`;++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.goindex 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.goindex 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+ 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+ }}- 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)+ 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.goindex 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("<p>secret</p>"), 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("<p>hi</p>"), 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("<p>hi</p>"), 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.goindex 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.htmlindex 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<span class="s">"name"</span>: <span class="s">"magpie-usage-glance"</span>,<span class="s">"version"</span>: <span class="s">"0.1.0"</span>,<span class="s">"magpie"</span>: {- <span class="s">"page"</span>: { <span class="s">"title"</span>: <span class="s">"Usage glance"</span>, <span class="s">"file"</span>: <span class="s">"page/index.html"</span>, <span class="s">"icon"</span>: <span class="s">"page/icon.svg"</span> },+ <span class="s">"page"</span>: {+ <span class="s">"title"</span>: <span class="s">"Usage glance"</span>, <span class="s">"file"</span>: <span class="s">"page/index.html"</span>, <span class="s">"icon"</span>: <span class="s">"page/icon.svg"</span>,+ <span class="s">"titles"</span>: { <span class="s">"zh"</span>: <span class="s">"用量速览"</span>, <span class="s">"ja"</span>: <span class="s">"使用量の概要"</span> }+ },<span class="s">"permissions"</span>: [<span class="s">"usage:summary"</span>]}}</pre>@@ -831,7 +834,8 @@ document.getElementById(<span class="s">"calls"</span>).textContent = `${s.calls<span class="k">const</span> opts = <span class="k">await</span> magpie.options.get() <span class="c">// this plugin's own options</span><span class="k">await</span> magpie.options.set({ ...opts, hideCost: <span class="k">true</span> })</pre></div>- <p>プラグインページの行には、オンにする前からページと読めるものが表示されます。<code>page.file</code> と <code>page.icon</code> はプラグイン内のパスです。ページのファイルは <code>file</code> のフォルダにあるものだけで、外を指すパスやリンクは配信されません。1 つのパッケージがページとプロバイダ、ミドルウェア、エージェントを兼ねることもできます。ページだけのプラグインはプラグインホストを起動しません。</p>+ <p>プラグインページの行には、オンにする前からページと読めるものが表示されます。<code>page.file</code> と <code>page.icon</code> はプラグイン内のパスです。ページのファイルは <code>file</code> のフォルダにあるものだけで、外を指すパスやリンクは配信されません。1 つのパッケージがページとプロバイダ、ミドルウェア、エージェントを兼ねることもできます。ページだけのプラグインはプラグインホストを起動しません。<code>page.titles</code>(パネルでは <code>titles</code>)は、言語コード(<code>zh</code>、<code>zh-TW</code>、<code>ja</code>、<code>de</code>)ごとのタブ名です。ほかの言語では <code>title</code> を使います。</p>+ <p>ページがスタイルを付けていないところは、最初から magpie の見た目になります。bridge がフォント、色、見出し、ボタン、入力欄、表のスタイルシートを重みなし(<code>:where()</code>)で加えるので、ページ自身のルールが常に勝ちます。自分のスタイルでは <code>--magpie-*</code> 変数を使うとウィンドウに揃います。</p><h3>ページが頼めること</h3><div class="table-wrap"><table><tr><th>フィールド / 呼び出し</th><th>返すもの</th></tr>@@ -849,6 +853,38 @@ document.getElementById(<span class="s">"calls"</span>).textContent = `${s.calls<li>ページが捕まえなかったエラーは、その場所に<span class="ui">このページは動作を停止しました</span>と<span class="ui">再試行</span>を表示します。ページ自身のスクリプトのエラーはページには「Script error.」としか届かないので、詳しくはウィンドウのコンソールを見てください。</li></ul>+ <h3 id="panels"><a class="anchor" href="#panels">magpie 自身のページに入るパネル</a></h3>+ <p>プラグインは、magpie 自身が描くページにパネルを加えることもできます。パネルはそれぞれプラグインのフォルダーにある小さなページで、ブリッジ、読み取り、オプション、サンドボックスはページと同じです。タイトルの見出しの下のカードに収まり、高さは描いた内容に合わせて決まります。</p>+ <div class="code">+ <span class="lang">package.json</span>+ <button class="copy" data-copy="pn-pkg">コピー</button>+ <pre id="pn-pkg">{+ <span class="s">"name"</span>: <span class="s">"magpie-provider-notes"</span>,+ <span class="s">"version"</span>: <span class="s">"0.1.0"</span>,+ <span class="s">"magpie"</span>: {+ <span class="s">"panels"</span>: [+ { <span class="s">"slot"</span>: <span class="s">"provider"</span>, <span class="s">"file"</span>: <span class="s">"ui/notes.html"</span>, <span class="s">"title"</span>: <span class="s">"Notes"</span> },+ { <span class="s">"slot"</span>: <span class="s">"usage"</span>, <span class="s">"file"</span>: <span class="s">"ui/spend.html"</span>, <span class="s">"title"</span>: <span class="s">"Top models today"</span> }+ ],+ <span class="s">"permissions"</span>: [<span class="s">"usage:summary"</span>]+ }+}</pre>+ </div>+ <div class="table-wrap"><table>+ <tr><th><code>slot</code></th><th>パネルが入る場所</th><th><code>magpie.context</code></th></tr>+ <tr><td><code>agents</code></td><td>「エージェント」ページの末尾</td><td><code>{}</code></td></tr>+ <tr><td><code>usage</code></td><td>使用量の「概要」の末尾</td><td><code>{}</code></td></tr>+ <tr><td><code>settings</code></td><td>設定の「<span class="ui">プラグイン</span>」タブ(プラグインがそこにパネルを置いているときだけ表示)</td><td><code>{}</code></td></tr>+ <tr><td><code>provider</code></td><td>保存した各プロバイダーの編集画面</td><td><code>{ provider: { id, name } }</code></td></tr>+ </table></div>+ <p>パネルは 1 つのプラグインにつき 8 個まで。パネルの高さは <code><html></code> に合わせて決まる(最大 2400px)ので、ページ自身に高さを任せ、<code>html</code> や <code>body</code> に固定の高さを付けないでください。パネルがエラーを出すか 10 秒以内に応答しないと、その場所に「<span class="ui">{name} は動作を停止しました</span>」と「<span class="ui">再試行</span>」が表示されます。周りのページと隣のパネルはそのまま動き続けます。</p>+ <h3 id="replaces"><a class="anchor" href="#replaces">組み込みページの代わりになる</a></h3>+ <p>ページは magpie 自身のページの代わりになれます。<code>magpie.page</code> に <code>"replaces"</code> を加え、<code>sessions</code>、<code>library</code>、<code>routing</code>、<code>usage</code> のどれかを指定します。そのタブが組み込みページのあった場所に入り、そのページへのリンクはプラグインのページを開きます。2 つのプラグインが同じページを指定したときは、プラグイン一覧で先にあるほうが代わりになり、もう一方は独立したページになります。プラグインをオフにすると、組み込みページが元どおりに戻ります。</p>+ <div class="code">+ <span class="lang">package.json</span>+ <button class="copy" data-copy="pg-replaces">コピー</button>+ <pre id="pg-replaces"><span class="s">"page"</span>: { <span class="s">"title"</span>: <span class="s">"My library"</span>, <span class="s">"file"</span>: <span class="s">"page/index.html"</span>, <span class="s">"replaces"</span>: <span class="s">"library"</span> }</pre>+ </div><h2 id="pi"><a class="anchor" href="#pi">pi パッケージ</a></h2><p>magpie は <a href="https://github.com/earendil-works/pi">pi</a> のパッケージも動かします。<code>pi.registerProvider</code> でプロバイダを登録する pi 拡張は、何も変えずに pi と同じように magpie で動き、ほかのプラグインと同じ方法で追加できます(<code>magpie plugin add pi-antigravity</code>)。</p><ul>diff --git a/site/public/docs/plugins.html b/site/public/docs/plugins.htmlindex 9224a888b..bf4479bda 100644--- a/site/public/docs/plugins.html+++ b/site/public/docs/plugins.html@@ -808,7 +808,10 @@ claude mcp add --transport http magpie-tools http://127.0.0.1:3425/mcp/magpie/to<span class="s">"name"</span>: <span class="s">"magpie-usage-glance"</span>,<span class="s">"version"</span>: <span class="s">"0.1.0"</span>,<span class="s">"magpie"</span>: {- <span class="s">"page"</span>: { <span class="s">"title"</span>: <span class="s">"Usage glance"</span>, <span class="s">"file"</span>: <span class="s">"page/index.html"</span>, <span class="s">"icon"</span>: <span class="s">"page/icon.svg"</span> },+ <span class="s">"page"</span>: {+ <span class="s">"title"</span>: <span class="s">"Usage glance"</span>, <span class="s">"file"</span>: <span class="s">"page/index.html"</span>, <span class="s">"icon"</span>: <span class="s">"page/icon.svg"</span>,+ <span class="s">"titles"</span>: { <span class="s">"zh"</span>: <span class="s">"用量速览"</span>, <span class="s">"ja"</span>: <span class="s">"使用量の概要"</span> }+ },<span class="s">"permissions"</span>: [<span class="s">"usage:summary"</span>]}}</pre>@@ -831,7 +834,8 @@ document.getElementById(<span class="s">"calls"</span>).textContent = `${s.calls<span class="k">const</span> opts = <span class="k">await</span> magpie.options.get() <span class="c">// this plugin's own options</span><span class="k">await</span> magpie.options.set({ ...opts, hideCost: <span class="k">true</span> })</pre></div>- <p>The Plugins page shows the page, and what it may read, on the plugin’s row before it is turned on. <code>page.file</code> and <code>page.icon</code> are paths inside the plugin. The page’s files are what sits in <code>file</code>’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.</p>+ <p>The Plugins page shows the page, and what it may read, on the plugin’s row before it is turned on. <code>page.file</code> and <code>page.icon</code> are paths inside the plugin. The page’s files are what sits in <code>file</code>’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. <code>page.titles</code> (and a panel’s <code>titles</code>) names the tab in other languages, by language code (<code>zh</code>, <code>zh-TW</code>, <code>ja</code>, <code>de</code>); <code>title</code> is used for any other.</p>+ <p>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 (<code>:where()</code>), so any rule of the page’s own wins. Use the <code>--magpie-*</code> variables to match the window in your own styles.</p><h3>What the page can ask</h3><div class="table-wrap"><table><tr><th>Field / call</th><th>What it gives</th></tr>@@ -849,6 +853,38 @@ document.getElementById(<span class="s">"calls"</span>).textContent = `${s.calls<li>An error the page doesn’t catch shows <span class="ui">This page stopped working</span> in its place, with <span class="ui">Try again</span>. Its own scripts’ errors reach it as “Script error.”, so look in the window’s console for the rest.</li></ul>+ <h3 id="panels"><a class="anchor" href="#panels">Panels in magpie’s own pages</a></h3>+ <p>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.</p>+ <div class="code">+ <span class="lang">package.json</span>+ <button class="copy" data-copy="pn-pkg">Copy</button>+ <pre id="pn-pkg">{+ <span class="s">"name"</span>: <span class="s">"magpie-provider-notes"</span>,+ <span class="s">"version"</span>: <span class="s">"0.1.0"</span>,+ <span class="s">"magpie"</span>: {+ <span class="s">"panels"</span>: [+ { <span class="s">"slot"</span>: <span class="s">"provider"</span>, <span class="s">"file"</span>: <span class="s">"ui/notes.html"</span>, <span class="s">"title"</span>: <span class="s">"Notes"</span> },+ { <span class="s">"slot"</span>: <span class="s">"usage"</span>, <span class="s">"file"</span>: <span class="s">"ui/spend.html"</span>, <span class="s">"title"</span>: <span class="s">"Top models today"</span> }+ ],+ <span class="s">"permissions"</span>: [<span class="s">"usage:summary"</span>]+ }+}</pre>+ </div>+ <div class="table-wrap"><table>+ <tr><th><code>slot</code></th><th>Where the panel goes</th><th><code>magpie.context</code></th></tr>+ <tr><td><code>agents</code></td><td>The end of the Agents page</td><td><code>{}</code></td></tr>+ <tr><td><code>usage</code></td><td>The end of Usage’s Overview</td><td><code>{}</code></td></tr>+ <tr><td><code>settings</code></td><td>A <span class="ui">Plugins</span> tab in Settings, there only while a plugin has a panel in it</td><td><code>{}</code></td></tr>+ <tr><td><code>provider</code></td><td>Each saved provider’s editor</td><td><code>{ provider: { id, name } }</code></td></tr>+ </table></div>+ <p>A plugin has at most 8 panels. A panel’s height follows its <code><html></code> (up to 2400px), so let the page size itself and don’t give <code>html</code> or <code>body</code> a fixed height. A panel that throws, or doesn’t answer in 10 seconds, shows <span class="ui">{name} stopped working</span> with <span class="ui">Try again</span> in its own place; the page around it and the panels beside it go on.</p>+ <h3 id="replaces"><a class="anchor" href="#replaces">Taking a built-in page’s place</a></h3>+ <p>A page can take the place of one of magpie’s own: add <code>"replaces"</code> to <code>magpie.page</code>, one of <code>sessions</code>, <code>library</code>, <code>routing</code> or <code>usage</code>. 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.</p>+ <div class="code">+ <span class="lang">package.json</span>+ <button class="copy" data-copy="pg-replaces">Copy</button>+ <pre id="pg-replaces"><span class="s">"page"</span>: { <span class="s">"title"</span>: <span class="s">"My library"</span>, <span class="s">"file"</span>: <span class="s">"page/index.html"</span>, <span class="s">"replaces"</span>: <span class="s">"library"</span> }</pre>+ </div><h2 id="pi"><a class="anchor" href="#pi">pi packages</a></h2><p>magpie also runs <a href="https://github.com/earendil-works/pi">pi</a>’s packages. A pi extension that registers a provider with <code>pi.registerProvider</code> works in magpie as it does in pi, with nothing to change, and is added like any plugin (<code>magpie plugin add pi-antigravity</code>).</p><ul>diff --git a/site/public/docs/zh/plugins.html b/site/public/docs/zh/plugins.htmlindex 75456bb09..f396c0098 100644--- a/site/public/docs/zh/plugins.html+++ b/site/public/docs/zh/plugins.html@@ -808,7 +808,10 @@ claude mcp add --transport http magpie-tools http://127.0.0.1:3425/mcp/magpie/to<span class="s">"name"</span>: <span class="s">"magpie-usage-glance"</span>,<span class="s">"version"</span>: <span class="s">"0.1.0"</span>,<span class="s">"magpie"</span>: {- <span class="s">"page"</span>: { <span class="s">"title"</span>: <span class="s">"Usage glance"</span>, <span class="s">"file"</span>: <span class="s">"page/index.html"</span>, <span class="s">"icon"</span>: <span class="s">"page/icon.svg"</span> },+ <span class="s">"page"</span>: {+ <span class="s">"title"</span>: <span class="s">"Usage glance"</span>, <span class="s">"file"</span>: <span class="s">"page/index.html"</span>, <span class="s">"icon"</span>: <span class="s">"page/icon.svg"</span>,+ <span class="s">"titles"</span>: { <span class="s">"zh"</span>: <span class="s">"用量速览"</span>, <span class="s">"ja"</span>: <span class="s">"使用量の概要"</span> }+ },<span class="s">"permissions"</span>: [<span class="s">"usage:summary"</span>]}}</pre>@@ -831,7 +834,8 @@ document.getElementById(<span class="s">"calls"</span>).textContent = `${s.calls<span class="k">const</span> opts = <span class="k">await</span> magpie.options.get() <span class="c">// this plugin's own options</span><span class="k">await</span> magpie.options.set({ ...opts, hideCost: <span class="k">true</span> })</pre></div>- <p>插件打开之前,插件页面就会在它的那一行显示这个页面和它能读什么。<code>page.file</code> 和 <code>page.icon</code> 是插件里面的路径;页面的文件就是 <code>file</code> 所在文件夹里的文件,指向外面的路径或链接不会被提供。一个包可以同时是页面、供应商、中间件或 agent。只有页面的插件不会启动插件宿主。</p>+ <p>插件打开之前,插件页面就会在它的那一行显示这个页面和它能读什么。<code>page.file</code> 和 <code>page.icon</code> 是插件里面的路径;页面的文件就是 <code>file</code> 所在文件夹里的文件,指向外面的路径或链接不会被提供。一个包可以同时是页面、供应商、中间件或 agent。只有页面的插件不会启动插件宿主。<code>page.titles</code>(以及面板的 <code>titles</code>)按语言代码(<code>zh</code>、<code>zh-TW</code>、<code>ja</code>、<code>de</code>)给出其他语言里的标签名,其余语言用 <code>title</code>。</p>+ <p>页面没写样式的地方本来就是 magpie 的样子:bridge 会加一份样式表,管字体、颜色、标题、按钮、输入框和表格,权重为零(<code>:where()</code>),页面自己的任何规则都会盖过它。自己写样式时,用 <code>--magpie-*</code> 变量和窗口保持一致。</p><h3>页面能请求什么</h3><div class="table-wrap"><table><tr><th>字段 / 调用</th><th>给出什么</th></tr>@@ -849,6 +853,38 @@ document.getElementById(<span class="s">"calls"</span>).textContent = `${s.calls<li>页面没接住的错误会在它的位置显示<span class="ui">此页面已停止工作</span>和<span class="ui">重试</span>。它自己脚本的错误在页面里只显示为“Script error.”,详细内容看窗口的控制台。</li></ul>+ <h3 id="panels"><a class="anchor" href="#panels">放进 magpie 自己页面里的面板</a></h3>+ <p>插件还可以往 magpie 自己画的页面里加面板。每个面板是插件文件夹里的一个小页面,桥接脚本、读取、选项和沙盒都跟页面一样。它放在一张卡片里,上面是它的标题,高度随它画出来的内容。</p>+ <div class="code">+ <span class="lang">package.json</span>+ <button class="copy" data-copy="pn-pkg">复制</button>+ <pre id="pn-pkg">{+ <span class="s">"name"</span>: <span class="s">"magpie-provider-notes"</span>,+ <span class="s">"version"</span>: <span class="s">"0.1.0"</span>,+ <span class="s">"magpie"</span>: {+ <span class="s">"panels"</span>: [+ { <span class="s">"slot"</span>: <span class="s">"provider"</span>, <span class="s">"file"</span>: <span class="s">"ui/notes.html"</span>, <span class="s">"title"</span>: <span class="s">"Notes"</span> },+ { <span class="s">"slot"</span>: <span class="s">"usage"</span>, <span class="s">"file"</span>: <span class="s">"ui/spend.html"</span>, <span class="s">"title"</span>: <span class="s">"Top models today"</span> }+ ],+ <span class="s">"permissions"</span>: [<span class="s">"usage:summary"</span>]+ }+}</pre>+ </div>+ <div class="table-wrap"><table>+ <tr><th><code>slot</code></th><th>面板放在哪里</th><th><code>magpie.context</code></th></tr>+ <tr><td><code>agents</code></td><td>「Agent」页面的末尾</td><td><code>{}</code></td></tr>+ <tr><td><code>usage</code></td><td>用量「概览」的末尾</td><td><code>{}</code></td></tr>+ <tr><td><code>settings</code></td><td>设置里的「<span class="ui">插件</span>」标签页,有插件在这里放了面板时才出现</td><td><code>{}</code></td></tr>+ <tr><td><code>provider</code></td><td>每个已保存 Provider 的编辑页</td><td><code>{ provider: { id, name } }</code></td></tr>+ </table></div>+ <p>一个插件最多 8 个面板。面板的高度跟随它的 <code><html></code>(最高 2400px),所以让页面自己决定高度,不要给 <code>html</code> 或 <code>body</code> 固定高度。面板出错,或 10 秒内没有应答,就在它自己的位置显示「<span class="ui">{name} 已停止工作</span>」和「<span class="ui">重试</span>」;所在的页面和旁边的面板照常运行。</p>+ <h3 id="replaces"><a class="anchor" href="#replaces">替代一个内置页面</a></h3>+ <p>页面可以替代 magpie 自己的某个页面:在 <code>magpie.page</code> 里加上 <code>"replaces"</code>,取 <code>sessions</code>、<code>library</code>、<code>routing</code> 或 <code>usage</code> 之一。它的标签就出现在内置页面原来的位置,指向那个页面的链接都会打开插件的页面。两个插件要替代同一个页面时,插件列表里排在前面的那个替代,另一个作为独立页面。关掉插件,内置页面就原样回来。</p>+ <div class="code">+ <span class="lang">package.json</span>+ <button class="copy" data-copy="pg-replaces">复制</button>+ <pre id="pg-replaces"><span class="s">"page"</span>: { <span class="s">"title"</span>: <span class="s">"My library"</span>, <span class="s">"file"</span>: <span class="s">"page/index.html"</span>, <span class="s">"replaces"</span>: <span class="s">"library"</span> }</pre>+ </div><h2 id="pi"><a class="anchor" href="#pi">pi 扩展包</a></h2><p>magpie 也运行 <a href="https://github.com/earendil-works/pi">pi</a> 的扩展包。用 <code>pi.registerProvider</code> 注册了供应商的 pi 扩展,在 magpie 里和在 pi 里一样工作,不用改任何东西,添加方式和其他插件相同(<code>magpie plugin add pi-antigravity</code>)。</p><ul>