Files
magpie/internal/gui/pagebridge.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

164 lines
8.0 KiB
JavaScript

// 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
// <script src="_magpie/bridge.js"></script>; 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
// magpie.context where a panel is (P5): { provider: {
// id, name } } in a provider's editor,
// else {}; set once magpie.ready is
// magpie.onAction(fn) fn({ id, provider | agent: { id, name } })
// when one of its magpie.actions is picked
// in a row's menu (P6); one picked before
// fn was given waits for it
//
// 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
// 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 = [];
let acting = null;
const acted = [];
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;
}
if (m.event === "action") {
if (acting) act(m.data); else acted.push(m.data);
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
//
// 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));
function act(data) {
try { Promise.resolve(acting(data)).catch(report); } catch (err) { report(err); }
}
const api = {
theme: null,
context: {},
onTheme(fn) { themed.push(fn); },
onAction(fn) {
acting = fn;
for (const d of acted.splice(0)) act(d);
},
options: {
get: () => call("options.get"),
set: (options) => call("options.set", { options }),
},
read: (name, params) => call("read", { name, params }),
};
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;
})();