Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
plugin: a plugin's page adds items to a provider's and an agent's row menu (P6)
yetoned783df46cbac
diff --git a/docs/subsystems/plugin-runtime.md b/docs/subsystems/plugin-runtime.mdindex 168faa264..8e38dbdc2 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), P4 (community plugins at each of those points) and P5 (community panels in magpie's own pages, and a plugin's page in a built-in's place). OpenCode plugins (npm packages in+the tool point, with web search; and the budget point, with key limits), P4 (community plugins at each of those points) P5 (community panels in magpie's own pages, and a plugin's page in a built-in's place) and P6 (a plugin's items in a provider's and an agent's row menu). 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).@@ -330,6 +330,43 @@ Tests: `TestWindowPanels`, `TestPluginPanelsServedShutIn`,`TestPluginPanelsReadWhatTheyDeclared`, `TestPluginPageReplacesFirstWins`,`plugin-panels.test.cjs`. Example: `internal/gui/testdata/panel-plugin`.+## P6: actions in magpie's menus++P6 lets a plugin's page add items to the row menus magpie draws: a+provider row's (right-click) and an agent row's (its handle, or+right-click). An item opens the plugin's page and tells it what was picked;+the page does the work. Read by `plugin.Window` with the rest of the window+manifest ([`page.go`](../../internal/plugin/page.go)); no Bun host.++- **The manifest.** `magpie.actions: [{id, menu, title, titles}]`. `menu`+ is one of `plugin.ActionMenus` (`provider`, `agent`); a session's menu is+ left out, since a session's title is the user's content. `id` matches+ `actionID` (`^[a-z0-9][a-z0-9-]{0,39}$`), an id given twice is the+ first's, and a plugin has 8 at most (`maxActions`). A plugin with no page+ has no actions: an action is a way into its page. A missing title is the+ page's, in each language (`windowParts` in+ [`pluginpage.go`](../../internal/gui/pluginpage.go)); `/api/plugin-pages`+ carries them on the page.+- **The menus.** `magpie.actions(menu, context)`+ ([`pluginpages.js`](../../internal/gui/assets/pluginpages.js)) gives the+ items, after magpie's own and a separator, named by `titled` and drawn+ as the plugin wrote them (`literal` in `openRowMenu`, not through `t()`).+ `openProviderMenu` passes `{provider: {id, name}}`, `openAgentMenu`+ `{agent: {id, name}}`, and nothing else of the row.+- **Picking one** runs `show(key)` (an unsaved edit the reader keeps+ stops it there), waits for the page's hello, and posts `{event:+ "action", data: {id, ...context}}` to that frame only. The bridge+ ([`pagebridge.js`](../../internal/gui/pagebridge.js)) hands it to+ `magpie.onAction(fn)`; an action that came before `fn` was given waits+ for it, and a throw in `fn` is the page's error ("stopped working").+- **The Plugins page** says on the row which menus a plugin adds to+ (`actionsLine` in [`plugins.js`](../../internal/gui/assets/plugins.js)),+ from the row's `actions` ([`plugins.go`](../../internal/gui/plugins.go)),+ said of a plugin switched off too.++Tests: `TestWindowActions`, `TestPluginPageActions`,+`plugin-actions.test.cjs`.+## Source of truth and composingWhat a plugin runs with is composed field by field (`Compose`), each value@@ -447,5 +484,10 @@ remembering its layer (`Source`):the size watch's loop notice, a replaced Library, the Settings tabcoming and going) in Chromium and WebKit, every language, 1100 and 420points (the Plugins page's rows at 980 and 420).+- P6: `go test ./internal/plugin/ -run TestWindowActions`,+ `go test ./internal/gui/ -run TestPluginPageActions` and+ `plugin-actions.test.cjs` (both menus, a page that gives its handler+ late, no plugin adding nothing, the Plugins row) in Chromium and WebKit,+ every language, 1100 and 420 points.- 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/gui/assets/app.js b/internal/gui/assets/app.jsindex afbbfdf2a..71452d638 100644--- a/internal/gui/assets/app.js+++ b/internal/gui/assets/app.js@@ -3566,6 +3566,7 @@ function openAgentMenu(anchor, a, inFold) {// everything magpie wrote comes out, what the user had goes back (Fate on Discord)...(a.wired ? [{ name: "Disconnect from magpie", icon: UNPLUG, sep: !reapply, tip: t(DISCONNECT_TIP, { agent: a.name }), run: () => askDisconnect(a) }] : []),{ name: "Hide", icon: EYE_OFF, sep: true, run: () => setAgentHidden(a, true) },+ ...magpie.actions?.("agent", { agent: { id: a.id, name: a.name } }) || [],];openRowMenu(anchor, acts);}@@ -3581,7 +3582,8 @@ function openRowMenu(anchor, acts) {b.type = "button";b.setAttribute("role", "menuitem");b.disabled = !!o.off;- b.append(svg(o.icon, 13, 1.5), el("span", "rm-name", t(o.name)));+ // a plugin's item (magpie.actions) is named in its own words+ b.append(svg(o.icon, 13, 1.5), el("span", "rm-name", o.literal ? o.name : t(o.name)));if (o.key) b.append(el("span", "rm-key", o.key));if (o.tip) b.title = o.tip;// an item that is off can say why, under its name and as its title@@ -5833,6 +5835,7 @@ function openProviderMenu(anchor, p) {{ name: "Move up", icon: MOVE_UP, key: ALT + "↑", off: k <= 0, run: () => stepProvider(p.id, -1) },{ name: "Move down", icon: MOVE_DOWN, key: ALT + "↓", off: k < 0 || k >= shown.length - 1, run: () => stepProvider(p.id, 1) },{ name: "Move to bottom", icon: MOVE_BOTTOM, key: ALT + SHIFT + "↓", off: i === on.length - 1, run: () => arrangeProvider(p.id, on.length - 1) },+ ...magpie.actions?.("provider", { provider: { id: p.id, name: p.name } }) || [],]);}diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.jsindex 06c497cdc..7d11c7fee 100644--- a/internal/gui/assets/i18n.js+++ b/internal/gui/assets/i18n.js@@ -836,6 +836,9 @@ const I18N = {"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 的任何内容",+ "Adds items to {where}, which open its page": "在{where}中添加菜单项,点击后打开它的页面",+ "providers' menus": "供应商的菜单",+ "agents' menus": "Agent 的菜单","the Agents page": "「Agent」页面","the Usage page": "「用量」页面","each provider's editor": "每个服务商的编辑页",@@ -4553,6 +4556,9 @@ const I18N = {"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 的任何內容",+ "Adds items to {where}, which open its page": "在{where}中加入選單項目,點選後打開它的頁面",+ "providers' menus": "供應商的選單",+ "agents' menus": "Agent 的選單","the Agents page": "「Agent」頁面","the Usage page": "「用量」頁面","each provider's editor": "每個服務商的編輯頁",@@ -8242,6 +8248,9 @@ const I18N = {"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 のものは何も読み取りません",+ "Adds items to {where}, which open its page": "{where}に項目を追加します。選ぶとそのページを開きます",+ "providers' menus": "プロバイダのメニュー",+ "agents' menus": "エージェントのメニュー","the Agents page": "「エージェント」ページ","the Usage page": "「使用量」ページ","each provider's editor": "各プロバイダーの編集画面",@@ -11945,6 +11954,9 @@ const I18N = {"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",+ "Adds items to {where}, which open its page": "Fügt {where} Einträge hinzu, die seine Seite öffnen",+ "providers' menus": "den Menüs der Anbieter",+ "agents' menus": "den Menüs der Agenten","the Agents page": "der Seite „Agenten“","the Usage page": "der Seite „Nutzung“","each provider's editor": "dem Editor jedes Anbieters",diff --git a/internal/gui/assets/pluginpages.js b/internal/gui/assets/pluginpages.jsindex eed6ba724..3b67be5e2 100644--- a/internal/gui/assets/pluginpages.js+++ b/internal/gui/assets/pluginpages.js@@ -10,17 +10,11 @@// 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.+// 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@@ -253,6 +247,30 @@}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'tdiff --git a/internal/gui/assets/plugins.js b/internal/gui/assets/plugins.jsindex e5b226dcc..f8044d014 100644--- a/internal/gui/assets/plugins.js+++ b/internal/gui/assets/plugins.js@@ -1196,6 +1196,7 @@// 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 (e.actions?.length && !ask) who.append(actionsLine(e.actions));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)@@ -1392,18 +1393,25 @@}// where a plugin's panels go in magpie's own pages (magpie.panels), and- // what they may read+ // the row menus its page adds items to (magpie.actions), titled with+ // their titles; picking an item tells the page the row's name onlyconst SLOTS = { agents: "the Agents page", usage: "the Usage page", settings: "Settings", provider: "each provider's editor" };- function panelsLine(panels, panelReads) {+ const MENUS = { provider: "providers' menus", agent: "agents' menus" };+ function whereLine(xs, key, names, text) {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;+ d.textContent = text([...new Set(xs.map((x) => x[key]))].map((s) => t(names[s] || s)).join(t(", ")));+ d.title = xs.map((x) => x.title).filter(Boolean).join("\n") || d.textContent;return d;}+ function panelsLine(panels, panelReads) {+ const reads = (panelReads || []).map((r) => t(READS[r] || r)).join(t(", "));+ return whereLine(panels, "slot", SLOTS, (where) => reads+ ? t("Adds panels to {where}, which can read {reads}", { where, reads })+ : t("Adds panels to {where}, which read nothing of magpie's", { where }));+ }+ function actionsLine(actions) {+ return whereLine(actions, "menu", MENUS, (where) => t("Adds items to {where}, which open its page", { where }));+ }function mwLine(m) {const d = el("div", "sub pm-mw");diff --git a/internal/gui/pagebridge.js b/internal/gui/pagebridge.jsindex a04aa1d4e..1316c3b2e 100644--- a/internal/gui/pagebridge.js+++ b/internal/gui/pagebridge.js@@ -13,6 +13,10 @@// 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.@@ -30,6 +34,8 @@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) => {@@ -55,6 +61,10 @@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);@@ -78,10 +88,17 @@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 }),diff --git a/internal/gui/pluginpage.go b/internal/gui/pluginpage.goindex fb682c03c..ed93103df 100644--- a/internal/gui/pluginpage.go+++ b/internal/gui/pluginpage.go@@ -76,8 +76,19 @@ type pluginPage struct {// plugin's in plugins.json's order to ask for itReplaces string `json:"replaces,omitempty"`Reads []string `json:"reads"` // what it may read, of plugin.PageReads- token string- dir string+ // Actions are its items in magpie's menus (plugin.ActionSpec); each+ // opens this page+ Actions []pluginAction `json:"actions,omitempty"`+ token string+ dir string+}++// pluginAction is an item a plugin's page adds to one of magpie's menus.+type pluginAction struct {+ ID string `json:"id"`+ Menu string `json:"menu"` // of plugin.ActionMenus+ Title string `json:"title"` // its own, or its page's+ Titles map[string]string `json:"titles,omitempty"`}// pluginPanel is a panel a plugin that is on adds to one of magpie's own@@ -143,6 +154,14 @@ func windowParts() (pages []pluginPage, panels []pluginPanel) {replaced[r] = truep.Replaces = r}+ for _, a := range w.Actions {+ act := pluginAction{ID: a.ID, Menu: a.Menu, Title: a.Title, Titles: a.Titles}+ // one that names no title is the page's own, in each language+ if act.Title == "" {+ act.Title, act.Titles = p.Title, p.Titles+ }+ p.Actions = append(p.Actions, act)+ }pages = append(pages, p)}for i, spec := range w.Panels {diff --git a/internal/gui/pluginpage_test.go b/internal/gui/pluginpage_test.goindex 622d43d8a..4753eb1f7 100644--- a/internal/gui/pluginpage_test.go+++ b/internal/gui/pluginpage_test.go@@ -251,3 +251,29 @@ func TestPluginPageWebGuard(t *testing.T) {t.Errorf("/api without the cookie: %d", w.Code)}}++// A page's actions (magpie.actions) come with it to the window, one that+// names no title by the page's own in each language; a plugin switched+// off adds no item to any menu.+func TestPluginPageActions(t *testing.T) {+ on, off := pagePlugins(t)+ for _, dir := range []string{on, off} {+ pkg := `{"name":"magpie-usage-glance","magpie":{"page":{"title":"Usage glance","titles":{"zh":"用量速览"},"file":"page/index.html"},+ "actions":[{"id":"check","menu":"provider","title":"Check balance","titles":{"ja":"残高を確認"}},{"id":"logs","menu":"agent"}]}}`+ if err := os.WriteFile(filepath.Join(dir, "package.json"), []byte(pkg), 0o644); err != nil {+ t.Fatal(err)+ }+ }+ 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) != 1 {+ t.Fatalf("pages: %s %v", w.Body, err)+ }+ a := pages[0].Actions+ if len(a) != 2 || a[0].ID != "check" || a[0].Menu != "provider" || a[0].Title != "Check balance" || a[0].Titles["ja"] != "残高を確認" {+ t.Fatalf("actions %+v", a)+ }+ if a[1].ID != "logs" || a[1].Menu != "agent" || a[1].Title != "Usage glance" || a[1].Titles["zh"] != "用量速览" {+ t.Errorf("an action with no title: %+v, want the page's", a[1])+ }+}diff --git a/internal/gui/plugins.go b/internal/gui/plugins.goindex 8f1093854..e4f0baaea 100644--- a/internal/gui/plugins.go+++ b/internal/gui/plugins.go@@ -146,6 +146,9 @@ type pluginEntryJSON struct {// they may read of magpie'sPanels []pluginPanelInfoJSON `json:"panels,omitempty"`PanelReads []string `json:"panelReads,omitempty"`+ // Actions are the items its page adds to magpie's menus+ // (magpie.actions), said of one switched off too+ Actions []pluginActionInfoJSON `json:"actions,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@@ -177,6 +180,13 @@ type pluginPanelInfoJSON struct {Title string `json:"title,omitempty"`}+// pluginActionInfoJSON is a menu item a plugin's page adds, as its row+// says it.+type pluginActionInfoJSON struct {+ Menu string `json:"menu"`+ Title string `json:"title,omitempty"`+}+// pluginClashJSON is a provider two plugins sign in to, as a row says it.type pluginClashJSON struct {plugin.Clash@@ -319,6 +329,9 @@ func pluginsState(ctx context.Context, w Windows) pluginsJSON {if len(w.Panels) > 0 {j.PanelReads = reads}+ for _, a := range w.Actions {+ j.Actions = append(j.Actions, pluginActionInfoJSON{Menu: a.Menu, Title: a.Title})+ }j.InMagpieOnly = plugin.InMagpieOnly(plugin.Target(e.Spec))}for _, c := range clashes[e.Spec] {diff --git a/internal/gui/tests/plugin-actions.test.cjs b/internal/gui/tests/plugin-actions.test.cjsnew file mode 100644index 000000000..e08b7c9c7--- /dev/null+++ b/internal/gui/tests/plugin-actions.test.cjs@@ -0,0 +1,170 @@+// Run with Node's test runner and Playwright on the module path; see README.md.+// A community plugin's actions (magpie.actions, pluginpages.js, P6): items+// its page adds to a provider's and an agent's row menu, after magpie's+// own, named in the plugin's words in the window's language. Picking one+// opens the plugin's page and tells it the action and that row's id and+// name, and nothing else of it; a page that gives magpie.onAction late+// still gets every action picked before. A page with no action adds+// nothing to a menu. The Plugins page says which menus a plugin adds to.+// Every language, both engines, a narrow window. The API is faked here;+// the server's side is TestWindowActions and 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 bridge = path.resolve(__dirname, "../pagebridge.js");++const TOK = "7".repeat(32);+const withActions = [{+ spec: "/x/magpie-row-tools", name: "magpie-row-tools", key: "plugin-row-tools", title: "Row tools", titles: { zh: "行工具" }, reads: [],+ url: `/_magpie/plugin/${TOK}/index.html`,+ actions: [+ { id: "check", menu: "provider", title: "Check balance", titles: { zh: "查余额", "zh-TW": "查餘額", ja: "残高を確認", de: "Guthaben prüfen" } },+ { id: "logs", menu: "agent", title: "Row tools", titles: { zh: "行工具" } },+ ],+}];+// the page gives its handler late: what was picked before waits for it+const HTML = `<!doctype html><meta charset="utf-8"><script src="_magpie/bridge.js"></script><ol id="got"></ol><script src="app.js"></script>`;+const JS = `setTimeout(() => magpie.onAction((a) => { const li = document.createElement("li"); li.textContent = JSON.stringify(a); document.getElementById("got").append(li); }), 400);`;++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 }));+const agents = [{ id: "codex", name: "Codex", icon: "generic", path: "/fixture/codex", fields: [{ key: "model", label: "model", value: "gpt-5.4", options: [{ value: "gpt-5.4", label: "gpt-5.4" }] }] }];++function server(lang, 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/agents/cli") return json({ agents: {}, pending: false });+ if (url.pathname === "/api/usage/quotas") return json([]);+ if (url.pathname === "/api/plugin-pages") return json(opts.pages);+ if (url.pathname === "/api/plugin-panels") return json([]);+ 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 rel = m[2];+ const body = rel === "_magpie/bridge.js" ? await fs.readFile(bridge) : rel === "index.html" ? HTML : rel === "app.js" ? JS : null;+ if (body == null) return route.fulfill({ status: 404, body: "" });+ const type = { ".html": "text/html", ".js": "text/javascript" }[path.extname(rel)];+ 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 want = { en: "Check balance", zh: "查余额", "zh-TW": "查餘額", ja: "残高を確認", de: "Guthaben prüfen" };+const got = async (page) => {+ const f = page.frames().find((x) => x.url().includes(TOK));+ if (!f) return [];+ return (await f.locator("#got li").allInnerTexts().catch(() => [])).map((x) => JSON.parse(x));+};+const menuNames = (page) => page.locator(".pop.row-menu .rm-item .rm-name").allInnerTexts();+const closeMenu = async (page) => { await page.keyboard.press("Escape"); await page.locator(".pop.row-menu").waitFor({ state: "detached" }); };++for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {+ test(`${engine}: a plugin's actions in the row menus open its page and tell it the row`, 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}`;+ for (const pages of [[], withActions]) {+ 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));+ await page.route("**/*", server(lang, { pages }));+ await page.goto("http://magpie.test/");+ // the agent's menu: magpie's own items, then the plugin's+ await page.locator('.row.agent[data-id="codex"] .ag-handle').click();+ await page.locator(".pop.row-menu").waitFor();+ const own = await page.evaluate(() => t("Hide"));+ const agentItems = await menuNames(page);+ if (!pages.length) {+ assert.equal(agentItems.at(-1), own, `${where}: no plugin, nothing added`);+ await closeMenu(page);+ await context.close();+ continue;+ }+ const logs = lang.startsWith("zh") ? "行工具" : "Row tools"; // zh-TW takes zh's+ assert.deepEqual(agentItems.slice(-2), [own, logs], `${where}: agent menu`);+ assert.equal(await page.locator(".pop.row-menu .rm-sep").count() >= 1, true, where);+ await closeMenu(page);++ // the provider's menu: its item in the window's language+ await page.evaluate(() => show("providers"));+ const row = page.locator('#providers > .row.provider[data-id="openai"]');+ await row.locator(".name").click({ button: "right" });+ await page.locator(".pop.row-menu").waitFor();+ const pvItems = await menuNames(page);+ assert.equal(pvItems.at(-1), want[lang], `${where}: provider menu`);+ assert.ok(await page.locator(".pop.row-menu").evaluate((m) => m.getBoundingClientRect().right <= innerWidth + 1), `${where}: menu fits`);+ await page.locator(".pop.row-menu .rm-item", { hasText: want[lang] }).click();+ await page.waitForFunction(() => view === "plugin-row-tools");+ await page.waitForFunction(() => document.querySelector("#view-plugin-row-tools iframe.plugin-frame"));+ for (let i = 0; i < 100 && (await got(page)).length < 1; i++) await page.waitForTimeout(50);+ assert.deepEqual(await got(page), [{ id: "check", provider: { id: "openai", name: "OpenAI" } }], `${where}: told the row, and only its id and name`);++ // picked again with the page open: told again, nothing drawn anew+ await page.evaluate(() => show("agents"));+ await page.locator('.row.agent[data-id="codex"] .ag-handle').click();+ await page.locator(".pop.row-menu .rm-item", { hasText: logs }).click();+ await page.waitForFunction(() => view === "plugin-row-tools");+ for (let i = 0; i < 100 && (await got(page)).length < 2; i++) await page.waitForTimeout(50);+ assert.deepEqual((await got(page))[1], { id: "logs", agent: { id: "codex", name: "Codex" } }, `${where}: agent action`);+ assert.equal(await page.locator("#view-plugin-row-tools iframe.plugin-frame").count(), 1, where);+ assert.deepEqual(errors, [], where);+ await context.close();+ }+ }+ }+ });++ test(`${engine}: Plugins says which menus a plugin adds to`, 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-row-tools", providers: [], moved: [], inMagpieOnly: true, page: { title: "Row tools", reads: [] }, actions: [{ menu: "provider", title: "Check balance" }, { menu: "agent", title: "Row tools" }] },+ ] };+ 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, { 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 tr = (k, v) => page.evaluate(([k, v]) => t(k, v), [k, v]);+ const row = view.locator(".pm-row").filter({ has: page.locator(".name", { hasText: "magpie-row-tools" }) });+ await row.waitFor();+ const lines = (await row.locator(".pm-page").allInnerTexts()).map((x) => x.trim());+ const menus = [await tr("providers' menus"), await tr("agents' menus")].join(await tr(", "));+ assert.deepEqual(lines, [await tr("Adds a page to the sidebar, which reads nothing of magpie's"), await tr("Adds items to {where}, which open its page", { where: menus })], where);+ if (lang !== "en") assert.ok(!lines[1].includes("Adds items"), `${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/page.go b/internal/plugin/page.goindex 0be430294..60c38ec9e 100644--- a/internal/plugin/page.go+++ b/internal/plugin/page.go@@ -5,17 +5,22 @@ import ("fmt""os""path/filepath"+ "regexp""slices""strings")// 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.+// (magpie.panels), the items it adds to magpie's menus (magpie.actions),+// 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 ownPanels []PanelSpec+ // Actions are its items in magpie's menus, each opening its page;+ // none without a page+ Actions []ActionSpec// Reads are the reads it asked for that magpie has (PageReads), in// the order asked.Reads []string@@ -45,6 +50,28 @@ type PanelSpec struct {Dir string // the folder the panel's files are served from: File's}+// ActionSpec is an item a plugin adds to one of magpie's menus+// (ActionMenus). Picking it opens the plugin's page, which is told the+// action's id and the row it was picked on (magpie.onAction).+type ActionSpec struct {+ ID string // its id among the plugin's actions: actionID+ Menu string // one of ActionMenus+ Title string // "" when it names none: the page's title then+ Titles map[string]string+}++// ActionMenus are the menus a plugin's action can be in: a provider+// row's (the page is told the provider's id and name) and an agent row's+// (the agent's id and name). Nothing else of the row is told.+var ActionMenus = []string{"provider", "agent"}++// actionID is what an action's id is: short, of lower-case letters,+// digits and dashes, so the page can switch on it+var actionID = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,39}$`)++// maxActions is how many actions one plugin adds, at most.+const maxActions = 8+// 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"}@@ -88,7 +115,8 @@ 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+// replaces}, magpie.panels [{slot, file, title}] and magpie.actions [{id,+// menu, 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@@ -109,6 +137,8 @@ func Window(target string) (w *WindowSpec, only bool) {Icon string `json:"icon"`Slot string `json:"slot"`Replaces string `json:"replaces"`+ ID string `json:"id"`+ Menu string `json:"menu"`}var pkg struct {Main string `json:"main"`@@ -116,6 +146,7 @@ func Window(target string) (w *WindowSpec, only bool) {Magpie struct {Page *part `json:"page"`Panels []part `json:"panels"`+ Actions []part `json:"actions"`Permissions []string `json:"permissions"`} `json:"magpie"`}@@ -149,6 +180,18 @@ func Window(target string) (w *WindowSpec, only bool) {}w.Panels = append(w.Panels, PanelSpec{Slot: slot, Title: strings.TrimSpace(pn.Title), Titles: titles(pn.Titles), File: file, Dir: filepath.Dir(file)})}+ // an action opens the plugin's page, so a plugin with none has no+ // action; an id given twice is the first's+ for _, a := range pkg.Magpie.Actions {+ if w.Page == nil || len(w.Actions) == maxActions {+ break+ }+ id, menu := strings.TrimSpace(a.ID), strings.TrimSpace(a.Menu)+ if !actionID.MatchString(id) || !slices.Contains(ActionMenus, menu) || slices.ContainsFunc(w.Actions, func(x ActionSpec) bool { return x.ID == id }) {+ continue+ }+ w.Actions = append(w.Actions, ActionSpec{ID: id, Menu: menu, Title: strings.TrimSpace(a.Title), Titles: titles(a.Titles)})+ }if w.Page == nil && len(w.Panels) == 0 {return nil, false}diff --git a/internal/plugin/page_test.go b/internal/plugin/page_test.goindex f07233916..22ba54725 100644--- a/internal/plugin/page_test.go+++ b/internal/plugin/page_test.go@@ -173,3 +173,61 @@ func TestWindowTitles(t *testing.T) {}}}++// A plugin's actions (magpie.actions) are items in a provider's or an+// agent's row menu that open its page: a plugin with no page has none,+// an action in a menu magpie hasn't, or with an id the page couldn't+// switch on, is dropped, an id given twice is the first's, and there are+// eight at most.+func TestWindowActions(t *testing.T) {+ root := t.TempDir()+ mk := func(name, magpie string) string {+ t.Helper()+ d := filepath.Join(root, name)+ if err := os.MkdirAll(d, 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(d, "index.html"), []byte("<p>hi</p>"), 0o644); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(d, "package.json"), []byte(`{"name":"`+name+`","magpie":`+magpie+`}`), 0o644); err != nil {+ t.Fatal(err)+ }+ return d+ }+ w, _ := Window(mk("acts", `{"page":{"file":"index.html"},"actions":[+ {"id":"check","menu":"provider","title":"Check balance","titles":{"zh":"查余额"}},+ {"id":"check","menu":"agent","title":"Twice"},+ {"id":"logs","menu":"agent"},+ {"id":"Bad Id","menu":"provider","title":"x"},+ {"id":"session","menu":"session","title":"x"},+ {"id":"","menu":"provider","title":"x"}]}`))+ if w == nil {+ t.Fatal("no window")+ }+ want := []ActionSpec{+ {ID: "check", Menu: "provider", Title: "Check balance", Titles: map[string]string{"zh": "查余额"}},+ {ID: "logs", Menu: "agent"},+ }+ if len(w.Actions) != len(want) {+ t.Fatalf("actions %+v, want %+v", w.Actions, want)+ }+ for i, a := range w.Actions {+ if a.ID != want[i].ID || a.Menu != want[i].Menu || a.Title != want[i].Title || a.Titles["zh"] != want[i].Titles["zh"] {+ t.Errorf("action %d: %+v, want %+v", i, a, want[i])+ }+ }+ if w, _ := Window(mk("nopage", `{"panels":[{"slot":"agents","file":"index.html"}],"actions":[{"id":"a","menu":"agent"}]}`)); w == nil || len(w.Actions) != 0 {+ t.Errorf("a plugin with no page: %+v, want panels and no actions", w)+ }+ many := `{"page":{"file":"index.html"},"actions":[`+ for i := range 12 {+ if i > 0 {+ many += ","+ }+ many += `{"id":"a` + string(rune('a'+i)) + `","menu":"agent"}`+ }+ if w, _ := Window(mk("many", many+`]}`)); w == nil || len(w.Actions) != maxActions {+ t.Errorf("12 actions: %+v, want %d", w, maxActions)+ }+}diff --git a/site/public/docs/ja/plugins.html b/site/public/docs/ja/plugins.htmlindex 848c3d4fd..ed6799ce5 100644--- a/site/public/docs/ja/plugins.html+++ b/site/public/docs/ja/plugins.html@@ -885,6 +885,24 @@ document.getElementById(<span class="s">"calls"</span>).textContent = `${s.calls<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>+ <h3 id="actions"><a class="anchor" href="#actions">magpie のメニューに入る項目</a></h3>+ <p>ページを持つプラグインは、magpie の行のメニューに項目を加えられます。プロバイダの行(右クリック)とエージェントの行(ハンドル、または右クリック)です。項目は magpie 自身の項目のあとに並び、ページのタイトルと同じくウィンドウの言語で表示されます。項目を選ぶとプラグインのページが開き、どの項目か、その行の id と名前だけが伝えられます。ページは <code>magpie.onAction</code> で受け取ります。ハンドラーを渡す前に選ばれた項目は、渡されるまで待ちます。</p>+ <div class="code">+ <span class="lang">package.json</span>+ <button class="copy" data-copy="pg-actions">コピー</button>+ <pre id="pg-actions"><span class="s">"page"</span>: { <span class="s">"title"</span>: <span class="s">"Balance"</span>, <span class="s">"file"</span>: <span class="s">"page/index.html"</span> },+<span class="s">"actions"</span>: [+ { <span class="s">"id"</span>: <span class="s">"check"</span>, <span class="s">"menu"</span>: <span class="s">"provider"</span>, <span class="s">"title"</span>: <span class="s">"Check balance"</span>, <span class="s">"titles"</span>: { <span class="s">"zh"</span>: <span class="s">"查余额"</span> } }+]</pre>+ </div>+ <div class="code">+ <span class="lang">page/app.js</span>+ <button class="copy" data-copy="pg-onaction">コピー</button>+ <pre id="pg-onaction">magpie.onAction(({ id, provider }) => {+ <span class="c">// id: "check"; provider: { id, name }</span>+});</pre>+ </div>+ <p><code>menu</code> は <code>provider</code> か <code>agent</code> です。<code>id</code> は小文字、数字、ハイフンで、40 文字まで。項目はプラグインごとに最大 8 個で、<code>title</code> のない項目はページのタイトルを使います。ページのないプラグインは項目を加えません。「プラグイン」ページには、プラグインがどのメニューに項目を加えるかが表示されます。</p><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 e86c7f18d..814ec5f8a 100644--- a/site/public/docs/plugins.html+++ b/site/public/docs/plugins.html@@ -885,6 +885,24 @@ document.getElementById(<span class="s">"calls"</span>).textContent = `${s.calls<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>+ <h3 id="actions"><a class="anchor" href="#actions">Items in magpie’s menus</a></h3>+ <p>A plugin with a page can add items to the menus of magpie’s rows: a provider’s (right-click it) and an agent’s (its handle, or right-click). They come after magpie’s own, named in the window’s language like a page’s title. Picking one opens the plugin’s page and tells it which item, and the row’s id and name, nothing else of it. The page handles it with <code>magpie.onAction</code>; an item picked before the page gave its handler waits for it.</p>+ <div class="code">+ <span class="lang">package.json</span>+ <button class="copy" data-copy="pg-actions">Copy</button>+ <pre id="pg-actions"><span class="s">"page"</span>: { <span class="s">"title"</span>: <span class="s">"Balance"</span>, <span class="s">"file"</span>: <span class="s">"page/index.html"</span> },+<span class="s">"actions"</span>: [+ { <span class="s">"id"</span>: <span class="s">"check"</span>, <span class="s">"menu"</span>: <span class="s">"provider"</span>, <span class="s">"title"</span>: <span class="s">"Check balance"</span>, <span class="s">"titles"</span>: { <span class="s">"zh"</span>: <span class="s">"查余额"</span> } }+]</pre>+ </div>+ <div class="code">+ <span class="lang">page/app.js</span>+ <button class="copy" data-copy="pg-onaction">Copy</button>+ <pre id="pg-onaction">magpie.onAction(({ id, provider }) => {+ <span class="c">// id: "check"; provider: { id, name }</span>+});</pre>+ </div>+ <p><code>menu</code> is <code>provider</code> or <code>agent</code>. An <code>id</code> is lower-case letters, digits and dashes, up to 40. A plugin has at most 8 items, and an item with no <code>title</code> takes its page’s. A plugin without a page adds no items. The Plugins page says which menus a plugin adds to.</p><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 6b7f439fe..c1592ec11 100644--- a/site/public/docs/zh/plugins.html+++ b/site/public/docs/zh/plugins.html@@ -885,6 +885,24 @@ document.getElementById(<span class="s">"calls"</span>).textContent = `${s.calls<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>+ <h3 id="actions"><a class="anchor" href="#actions">magpie 菜单里的菜单项</a></h3>+ <p>有页面的插件可以往 magpie 行的菜单里加菜单项:供应商的(右键点它)和 Agent 的(点它的拖动柄,或右键)。它们排在 magpie 自己的菜单项之后,跟页面标题一样按窗口的语言显示。点一个菜单项会打开插件的页面,并告诉它点的是哪一项,以及那一行的 id 和名字,别的都不给。页面用 <code>magpie.onAction</code> 处理;页面还没注册处理函数时点的菜单项会等它注册后再送到。</p>+ <div class="code">+ <span class="lang">package.json</span>+ <button class="copy" data-copy="pg-actions">复制</button>+ <pre id="pg-actions"><span class="s">"page"</span>: { <span class="s">"title"</span>: <span class="s">"Balance"</span>, <span class="s">"file"</span>: <span class="s">"page/index.html"</span> },+<span class="s">"actions"</span>: [+ { <span class="s">"id"</span>: <span class="s">"check"</span>, <span class="s">"menu"</span>: <span class="s">"provider"</span>, <span class="s">"title"</span>: <span class="s">"Check balance"</span>, <span class="s">"titles"</span>: { <span class="s">"zh"</span>: <span class="s">"查余额"</span> } }+]</pre>+ </div>+ <div class="code">+ <span class="lang">page/app.js</span>+ <button class="copy" data-copy="pg-onaction">复制</button>+ <pre id="pg-onaction">magpie.onAction(({ id, provider }) => {+ <span class="c">// id: "check"; provider: { id, name }</span>+});</pre>+ </div>+ <p><code>menu</code> 是 <code>provider</code> 或 <code>agent</code>。<code>id</code> 由小写字母、数字和短横线组成,最长 40 个字符。一个插件最多 8 个菜单项,没写 <code>title</code> 的用它页面的标题。没有页面的插件不加菜单项。「插件」页面会写出插件往哪些菜单里加了菜单项。</p><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>