From 64b0f3a201b7dd4f062ab746f1ff77a259910ebd Mon Sep 17 00:00:00 2001 From: yetone Date: Thu, 15 Oct 2026 19:15:34 +0800 Subject: [PATCH] plugins: a community plugin's own page in magpie's window, shut in a sandboxed frame (P4) A plugin's package.json may declare magpie.page {title, file, icon} and magpie.permissions.reads. While the plugin is on, its page gets a tab in a "Plugins" group after the built-in pages, drawn in an iframe sandboxed to allow-scripts only (an opaque origin: no cookie, no storage, no parent). Its files come from /_magpie/plugin// (HMAC of the spec with a per-process secret) under a CSP with connect-src 'none' and frame-ancestors 'self'; a path that leaves the page's folder, a symlink out, or an off plugin's token is refused. The window's postMessage bridge answers only that frame (event.source checked) with theme and language, the plugin's own options.get/set (throttled), and the reads it declared; any other read is refused in the window and again by the server, and no read carries a secret. /api refuses Origin: null and frame/iframe fetch-dest requests (noFramedAPI), so the frame never reaches the GUI's API even with the cookie. A page that throws or never says hello shows the kernel's broken-page state with Try again. The Plugins page shows the page and what it reads before the plugin is turned on. Docs: gui-shell.md, plugin-runtime.md (P4 section), site docs en/zh/ja with an example plugin; i18n zh, zh-TW, ja, de; fixture in internal/gui/testdata/page-plugin. Run (worktree at base 4df1ba0c6, -p 2, one package at a time): - go test -count=1 -timeout 45m: internal/gui ok, internal/plugin ok, internal/pluginrt ok, plugins/... (budget groups middleware otel redact rotation search) ok. - gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows clean. - Playwright (chromium + webkit, 5 languages, narrow widths): plugin-page 4/4, plugin-kernel 4/4, builtins 4/4, i18n-keys, gui-de, gui-ja, gui-zh-tw 3/3, plugin-middleware 24/24, plugin-own-icon 22/22, plugin-options 22/22, plugin-local 8/8, plugin-agent 22/22, click-scroll 22/22. Broken by hand, each went red: CSP without connect-src; apiFramed always false; the server's read check removed; the noFramedAPI wrap removed from api.go (red through the real Handler); inside() letting every path through; CORP same-origin re-added; in JS the client read check removed, the ev.source check removed, and allow-same-origin added to the sandbox. Without the Array.isArray guard on /api/plugin-pages, plugin-kernel, builtins and plugin-middleware/own-icon/options went red (their mocks answer a non-list) - that was found by the run, then fixed. Real use: built magpie, `magpie web` on 127.0.0.1:3472 (gateway 3471) in a sandbox HOME with the example plugin added. curl: the page file loads with the CSP and no cookie, traversal and a bad token are 404, /api with Origin: null or Sec-Fetch-Dest: iframe is 403 even with the cookie, an undeclared read 403, a declared one 200. Chromium and WebKit at 1100 and 420: the page draws its declared read, the probe's fetch/absolute fetch/top access/undeclared read are all refused, an of /api is refused, no page errors. Real use found that a Cross-Origin-Resource-Policy: same-origin header blocked the frame's own files (its origin is opaque); it is gone and a test guards it. Not tried: the desktop (Wails) window. Market cards of plugins not yet installed don't show a page's reads. The Playwright suite mirrors the CSP in a mock route rather than the Go server (the Go tests and real use cover the server). --- docs/subsystems/gui-shell.md | 17 + docs/subsystems/plugin-runtime.md | 8 +- internal/gui/api.go | 15 +- internal/gui/assets/app.css | 5 + internal/gui/assets/app.js | 5 +- internal/gui/assets/i18n.js | 44 ++ internal/gui/assets/index.html | 1 + internal/gui/assets/kernel.js | 7 + internal/gui/assets/pluginpages.js | 200 +++++++++ internal/gui/assets/plugins.js | 30 +- internal/gui/pagebridge.js | 71 ++++ internal/gui/pluginpage.go | 391 ++++++++++++++++++ internal/gui/pluginpage_test.go | 253 ++++++++++++ internal/gui/plugins.go | 17 + .../gui/testdata/page-plugin/package.json | 9 + internal/gui/testdata/page-plugin/page/app.js | 16 + .../gui/testdata/page-plugin/page/icon.svg | 1 + .../gui/testdata/page-plugin/page/index.html | 17 + .../gui/testdata/page-plugin/page/style.css | 4 + internal/gui/tests/plugin-page.test.cjs | 264 ++++++++++++ internal/gui/web.go | 7 + internal/plugin/agent.go | 9 +- internal/plugin/page.go | 141 +++++++ internal/plugin/page_test.go | 71 ++++ internal/plugin/store.go | 3 + site/public/docs/ja/plugins.html | 51 +++ site/public/docs/plugins.html | 51 +++ site/public/docs/zh/plugins.html | 51 +++ 28 files changed, 1744 insertions(+), 15 deletions(-) create mode 100644 internal/gui/assets/pluginpages.js create mode 100644 internal/gui/pagebridge.js create mode 100644 internal/gui/pluginpage.go create mode 100644 internal/gui/pluginpage_test.go create mode 100644 internal/gui/testdata/page-plugin/package.json create mode 100644 internal/gui/testdata/page-plugin/page/app.js create mode 100644 internal/gui/testdata/page-plugin/page/icon.svg create mode 100644 internal/gui/testdata/page-plugin/page/index.html create mode 100644 internal/gui/testdata/page-plugin/page/style.css create mode 100644 internal/gui/tests/plugin-page.test.cjs create mode 100644 internal/plugin/page.go create mode 100644 internal/plugin/page_test.go diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md index 416771bdc..08bccd672 100644 --- a/docs/subsystems/gui-shell.md +++ b/docs/subsystems/gui-shell.md @@ -307,6 +307,23 @@ posted and doesn't make the editor dirty. [`plugin-options.test.cjs`](../../internal/gui/tests/plugin-options.test.cjs) covers it. +### A plugin's own page + +A community plugin that declares `magpie.page` gets a tab in a Plugins +group at the sidebar's foot (`pluginpages.js`, loaded after `plugins.js`), +listed from `GET /api/plugin-pages` and again whenever Plugins reloads its +list (`window.loadPluginPages`). The tab's title is the plugin's own and is +not translated; `renderCrumb` and the sub-nav's label read its plain +`` where a built-in tab has `span[data-t]`. The frame is made the +first time the page opens and fills the view (`.view.plugin-page`, +`.plugin-frame`). The theme and language reach it on every change of +`data-theme`, `lang`, `class` or `style` on `:root`. A page gone off or +away loses its tab, and the window goes to Plugins if it was on it. The +security model, the bridge and the reads are in +[plugin-runtime.md](plugin-runtime.md#p4-community-plugins-at-every-point). +[`plugin-page.test.cjs`](../../internal/gui/tests/plugin-page.test.cjs) +covers it in both engines, every language and a narrow window. + ### Shared UI rules - Settings → General is laid out as macOS System Settings is (1ooogle on X): a row says its name alone when that says enough (Appearance, Colorblind mode, Language, Text size, the fonts, the tray click, the Codex model rows, Open at login, Show in Dock), and keeps one short line where the setting isn't clear from its name or has a consequence (Long conversations, Lightweight mode, Prevent sleep, Session terminal, Codex subagents). A font row's line shows only while its fonts load or fail; the text size keys are the choices' tooltip, and Colorblind mode's note is its Off/On control's (`#colorblindSegs`). Colorblind mode (`settings.Colorblind`, `data-colorblind="1"` on `:root`, #2073) switches the chart series (`--c1`…`--c7`) in both light and dark themes to an Okabe–Ito palette where adjacent series differ in hue and lightness. On a quota curve each window (`data-series`, its index mod 7, set by `drawQuotaPlot` and `quotaCurve`'s legend only) gets a dash of its own on `path.qc-line`, its legend key shows a sample of that line (`.qc-sample`) for the dot, and the even paces (`line.qc-even`) are dotted; the curve's tooltip says so. The balance curve sets no `data-series` and keeps its solid line, dashed fit and dot. The Context tab's "good" grade, which takes `--c2` as a colour rather than a series, keeps a blue (`--c1`). Language is one menu button showing the language picked, opened in the app's menu (`renderLangPick`). See `settings-general.test.cjs` and `quota-curve.test.cjs`. diff --git a/docs/subsystems/plugin-runtime.md b/docs/subsystems/plugin-runtime.md index 019a70b0e..a8af57b10 100644 --- a/docs/subsystems/plugin-runtime.md +++ b/docs/subsystems/plugin-runtime.md @@ -247,13 +247,15 @@ asks it. ## P4: community plugins at every point -P4 opens each gateway extension point to community plugins (OpenCode -plugins, npm packages in the plugin host), each behind the built-in plugin -that serves the point, so off still means off. +P4 opens each extension point, the gateway's and the window's, to +community plugins (OpenCode plugins, npm packages in the plugin host). A +gateway point stays behind the built-in plugin that serves it, so off +still means off; a page is its own plugin's to turn on and off. | Point | What a community plugin gives | Served by | Reference | | --- | --- | --- | --- | | Tool | Its OpenCode `tool` hook's tools, offered to every agent by magpie's MCP server at `/mcp/magpie/tools`, each named `_`, each call held to the calling key's limit and run in the host within 55s. Off, no tool is listed and a call says the plugin is off. | `plugins/tools` ("Plugin tools", Essential; `InUse` counts the plugins on that give tools, from `plugin-tools.json`), `gwtool.PluginTools` | [Plugin tools](plugin-tools.md) | +| A page in the window | `magpie.page {title, file, icon}` and `magpie.permissions` in package.json, installed from npm, GitHub or a folder like any plugin (`plugin.WindowPage`: `file` an .html inside the plugin, the icon in the page's folder, reads kept to `plugin.PageReads`). An on plugin's page gets a tab in the sidebar's Plugins group, after the built-in pages (`pluginpages.js`, a kernel `page` part). It runs in an iframe sandboxed to `allow-scripts`, its files served from `/_magpie/plugin//` (an HMAC of the spec with a secret of this run) under a policy of `sandbox allow-scripts`, its own folder only, `connect-src 'none'`. The frame talks to the window by `postMessage`: the window answers only its own frame (`ev.source`), with the theme, its own options (`/api/plugin-pages/options`, at most once a second, saved without restarting the host for a page-only plugin) and the reads it declared (`/api/plugin-pages/read`, checked again by the server): `usage:summary` (totals and the top 20 models) and `providers:list` (ids and names). Nothing secret is readable, since a page can still send its frame to another site. `noFramedAPI` turns away every `/api/` request a sandboxed frame or another site can send (`Origin: null`, `Sec-Fetch-Dest` a frame, a cross-site subresource), since the desktop window's API has no key; `webGuard` lets the prefix through without the cookie the frame never sends, and the token is the key. A page that throws, or doesn't say hello in 10s, is broken through the kernel (`ctx.broke`), with Try again. The Plugins page shows the page and its reads on the row before the plugin is on. A plugin that is only a page is in-magpie-only: no Bun host starts for it. Tests: `TestWindowPageStaysInside`, `TestPluginPageServedShutIn`, `TestPluginPageReadsWhatItDeclared`, `TestPluginPageNoAPI`, `TestPluginPageWebGuard`, `plugin-page.test.cjs`. Example: `internal/gui/testdata/page-plugin`. | the window, no built-in plugin: the page is the plugin's own on/off | [`page.go`](../../internal/plugin/page.go), [`pluginpage.go`](../../internal/gui/pluginpage.go), [`pagebridge.js`](../../internal/gui/pagebridge.js), [`pluginpages.js`](../../internal/gui/assets/pluginpages.js) | ## Source of truth and composing diff --git a/internal/gui/api.go b/internal/gui/api.go index e94d4b693..6944f2c37 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -789,6 +789,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { mux := http.NewServeMux() mux.Handle("/", devPage(revalidated(http.FileServer(http.FS(staticFS()))))) devRoutes(mux) + pluginPageRoutes(mux) // boot.js hands the page the saved language and theme before it paints: // they came only with the settings, so the tabs showed English first mux.HandleFunc("GET /boot.js", func(rw http.ResponseWriter, r *http.Request) { @@ -2183,7 +2184,19 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { }) agentModelsAPI(mux) devListen(mux) - return held(mux) + return noFramedAPI(held(mux)) +} + +// noFramedAPI turns away a request for /api that no page of the window's +// own makes (apiFramed): a plugin's page in its frame among them. +func noFramedAPI(h http.Handler) http.Handler { + return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { + if apiFramed(r) { + http.Error(rw, "magpie's API answers magpie's own window only", http.StatusForbidden) + return + } + h.ServeHTTP(rw, r) + }) } // held has a page's reads share one build of the catalog, which every row diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 89870923c..71c2eca26 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -3083,6 +3083,11 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; } /* a plugin's page that broke (kernel.js): what broke, and Try again */ .slot-error .row { gap: 14px; padding: 12px 14px; } .slot-error .sub { margin-top: 2px; color: var(--fg-2); overflow-wrap: anywhere; } +/* a community plugin's page (pluginpages.js): its frame fills the page */ +.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; } +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; } .row.pref .sub { margin-top: 2px; color: var(--fg-2); } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 8cf84999c..29e070098 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -22264,7 +22264,7 @@ function navSubs() { }; at.after(box); } - box.setAttribute("aria-label", at.querySelector("span[data-t]")?.textContent || ""); + box.setAttribute("aria-label", (at.querySelector("span[data-t]") || at.querySelector("span"))?.textContent || ""); for (const s of box.querySelectorAll(".nav-s")) s.remove(); items.forEach((b, i) => { const [name, n] = b.textContent.trim().split(" · "); @@ -22363,7 +22363,8 @@ function renderCrumb(items) { let gl = b?.previousElementSibling; while (gl && !gl.matches(".nav-gl")) gl = gl.previousElementSibling; if (gl) parts.push(gl.textContent); - if (b) parts.push(b.querySelector("span[data-t]").textContent); + // a plugin's page's tab has its own title, not one translated here + if (b) parts.push((b.querySelector("span[data-t]") || b.querySelector("span"))?.textContent || ""); } const on = items.find((b) => b.classList.contains("on")); if (on) parts.push(on.textContent.trim().split(" · ")[0]); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index da9132396..3bfbb691f 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -792,6 +792,17 @@ const I18N = { "Recent calls at a time": "每次显示的最近调用", "How many of the gateway's recent calls the page shows, and how many more each Show more adds": "页面显示多少条网关最近的调用,以及每次“显示其余”再多显示多少条", "This page stopped working": "此页面已停止工作", + "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": "为侧边栏添加一个自己的页面。它与 magpie 的其余部分隔离运行,只能读取这一行列出的内容", + "your usage totals, by model": "你的用量合计(按模型)", + "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 的任何内容", + "{name}'s page didn't answer": "{name} 的页面没有响应", + "A page's options are an object": "页面的选项须是一个对象", + "{name} doesn't ask to read {what}": "{name} 没有声明读取 {what}", + "No such call: {what}": "没有这个调用:{what}", + "The page hit an error": "页面出错了", "Only what a gateway for other computers needs: no Agents or Library, nor this computer's agents' settings": "只显示给其他电脑当网关所需的内容:不显示 Agent 和资源库,也不显示本机 Agent 的设置", "Now on: magpie web was started with --gateway": "当前开启:magpie web 以 --gateway 启动", "Now on: no agents on this computer": "当前开启:本机没有 Agent", @@ -4382,6 +4393,17 @@ const I18N = { "Recent calls at a time": "每次顯示的最近呼叫", "How many of the gateway's recent calls the page shows, and how many more each Show more adds": "頁面顯示多少筆閘道最近的呼叫,以及每次「顯示其餘」再多顯示多少筆", "This page stopped working": "此頁面已停止運作", + "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": "為側邊欄加入一個自己的頁面。它與 magpie 的其餘部分隔離執行,只能讀取這一列列出的內容", + "your usage totals, by model": "你的用量合計(依模型)", + "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 的任何內容", + "{name}'s page didn't answer": "{name} 的頁面沒有回應", + "A page's options are an object": "頁面的選項須是一個物件", + "{name} doesn't ask to read {what}": "{name} 沒有宣告讀取 {what}", + "No such call: {what}": "沒有這個呼叫:{what}", + "The page hit an error": "頁面出錯了", "Only what a gateway for other computers needs: no Agents or Library, nor this computer's agents' settings": "只顯示給其他電腦當閘道所需的內容:不顯示 Agent 和資源庫,也不顯示本機 Agent 的設定", "Now on: magpie web was started with --gateway": "目前開啟:magpie web 以 --gateway 啟動", "Now on: no agents on this computer": "目前開啟:本機沒有 Agent", @@ -7944,6 +7966,17 @@ const I18N = { "Recent calls at a time": "一度に表示する最近の呼び出し", "How many of the gateway's recent calls the page shows, and how many more each Show more adds": "ページに表示するゲートウェイの最近の呼び出しの数と、「さらに表示」ごとに追加する数", "This page stopped working": "このページは動作を停止しました", + "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": "サイドバーに独自のページを追加します。magpie のほかの部分から切り離されて動き、この行に示されたものだけを読み取れます", + "your usage totals, by model": "使用量の合計(モデル別)", + "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 のものは何も読み取りません", + "{name}'s page didn't answer": "{name} のページが応答しませんでした", + "A page's options are an object": "ページのオプションはオブジェクトです", + "{name} doesn't ask to read {what}": "{name} は {what} の読み取りを宣言していません", + "No such call: {what}": "そのような呼び出しはありません:{what}", + "The page hit an error": "ページでエラーが起きました", "Only what a gateway for other computers needs: no Agents or Library, nor this computer's agents' settings": "他のコンピューターのゲートウェイに必要なものだけ:エージェント、ライブラリ、このコンピューターのエージェントの設定は表示しません", "Now on: magpie web was started with --gateway": "現在オン:magpie web が --gateway で起動されています", "Now on: no agents on this computer": "現在オン:このコンピューターにエージェントがありません", @@ -11520,6 +11553,17 @@ const I18N = { "Recent calls at a time": "Letzte Aufrufe auf einmal", "How many of the gateway's recent calls the page shows, and how many more each Show more adds": "Wie viele der letzten Aufrufe des Gateways die Seite zeigt und wie viele jedes „weitere anzeigen“ hinzufügt", "This page stopped working": "Diese Seite funktioniert nicht mehr", + "Page": "Seite", + "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": "Fügt der Seitenleiste eine eigene Seite hinzu. Sie läuft abgeschottet vom Rest von magpie und kann nur lesen, was diese Zeile nennt", + "your usage totals, by model": "deine Nutzungssummen, nach Modell", + "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", + "{name}'s page didn't answer": "Die Seite von {name} hat nicht geantwortet", + "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}", + "The page hit an error": "Die Seite hat einen Fehler", "Only what a gateway for other computers needs: no Agents or Library, nor this computer's agents' settings": "Nur, was ein Gateway für andere Computer braucht: keine Agenten oder Bibliothek, keine Einstellungen der Agenten auf diesem Computer", "Now on: magpie web was started with --gateway": "Jetzt an: magpie web wurde mit --gateway gestartet", "Now on: no agents on this computer": "Jetzt an: keine Agenten auf diesem Computer", diff --git a/internal/gui/assets/index.html b/internal/gui/assets/index.html index 4694a7ee6..5624cd254 100644 --- a/internal/gui/assets/index.html +++ b/internal/gui/assets/index.html @@ -455,6 +455,7 @@ + diff --git a/internal/gui/assets/kernel.js b/internal/gui/assets/kernel.js index b59eeee97..6f92d7ce9 100644 --- a/internal/gui/assets/kernel.js +++ b/internal/gui/assets/kernel.js @@ -25,6 +25,13 @@ // ctx.config has it onConfig(fn) { p.onConfig.push(fn); }, onDispose(fn) { p.disposers.push(fn); }, + // a page of the plugin's that broke after its hook returned (a + // frame's own error, one that never answered): it shows what broke, + // with a Try again, as a hook that throws does + broke(key, err) { + const page = pages.get(key); + if (page && page.plugin === p && !page.broken) fail(page, "open", [], err); + }, slots: { add: (slot, part) => add(p, slot, part) }, ui, }; diff --git a/internal/gui/assets/pluginpages.js b/internal/gui/assets/pluginpages.js new file mode 100644 index 000000000..7c88dd050 --- /dev/null +++ b/internal/gui/assets/pluginpages.js @@ -0,0 +1,200 @@ +// A community plugin's own page in the window (docs/subsystems/ +// plugin-runtime.md, P4): package.json's magpie.page, in a tab of the +// sidebar's Plugins group, after the built-in pages. The page runs in a +// frame sandboxed to scripts alone, in an origin of its own: it has no +// way to the window, to magpie's API (apiFramed) or to the network (its +// policy, pluginpage.go). What it asks of the window comes by message, +// from that frame only, and the window answers only what the page may: +// the theme, its own options, and the reads its package declared +// (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. +(() => { + if (mode !== "window") return; + // how long a page has to say hello before it is taken as broken + const HELLO_MS = 10e3; + const pages = new Map(); // key → { entry, frame, hello, timer } + let ctx = null; + 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"]; + function theme() { + const css = getComputedStyle(document.documentElement); + const tokens = {}; + for (const k of TOKENS) tokens[k] = css.getPropertyValue("--" + k).trim(); + const dark = document.documentElement.dataset.theme === "dark" + || (document.documentElement.dataset.theme !== "light" && matchMedia("(prefers-color-scheme: dark)").matches); + return { dark, lang: locale, tokens }; + } + + function post(win, msg) { win?.postMessage({ magpie: 1, ...msg }, "*"); } + + // the theme or the language changed: every page open is told + function pushTheme() { + const data = theme(); + for (const p of pages.values()) if (p.hello) post(p.frame?.contentWindow, { event: "theme", data }); + } + 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)); } + + // the page's frame, made the first time the page is opened (and again + // after Try again): a plugin's page costs nothing until it is looked at + function open(key) { + const p = pages.get(key); + if (!p) return undefined; + if (p.frame?.isConnected) return p.ready; + const main = $("#view-" + key); + const f = document.createElement("iframe"); + f.className = "plugin-frame"; + // scripts, and nothing else: no same origin (no cookie, no storage of + // the window's, no reach into it), no forms, popups or top navigation + f.setAttribute("sandbox", "allow-scripts"); + f.setAttribute("referrerpolicy", "no-referrer"); + f.setAttribute("allow", ""); + f.title = p.entry.title; + 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); + }); + main.replaceChildren(f); + return p.ready; + } + + async function answer(p, m) { + const e = p.entry; + switch (m.method) { + case "hello": + p.hello = true; + clearTimeout(p.timer); + p.said?.(); + return theme(); + case "theme": + return theme(); + case "options.get": + return api("plugin-pages/options", { spec: e.spec }); + case "options.set": { + const o = m.params?.options; + if (!o || typeof o !== "object" || Array.isArray(o)) throw new Error(t("A page's options are an object")); + return api("plugin-pages/options", { spec: e.spec, options: o }); + } + case "read": { + 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 })); + return api("plugin-pages/read", { spec: e.spec, read: name, params: m.params?.params || {} }); + } + } + throw new Error(t("No such call: {what}", { what: String(m.method) })); + } + + addEventListener("message", async (ev) => { + // only a page's own frame is listened to: another window's message, + // or one that names a page, is nothing + let key = "", p = null; + for (const [k, x] of pages) if (x.frame && ev.source === x.frame.contentWindow) { key = k; p = x; break; } + if (!p) 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"))); + return; + } + const src = ev.source; + try { + post(src, { id: m.id, result: await answer(p, m) }); + } catch (err) { + post(src, { id: m.id, error: String(err?.message || err) }); + } + }); + + // the sidebar's tab for each page, in a Plugins group of its own after + // the built-in pages + function tab(e) { + const b = document.createElement("button"); + b.dataset.view = e.key; + b.dataset.pluginPage = ""; + if (e.icon) { + const img = document.createElement("img"); + img.className = "nav-ic"; + img.src = e.icon; + img.alt = ""; + img.width = img.height = 16; + b.append(img); + } else { + const s = svg(PUZZLE, 16, 1.5); + s.classList.add("nav-ic"); + s.setAttribute("aria-hidden", "true"); + b.append(s); + } + b.append(el("span", "", e.title)); + b.onclick = () => { show(e.key); b.blur(); }; + return b; + } + + async function load() { + let list; + try { list = await api("plugin-pages"); } catch { return; } + // an answer that isn't a list is not known: the tabs drawn stay + if (!Array.isArray(list)) return; + const nav = $("#nav"); + const keys = new Set(list.map((e) => e.key)); + // a page whose plugin went off, or away: its tab goes, and the window + // leaves it if it was open + for (const b of nav.querySelectorAll("button[data-plugin-page]")) if (!keys.has(b.dataset.view)) b.remove(); + for (const [k, p] of pages) { + if (keys.has(k)) continue; + p.frame?.remove(); + p.frame = null; + p.gone = true; + if (view === k) show("plugins"); + } + let head = nav.querySelector(".nav-gl[data-plugin-pages]"); + if (!list.length) { head?.remove(); return; } + if (!head) { + head = el("span", "nav-gl", t("Plugins")); + head.dataset.pluginPages = ""; + head.dataset.en = "Plugins"; + head.setAttribute("data-t", ""); + nav.append(head); + } + let at = head; + for (const e of list) { + let p = pages.get(e.key); + 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) }); + } else if (p.entry.url !== e.url || p.gone) { + p.frame?.remove(); + p.frame = null; + } + p.gone = false; + p.entry = e; + const part = magpie.page(e.key); + if (part) part.title = e.title; + let b = nav.querySelector(`button[data-plugin-page][data-view="${e.key}"]`); + if (!b) b = tab(e); + b.classList.toggle("on", view === e.key); + at.after(b); + at = b; + } + // a reload of a plugin's page, or the one the window was left on, + // comes back to it once its tab is there + if (view === "agents" && !opened) { + opened = true; + let want = params.get("view") || ""; + if (!want) { try { want = localStorage.getItem("magpie.lastView") || ""; } catch { /* none kept */ } } + if (pages.has(want)) show(want); + } + } + let opened = false; + window.loadPluginPages = load; + load(); +})(); diff --git a/internal/gui/assets/plugins.js b/internal/gui/assets/plugins.js index 9050fc68d..340a2285b 100644 --- a/internal/gui/assets/plugins.js +++ b/internal/gui/assets/plugins.js @@ -39,6 +39,7 @@ const PLUG = "M6 2v3 M10 2v3 M4.5 5h7v2.5a3.5 3.5 0 0 1-7 0z M8 11v3"; const PIPE = "M1.5 8h3 M11.5 8h3 M4.5 4.5h7v7h-7z"; const TERM = "M2 3.5h12v9H2z M4.5 6.5l2 1.5-2 1.5 M8 9.5h3"; + const PAGE = "M2 3.5h12v9H2z M2 6h12 M4 4.75h.01"; const FOLDER = "M14.7 12.7a1.3 1.3 0 0 1-1.3 1.3H2.6a1.3 1.3 0 0 1-1.3-1.3V3.3A1.3 1.3 0 0 1 2.6 2h3.3l1.3 2h6.2a1.3 1.3 0 0 1 1.3 1.3z"; // a folder's path is its name whole, as plugin.Name: C:\Users\me@corp\… @@ -112,11 +113,13 @@ // subscription and serves its models; middleware ("mw") runs in the // gateway on every agent's requests and replies, whatever serves them; // an agent ("ag") is one magpie has no wiring of its own for, which it - // then connects as it does its own + // then connects as it does its own; a page ("pg") is a page of its own + // in the window's sidebar (pluginpages.js) const KINDS = { pv: [PLUG, "Provider", "Signs in to a subscription and serves its models"], mw: [PIPE, "Middleware", "Runs in magpie's gateway on the requests your agents send and on the replies"], ag: [TERM, "Agent", "Adds an agent magpie has no setup of its own for: pick its model on the Agents page and it goes through magpie"], + 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"], }; const kindOf = (l) => l.kind === "middleware" ? "mw" : l.kind === "agent" ? "ag" : "pv"; function kindChip(kind) { @@ -129,7 +132,7 @@ function logo(ic, big, kind) { const box = el("span", "pm-logo" + (big ? " big" : "")); if (ic) box.append(icon(ic)); - else box.append(glyph(kind === "mw" ? PIPE : kind === "ag" ? TERM : PUZZLE, big ? 22 : 17, 1.4)); + else box.append(glyph(kind === "mw" ? PIPE : kind === "ag" ? TERM : kind === "pg" ? PAGE : PUZZLE, big ? 22 : 17, 1.4)); return box; } @@ -145,6 +148,8 @@ try { mine = await api("plugins"); failed = ""; + // a plugin turned on or off brings its page's tab, or takes it + window.loadPluginPages?.(); } catch (e) { failed = e.message; } @@ -1017,6 +1022,7 @@ if (ag || e.isAgent) nm.append(kindChip("ag")); // a plugin of tools alone signs in to nothing: no Provider chip const toolsOnly = !!e.tools?.length && !e.providers?.length; + if (e.page) nm.append(kindChip("pg")); if (e.providers?.length || !(e.middlewareOnly || e.inMagpieOnly || toolsOnly || (mw && !e.isMiddleware) || (ag && !e.isAgent))) nm.append(kindChip("pv")); who.append(nm); const subs = subsOf(pkg); @@ -1048,8 +1054,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 || toolsOnly) && !e.providers.length) { - // only middleware, an agent or tools: its own line says what it does + } else if ((mw || ag || toolsOnly || e.page && e.inMagpieOnly) && !e.providers.length) { + // only middleware, an agent, tools or a page: 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(", ")) }); @@ -1063,10 +1069,12 @@ if (mw && !e.off && !ask) who.append(mwLine(mw)); if (ag && !e.off && !ask) who.append(agentLine(ag)); if (e.tools?.length && !e.off && !ask) who.append(toolsLine(e.tools)); + // off too: what its page may read is said before it is turned on + if (e.page && !ask) who.append(pageLine(e.page)); if (mw && !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" : ""), 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.isAgent && !e.isMiddleware ? "pg" : ""), 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 @@ -1241,6 +1249,18 @@ return d; } + // what a plugin's page may read of magpie's: what its package.json's + // magpie.permissions declares, each a read with no secret in it + const READS = { "usage:summary": "your usage totals, by model", "providers:list": "your providers' names" }; + 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"); + return d; + } + function mwLine(m) { const d = el("div", "sub pm-mw"); if (m.error) { diff --git a/internal/gui/pagebridge.js b/internal/gui/pagebridge.js new file mode 100644 index 000000000..d36cf9c1d --- /dev/null +++ b/internal/gui/pagebridge.js @@ -0,0 +1,71 @@ +// The page's side of a plugin page's messages to magpie's window +// (docs/subsystems/plugin-runtime.md, P4). A plugin's page loads it with +// ; it is served beside every +// page's own files. +// +// await magpie.ready the window's theme, once it has answered +// magpie.theme { dark, lang, tokens: { bg, fg, … } } +// magpie.onTheme(fn) fn(theme) on each change of it +// await magpie.options.get() the plugin's own options (plugins.json) +// 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 +// +// 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 +// error the page doesn't catch shows the window's "This page stopped +// working" in its place. +(() => { + const waiting = new Map(); + let next = 0; + const themed = []; + function call(method, params) { + const id = ++next; + return new Promise((resolve, reject) => { + waiting.set(id, { resolve, reject }); + parent.postMessage({ magpie: 1, id, method, params }, "*"); + }); + } + function paint(theme) { + const root = document.documentElement; + root.dataset.theme = theme.dark ? "dark" : "light"; + // the frame's canvas matches the window's, not a white sheet in dark + root.style.colorScheme = theme.dark ? "dark" : "light"; + root.lang = theme.lang || "en"; + for (const [k, v] of Object.entries(theme.tokens || {})) root.style.setProperty("--magpie-" + k, v); + } + addEventListener("message", (e) => { + if (e.source !== parent) return; + const m = e.data; + if (!m || m.magpie !== 1) return; + if (m.event === "theme") { + api.theme = m.data; + paint(m.data); + for (const fn of themed) { try { fn(m.data); } catch (err) { report(err); } } + return; + } + const w = waiting.get(m.id); + if (!w) return; + waiting.delete(m.id); + if (m.error) w.reject(new Error(m.error)); else w.resolve(m.result); + }); + function report(err) { + parent.postMessage({ magpie: 1, method: "error", params: { message: String(err?.message || err) } }, "*"); + } + // 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))); + addEventListener("unhandledrejection", (e) => report(e.reason)); + const api = { + theme: null, + onTheme(fn) { themed.push(fn); }, + options: { + get: () => call("options.get"), + set: (options) => call("options.set", { options }), + }, + read: (name, params) => call("read", { name, params }), + }; + api.ready = call("hello").then((theme) => { api.theme = theme; paint(theme); return theme; }); + window.magpie = api; +})(); diff --git a/internal/gui/pluginpage.go b/internal/gui/pluginpage.go new file mode 100644 index 000000000..1c0ab449c --- /dev/null +++ b/internal/gui/pluginpage.go @@ -0,0 +1,391 @@ +package gui + +import ( + "crypto/hmac" + "crypto/rand" + "crypto/sha256" + _ "embed" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "net/http" + "os" + "path/filepath" + "slices" + "strings" + "sync" + "time" + + "github.com/yetone/magpie/internal/plugin" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/usage" +) + +// 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 +// 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), +// and what it may read of magpie's it asks the window for, which asks +// /api/plugin-pages/read for the reads its package declared. + +// pluginPagePrefix is where a plugin's page's files are served: +// pluginPagePrefix + token + "/" + the file's path in the page's folder. +const pluginPagePrefix = "/_magpie/plugin/" + +// pluginBridgePath is the window's side of the page's messages, served +// beside every page's files: a page loads it as +// + + + +

Today

+

…

+

+ + + diff --git a/internal/gui/testdata/page-plugin/page/style.css b/internal/gui/testdata/page-plugin/page/style.css new file mode 100644 index 000000000..24840af15 --- /dev/null +++ b/internal/gui/testdata/page-plugin/page/style.css @@ -0,0 +1,4 @@ +body { margin: 0; padding: 16px; font: 13px/1.5 var(--magpie-font, system-ui); color: var(--magpie-fg); background: var(--magpie-bg); } +h1 { font-size: 15px; font-weight: 600; margin: 0 0 8px; } +p { margin: 0 0 4px; } +button { font: inherit; color: var(--magpie-accent); background: none; border: 0; padding: 0; cursor: pointer; } diff --git a/internal/gui/tests/plugin-page.test.cjs b/internal/gui/tests/plugin-page.test.cjs new file mode 100644 index 000000000..af2c37d73 --- /dev/null +++ b/internal/gui/tests/plugin-page.test.cjs @@ -0,0 +1,264 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A community plugin's own page in the window (pluginpages.js, P4): the +// example plugin (testdata/page-plugin) gets a tab in the sidebar's +// Plugins group and draws in a frame sandboxed to scripts, with the +// window's theme, its own options and the read it declared. The frame +// can't reach magpie's API: its policy stops the fetch, and with the +// policy gone the request it would send carries Origin: null, which +// apiFramed turns away (TestPluginPageNoAPI). A read it didn't declare is +// refused, and a message from another frame is nothing. A page that +// throws shows "This page stopped working" with Try again. The Plugins +// page says what a page may read before it is on. Every language, both +// engines, a narrow window. The API is faked here; the server's side is +// pluginpage_test.go. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const example = path.resolve(__dirname, "../testdata/page-plugin/page"); +const bridge = path.resolve(__dirname, "../pagebridge.js"); + +const GLANCE = "a".repeat(32), PROBE = "b".repeat(32), OPEN = "c".repeat(32), BROKEN = "d".repeat(32); +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` : "", +}); +const pages = [ + entry(GLANCE, "glance", "Usage glance", ["usage:summary"]), + entry(PROBE, "probe", "Probe", []), + entry(OPEN, "open", "Probe without a policy", []), + entry(BROKEN, "broken", "Broken", []), +]; + +// what pluginpage.go's pagePolicy sends, for this host +const policy = (tok) => { + const own = `magpie.test/_magpie/plugin/${tok}/`; + 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'", + "worker-src 'none'", "object-src 'none'", "form-action 'none'", "base-uri 'none'", "frame-ancestors 'self'", + ].join("; "); +}; + +// a page that tries every way out it has, and tells the window what came +// of each (its message has no magpie:1, so the window's bridge ignores it) +const PROBE_HTML = `

probe

`; +const PROBE_JS = `(async () => { + const out = {}; + await magpie.ready; + try { const r = await fetch("/api/state?probe=1"); out.fetch = "status " + r.status; } catch (e) { out.fetch = "refused"; } + try { out.storage = typeof localStorage.length; } catch (e) { out.storage = "refused"; } + try { out.cookie = document.cookie; } catch (e) { out.cookie = "refused"; } + 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; } + parent.postMessage({ probe: out }, "*"); +})();`; +const BROKEN_HTML = `

