Files
magpie/internal/gui/assets/pluginpages.js
T
yetone d783df46cb plugin: a plugin's page adds items to a provider's and an agent's row menu (P6)
package.json's magpie.actions: [{id, menu, title, titles}] puts items in
the row menus magpie draws, after its own: a provider row's (right-click)
and an agent row's (its handle, or right-click). Picking one opens the
plugin's page and posts it {event: "action", data: {id, provider|agent:
{id, name}}}, nothing else of the row; the bridge's magpie.onAction(fn)
gets it, and an action picked before fn was given waits for it.

- plugin.Window reads them (page.go): menu one of ActionMenus (provider,
  agent; a session's menu is left out, its title is user content), id
  ^[a-z0-9][a-z0-9-]{0,39}$, an id given twice is the first's, 8 at most,
  none for a plugin with no page.
- /api/plugin-pages carries them on the page; a missing title is the
  page's, in each language (pluginpage.go).
- pluginpages.js: magpie.actions(menu, context) gives the row menu's
  items; openRowMenu draws a plugin's name as written (literal), not
  through t().
- The Plugins page says which menus a plugin adds to (actionsLine),
  translated in zh, zh-TW, ja and de.
- Docs: plugin-runtime.md's P6 section and verification; the site's
  plugin docs (en, zh, ja) gain "Items in magpie's menus".
- The core's budget (TestCoreScriptBudget) is not raised (#2710): with
  P6 the core came to 1,447,648 bytes, 648 over. pluginpages.js's header
  now says P5's and P6's part in one paragraph and points to
  plugin-runtime.md, which says it in full, and plugins.js's panels and
  actions lines share whereLine: 1,446,845, 155 under.

Run:
- Full: this series (P5, the Plugins dot, the probe test, P6, and a
  built-ins-on commit since dropped for main's own 5a2414acd) was run
  together, at load 200-660.
  At the pushed tree, 88dfab2d3 on origin/main 5380114da (rebased
  from 210bc2b77, no conflicts; its GUI assets and tests are the same
  bytes as the tree the GUI runs below used, diff -rq): gofmt clean,
  vet darwin/linux nogui/windows ok, TestCoreScriptBudget ok
  (1,446,845 of 1,447,000). go test -timeout 45m ./... at load
  193-278: 62 packages ok, red in TestMainWindowCorners (#1936) and
  TestPluginStreamLargeReplies JSON_fast (client timeout; alone 1 of
  3 red here, 0 of 3 on 5380114da side by side at load ~280; the
  series doesn't touch the stream path; #2551 reopened with the
  output, taken). Two earlier runs at this tree are discarded: one
  stopped when the disk filled, one when another session's go clean
  -cache emptied the build cache mid-run. The whole GUI suite at
  this tree was not finished (the disk filled); the files the series
  reaches ran (1318 tests, 124 red), and the 39 red files ran again
  at concurrency 1 on both trees: here 148 ok 120 red, origin/main
  135 ok 127 red. Both sides' reds are page.goto/launch timeouts
  under load (66 here, 71 there) and the same assertions:
  title-bar-tools' and settings-proxy-auth's "access control checks"
  on a cut-off /api/providers read (#2740, taken next), sidebar's
  "the list unrolls" and WebKit "#prefs pressed darkens" (#2684;
  alone, 1 red here, 3 on main), side-toggle (#2732); plugin-move
  red on main only. Six files again one by one on both trees:
  plugin-actions red 1 of 6 here, a 5s goto of ?view=plugins at load
  260; plugin-clash red on both; plugin-own-icon, plugin-gateway,
  plugin-checkin ok on both; settings-proxy-auth ok here, 3 red on
  main.
  At 976c9893a (on origin/main 6f950653f): go test -timeout 45m ./...
  red only in TestMainWindowCorners (#1936, the window's process
  killed at its deadline) and TestSetAnswersWhileDevinAndProvidersHang
  (#1375, 3 of 3 alone). The whole GUI suite, both engines: 10834
  tests, 237 red in 73 files, 184 of them a 180s browser launch. Those
  73 files run again at concurrency 2: 52 green, among them every
  plugin-* and agent-* file and plugin-actions; the 21 still red were
  run at origin/main f191d6423 and are red there too: codex-predictions
  (#2624), lightweight (#2638), segs-glide (#2683), usage-agents-hide
  (#2276), provider-advanced-fold (#2552), routing-bodies (#2559),
  routing-model-rest and rest-try-now (#2115, #2564), routing-keys-fold
  (#1612), routing-wb-restricted (#1905), routing-request-metrics
  (#2571), quota-count-wrap and quota-name-translated (#2228), s3-sync
  (#2448), usage-checkin (#2549), usage-ledger-abort (#2700),
  tencent-access-key (#2733), usage-range (#2734); side-toggle's WebKit
  motion red 1 of 3 on main, 0 of 3 here (#2732); usage-fold green alone.
  Rebased onto origin/main 717b69f78 (60725faa1, no conflicts): gofmt
  clean, vet darwin/linux nogui/windows ok; go test -timeout 45m ./...
  red in TestSetAnswersWhileDevinAndProvidersHang (#1375) and agent and
  gateway at the 45m alarm with tests still moving at load 400+, both ok
  alone (1173s, 1167s); 105 GUI files the series reaches (plugin*,
  sidebar*, side-*, settings*, title*, header*, agent-*): 1322 tests,
  23 red, run alone 214 of 218 ok, the 4 left in sidebar and
  sidebar-overlay-scrollbar (WebKit), red on 717b69f78 too (#2684,
  #1863). The whole GUI suite was not run again after the rebase.
- gofmt -l clean; go vet darwin, linux (-tags nogui) and windows ok;
  TestCoreScriptBudget ok.
- go test -run 'TestWindowActions|TestPluginPageActions' ok: duplicate,
  malformed and session-menu ids dropped, 12 actions kept to 8, none
  without a page, an off plugin's not served.
- plugin-actions.test.cjs: chromium and webkit, en zh zh-TW ja de, at
  1100 and 420: no page adds nothing; the agent menu ends with Hide then
  the plugin's item; the provider menu's item is in the window's
  language; a pick opens the page, which gets exactly {id, provider|
  agent: {id, name}} once, in one frame, though it calls onAction 400ms
  late. The Plugins row says which menus.
- Broken by hand, each red then restored: the bridge not holding an
  action picked before onAction (the late-registering fixture), the
  provider's whole row posted in place of {id, name} (the exact-data
  check), any id and any menu accepted (TestWindowActions).
- Neighbours in both engines: plugin-page, agent-cli-missing,
  agent-disconnect, group-bulk-remove, model-test-why and provider-find
  ok; plugin-panels red before P5's fixture fix (padding, in that
  commit), ok after.
- Real use: a dev build (-tags dev) in a sandbox HOME with a
  local plugin of two actions; WebKit on its dev UI picked "Inspect
  agent" on Claude Code and "Inspect provider" on a local provider, and
  the page logged {"id":"about-agent","agent":{"id":"claude","name":
  "Claude Code"}} then {"id":"about-provider","provider":{"id":
  "local-try","name":"Local Try"}}, one frame. Not clicked in the
  WKWebView window itself; the frame's loading there is
  TestPluginPageLoadsItsFilesInTheWindow's.
2026-10-18 07:13:12 +08:00

371 lines
15 KiB
JavaScript

// 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.
//
// Panels (magpie.panels, P5) are framed the same way in a page's
// .plugin-slot, as tall as they draw, and one that breaks says so in its
// place. A page may take a built-in one's place (magpie.page.replaces),
// and its actions (magpie.actions, P6) are row menu items that open it:
// plugin-runtime.md says the rest.
(() => {
if (mode !== "window") return;
// how long a page has to say hello before it is taken as broken
const HELLO_MS = 10e3;
const pages = new Map(); // key → { entry, frame, hello, timer }
const panels = new Map(); // frame → { entry, frame, context, hello, timer, body }
let panelList = []; // /api/plugin-panels: every panel of a plugin on
let ctx = null;
// a built-in page → the plugin's page in its place (magpie.page.replaces)
let replaced = new Map();
magpie.replacing = (v) => replaced.get(v) || v;
magpie.plugin("plugin-pages", (c) => { ctx = c; });
const TOKENS = ["bg", "card", "fg", "fg-2", "muted", "faint", "line", "accent", "accent-soft", "accent-fg", "green", "red", "amber", "font", "code"];
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(), ...panels.values()]) if (p.hello) post(p.frame?.contentWindow, { event: "theme", data });
}
new MutationObserver(pushTheme).observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme", "lang", "class", "style"] });
matchMedia("(prefers-color-scheme: dark)").addEventListener?.("change", pushTheme);
function broke(key, why) { ctx?.broke(key, new Error(why)); }
// a page's or a panel's title in the window's language: its titles
// (magpie.page.titles, {"zh": "…"}) by the language, then by its first
// part (zh for zh-TW), else its title
function titled(e) {
const m = e.titles || {};
return m[locale] || m[locale.split("-")[0]] || e.title;
}
// the page's frame, made the first time the page is opened (and again
// after Try again): a plugin's page costs nothing until it is looked at
function open(key) {
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 = 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: titled(p.entry) }))); }, 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?.();
// 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":
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: titled(e), 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) {
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") {
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;
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", "", 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
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();
// 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();
p.frame = null;
p.gone = true;
if (view === k) show("plugins");
}
let head = nav.querySelector(".nav-gl[data-plugin-pages]");
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";
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: 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;
}
p.gone = false;
p.entry = e;
const part = magpie.page(e.key);
if (part) part.title = titled(e);
let b = nav.querySelector(`button[data-plugin-page][data-view="${e.key}"]`);
if (!b) b = tab(e);
else b.querySelector("span").textContent = titled(e);
b.classList.toggle("on", view === e.key);
// in the place of the built-in page it replaces, which steps aside
// (and the reader on it is taken to the plugin's); else in the
// Plugins group
const built = e.replaces && nav.querySelector(`button[data-view="${e.replaces}"]:not([data-plugin-page])`);
if (built) {
built.dataset.replaced = e.key;
built.after(b);
if (view === e.replaces) show(e.key);
continue;
}
at.after(b);
at = b;
}
navSubs();
// a reload of a plugin's page, or the one the window was left on,
// comes back to it once its tab is there
if (view === "agents" && !opened) {
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;
// ---- actions ----
// the row menu's items for menu ("provider", "agent"), each told
// context: { provider: { id, name } } or { agent: { id, name } }
magpie.actions = (menu, context) => {
const items = [];
for (const [key, p] of pages) {
if (p.gone) continue;
for (const a of p.entry.actions || []) {
if (a.menu !== menu) continue;
items.push({ name: titled(a), literal: true, icon: PUZZLE, sep: !items.length, run: () => act(key, a.id, context) });
}
}
return items;
};
async function act(key, id, context) {
// a reader who keeps an unsaved edit where they are stays there
if (await show(key) === false) return;
const p = pages.get(key);
try { await open(key); } catch { return; } // its page says it broke
post(p?.frame?.contentWindow, { event: "action", data: { id, ...context } });
}
// ---- 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"] });
})();