diff --git a/docs/subsystems/gateway-request-hooks.md b/docs/subsystems/gateway-request-hooks.md index 8084b634f..d3f73e834 100644 --- a/docs/subsystems/gateway-request-hooks.md +++ b/docs/subsystems/gateway-request-hooks.md @@ -28,6 +28,10 @@ its alias `magpie.gateway`, `*.gateway.js`), so a hook that imports `node:fs` is never also loaded as middleware. Bun runs TypeScript directly. A gateway-only package does not need provider main/exports, a client MCP installation, or a client skill. +Discover lists a GitHub repository tagged `magpie-plugin` whose package.json has +`magpie.hooks` and no main or exports as a Request hook, picked out with +middleware (`TaggedRepos` checks that the hooks file is committed, as it does +middleware's; `TestTaggedHooksAlone`, `plugin-github-hooks.test.cjs`). `export async function onRequest(body, ctx)` receives the client protocol JSON before routing. Return a JSON object to add context; return `undefined` to keep diff --git a/internal/gui/assets/plugins.js b/internal/gui/assets/plugins.js index 08eecd7cf..3769009b8 100644 --- a/internal/gui/assets/plugins.js +++ b/internal/gui/assets/plugins.js @@ -129,7 +129,7 @@ pg: [PAGE, "Page", "Adds a page of its own to the sidebar. It runs shut off from the rest of magpie and can read only what its row lists"], pn: [PAGE, "Panels", "Adds panels to magpie's own pages. They run shut off from the rest of magpie and can read only what its row lists"], }; - const kindOf = (l) => ({ middleware: "mw", agent: "ag", tools: "tl", page: "pg" })[l.kind] || "pv"; + const kindOf = (l) => ({ middleware: "mw", hooks: "mw", agent: "ag", tools: "tl", page: "pg" })[l.kind] || "pv"; function kindChip(kind, name) { const [d, word, tip] = KINDS[kind]; const c = el("span", "pm-chip kind " + kind); @@ -544,7 +544,7 @@ top.append(logo(l.icon || l.npm?.icon, false, kindOf(l)), who, go); const sum = el("p", "pm-sum", summary(l)); const meta = el("div", "pm-meta"); - meta.append(kindChip(kindOf(l))); + meta.append(kindChip(kindOf(l), l.kind === "hooks" && "Request hook")); if (l.github) meta.append(stars(l.github.stars)); if (l.npm?.weekly) { const d = el("span", "pm-dl"); diff --git a/internal/gui/tests/plugin-github-hooks.test.cjs b/internal/gui/tests/plugin-github-hooks.test.cjs new file mode 100644 index 000000000..8f6bb7c8c --- /dev/null +++ b/internal/gui/tests/plugin-github-hooks.test.cjs @@ -0,0 +1,107 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A repository tagged magpie-plugin that is gateway hooks alone +// (package.json's magpie.hooks and no entry of its own; MengXiangxi, +// #3821) is in "Unofficial, on GitHub" as an installed one's row has it: +// the gateway's chip saying Request hook, never Provider, and picked out +// under Middleware, as it runs in the gateway too. The repositories are +// seven of /api/plugins/github's real answer of 2026-10-27, from a magpie +// built at this change: two providers, three middleware and two of hooks +// alone (past six, the section has its kinds to pick from). +// The API is faked here and no request leaves the page. English, Chinese, +// Traditional Chinese, Japanese and German, 980px and 420px. +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 REPOS = [ + { "spec": "magpie-gemini-web", "repo": "BUKOWSKIREAL/magpie-gemini-web", "url": "https://github.com/BUKOWSKIREAL/magpie-gemini-web", "owner": "BUKOWSKIREAL", "ownerAvatar": "https://avatars.githubusercontent.com/u/233685554?v=4", "description": "Gemini Web provider for Magpie with a local backend and experimental Argon support", "stars": 101, "license": "MIT", "pushed": "2026-10-24T05:28:43Z", "package": "magpie-gemini-web", "version": "0.5.6" }, + { "spec": "github:mu-zi-lee/magpie-doubao-translate", "repo": "mu-zi-lee/magpie-doubao-translate", "url": "https://github.com/mu-zi-lee/magpie-doubao-translate", "owner": "mu-zi-lee", "ownerAvatar": "https://avatars.githubusercontent.com/u/75201518?v=4", "description": "Magpie 豆包翻译插件:通过 Cookie 直连豆包 AI、火山及微软翻译,无需 Docker 或额外 API Key。|Magpie plugin for Doubao web translation: access Doubao AI, Volcengine and Microsoft Translator via Cookie, without Docker or an extra API key.", "stars": 9, "license": "MIT", "pushed": "2026-10-09T19:22:04Z", "package": "magpie-doubao-translate", "version": "0.1.2" }, + { "spec": "github:euanguo/magpie-middleware-image-slim", "repo": "euanguo/magpie-middleware-image-slim", "url": "https://github.com/euanguo/magpie-middleware-image-slim", "owner": "euanguo", "ownerAvatar": "https://avatars.githubusercontent.com/u/82928935?v=4", "description": "magpie gateway middleware: keep the newest images and replace older inline images with a text placeholder — agents resend every screenshot on every turn otherwise", "stars": 2, "license": "MIT", "pushed": "2026-10-10T16:41:27Z", "package": "magpie-middleware-image-slim", "version": "0.2.0", "kind": "middleware" }, + { "spec": "github:ezdemo/magpie-haiku55-thinking", "repo": "ezdemo/magpie-haiku55-thinking", "url": "https://github.com/ezdemo/magpie-haiku55-thinking", "owner": "ezdemo", "ownerAvatar": "https://avatars.githubusercontent.com/u/41895036?v=4", "description": "Magpie Haiku 5.5 thinking middleware with a verified OpenDesign compatibility workaround", "stars": 1, "license": "MIT", "pushed": "2026-10-12T15:07:50Z", "package": "magpie-opendesign-compatible-fix", "version": "0.1.0", "kind": "middleware" }, + { "spec": "github:MengXiangxi/magpie-openviking", "repo": "MengXiangxi/magpie-openviking", "url": "https://github.com/MengXiangxi/magpie-openviking", "owner": "MengXiangxi", "ownerAvatar": "https://avatars.githubusercontent.com/u/10251566?v=4", "description": "OpenViking memory recall and opt-in capture through Magpie async gateway hooks", "stars": 1, "license": "MIT", "pushed": "2026-10-27T02:43:30Z", "package": "magpie-openviking", "version": "0.1.0", "kind": "hooks" }, + { "spec": "github:sdloghub/magpie-session-patcher", "repo": "sdloghub/magpie-session-patcher", "url": "https://github.com/sdloghub/magpie-session-patcher", "owner": "sdloghub", "ownerAvatar": "https://avatars.githubusercontent.com/u/52274876?v=4", "description": "Magpie gateway middleware: opt-in outbound history filtering, optional reasoning cleanup and prompt append", "stars": 0, "pushed": "2026-10-25T07:15:36Z", "package": "magpie-session-patcher", "version": "0.1.1", "kind": "middleware" }, + { "spec": "github:IvanXxxxyyuffff/magpie-system-prompt-file", "repo": "IvanXxxxyyuffff/magpie-system-prompt-file", "url": "https://github.com/IvanXxxxyyuffff/magpie-system-prompt-file", "owner": "IvanXxxxyyuffff", "ownerAvatar": "https://avatars.githubusercontent.com/u/128815537?v=4", "description": "Magpie plugin: a system prompt (persona) loaded from a local .md / .txt file and injected into every agent request. macOS + Windows.", "stars": 0, "license": "MIT", "pushed": "2026-10-26T15:01:39Z", "package": "magpie-system-prompt-file", "version": "0.3.0", "kind": "hooks" }, +]; +const name = (r) => r.repo.split("/")[1]; + +function server(lang, fetched) { + return async (route) => { + const url = new URL(route.request().url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${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/gateway/trace") return json({ routes: [] }); + if (url.pathname === "/api/plugins") return json({ bun: true, bunVersion: "1.4.2", plugins: [], picker: false, movable: [] }); + if (url.pathname === "/api/plugins/listings") return json({ listings: [] }); + if (url.pathname === "/api/plugins/npm") return json({ npm: {} }); + if (url.pathname === "/api/plugins/github") return json({ repos: REPOS, topic: "magpie-plugin" }); + if (url.pathname === "/api/plugins/search") return json({ hits: [] }); + if (url.pathname === "/api/plugins/updates") return json({ waiting: [], updated: [] }); + if (url.pathname.startsWith("/api/")) return json({}); + if (url.host !== "magpie.test" || !/^\/[\w./-]*$/.test(url.pathname)) { fetched.push(url.href); 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: "" }); } + }; +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": a repository of gateway hooks alone is a request hook", async (t) => { + assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit"); + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || "chromium" })); + t.after(() => browser.close()); + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) for (const width of [980, 420]) { + await t.test(`${lang} ${width}px`, async () => { + const ctx = await browser.newContext({ viewport: { width, height: 860 } }); + const page = await ctx.newPage(); + page.setDefaultTimeout(6000); + const errors = [], fetched = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", server(lang, fetched)); + await page.addInitScript(() => { try { localStorage.setItem("magpie.pluginTab", "discover"); } catch {} }); + try { + await page.goto("http://magpie.test/?view=plugins"); + const sec = page.locator("#view-plugins .pm-ghsec"); + const cards = sec.locator(".pm-card"); + await cards.first().waitFor(); + assert.deepEqual(await cards.locator(".pm-name b").allInnerTexts(), REPOS.map(name), "every one listed, in GitHub's order"); + const tr = (s) => page.evaluate((s) => t(s), s); + const hook = await tr("Request hook"); + if (lang !== "en") assert.notEqual(hook, "Request hook", "Request hook in " + lang); + + // each card's one chip: the gateway's for middleware and hooks, + // which say Request hook, as an installed one's row does + for (const r of REPOS) { + const chip = cards.filter({ has: page.locator(".pm-name b", { hasText: new RegExp("^" + name(r) + "$") }) }).locator(".pm-chip.kind"); + assert.equal(await chip.count(), 1, r.repo); + const want = r.kind === "hooks" ? hook : await tr(r.kind === "middleware" ? "Middleware" : "Provider"); + assert.equal((await chip.innerText()).trim(), want, r.repo); + assert.equal(await chip.evaluate((e) => e.classList.contains("mw")), !!r.kind, r.repo + "'s chip is the gateway's"); + } + + // picked out under Middleware, with the middleware + const kinds = sec.locator(".pm-ghkinds .opt"); + assert.deepEqual(await kinds.allTextContents(), [await tr("All") + " · 7", await tr("Provider") + " · 2", await tr("Middleware") + " · 5"]); + await kinds.nth(2).click(); + assert.deepEqual(await cards.locator(".pm-name b").allInnerTexts(), REPOS.filter((r) => r.kind).map(name)); + await kinds.nth(1).click(); + assert.deepEqual(await cards.locator(".pm-name b").allInnerTexts(), REPOS.filter((r) => !r.kind).map(name)); + + const over = await page.evaluate(() => [document.querySelector("#view-plugins").scrollWidth - document.querySelector("#view-plugins").clientWidth, document.documentElement.scrollWidth - innerWidth]); + assert.deepEqual(over.map((x) => Math.max(0, x)), [0, 0], "scrolls sideways: " + over); + if (process.env.ARTIFACT_DIR) await sec.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `plugin-github-hooks-${engine}-${lang}-${width}.png`) }); + assert.deepEqual(errors, []); + } finally { + await ctx.close(); + } + }); + } + }); +} diff --git a/internal/plugin/github.go b/internal/plugin/github.go index 1a18ae149..241ad102b 100644 --- a/internal/plugin/github.go +++ b/internal/plugin/github.go @@ -45,7 +45,7 @@ type Tagged struct { // it as, its version, and whether it is gateway middleware or an agent Package string `json:"package,omitempty"` Version string `json:"version,omitempty"` - Kind string `json:"kind,omitempty"` // "middleware", "agent" or "page" when that is all it is + Kind string `json:"kind,omitempty"` // "middleware", "agent", "page" or "hooks" when that is all it is // its package.json's magpie.icon, as an installed plugin gives its // provider one: an https URL or a data:image URI, as it is written Icon string `json:"icon,omitempty"` @@ -407,6 +407,7 @@ func readTagged(pc context.Context, t Tagged, branch string) (Tagged, bool, bool Magpie struct { Middleware string `json:"middleware"` Agent string `json:"agent"` + Hooks string `json:"hooks"` Icon string `json:"icon"` Page struct { File string `json:"file"` @@ -436,6 +437,11 @@ func readTagged(pc context.Context, t Tagged, branch string) (Tagged, bool, bool t.Kind = "agent" case strings.TrimSpace(pj.Magpie.Page.File) != "": t.Kind = "page" + // gateway hooks alone (magpie.hooks) need no entry of their + // own, as the host loads them: the hooks file is the one to + // find (#3821) + case strings.TrimSpace(pj.Magpie.Hooks) != "": + t.Kind = "hooks" } } // published to npm from this repository: npm's copy is the one @@ -471,6 +477,8 @@ func readTagged(pc context.Context, t Tagged, branch string) (Tagged, bool, bool entry = pj.Magpie.Agent } else if t.Kind == "page" { entry = pj.Magpie.Page.File + } else if t.Kind == "hooks" { + entry = pj.Magpie.Hooks } else if t.Kind != "middleware" { entry = pkgEntry(pj.Exports, pj.Main) if !IsGit(t.Spec) { diff --git a/internal/plugin/github_hooks_test.go b/internal/plugin/github_hooks_test.go new file mode 100644 index 000000000..03b6f6eae --- /dev/null +++ b/internal/plugin/github_hooks_test.go @@ -0,0 +1,67 @@ +package plugin + +import ( + "context" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "slices" + "strings" + "sync" + "testing" +) + +// A repository of gateway hooks alone, package.json's magpie.hooks with +// no main, exports or index.js, installs and runs, but the GitHub list +// took it for one whose index.js Bun loads, found none, and left it out +// without a word (MengXiangxi, #3821). It is listed now, a request hook, +// when its hooks file is in the repository; one whose hooks file isn't +// (a dist built only to publish) couldn't be installed from it, and is +// left out, as a middleware's is. The first package.json is +// IvanXxxxyyuffff/magpie-system-prompt-file's, one the report names, as +// it is; neither package is on npm. +func TestTaggedHooksAlone(t *testing.T) { + var mu sync.Mutex + var asked []string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, q *http.Request) { + mu.Lock() + asked = append(asked, q.URL.Path) + mu.Unlock() + name, ok := strings.CutPrefix(q.URL.Path, "/raw/") + f, err := os.ReadFile(filepath.Join("testdata/github/raw", filepath.FromSlash(name))) + if !ok || err != nil { + http.Error(w, `"Not Found"`, 404) + return + } + w.Write(f) + })) + t.Cleanup(srv.Close) + api, raw, reg := githubAPI, githubRaw, npmRegistry + githubAPI, githubRaw, npmRegistry = srv.URL, srv.URL+"/raw", srv.URL+"/npm" + t.Cleanup(func() { githubAPI, githubRaw, npmRegistry = api, raw, reg }) + + read := func(repo string) (Tagged, bool, bool, error) { + mu.Lock() + asked = nil + mu.Unlock() + return readTagged(context.Background(), Tagged{Spec: "github:" + repo, Repo: repo}, "main") + } + got, keep, known, err := read("IvanXxxxyyuffff/magpie-system-prompt-file") + if !keep || !known || err != nil || got.Kind != "hooks" || got.Spec != "github:IvanXxxxyyuffff/magpie-system-prompt-file" || + got.Package != "magpie-system-prompt-file" || got.Version != "0.3.0" { + t.Fatalf("hooks alone: %+v, kept %v, known %v, %v", got, keep, known, err) + } + // its hooks file is the one looked for, not an index.js it needn't have + mu.Lock() + a := slices.Clone(asked) + mu.Unlock() + if !slices.Contains(a, "/raw/IvanXxxxyyuffff/magpie-system-prompt-file/main/system-prompt.hooks.mjs") || slices.ContainsFunc(a, func(p string) bool { return strings.HasSuffix(p, "/index.js") }) { + t.Fatalf("asked %v", a) + } + + got, keep, known, err = read("someone/hooks-gone") + if keep || !known || err != nil { + t.Fatalf("hooks whose file isn't committed: %+v, kept %v, known %v, %v", got, keep, known, err) + } +} diff --git a/internal/plugin/testdata/github/raw/IvanXxxxyyuffff/magpie-system-prompt-file/main/package.json b/internal/plugin/testdata/github/raw/IvanXxxxyyuffff/magpie-system-prompt-file/main/package.json new file mode 100644 index 000000000..075d14eab --- /dev/null +++ b/internal/plugin/testdata/github/raw/IvanXxxxyyuffff/magpie-system-prompt-file/main/package.json @@ -0,0 +1,34 @@ +{ + "name": "magpie-system-prompt-file", + "version": "0.3.0", + "description": "Magpie plugin: a system prompt (persona) loaded from a local .md / .txt file and injected into every agent request. macOS + Windows.", + "type": "module", + "license": "MIT", + "keywords": [ + "magpie", + "magpie-plugin", + "gateway-hook", + "system-prompt", + "persona", + "prompt", + "md", + "txt", + "claude", + "codex", + "gemini" + ], + "magpie": { + "hooks": "./system-prompt.hooks.mjs", + "options": { + "prompt_file": "~/.config/magpie/prompts/system.md", + "prompt_files": [], + "system_prompt": "", + "override": true, + "position": "append", + "agents": [], + "models": [], + "strip_frontmatter": true, + "gatewayTimeoutMs": 3000 + } + } +} diff --git a/internal/plugin/testdata/github/raw/IvanXxxxyyuffff/magpie-system-prompt-file/main/system-prompt.hooks.mjs b/internal/plugin/testdata/github/raw/IvanXxxxyyuffff/magpie-system-prompt-file/main/system-prompt.hooks.mjs new file mode 100644 index 000000000..54d8a22cf --- /dev/null +++ b/internal/plugin/testdata/github/raw/IvanXxxxyyuffff/magpie-system-prompt-file/main/system-prompt.hooks.mjs @@ -0,0 +1,2 @@ +// stands in for the repository's hooks file: only that it is there is read +export async function onRequest() {} diff --git a/internal/plugin/testdata/github/raw/someone/hooks-gone/main/package.json b/internal/plugin/testdata/github/raw/someone/hooks-gone/main/package.json new file mode 100644 index 000000000..0f7f832ff --- /dev/null +++ b/internal/plugin/testdata/github/raw/someone/hooks-gone/main/package.json @@ -0,0 +1,9 @@ +{ + "name": "magpie-recall-built", + "version": "0.1.0", + "type": "module", + "files": ["dist/"], + "magpie": { + "hooks": "./dist/recall.hooks.mjs" + } +}