drawn

`; + +function server(lang, seen, plugins) { + return async (route) => { + const req = route.request(); + const url = new URL(req.url()); + const json = (data) => route.fulfill({ json: data }); + if (url.searchParams.get("probe")) { + seen.api.push(await req.allHeaders()); + return route.fulfill({ status: 403, body: "" }); + } + 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: [], 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(pages); + if (url.pathname === "/api/plugin-pages/read") { + const b = req.postDataJSON(); + seen.reads.push(b); + return json({ period: "today", calls: 12, errors: 0, input: 1000, output: 234, cost: 0.5, models: [] }); + } + 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(plugins); + if (url.pathname === "/api/plugins/market") return json({ listings: [], state: 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 headers = { "X-Content-Type-Options": "nosniff", "Referrer-Policy": "no-referrer", "Cache-Control": "no-cache" }; + if (tok !== OPEN) headers["Content-Security-Policy"] = policy(tok); + const type = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml" }[path.extname(rel)]; + let body; + if (rel === "_magpie/bridge.js") body = await fs.readFile(bridge); + else if (tok === GLANCE) body = await fs.readFile(path.join(example, rel)).catch(() => null); + else if ((tok === PROBE || tok === OPEN) && rel === "index.html") body = PROBE_HTML; + else if ((tok === PROBE || tok === OPEN) && rel === "probe.js") body = PROBE_JS; + else if (tok === BROKEN && rel === "index.html") body = BROKEN_HTML; + else if (tok === BROKEN && rel === "app.js") body = seen.broken ? "throw new Error('fixture: the page broke')" : "1"; + if (body == null) return route.fulfill({ status: 404, body: "" }); + return route.fulfill({ status: 200, headers: { ...headers, "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 plugins = { bun: true, bunVersion: "1.3.0", plugins: [ + { spec: "/x/magpie-usage-glance", providers: [], moved: [], inMagpieOnly: true, page: { title: "Usage glance", reads: ["usage:summary", "providers:list"] } }, + { spec: "/x/quiet-page", off: true, providers: [], moved: [], inMagpieOnly: true, page: { title: "Quiet", reads: [] } }, +] }; + +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-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); +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(`${engine}: a plugin's page draws in its frame, 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: 700 }, reducedMotion: "reduce" }); + const page = await context.newPage(); + page.setDefaultTimeout(8000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const seen = { api: [], reads: [], options: [] }; + await page.route("**/*", server(lang, seen, plugins)); + await page.goto("http://magpie.test/"); + + // the sidebar's Plugins group, after the built-in pages + const head = page.locator("#nav .nav-gl[data-plugin-pages]"); + await head.waitFor({ state: "attached" }); + assert.equal(await head.textContent(), await page.evaluate(() => t("Plugins")), where); + const tabs = page.locator("#nav button[data-plugin-page]"); + 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); + // no frame until the page is looked at + assert.equal(await page.locator("iframe.plugin-frame").count(), 0, `${where}: nothing loaded unseen`); + + // the example: its declared read, the theme, its options + await page.evaluate(() => show("plugin-glance")); + const glance = await frameReady(page, GLANCE); + assert.equal(await page.locator("#view-plugin-glance iframe").getAttribute("sandbox"), "allow-scripts", where); + await glance.waitForFunction(() => document.getElementById("cost").textContent === "$0.50"); + assert.equal(await glance.locator("#calls").textContent(), "12 calls, 1234 tokens", where); + assert.deepEqual(seen.reads.map((r) => [r.spec, r.read]), [["/x/glance", "usage:summary"]], where); + assert.equal(await glance.evaluate(() => document.documentElement.lang), lang, `${where}: the window's language`); + assert.equal(await glance.evaluate(() => document.documentElement.dataset.theme), "light", where); + await page.evaluate(() => { document.documentElement.dataset.theme = "dark"; }); + await glance.waitForFunction(() => document.documentElement.dataset.theme === "dark"); + assert.ok((await glance.evaluate(() => document.documentElement.style.getPropertyValue("--magpie-bg"))).length > 0, `${where}: the tokens`); + await glance.locator("#hide").click(); + await glance.waitForFunction(() => document.getElementById("cost").textContent === ""); + assert.deepEqual(seen.options.map((o) => [o.spec, o.options.hideCost]), [["/x/glance", true]], `${where}: its own options`); + // the frame fits the window + assert.ok(await page.evaluate(() => { const v = document.querySelector("#view-plugin-glance"); const f = v.querySelector("iframe"); return f.getBoundingClientRect().width <= v.clientWidth + 1 && v.scrollWidth <= v.clientWidth + 1 && f.getBoundingClientRect().height > 200; }), `${where}: fits`); + + if (lang === "en" && width === 1100) { + // every way out of the frame is shut; a read it didn't declare + // is refused before it reaches the server + const got = page.evaluate(() => new Promise((res) => addEventListener("message", (e) => { if (e.data?.probe) res(e.data.probe); }))); + await page.evaluate(() => show("plugin-probe")); + const probe = await got; + assert.equal(probe.fetch, "refused", `${where}: the policy stops a fetch of /api`); + assert.equal(probe.storage, "refused", `${where}: no storage`); + assert.equal(probe.cookie, "refused", `${where}: no cookie`); + assert.equal(probe.top, "refused", `${where}: no reach into the window`); + assert.equal(probe.read, "Probe doesn't ask to read usage:summary", where); + 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`); + + // with the policy gone, what the frame's fetch would send is what + // apiFramed turns away + const got2 = page.evaluate(() => new Promise((res) => addEventListener("message", (e) => { if (e.data?.probe) res(e.data.probe); }))); + await page.evaluate(() => show("plugin-open")); + const open = await got2; + assert.equal(open.fetch.startsWith("status") || open.fetch === "refused", true, where); + assert.equal(seen.api.length, 1, `${where}: the fetch went out`); + assert.equal(seen.api[0].origin, "null", `${where}: as Origin: null`); + assert.ok(!seen.api[0].cookie, `${where}: without a cookie`); + + // a message from another frame naming a page is nothing + const before = seen.reads.length; + await page.evaluate(() => { + const f = document.createElement("iframe"); + f.srcdoc = `