Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6350: rebuild the plugin system (2/4) — Action API + Surface + SDK (#7157)
Jiayuan Zhang97195885fae5
diff --git a/examples/plugins/hello-panel/README.md b/examples/plugins/hello-panel/README.mdnew file mode 100644index 0000000000..5e11739fb9--- /dev/null+++ b/examples/plugins/hello-panel/README.md@@ -0,0 +1,33 @@+# Hello Panel++The reference Multica plugin: one `issue_panel` surface that exercises every+part of the Action API a v1 surface can reach.++It is also the fixture the surface end-to-end tests run against, so keep it+boring — it should demonstrate the contract, not the framework of the week.++## What it shows++- `multica.context.get()` — who is looking and which issue the panel is on+- `multica.issue.get()` — reading the issue behind `issues:read`+- `multica.issue.comment()` — a write that lands as **the user**, marked with+ the plugin (`via_plugin_id`), behind `comments:write`+- `multica.storage.user` — per-member state behind `storage:user`+- `multica.ui.resize()` — asking the host for the height it actually needs++## Running it++The manifest and `ui/main.js` must be served over public HTTPS from the same+directory, because `entry` resolves relative to the manifest URL and Multica+never re-hosts plugin code. Install by pasting the manifest URL into+**Settings → Plugins**.++`MULTICA_PLUGIN_DIR` installs (`local:hello-panel`) are for developing the+manifest itself: the install and consent flow work, but the panel cannot load a+script from the server's filesystem and says so instead of rendering blank.++## Note on scopes++This plugin declares no `net:` scope, so its surface gets+`connect-src 'none'` — it literally cannot send data anywhere. Everything it+does goes through the host bridge, which is the point.diff --git a/examples/plugins/hello-panel/multica.plugin.json b/examples/plugins/hello-panel/multica.plugin.jsonnew file mode 100644index 0000000000..8e678351e5--- /dev/null+++ b/examples/plugins/hello-panel/multica.plugin.json@@ -0,0 +1,20 @@+{+ "manifest_version": 1,+ "key": "ai.multica.hello-panel",+ "name": "Hello Panel",+ "description": "The reference surface: reads the current issue, posts a comment, and stores a per-member note.",+ "version": "1.0.0",+ "author": { "name": "multica", "url": "https://multica.ai" },+ "scopes": ["issues:read", "comments:write", "storage:user"],+ "contributes": {+ "surfaces": [+ {+ "key": "hello",+ "type": "issue_panel",+ "name": "Hello",+ "entry": "ui/main.js",+ "platforms": ["web", "desktop"]+ }+ ]+ }+}diff --git a/examples/plugins/hello-panel/ui/main.js b/examples/plugins/hello-panel/ui/main.jsnew file mode 100644index 0000000000..941bf22608--- /dev/null+++ b/examples/plugins/hello-panel/ui/main.js@@ -0,0 +1,129 @@+// Hello Panel — the reference Multica surface.+//+// Plain ES module, no build step: the point is to show the contract, not a+// toolchain. It runs in a sandboxed iframe with an opaque origin, so there is+// no cookie, no localStorage and no access to the page around it. Everything it+// does goes through the host bridge.+//+// In a real plugin you would `import { multica } from "@multica/plugin-sdk"`.+// This file inlines a minimal client so it can be served as a single static+// file with nothing to install.++const pending = new Map();+let port = null;+let sequence = 0;++window.addEventListener("message", (event) => {+ const data = event.data;+ if (!data || data.type !== "multica:plugin-bridge-init" || !event.ports[0]) return;+ // Only the embedder may hand this frame a port, and only once. Sibling frames+ // are mutually opaque but `parent.frames[i]` is an allowed cross-origin+ // access, so another plugin on this page could otherwise deliver its own port+ // and become this surface's "host" — reading everything it writes. Origin is+ // useless here (a sandboxed frame sees "null"), so identity is the window+ // reference.+ if (event.source !== window.parent || port) return;+ port = event.ports[0];+ port.onmessage = (message) => {+ const payload = message.data;+ if (payload?.kind === "theme") return applyTheme(payload.theme);+ const entry = pending.get(payload?.id);+ if (!entry) return;+ pending.delete(payload.id);+ if (payload.ok) entry.resolve(payload.data);+ else entry.reject(new Error(payload.error));+ };+ port.start();+ applyTheme(data.theme);+ start();+});++// Announce until the host answers with a port. One announcement is not enough+// in either direction: this frame can finish executing before the embedder's+// effect attaches its listener, and a host waiting on the iframe load event can+// miss that event entirely. Repeating makes the handshake independent of who is+// ready first — the one ordering neither side controls.+(function announce(attempts) {+ if (port || attempts > 50) return;+ window.parent.postMessage({ type: "multica:plugin-surface-ready" }, "*");+ setTimeout(() => announce(attempts + 1), 120);+})(0);++function applyTheme(theme) {+ for (const [name, value] of Object.entries(theme ?? {})) {+ document.documentElement.style.setProperty(name, value);+ }+}++function call(method, path, body) {+ const id = `r${++sequence}`;+ return new Promise((resolve, reject) => {+ pending.set(id, { resolve, reject });+ port.postMessage({ id, kind: "action", method, path, body });+ });+}++function resize() {+ // The host clamps this; asking for the content height is the normal case.+ port.postMessage({ id: `resize${Date.now()}`, kind: "ui.resize", height: document.body.scrollHeight + 16 });+}++const NOTE_KEY = "note";++async function start() {+ const root = document.getElementById("root");+ root.innerHTML = `+ <div style="padding:12px 14px; display:grid; gap:10px">+ <div id="who" style="color:var(--muted-foreground)">Loading…</div>+ <div id="title" style="font-weight:600"></div>+ <div style="display:flex; gap:8px">+ <input id="note" placeholder="A note only you can see"+ style="flex:1; padding:6px 8px; border:1px solid var(--border); border-radius:var(--radius,6px);+ background:var(--background); color:var(--foreground)">+ <button id="save" style="padding:6px 10px">Save</button>+ </div>+ <button id="comment" style="padding:6px 10px; justify-self:start">Post a test comment</button>+ <div id="status" style="color:var(--muted-foreground); min-height:1.2em"></div>+ </div>`;++ const status = (text) => { root.querySelector("#status").textContent = text; resize(); };++ try {+ const context = await call("GET", "/context");+ root.querySelector("#who").textContent =+ `${context.user.name} · ${context.workspace.name}` + (context.issue ? ` · ${context.issue.identifier}` : "");++ const issue = await call("GET", `/issues/${encodeURIComponent(context.issue.id)}`);+ root.querySelector("#title").textContent = issue.title;++ // storage:user — per member, so another member opening the same panel on+ // the same issue sees their own note, not this one.+ const saved = await call("GET", `/storage/user/${NOTE_KEY}`).catch(() => null);+ if (saved) root.querySelector("#note").value = saved.value;++ root.querySelector("#save").onclick = async () => {+ try {+ await call("PUT", `/storage/user/${NOTE_KEY}`, { value: root.querySelector("#note").value });+ status("Saved.");+ } catch (error) {+ status(error.message);+ }+ };++ root.querySelector("#comment").onclick = async () => {+ try {+ // Lands as the signed-in user, marked with this plugin. If the admin+ // did not grant comments:write, this is a 403 that names the scope.+ await call("POST", `/issues/${encodeURIComponent(context.issue.id)}/comments`, {+ content: "Posted from Hello Panel.",+ });+ status("Comment posted.");+ } catch (error) {+ status(error.message);+ }+ };+ } catch (error) {+ status(error.message);+ }+ resize();+}diff --git a/examples/plugins/release-checklist/multica.plugin.json b/examples/plugins/release-checklist/multica.plugin.jsonnew file mode 100644index 0000000000..7216e981b2--- /dev/null+++ b/examples/plugins/release-checklist/multica.plugin.json@@ -0,0 +1,53 @@+{+ "manifest_version": 1,+ "key": "ai.multica.release-checklist",+ "name": "Release Checklist",+ "description": "A per-issue definition-of-done checklist. The team edits the items once in plugin settings; every issue gets its own state, and completing the list posts a sign-off comment.",+ "version": "1.0.0",+ "author": {+ "name": "multica",+ "url": "https://multica.ai"+ },+ "scopes": [+ "issues:read",+ "comments:write",+ "storage:workspace"+ ],+ "config": {+ "items": {+ "type": "string",+ "label": "Checklist items",+ "description": "One per line. Shared by the whole workspace.",+ "required": true,+ "placeholder": "Tests pass\nDocs updated\nMigration reviewed",+ "multiline": true+ },+ "signoff_template": {+ "type": "string",+ "label": "Sign-off comment",+ "description": "Posted when every item is checked. {{items}} expands to the completed list.",+ "required": true,+ "placeholder": "Release checklist complete:\n{{items}}",+ "multiline": true+ },+ "strict": {+ "type": "bool",+ "label": "Require sign-off before posting",+ "description": "When on, the comment is only offered once every item is checked."+ }+ },+ "contributes": {+ "surfaces": [+ {+ "key": "checklist",+ "type": "issue_panel",+ "name": "Release Checklist",+ "entry": "ui/main.js",+ "platforms": [+ "web",+ "desktop"+ ]+ }+ ]+ }+}diff --git a/examples/plugins/release-checklist/ui/main.js b/examples/plugins/release-checklist/ui/main.jsnew file mode 100644index 0000000000..b373e3514a--- /dev/null+++ b/examples/plugins/release-checklist/ui/main.js@@ -0,0 +1,235 @@+// Release Checklist — a plugin with real state, not a hello-world.+//+// The workspace defines the checklist once in plugin settings; each issue keeps+// its own tick state in workspace-scoped plugin storage, and completing the list+// posts a sign-off comment authored by whoever ticked the last box.+//+// Everything below runs in a sandboxed iframe with an opaque origin: no cookies,+// no localStorage, no access to the page around it. State lives in+// multica.storage (server-side), and the comment goes through the host bridge on+// the user's own session.++const pending = new Map();+let port = null;+let sequence = 0;++window.addEventListener("message", (event) => {+ const data = event.data;+ if (!data || data.type !== "multica:plugin-bridge-init" || !event.ports[0]) return;+ // Only the embedder may hand this frame a port, and only once. Sibling frames+ // are mutually opaque but `parent.frames[i]` is an allowed cross-origin+ // access, so another plugin on this page could otherwise deliver its own port+ // and become this surface's "host" — reading everything it writes. Origin is+ // useless here (a sandboxed frame sees "null"), so identity is the window+ // reference.+ if (event.source !== window.parent || port) return;+ port = event.ports[0];+ port.onmessage = (message) => {+ const payload = message.data;+ if (payload?.kind === "theme") return applyTheme(payload.theme);+ const entry = pending.get(payload?.id);+ if (!entry) return;+ pending.delete(payload.id);+ if (payload.ok) entry.resolve(payload.data);+ else entry.reject(Object.assign(new Error(payload.error), { status: payload.status }));+ };+ port.start();+ applyTheme(data.theme);+ boot();+});++// Announce until the host answers with a port. One announcement is not enough+// in either direction: this frame can finish executing before the embedder's+// effect attaches its listener, and a host waiting on the iframe load event can+// miss that event entirely. Repeating makes the handshake independent of who is+// ready first — the one ordering neither side controls.+(function announce(attempts) {+ if (port || attempts > 50) return;+ window.parent.postMessage({ type: "multica:plugin-surface-ready" }, "*");+ setTimeout(() => announce(attempts + 1), 120);+})(0);++function applyTheme(theme) {+ for (const [name, value] of Object.entries(theme ?? {})) {+ document.documentElement.style.setProperty(name, value);+ }+}++function call(method, path, body) {+ const id = `r${++sequence}`;+ return new Promise((resolve, reject) => {+ pending.set(id, { resolve, reject });+ port.postMessage({ id, kind: "action", method, path, body });+ });+}++function resize() {+ port.postMessage({ id: `z${Date.now()}`, kind: "ui.resize", height: document.body.scrollHeight + 8 });+}++// --- business logic -------------------------------------------------------++/** Items come from workspace config, so one team edits them in one place. */+function parseItems(config) {+ return String(config.items ?? "")+ .split("\n")+ .map((line) => line.trim())+ .filter(Boolean);+}++/** State is per issue, keyed so two issues never share ticks. */+const stateKey = (issueId) => `checklist:${issueId}`;++/**+ * Ticks are stored as the item TEXT, not an index. If someone edits the+ * checklist in settings, an index-keyed state would silently re-point every+ * tick at a different item; keying by text loses the tick instead, which is the+ * honest outcome.+ */+function readState(raw) {+ if (!raw) return new Set();+ try {+ const parsed = JSON.parse(raw);+ return new Set(Array.isArray(parsed?.done) ? parsed.done : []);+ } catch {+ return new Set();+ }+}++function renderSignoff(template, items) {+ return String(template ?? "").replace("{{items}}", items.map((item) => `- ${item}`).join("\n"));+}++// --- rendering ------------------------------------------------------------++// Styles live here rather than in a stylesheet so the whole surface is one+// static file. Everything visual is expressed in the tokens the host pushes in,+// so the panel follows the product's theme without shipping its own palette.+const STYLES = `+.wrap { padding: 12px 14px; display: grid; gap: 10px; }+.head { display: flex; align-items: baseline; gap: 8px; }+.count { font-weight: 600; }+.muted { color: var(--muted-foreground); font-size: var(--text-caption, 12px); }+.list { list-style: none; margin: 0; padding: 0; display: grid; gap: 6px; }+.list label { display: flex; align-items: center; gap: 8px; cursor: pointer; }+.struck { text-decoration: line-through; color: var(--muted-foreground); }+.foot { display: flex; align-items: center; gap: 10px; border-top: 1px solid var(--border); padding-top: 10px; }+button {+ padding: 5px 10px; border-radius: var(--radius, 6px);+ border: 1px solid var(--border); background: var(--background); color: var(--foreground);+ font: inherit; cursor: pointer;+}+button:disabled { opacity: .5; cursor: not-allowed; }+`;++function installStyles() {+ const style = document.createElement("style");+ style.textContent = STYLES;+ document.head.appendChild(style);+}++const el = (id) => document.getElementById(id);++async function boot() {+ installStyles();+ const root = el("root");+ root.innerHTML = `<div class="wrap"><div id="status" class="muted">Loading…</div></div>`;+ resize();++ let context;+ try {+ context = await call("GET", "/context");+ } catch (error) {+ return fail(`Could not read context: ${error.message}`);+ }+ if (!context.issue) return fail("This panel only works on an issue.");++ const items = parseItems(context.config);+ if (items.length === 0) {+ return fail("No checklist items configured yet — set them in Settings → Plugins.");+ }++ let done;+ try {+ const stored = await call("GET", `/storage/workspace/${encodeURIComponent(stateKey(context.issue.id))}`);+ done = readState(stored?.value);+ } catch (error) {+ if (error.status !== 404) return fail(`Could not read saved state: ${error.message}`);+ done = new Set();+ }++ render(context, items, done);+}++function fail(message) {+ el("root").innerHTML = `<div class="wrap"><div class="muted">${escapeHtml(message)}</div></div>`;+ resize();+}++function escapeHtml(value) {+ return String(value).replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]);+}++function render(context, items, done) {+ const complete = items.every((item) => done.has(item));+ const strict = context.config.strict === true;++ el("root").innerHTML = `+ <div class="wrap">+ <div class="head">+ <span class="count">${done.size} / ${items.length}</span>+ <span class="muted">${escapeHtml(context.issue.identifier)}</span>+ </div>+ <ul class="list">+ ${items.map((item, index) => `+ <li>+ <label>+ <input type="checkbox" data-index="${index}" ${done.has(item) ? "checked" : ""}>+ <span class="${done.has(item) ? "struck" : ""}">${escapeHtml(item)}</span>+ </label>+ </li>`).join("")}+ </ul>+ <div class="foot">+ <button id="signoff" ${strict && !complete ? "disabled" : ""}>Post sign-off</button>+ <span id="status" class="muted">${complete ? "All items complete." : ""}</span>+ </div>+ </div>`;++ const status = (text) => { el("status").textContent = text; resize(); };++ for (const box of document.querySelectorAll('input[type="checkbox"]')) {+ box.addEventListener("change", async () => {+ const item = items[Number(box.dataset.index)];+ if (box.checked) done.add(item); else done.delete(item);+ try {+ // storage:workspace — the whole team sees the same ticks on this issue.+ await call("PUT", `/storage/workspace/${encodeURIComponent(stateKey(context.issue.id))}`,+ { value: JSON.stringify({ done: [...done] }) });+ render(context, items, done);+ } catch (error) {+ if (box.checked) done.delete(item); else done.add(item);+ box.checked = !box.checked;+ status(error.message);+ }+ });+ }++ el("signoff").addEventListener("click", async () => {+ const outstanding = items.filter((item) => !done.has(item));+ if (strict && outstanding.length > 0) return status(`${outstanding.length} item(s) still open.`);+ status("Posting…");+ try {+ // Lands as the signed-in user, recorded as posted through this plugin.+ await call("POST", `/issues/${encodeURIComponent(context.issue.id)}/comments`, {+ content: renderSignoff(context.config.signoff_template, items.filter((item) => done.has(item))),+ });+ status("Sign-off posted.");+ } catch (error) {+ // 403 here means the admin did not grant comments:write — a different fix+ // from a network failure, so it is surfaced verbatim.+ status(error.message);+ }+ });++ resize();+}diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex f08fadeba5..6a5f4dcf25 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -2471,6 +2471,28 @@ export class ApiClient {});}+ /**+ * Performs one Action API call on behalf of a plugin surface.+ *+ * The surface has no credential — it asked the host over postMessage, and+ * this re-issues the call on the signed-in user's session. The installation+ * travels in a header the iframe cannot set for itself; the server derives+ * the workspace from it rather than trusting anything the client sends.+ */+ async callPluginAction(+ installationId: string,+ request: { method: "GET" | "POST" | "PATCH" | "PUT" | "DELETE"; path: string; body?: unknown; issueId?: string },+ ): Promise<unknown> {+ const query = request.path === "/context" && request.issueId+ ? `?issue_id=${encodeURIComponent(request.issueId)}`+ : "";+ return this.fetch<unknown>(`/api/v1/plugin${request.path}${query}`, {+ method: request.method,+ headers: { "X-Multica-Plugin-Installation": installationId },+ body: request.body === undefined ? undefined : JSON.stringify(request.body),+ });+ }+async uninstallPlugin(workspaceId: string, installationId: string): Promise<void> {await this.fetch(`/api/workspaces/${workspaceId}/plugins/${installationId}`, {method: "DELETE",diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 87b1606fbf..4ecffe277f 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -88,6 +88,7 @@ export const PluginConfigFieldSchema = z.object({required: z.boolean().default(false),options: z.array(z.string()).default([]),placeholder: z.string().optional(),+ multiline: z.boolean().default(false),}).loose();export const PluginSurfaceSchema = z.object({diff --git a/packages/core/types/plugin.ts b/packages/core/types/plugin.tsindex 507184ef82..562fee010c 100644--- a/packages/core/types/plugin.ts+++ b/packages/core/types/plugin.ts@@ -15,6 +15,8 @@ export interface PluginConfigField {required: boolean;options?: string[];placeholder?: string;+ /** String fields only: render a textarea instead of a single-line input. */+ multiline?: boolean;}export type PluginSurfaceType = "issue_panel" | "sidebar_panel" | "modal";diff --git a/packages/plugin-sdk/README.md b/packages/plugin-sdk/README.mdnew file mode 100644index 0000000000..011b85e846--- /dev/null+++ b/packages/plugin-sdk/README.md@@ -0,0 +1,64 @@+# @multica/plugin-sdk++What a Multica plugin surface imports.++```js+import { multica } from "@multica/plugin-sdk";++const ctx = await multica.context.get();+const issue = await multica.issue.get();+await multica.issue.comment({ body: "hello" });+const note = await multica.storage.user.get("note");+multica.ui.resize(320);+```++## What a surface is++An ordinary script in a sandboxed iframe. Multica never executes plugin code on+its servers — a surface runs in the user's browser, or on your own server behind+a hook.++The frame is mounted with `sandbox="allow-scripts"` and **not**+`allow-same-origin`, so it has an opaque origin. Consequences worth knowing+before you write one:++- **No browser storage.** `localStorage`, `sessionStorage` and cookies all throw+ or are empty. Use `multica.storage` — it is server-side, scoped per workspace+ or per member, and survives the frame.+- **`Origin: null` on your own requests.** If your surface calls your backend+ directly, that backend must accept a null origin in CORS.+- **A CSP you did not write.** The host generates the document and derives+ `connect-src` from the `net:` scopes in your manifest. Declare every host you+ intend to reach; a surface with no `net:` scope cannot make network requests+ at all. `net:` is an exact host — declare `net:api.example.com` separately from+ `net:example.com`.++## What you can do, and what bounds it++Every call becomes a message to the host, which performs it on the signed-in+user's own session. Two limits apply at once:++1. the scopes the workspace admin granted your plugin, and+2. what that particular user could already do themselves.++So a member without access to an issue gets a 404 through your surface too, and+a scope the admin declined is a 403 that names it. Errors are+`MulticaPluginError` with a `status` mirroring HTTP.++A comment you post is authored by **the user**, recorded as having been made+through your plugin. It does not run `@mention` trigger dispatch — a surface+cannot start agent runs as a side effect of posting text.++## Theme++The host pushes design tokens in at init and again on every theme switch, and+the SDK writes them as custom properties on `:root`. Use `var(--foreground)`,+`var(--background)`, `var(--border)`, `var(--radius)` and friends and your+surface will look native without shipping a stylesheet.++`multica.ui.onThemeChange(fn)` if you need to react in JS.++## Sizing++The frame does not auto-size. Call `multica.ui.resize(px)` after your content+settles; the host clamps the value.diff --git a/packages/plugin-sdk/eslint.config.mjs b/packages/plugin-sdk/eslint.config.mjsnew file mode 100644index 0000000000..50da62496d--- /dev/null+++ b/packages/plugin-sdk/eslint.config.mjs@@ -0,0 +1,3 @@+import reactConfig from "@multica/eslint-config/react";++export default [...reactConfig];diff --git a/packages/plugin-sdk/index.ts b/packages/plugin-sdk/index.tsnew file mode 100644index 0000000000..c875a97bde--- /dev/null+++ b/packages/plugin-sdk/index.ts@@ -0,0 +1,298 @@+/**+ * @multica/plugin-sdk — what a plugin surface imports.+ *+ * A surface is an ordinary script running in a sandboxed iframe. It holds no+ * credential and cannot reach Multica's API directly: every call here becomes a+ * message to the host page, which performs the call on the signed-in user's own+ * session and sends the result back. That indirection is the whole security+ * story — a plugin can never do more than the person looking at it, and there+ * is no token in the frame to leak.+ *+ * Zero runtime dependencies, and deliberately no import of `@multica/core` or+ * `@multica/ui`: this ships to third parties.+ */++import {+ BRIDGE_INIT_MESSAGE,+ BRIDGE_PROTOCOL_VERSION,+ BRIDGE_READY_MESSAGE,+ isBridgeEvent,+ isBridgeResponse,+ type BridgeMethod,+ type BridgeRequest,+ type ThemeTokens,+} from "./protocol";++export type { ThemeTokens } from "./protocol";++export interface PluginContext {+ workspace: { id: string; name: string; slug: string };+ user: { id: string; name: string };+ issue?: { id: string; identifier: string; title: string };+ /** Non-secret installation configuration. Secrets never reach the frame. */+ config: Record<string, unknown>;+ /** Domains this installation was granted via `net:` scopes. */+ granted_net_domains: string[];+}++export interface Issue {+ id: string;+ identifier: string;+ title: string;+ description?: string | null;+ status: string;+ priority: string;+}++export interface Comment {+ id: string;+ author_type: string;+ author_id: string;+ content: string;+ type: string;+ parent_id?: string;+ created_at: string;+}++export interface StorageKey {+ key: string;+ size_bytes: number;+ updated_at: string;+}++/** Thrown when the host refuses or the call fails. `status` mirrors HTTP. */+export class MulticaPluginError extends Error {+ readonly status: number;++ constructor(status: number, message: string) {+ super(message);+ this.name = "MulticaPluginError";+ this.status = status;+ }+}++const DEFAULT_TIMEOUT_MS = 15_000;+const ANNOUNCE_INTERVAL_MS = 120;+const ANNOUNCE_ATTEMPTS = 50;++type Pending = {+ resolve: (value: unknown) => void;+ reject: (error: Error) => void;+ timer: ReturnType<typeof setTimeout>;+};++class Bridge {+ private port: MessagePort | null = null;+ private readonly pending = new Map<string, Pending>();+ private readonly queued: BridgeRequest[] = [];+ private ready: Promise<void>;+ private markReady!: () => void;+ private sequence = 0;+ private theme: ThemeTokens = {};+ private readonly themeListeners = new Set<(theme: ThemeTokens) => void>();++ constructor() {+ this.ready = new Promise((resolve) => {+ this.markReady = resolve;+ });+ if (typeof window !== "undefined") {+ window.addEventListener("message", this.onWindowMessage);+ this.announce();+ }+ }++ /**+ * Announces until the host answers with a port.+ *+ * One announcement is not enough in either direction: a srcdoc frame can+ * finish executing before the embedder's effect attaches its listener, and a+ * host that waits on the iframe load event can miss it entirely. Repeating+ * until the port arrives makes the handshake independent of who is ready+ * first, which is the only ordering nobody controls.+ */+ private announce() {+ if (typeof window === "undefined" || !window.parent) return;+ let attempts = 0;+ const beat = () => {+ if (this.port || attempts++ > ANNOUNCE_ATTEMPTS) return;+ // targetOrigin "*" because this frame has an opaque origin and cannot+ // know the embedder's. The message carries nothing but the signal.+ window.parent.postMessage({ type: BRIDGE_READY_MESSAGE }, "*");+ setTimeout(beat, ANNOUNCE_INTERVAL_MS);+ };+ beat();+ }++ private onWindowMessage = (event: MessageEvent) => {+ const data = event.data as { type?: string; version?: number; theme?: ThemeTokens } | null;+ if (!data || data.type !== BRIDGE_INIT_MESSAGE) return;+ const port = event.ports?.[0];+ if (!port) return;+ // Only the embedder may hand this frame a port.+ //+ // Sibling frames are mutually opaque, but `parent.frames[i]` is an indexed+ // cross-origin access the spec allows, so another plugin on the same page+ // can postMessage into this one. Without this check it could deliver its own+ // MessagePort and become this surface's "host": feed it fabricated issue+ // data and read everything the surface writes, including whatever it puts in+ // storage:user. Origin cannot be compared — a sandboxed frame sees "null" —+ // so the embedder is identified by window reference, mirroring the host's+ // own check on the readiness signal.+ if (event.source !== window.parent) return;+ // First init wins. A hijacker that lost the race could otherwise send a+ // second init and take the channel over afterwards.+ if (this.port) return;+ if (data.version !== BRIDGE_PROTOCOL_VERSION) {+ // A host newer or older than this SDK: fail loudly rather than guess at a+ // shape neither side agreed on.+ return;+ }+ this.port = port;+ port.onmessage = this.onPortMessage;+ port.start?.();+ if (data.theme) this.applyTheme(data.theme);+ for (const request of this.queued.splice(0)) port.postMessage(request);+ this.markReady();+ };++ private onPortMessage = (event: MessageEvent) => {+ const message = event.data;+ if (isBridgeEvent(message)) {+ this.applyTheme(message.theme);+ return;+ }+ if (!isBridgeResponse(message)) return;+ const pending = this.pending.get(message.id);+ if (!pending) return;+ this.pending.delete(message.id);+ clearTimeout(pending.timer);+ if (message.ok) pending.resolve(message.data);+ else pending.reject(new MulticaPluginError(message.status, message.error));+ };++ private applyTheme(theme: ThemeTokens) {+ this.theme = theme;+ if (typeof document !== "undefined") {+ for (const [name, value] of Object.entries(theme)) {+ document.documentElement.style.setProperty(name, value);+ }+ }+ for (const listener of this.themeListeners) listener(theme);+ }++ onThemeChange(listener: (theme: ThemeTokens) => void): () => void {+ this.themeListeners.add(listener);+ if (Object.keys(this.theme).length > 0) listener(this.theme);+ return () => this.themeListeners.delete(listener);+ }++ /** Fire-and-forget: the host never answers these. */+ notify(request: BridgeRequest) {+ if (this.port) this.port.postMessage(request);+ else this.queued.push(request);+ }++ async request<T>(method: BridgeMethod, path: string, body?: unknown): Promise<T> {+ await this.ready;+ const id = `r${++this.sequence}`;+ const request: BridgeRequest = { id, kind: "action", method, path, body };+ return new Promise<T>((resolve, reject) => {+ const timer = setTimeout(() => {+ this.pending.delete(id);+ reject(new MulticaPluginError(408, `Multica did not answer ${method} ${path} in time`));+ }, DEFAULT_TIMEOUT_MS);+ this.pending.set(id, { resolve: resolve as (value: unknown) => void, reject, timer });+ this.port?.postMessage(request);+ });+ }+}++const bridge = new Bridge();++function storageApi(scope: "workspace" | "user") {+ return {+ async list(): Promise<StorageKey[]> {+ const result = await bridge.request<{ keys: StorageKey[] }>("GET", `/storage/${scope}`);+ return result.keys ?? [];+ },+ async get(key: string): Promise<string | null> {+ try {+ const result = await bridge.request<{ value: string }>("GET", `/storage/${scope}/${encodeURIComponent(key)}`);+ return result.value;+ } catch (error) {+ // A missing key is an ordinary outcome, not an error to handle.+ if (error instanceof MulticaPluginError && error.status === 404) return null;+ throw error;+ }+ },+ async set(key: string, value: string): Promise<void> {+ await bridge.request<void>("PUT", `/storage/${scope}/${encodeURIComponent(key)}`, { value });+ },+ async delete(key: string): Promise<void> {+ await bridge.request<void>("DELETE", `/storage/${scope}/${encodeURIComponent(key)}`);+ },+ };+}++let cachedContext: PluginContext | null = null;++export const multica = {+ context: {+ /** Who is looking, where, and which issue this surface is mounted on. */+ async get(force = false): Promise<PluginContext> {+ if (cachedContext && !force) return cachedContext;+ cachedContext = await bridge.request<PluginContext>("GET", "/context");+ return cachedContext;+ },+ },++ issue: {+ /** Defaults to the issue this surface is mounted on. */+ async get(issueId?: string): Promise<Issue> {+ const id = issueId ?? (await requireIssueId());+ return bridge.request<Issue>("GET", `/issues/${encodeURIComponent(id)}`);+ },+ async update(patch: { title?: string; description?: string }, issueId?: string): Promise<Issue> {+ const id = issueId ?? (await requireIssueId());+ return bridge.request<Issue>("PATCH", `/issues/${encodeURIComponent(id)}`, patch);+ },+ async comments(issueId?: string): Promise<Comment[]> {+ const id = issueId ?? (await requireIssueId());+ const result = await bridge.request<{ comments: Comment[] }>("GET", `/issues/${encodeURIComponent(id)}/comments`);+ return result.comments ?? [];+ },+ async comment(input: { body: string; parentId?: string }, issueId?: string): Promise<Comment> {+ const id = issueId ?? (await requireIssueId());+ return bridge.request<Comment>("POST", `/issues/${encodeURIComponent(id)}/comments`, {+ content: input.body,+ parent_id: input.parentId,+ });+ },+ },++ storage: {+ workspace: storageApi("workspace"),+ user: storageApi("user"),+ },++ ui: {+ /** Ask the host for a different frame height, in CSS pixels. */+ resize(height: number) {+ bridge.notify({ id: `resize${Date.now()}`, kind: "ui.resize", height: Math.max(0, Math.round(height)) });+ },+ /** Current design tokens, and a subscription for theme switches. */+ onThemeChange(listener: (theme: ThemeTokens) => void): () => void {+ return bridge.onThemeChange(listener);+ },+ },+};++async function requireIssueId(): Promise<string> {+ const context = await multica.context.get();+ if (!context.issue) {+ throw new MulticaPluginError(400, "This surface is not mounted on an issue; pass an issue id explicitly.");+ }+ return context.issue.id;+}++export default multica;diff --git a/packages/plugin-sdk/package.json b/packages/plugin-sdk/package.jsonnew file mode 100644index 0000000000..3e756afb81--- /dev/null+++ b/packages/plugin-sdk/package.json@@ -0,0 +1,25 @@+{+ "name": "@multica/plugin-sdk",+ "version": "0.1.0",+ "description": "Client SDK for Multica plugin surfaces.",+ "type": "module",+ "license": "Apache-2.0",+ "scripts": {+ "typecheck": "tsc --noEmit",+ "lint": "eslint ."+ },+ "exports": {+ ".": "./index.ts",+ "./protocol": "./protocol.ts"+ },+ "files": [+ "index.ts",+ "protocol.ts",+ "README.md"+ ],+ "devDependencies": {+ "@multica/eslint-config": "workspace:*",+ "@multica/tsconfig": "workspace:*",+ "typescript": "catalog:"+ }+}diff --git a/packages/plugin-sdk/protocol.ts b/packages/plugin-sdk/protocol.tsnew file mode 100644index 0000000000..a87446afd4--- /dev/null+++ b/packages/plugin-sdk/protocol.ts@@ -0,0 +1,88 @@+/**+ * The bridge wire format, shared in spirit by the surface (this package) and+ * the host (`packages/views/plugins`). It is duplicated rather than imported:+ * the SDK ships to plugin authors and must not pull `@multica/core` or+ * `@multica/ui` in behind it, and the host must not depend on a package a+ * third party could install a different version of.+ *+ * Two properties matter more than the shape:+ *+ * - Identity is bound by a MessagePort, not by `event.origin`. A surface runs+ * in a sandboxed iframe with no `allow-same-origin`, so its origin is the+ * opaque string "null" — every surface would look identical. The host hands+ * each iframe its own port at init and only ever listens on that port, so+ * "which plugin sent this" is answered by which channel it arrived on.+ * - No credential crosses this boundary. The surface asks; the host performs+ * the call on the user's session and returns the result.+ */++export const BRIDGE_PROTOCOL_VERSION = 1;++/** Marks the single window message that carries the port. */+export const BRIDGE_INIT_MESSAGE = "multica:plugin-bridge-init";++/**+ * Posted by the surface to its embedder once its message listener is attached.+ *+ * The handshake has to start from the guest. A srcdoc frame can finish loading+ * before the embedder's React `onLoad` handler is even attached, so a host that+ * connects on load either misses the event entirely or sends the port before+ * anything is listening for it — both look identical from outside: a blank+ * panel. The host answers this signal instead, and matches `event.source`+ * against the iframe it created so another frame cannot claim the port.+ */+export const BRIDGE_READY_MESSAGE = "multica:plugin-surface-ready";++export type BridgeInitMessage = {+ type: typeof BRIDGE_INIT_MESSAGE;+ version: number;+ theme: ThemeTokens;+};++/** Design tokens the host pushes so a surface matches the product it sits in. */+export type ThemeTokens = Record<string, string>;++export type BridgeMethod = "GET" | "POST" | "PATCH" | "PUT" | "DELETE";++export type BridgeRequest =+ | {+ id: string;+ kind: "action";+ method: BridgeMethod;+ /** Path under the plugin Action API, e.g. "/issues/{id}/comments". */+ path: string;+ body?: unknown;+ }+ | {+ id: string;+ kind: "ui.resize";+ height: number;+ };++export type BridgeResponse =+ | { id: string; ok: true; status: number; data: unknown }+ | { id: string; ok: false; status: number; error: string };++/** Host-initiated, unsolicited: theme changes while the surface is mounted. */+export type BridgeEvent = { kind: "theme"; theme: ThemeTokens };++export type BridgeMessage = BridgeResponse | BridgeEvent;++export function isBridgeResponse(message: unknown): message is BridgeResponse {+ if (typeof message !== "object" || message === null) return false;+ const candidate = message as Record<string, unknown>;+ return typeof candidate.id === "string" && typeof candidate.ok === "boolean";+}++export function isBridgeEvent(message: unknown): message is BridgeEvent {+ if (typeof message !== "object" || message === null) return false;+ return (message as Record<string, unknown>).kind === "theme";+}++export function isBridgeRequest(message: unknown): message is BridgeRequest {+ if (typeof message !== "object" || message === null) return false;+ const candidate = message as Record<string, unknown>;+ if (typeof candidate.id !== "string") return false;+ if (candidate.kind === "ui.resize") return typeof candidate.height === "number";+ return candidate.kind === "action" && typeof candidate.path === "string" && typeof candidate.method === "string";+}diff --git a/packages/plugin-sdk/tsconfig.json b/packages/plugin-sdk/tsconfig.jsonnew file mode 100644index 0000000000..5aa3f57f74--- /dev/null+++ b/packages/plugin-sdk/tsconfig.json@@ -0,0 +1,9 @@+{+ "extends": "@multica/tsconfig/react-library.json",+ "compilerOptions": {+ "outDir": "dist",+ "rootDir": "."+ },+ "include": ["**/*.ts", "**/*.tsx"],+ "exclude": ["node_modules", "dist"]+}diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsxindex d4ad548ba3..cc8851248e 100644--- a/packages/views/issues/components/issue-detail.tsx+++ b/packages/views/issues/components/issue-detail.tsx@@ -88,6 +88,7 @@ import { collectThreadReplies, deriveThreadResolution } from "./thread-utils";import { IssueAgentHeaderChip } from "./issue-agent-header-chip";import { ExecutionLogSection } from "./execution-log-section";import { QuickActionsSection } from "./quick-actions-section";+import { PluginPanelSection } from "../../plugins";import { PullRequestList } from "./pull-request-list";import { useGitHubSettings } from "@multica/core/github";import { useQuery } from "@tanstack/react-query";@@ -2387,6 +2388,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = trclick an action they cannot run, and the refusal is explained at runtime rather than by a silently shorter list. */}<QuickActionsSection issueId={issue.id} />+ <PluginPanelSection issueId={issue.id} />{/* Parent issue — standalone section, only when the issue has aparent. Setting a parent is reachable via the issue actions menu;diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.jsonindex d80e983158..5ceb0bf7c4 100644--- a/packages/views/locales/en/issues.json+++ b/packages/views/locales/en/issues.json@@ -790,5 +790,10 @@"manage_hint": "Order and visibility only affect you","visible_toggle": "Show in view bar","more_label": "More views"+ },+ "plugins": {+ "panels": "Plugins",+ "surface_failed": "{{name}} could not load its interface.",+ "surface_local_only": "{{name}} was installed from a local source, so its interface cannot be loaded in the browser."}}diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.jsonindex 71a4f5b550..e208fab2cc 100644--- a/packages/views/locales/ja/issues.json+++ b/packages/views/locales/ja/issues.json@@ -760,5 +760,10 @@"manage_hint": "並び順と表示設定は自分にのみ適用されます","visible_toggle": "ビューバーに表示","more_label": "その他のビュー"+ },+ "plugins": {+ "panels": "Plugins",+ "surface_failed": "{{name}} のインターフェースを読み込めませんでした。",+ "surface_local_only": "{{name}} はローカルソースからインストールされているため、ブラウザでインターフェースを読み込めません。"}}diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.jsonindex 53785955b2..7babc3647f 100644--- a/packages/views/locales/ko/issues.json+++ b/packages/views/locales/ko/issues.json@@ -760,5 +760,10 @@"manage_hint": "순서와 표시 설정은 본인에게만 적용됩니다","visible_toggle": "뷰 바에 표시","more_label": "더 많은 뷰"+ },+ "plugins": {+ "panels": "Plugins",+ "surface_failed": "{{name}}의 인터페이스를 불러오지 못했습니다.",+ "surface_local_only": "{{name}}은(는) 로컬 소스에서 설치되어 브라우저에서 인터페이스를 불러올 수 없습니다."}}diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.jsonindex 0ea113a251..4f1a77aba6 100644--- a/packages/views/locales/zh-Hans/issues.json+++ b/packages/views/locales/zh-Hans/issues.json@@ -760,5 +760,10 @@"manage_hint": "排序与显隐只影响你自己","visible_toggle": "在视图栏显示","more_label": "更多视图"+ },+ "plugins": {+ "panels": "Plugins",+ "surface_failed": "{{name}} 的界面加载失败。",+ "surface_local_only": "{{name}} 是从本地源安装的,界面无法在浏览器里加载。"}}diff --git a/packages/views/package.json b/packages/views/package.jsonindex 4fbad0b43a..dd6e1749bb 100644--- a/packages/views/package.json+++ b/packages/views/package.json@@ -122,6 +122,7 @@},"devDependencies": {"@multica/eslint-config": "workspace:*",+ "@multica/plugin-sdk": "workspace:*","@multica/tsconfig": "workspace:*","@testing-library/jest-dom": "catalog:","@testing-library/react": "catalog:",diff --git a/packages/views/plugins/index.ts b/packages/views/plugins/index.tsnew file mode 100644index 0000000000..cacbcb8a49--- /dev/null+++ b/packages/views/plugins/index.ts@@ -0,0 +1,3 @@+export { PluginPanelSection } from "./plugin-panel-section";+export { PluginSurfaceFrame } from "./plugin-surface-frame";+export { buildSurfaceCSP, buildSurfaceDocument, resolveSurfaceEntry, surfaceConnectSources } from "./surface-document";diff --git a/packages/views/plugins/plugin-panel-section.test.tsx b/packages/views/plugins/plugin-panel-section.test.tsxnew file mode 100644index 0000000000..b15cb847b3--- /dev/null+++ b/packages/views/plugins/plugin-panel-section.test.tsx@@ -0,0 +1,115 @@+import type { ReactNode } from "react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { render, screen } from "@testing-library/react";+import { I18nProvider } from "@multica/core/i18n/react";+import enCommon from "../locales/en/common.json";+import enIssues from "../locales/en/issues.json";++const data = vi.hoisted(() => ({+ installed: { plugins: [] as Array<Record<string, unknown>> },+ flagEnabled: true,+}));++vi.mock("@tanstack/react-query", () => ({+ useQuery: () => ({ data: data.installed, isLoading: false, isError: false }),+}));+vi.mock("@multica/core/plugins", () => ({ pluginInstallationsOptions: () => ({ queryKey: ["plugins"] }) }));+vi.mock("@multica/core/paths", () => ({ useCurrentWorkspace: () => ({ id: "workspace-1", name: "Acme", slug: "acme" }) }));+vi.mock("@multica/core/config", () => ({ useFeatureEnabled: () => data.flagEnabled }));+vi.mock("../platform/local-directory", () => ({ isDesktopShell: () => false }));++import { PluginPanelSection } from "./plugin-panel-section";++const TEST_RESOURCES = { en: { common: enCommon, issues: enIssues } };++function Wrapper({ children }: { children: ReactNode }) {+ return <I18nProvider locale="en" resources={TEST_RESOURCES}>{children}</I18nProvider>;+}++function installation(overrides: Record<string, unknown> = {}) {+ return {+ id: "installation-1",+ plugin_key: "com.example.hello",+ name: "Hello Panel",+ version: "1.0.0",+ source_url: "https://example.com/plugin/multica.plugin.json",+ enabled: true,+ granted_scopes: ["issues:read"],+ config_schema: [],+ config: {},+ configured_secrets: [],+ surfaces: [{ key: "hello", type: "issue_panel", name: "Hello", entry: "ui/main.js", platforms: [] }],+ hooks: [],+ resources: [],+ created_at: "",+ updated_at: "",+ ...overrides,+ };+}++describe("PluginPanelSection", () => {+ beforeEach(() => {+ data.installed.plugins = [];+ data.flagEnabled = true;+ });++ it("mounts an enabled issue_panel in a sandbox that never gets allow-same-origin", () => {+ data.installed.plugins = [installation()];+ render(<PluginPanelSection issueId="issue-1" />, { wrapper: Wrapper });++ const frame = screen.getByTitle("Hello Panel — Hello");+ // allow-scripts WITHOUT allow-same-origin is the entire isolation boundary.+ // The pairing is what the HTML spec calls out as defeating the sandbox, so+ // this assertion is the regression guard for the whole surface model.+ expect(frame).toHaveAttribute("sandbox", "allow-scripts");+ expect(frame.getAttribute("sandbox")).not.toContain("allow-same-origin");+ // srcDoc, not src: the host generates the document so it can set the CSP.+ expect(frame).toHaveAttribute("srcdoc");+ expect(frame).not.toHaveAttribute("src");+ });++ it("does not mount a disabled installation", () => {+ data.installed.plugins = [installation({ enabled: false })];+ render(<PluginPanelSection issueId="issue-1" />, { wrapper: Wrapper });+ expect(screen.queryByTitle("Hello Panel — Hello")).not.toBeInTheDocument();+ });++ it("ignores surfaces that belong somewhere other than the issue page", () => {+ data.installed.plugins = [installation({+ surfaces: [{ key: "side", type: "sidebar_panel", name: "Side", entry: "ui/main.js", platforms: [] }],+ })];+ render(<PluginPanelSection issueId="issue-1" />, { wrapper: Wrapper });+ expect(screen.queryByTitle("Hello Panel — Side")).not.toBeInTheDocument();+ });++ it("does not render a surface this platform is excluded from", () => {+ // platforms is a filter, not a hint: a desktop-only panel appearing on web+ // is a surface running somewhere its author said it should not.+ data.installed.plugins = [installation({+ surfaces: [{ key: "hello", type: "issue_panel", name: "Hello", entry: "ui/main.js", platforms: ["desktop"] }],+ })];+ render(<PluginPanelSection issueId="issue-1" />, { wrapper: Wrapper });+ expect(screen.queryByTitle("Hello Panel — Hello")).not.toBeInTheDocument();+ });++ it("renders a surface that declares no platforms at all", () => {+ data.installed.plugins = [installation()];+ render(<PluginPanelSection issueId="issue-1" />, { wrapper: Wrapper });+ expect(screen.getByTitle("Hello Panel — Hello")).toBeInTheDocument();+ });++ it("renders nothing when the feature flag is off", () => {+ data.flagEnabled = false;+ data.installed.plugins = [installation()];+ const { container } = render(<PluginPanelSection issueId="issue-1" />, { wrapper: Wrapper });+ expect(container).toBeEmptyDOMElement();+ });++ it("says why a local install cannot render instead of showing an empty frame", () => {+ data.installed.plugins = [installation({ source_url: "local:hello" })];+ render(<PluginPanelSection issueId="issue-1" />, { wrapper: Wrapper });++ expect(screen.queryByTitle("Hello Panel — Hello")).not.toBeInTheDocument();+ expect(screen.getByText(/installed from a local source/i)).toBeInTheDocument();+ });+});diff --git a/packages/views/plugins/plugin-panel-section.tsx b/packages/views/plugins/plugin-panel-section.tsxnew file mode 100644index 0000000000..95e1dc5620--- /dev/null+++ b/packages/views/plugins/plugin-panel-section.tsx@@ -0,0 +1,59 @@+"use client";++import { useMemo } from "react";+import { useQuery } from "@tanstack/react-query";+import { pluginInstallationsOptions } from "@multica/core/plugins";+import { useCurrentWorkspace } from "@multica/core/paths";+import { useFeatureEnabled } from "@multica/core/config";+import { PLUGINS_V1_FLAG } from "@multica/core/feature-flags";+import { useT } from "../i18n";+import { isDesktopShell } from "../platform/local-directory";+import { PluginSurfaceFrame } from "./plugin-surface-frame";++/**+ * Renders every enabled `issue_panel` surface on an issue.+ *+ * Disabled installations are filtered here AND refused by the Action API — the+ * client filter is presentation, the server check is the control. A surface+ * left open in a stale tab stops working even though this component never+ * re-rendered.+ */+export function PluginPanelSection({ issueId }: { issueId: string }) {+ const { t } = useT("issues");+ const platform = isDesktopShell() ? "desktop" : "web";+ const workspace = useCurrentWorkspace();+ const wsId = workspace?.id ?? "";+ const pluginsEnabled = useFeatureEnabled(PLUGINS_V1_FLAG, false);++ const { data } = useQuery({ ...pluginInstallationsOptions(wsId), enabled: pluginsEnabled && wsId.length > 0 });++ const panels = useMemo(() => {+ const installations = data?.plugins ?? [];+ return installations+ .filter((installation) => installation.enabled === true)+ .flatMap((installation) =>+ installation.surfaces+ .filter((surface) => surface.type === "issue_panel")+ // An empty list means "anywhere"; a declared list is a filter, not a+ // hint, or a desktop-only panel renders on web anyway.+ .filter((surface) => (surface.platforms ?? []).length === 0 || (surface.platforms ?? []).includes(platform))+ .map((surface) => ({ installation, surface })),+ );+ }, [data, platform]);++ if (!pluginsEnabled || panels.length === 0) return null;++ return (+ <section className="space-y-3">+ <h3 className="px-0.5 text-caption font-medium text-muted-foreground">{t(($) => $.plugins.panels)}</h3>+ {panels.map(({ installation, surface }) => (+ <PluginSurfaceFrame+ key={`${installation.id}:${surface.key}`}+ installation={installation}+ surface={surface}+ issueId={issueId}+ />+ ))}+ </section>+ );+}diff --git a/packages/views/plugins/plugin-sdk-handshake.test.ts b/packages/views/plugins/plugin-sdk-handshake.test.tsnew file mode 100644index 0000000000..0c9a3117fe--- /dev/null+++ b/packages/views/plugins/plugin-sdk-handshake.test.ts@@ -0,0 +1,111 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from "vitest";++// Lives here rather than beside the SDK on purpose: @multica/plugin-sdk ships+// as TypeScript source to third parties and carries no test runner of its own,+// and packages/views is its only consumer in this repo.+//+// The guest half of the handshake. Sibling surfaces are mutually opaque but+// `parent.frames[i]` is an allowed cross-origin access, so another plugin on the+// same page can postMessage into this one. What stops it from becoming this+// surface's "host" is the two checks below — neither is visible from reading a+// plugin's own code, which is exactly why they are pinned here.+//+// Runs on a hand-built window rather than jsdom: the SDK touches exactly+// `addEventListener` and `parent`, and a package that ships to third parties is+// better off with no test-only dependency at all.++class FakeWindow extends EventTarget {+ parent: FakeWindow = this;+ readonly sent: unknown[] = [];+ postMessage(message: unknown) {+ this.sent.push(message);+ }+}++let fakeWindow: FakeWindow;++async function loadSdk() {+ vi.resetModules();+ fakeWindow = new FakeWindow();+ vi.stubGlobal("window", fakeWindow);+ // The SDK writes theme tokens to documentElement when a host sends them; no+ // theme is sent here, so a document is never touched.+ vi.stubGlobal("document", undefined);+ return import("@multica/plugin-sdk");+}++function initFrom(source: unknown, port: MessagePort) {+ const event = new MessageEvent("message", {+ data: { type: "multica:plugin-bridge-init", version: 1 },+ });+ Object.defineProperty(event, "source", { value: source, configurable: true });+ Object.defineProperty(event, "ports", { value: [port], configurable: true });+ fakeWindow.dispatchEvent(event);+}++const settle = () => new Promise((resolve) => setTimeout(resolve, 0));++describe("surface bridge handshake", () => {+ beforeEach(() => {+ vi.useRealTimers();+ });++ it("accepts a port from the embedder and answers on it", async () => {+ const { multica } = await loadSdk();+ const channel = new MessageChannel();+ const asked: unknown[] = [];+ channel.port2.onmessage = (event) => {+ asked.push(event.data);+ const request = event.data as { id: string };+ channel.port2.postMessage({ id: request.id, ok: true, status: 200, data: { workspace: {}, user: {}, config: {} } });+ };+ channel.port2.start();++ initFrom(fakeWindow.parent, channel.port1);+ await multica.context.get(true);++ expect(asked).toHaveLength(1);+ expect(asked[0]).toMatchObject({ kind: "action", method: "GET", path: "/context" });+ });++ it("ignores an init from a window that is not the embedder", async () => {+ const { multica } = await loadSdk();+ const hostile = new MessageChannel();+ const seen: unknown[] = [];+ hostile.port2.onmessage = (event) => seen.push(event.data);+ hostile.port2.start();++ // A sibling plugin frame shouting an init with its own port.+ initFrom(new FakeWindow(), hostile.port1);+ void multica.context.get(true);+ await settle();++ expect(seen).toHaveLength(0);+ });++ it("keeps the first port when a second init arrives", async () => {+ const { multica } = await loadSdk();+ const real = new MessageChannel();+ const hijack = new MessageChannel();+ const onReal: unknown[] = [];+ const onHijack: unknown[] = [];+ real.port2.onmessage = (event) => onReal.push(event.data);+ hijack.port2.onmessage = (event) => onHijack.push(event.data);+ real.port2.start();+ hijack.port2.start();++ initFrom(fakeWindow.parent, real.port1);+ // Even from the embedder's own window: a hijacker that lost the race must+ // not be able to take the channel over afterwards.+ initFrom(fakeWindow.parent, hijack.port1);+ void multica.context.get(true);+ await settle();++ // The property under test is that the second init cannot capture the+ // channel — traffic keeps going to the port bound first, and the hijacker's+ // port stays silent.+ expect(onHijack).toHaveLength(0);+ expect(onReal.length).toBeGreaterThan(0);+ });+});diff --git a/packages/views/plugins/plugin-sdk-protocol.test.ts b/packages/views/plugins/plugin-sdk-protocol.test.tsnew file mode 100644index 0000000000..bee5e3b250--- /dev/null+++ b/packages/views/plugins/plugin-sdk-protocol.test.ts@@ -0,0 +1,49 @@+// @vitest-environment node+import { describe, expect, it } from "vitest";+import { isBridgeEvent, isBridgeRequest, isBridgeResponse } from "@multica/plugin-sdk/protocol";++// Beside plugin-sdk-handshake.test.ts, and here for the same reason.+//+// The guards are the only thing standing between a hostile message and the+// bridge's handlers on both sides. Anything that is not exactly the agreed+// shape has to fall through, not be coerced into something close enough.++describe("bridge message guards", () => {+ it("accepts the shapes both sides agreed on", () => {+ expect(isBridgeRequest({ id: "r1", kind: "action", method: "GET", path: "/context" })).toBe(true);+ expect(isBridgeRequest({ id: "r1", kind: "ui.resize", height: 200 })).toBe(true);+ expect(isBridgeResponse({ id: "r1", ok: true, status: 200, data: {} })).toBe(true);+ expect(isBridgeResponse({ id: "r1", ok: false, status: 403, error: "nope" })).toBe(true);+ expect(isBridgeEvent({ kind: "theme", theme: {} })).toBe(true);+ });++ it("rejects anything that only looks close enough", () => {+ for (const value of [+ null,+ undefined,+ "action",+ 42,+ {},+ { kind: "action", method: "GET", path: "/context" }, // no id to pair a reply to+ { id: 7, kind: "action", method: "GET", path: "/context" }, // id must be a string+ { id: "r1", kind: "action", method: "GET" }, // no path+ { id: "r1", kind: "ui.resize" }, // no height+ { id: "r1", kind: "ui.resize", height: "200" }, // height must be a number+ { id: "r1", kind: "navigate", url: "https://evil.test" }, // unknown kind+ ]) {+ expect(isBridgeRequest(value)).toBe(false);+ }+ });++ it("does not confuse a response with an event or vice versa", () => {+ // Both travel on the same port, so a mix-up would either resolve a call+ // with a theme payload or apply a response as design tokens.+ expect(isBridgeEvent({ id: "r1", ok: true, status: 200, data: {} })).toBe(false);+ expect(isBridgeResponse({ kind: "theme", theme: {} })).toBe(false);+ });++ it("rejects a response with no boolean outcome", () => {+ expect(isBridgeResponse({ id: "r1", status: 200 })).toBe(false);+ expect(isBridgeResponse({ id: "r1", ok: "true" })).toBe(false);+ });+});diff --git a/packages/views/plugins/plugin-surface-frame.tsx b/packages/views/plugins/plugin-surface-frame.tsxnew file mode 100644index 0000000000..c26d9de152--- /dev/null+++ b/packages/views/plugins/plugin-surface-frame.tsx@@ -0,0 +1,115 @@+"use client";++import { useEffect, useMemo, useRef, useState } from "react";+import type { PluginInstallation, PluginSurface } from "@multica/core/types";+import { cn } from "@multica/ui/lib/utils";+import { useT } from "../i18n";+import { buildSurfaceDocument, readThemeTokens, resolveSurfaceEntry } from "./surface-document";+import { createSurfaceBridge } from "./surface-bridge";++const DEFAULT_HEIGHT = 220;++interface PluginSurfaceFrameProps {+ installation: PluginInstallation;+ surface: PluginSurface;+ issueId?: string;+ className?: string;+}++/**+ * Mounts one plugin surface.+ *+ * `sandbox="allow-scripts"` WITHOUT `allow-same-origin` is the whole isolation+ * boundary and must never be loosened: the pairing is called out in the HTML+ * spec as defeating the sandbox, and it is what would hand a third-party script+ * our cookies and storage. Same rule, same reason as+ * `packages/views/editor/code-block-iframe.tsx`.+ */+export function PluginSurfaceFrame({ installation, surface, issueId, className }: PluginSurfaceFrameProps) {+ const frameRef = useRef<HTMLIFrameElement>(null);+ const anchorRef = useRef<HTMLDivElement>(null);+ const [height, setHeight] = useState(DEFAULT_HEIGHT);+ const [failed, setFailed] = useState(false);++ const entryUrl = useMemo(() => resolveSurfaceEntry(installation, surface), [installation, surface]);++ // Tokens are read off a mounted element, so the frame inherits whatever theme+ // the app is actually in rather than a hardcoded copy that drifts. It has to+ // happen after mount: on first render the ref is still null and the surface+ // would be built with no theme at all.+ const [theme, setTheme] = useState<Record<string, string>>({});+ useEffect(() => setTheme(readThemeTokens(anchorRef.current)), []);++ const surfaceDocument = useMemo(() => {+ if (!entryUrl) return null;+ return buildSurfaceDocument({ entryUrl, grantedScopes: installation.granted_scopes, theme });+ }, [entryUrl, installation.granted_scopes, theme]);++ // One bridge per rendered document. srcDoc changing reloads the frame — and+ // therefore restarts the guest's handshake — so the old bridge is finished:+ // close() is terminal, and reusing a closed one across a document change is+ // exactly how the panel ends up permanently blank.+ const bridge = useMemo(+ () => createSurfaceBridge({ installationId: installation.id, issueId, onResize: setHeight }),+ [installation.id, issueId, surfaceDocument],+ );++ // Arm as soon as the frame element exists. The surface announces itself once+ // its listener is attached, so there is no load event to race.+ useEffect(() => {+ if (frameRef.current) bridge.connect(frameRef.current, readThemeTokens(anchorRef.current));+ return () => bridge.close();+ }, [bridge]);++ useEffect(() => {+ // A surface whose script 404s posts this to the parent window rather than+ // rendering blank — the frame has no other way to tell us.+ const onMessage = (event: MessageEvent) => {+ if ((event.data as { type?: string } | null)?.type !== "multica:plugin-surface-error") return;+ // Same window-identity rule as the bridge: without it any frame on the+ // page could light up the failure banner on every other panel.+ if (!frameRef.current?.contentWindow || event.source !== frameRef.current.contentWindow) return;+ setFailed(true);+ };+ window.addEventListener("message", onMessage);+ return () => window.removeEventListener("message", onMessage);+ }, []);++ if (!surfaceDocument) {+ return (+ <div ref={anchorRef} className={cn("rounded-lg border border-surface-border px-4 py-3 text-caption text-muted-foreground", className)}>+ {/* A local: install has no URL to load a script from — say so instead of+ showing an empty box the user cannot act on. */}+ <PluginSurfaceNotice installation={installation} kind="unavailable" />+ </div>+ );+ }++ return (+ <div ref={anchorRef} className={cn("overflow-hidden rounded-lg border border-surface-border", className)}>+ {failed ? (+ <div className="px-4 py-3 text-caption text-muted-foreground">+ <PluginSurfaceNotice installation={installation} kind="failed" />+ </div>+ ) : null}+ <iframe+ // Keyed on the issue as well: a new bridge is created when issueId+ // changes, but an unchanged document would not reload, and the guest+ // stops announcing once answered — the fresh bridge would wait forever.+ key={`${installation.id}:${surface.key}:${issueId ?? ""}`}+ ref={frameRef}+ title={`${installation.name} — ${surface.name}`}+ srcDoc={surfaceDocument}+ sandbox="allow-scripts"+ className="w-full border-0 bg-transparent"+ style={{ height }}+ />+ </div>+ );+}++function PluginSurfaceNotice({ installation, kind }: { installation: PluginInstallation; kind: "unavailable" | "failed" }) {+ const { t } = useT("issues");+ if (kind === "failed") return <>{t(($) => $.plugins.surface_failed, { name: installation.name })}</>;+ return <>{t(($) => $.plugins.surface_local_only, { name: installation.name })}</>;+}diff --git a/packages/views/plugins/surface-bridge.test.ts b/packages/views/plugins/surface-bridge.test.tsnew file mode 100644index 0000000000..6e1d1eab93--- /dev/null+++ b/packages/views/plugins/surface-bridge.test.ts@@ -0,0 +1,150 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const mockCall = vi.hoisted(() => vi.fn());+vi.mock("@multica/core/api", () => ({ api: { callPluginAction: mockCall } }));++import { createSurfaceBridge } from "./surface-bridge";++// The bridge is the only path from a surface into Multica, so what it refuses+// matters more than what it forwards. None of this is visible from the+// component: it only holds if the guards run before the fetch.++function connectedBridge(options: Parameters<typeof createSurfaceBridge>[0] = { installationId: "installation-1" }) {+ const bridge = createSurfaceBridge(options);+ const posted: unknown[] = [];+ const frame = {+ contentWindow: {+ postMessage: (_message: unknown, _origin: string, transfer: MessagePort[]) => {+ const port = transfer[0];+ if (!port) throw new Error("bridge did not transfer a port");+ port.onmessage = (event: MessageEvent) => posted.push(event.data);+ port.start();+ (frame as unknown as { port: MessagePort }).port = port;+ },+ },+ } as unknown as HTMLIFrameElement & { port: MessagePort };++ bridge.connect(frame, {});+ // The guest announces itself; the host answers that, not the iframe's load+ // event. `source` has to be the frame's own window or the host must ignore it.+ announce(frame.contentWindow as unknown as Window);+ return { bridge, frame, posted };+}++/**+ * Fires the surface's readiness signal as if it came from `source`.+ *+ * `MessageEvent.source` is getter-only, so it is redefined on the instance. The+ * host reads it by identity, which is exactly the check being exercised.+ */+function announce(source: Window | null) {+ const event = new MessageEvent("message", { data: { type: "multica:plugin-surface-ready" } });+ Object.defineProperty(event, "source", { value: source, configurable: true });+ window.dispatchEvent(event);+}++const settle = () => new Promise((resolve) => setTimeout(resolve, 0));++describe("surface bridge", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockCall.mockResolvedValue({ ok: true });+ });++ it("forwards an allowed path with the installation that owns the channel", async () => {+ const { frame } = connectedBridge({ installationId: "installation-1", issueId: "issue-1" });+ frame.port.postMessage({ id: "r1", kind: "action", method: "GET", path: "/context" });+ await settle();++ expect(mockCall).toHaveBeenCalledWith("installation-1", expect.objectContaining({+ method: "GET",+ path: "/context",+ issueId: "issue-1",+ }));+ });++ it("refuses a path outside the Action API before it reaches the network", async () => {+ // A surface asking for /me or ../admin must never turn into a real request:+ // the Action API's scope checks only exist on the paths it defines.+ const { frame, posted } = connectedBridge();+ for (const path of ["/me", "/workspaces/w1/plugins", "/../admin", "/issues/i1/comments/extra"]) {+ frame.port.postMessage({ id: `bad-${path}`, kind: "action", method: "GET", path });+ }+ await settle();++ expect(mockCall).not.toHaveBeenCalled();+ expect(posted).toHaveLength(4);+ for (const response of posted as Array<{ ok: boolean; status: number }>) {+ expect(response.ok).toBe(false);+ expect(response.status).toBe(400);+ }+ });++ it("passes the refusal status through so a surface can tell 403 from 404", async () => {+ // 403 means "the admin did not grant this scope" — a different fix for a+ // plugin author than a missing resource, so it must not be flattened.+ mockCall.mockRejectedValue(Object.assign(new Error("not granted comments:write"), { status: 403 }));+ const { frame, posted } = connectedBridge();+ frame.port.postMessage({ id: "r1", kind: "action", method: "POST", path: "/issues/i1/comments", body: {} });+ await settle();++ expect(posted[0]).toMatchObject({ id: "r1", ok: false, status: 403 });+ });++ it("refuses a method outside the allowlist before it reaches fetch", async () => {+ const { frame, posted } = connectedBridge();+ frame.port.postMessage({ id: "r1", kind: "action", method: "TRACE", path: "/context" });+ frame.port.postMessage({ id: "r2", kind: "action", method: "get", path: "/context" });+ await settle();++ expect(mockCall).not.toHaveBeenCalled();+ expect(posted).toHaveLength(0);+ });++ it("ignores messages that are not bridge requests", async () => {+ const { frame, posted } = connectedBridge();+ frame.port.postMessage({ hello: "world" });+ frame.port.postMessage({ id: 7, kind: "action", method: "GET", path: "/context" });+ await settle();++ expect(mockCall).not.toHaveBeenCalled();+ expect(posted).toHaveLength(0);+ });++ it("clamps a resize so a surface cannot push the page out of view", async () => {+ const heights: number[] = [];+ const { frame } = connectedBridge({ installationId: "installation-1", onResize: (h) => heights.push(h) });+ frame.port.postMessage({ id: "r1", kind: "ui.resize", height: 10_000_000 });+ frame.port.postMessage({ id: "r2", kind: "ui.resize", height: -5 });+ frame.port.postMessage({ id: "r3", kind: "ui.resize", height: 320 });+ await settle();++ expect(heights).toEqual([4000, 0, 320]);+ });++ it("ignores a readiness signal from a window it does not own", async () => {+ // Every sandboxed frame reports the opaque origin "null", so the window+ // reference is the only thing that distinguishes this surface from any+ // other frame on the page — including a hostile one shouting the signal.+ const bridge = createSurfaceBridge({ installationId: "installation-1" });+ let transferred = false;+ const frame = {+ contentWindow: { postMessage: () => { transferred = true; } },+ } as unknown as HTMLIFrameElement;+ bridge.connect(frame, {});+ announce({} as Window);+ await settle();++ expect(transferred).toBe(false);+ bridge.close();+ });++ it("stops answering once closed", async () => {+ const { bridge, frame } = connectedBridge();+ bridge.close();+ frame.port.postMessage({ id: "r1", kind: "action", method: "GET", path: "/context" });+ await settle();++ expect(mockCall).not.toHaveBeenCalled();+ });+});diff --git a/packages/views/plugins/surface-bridge.ts b/packages/views/plugins/surface-bridge.tsnew file mode 100644index 0000000000..825b9d4d71--- /dev/null+++ b/packages/views/plugins/surface-bridge.ts@@ -0,0 +1,158 @@+import { api } from "@multica/core/api";++/**+ * The host half of the bridge.+ *+ * A surface asks; the host performs the call on the signed-in user's own+ * session and returns the result. The plugin holds no credential, so this is+ * the only path from a surface into Multica.+ *+ * Identity is bound by the MessagePort, not by `event.origin`. A sandboxed+ * frame without `allow-same-origin` has the opaque origin "null" — every+ * surface would present the same string, so comparing it would authenticate+ * nothing. Instead the host creates one channel per iframe, transfers one end+ * in, and only ever listens on the other; which plugin sent a message is+ * answered by which channel it arrived on.+ */++const BRIDGE_PROTOCOL_VERSION = 1;+const BRIDGE_INIT_MESSAGE = "multica:plugin-bridge-init";+const BRIDGE_READY_MESSAGE = "multica:plugin-surface-ready";++type BridgeMethod = "GET" | "POST" | "PATCH" | "PUT" | "DELETE";++type BridgeRequest =+ | { id: string; kind: "action"; method: BridgeMethod; path: string; body?: unknown }+ | { id: string; kind: "ui.resize"; height: number };++/** Paths a surface may name. Anything else is refused before it reaches fetch. */+const ALLOWED_PATHS: RegExp[] = [+ /^\/context$/,+ /^\/issues\/[^/]+$/,+ /^\/issues\/[^/]+\/comments$/,+ /^\/storage\/(workspace|user)$/,+ /^\/storage\/(workspace|user)\/[^/]+$/,+];++const MAX_RESIZE_PX = 4000;++function isAllowedPath(path: string): boolean {+ return ALLOWED_PATHS.some((pattern) => pattern.test(path));+}++const ALLOWED_METHODS = new Set(["GET", "POST", "PATCH", "PUT", "DELETE"]);++function isBridgeRequest(value: unknown): value is BridgeRequest {+ if (typeof value !== "object" || value === null) return false;+ const candidate = value as Record<string, unknown>;+ if (typeof candidate.id !== "string") return false;+ if (candidate.kind === "ui.resize") return typeof candidate.height === "number";+ return (+ candidate.kind === "action" &&+ typeof candidate.path === "string" &&+ // An allowlist, not "is a string": an arbitrary verb would otherwise reach+ // fetch and rely on the server's 405 to stop it.+ typeof candidate.method === "string" && ALLOWED_METHODS.has(candidate.method)+ );+}++export interface SurfaceBridgeOptions {+ installationId: string;+ /** Mounted-on issue, forwarded to /context so the surface knows where it is. */+ issueId?: string;+ onResize?: (height: number) => void;+}++export interface SurfaceBridge {+ /**+ * Waits for the surface to announce itself, then hands it a port.+ *+ * Driven by the guest rather than by the iframe's load event: a srcdoc frame+ * can finish loading before React attaches `onLoad`, so a load-driven host+ * either never fires or sends the port before the guest is listening. Both+ * failures look the same from outside — a blank panel.+ */+ connect(frame: HTMLIFrameElement, theme: Record<string, string>): void;+ /** Pushes a theme change to an already-connected frame. */+ pushTheme(theme: Record<string, string>): void;+ close(): void;+}++export function createSurfaceBridge(options: SurfaceBridgeOptions): SurfaceBridge {+ let channel: MessageChannel | null = null;+ let closed = false;+ const readyListeners: Array<(event: MessageEvent) => void> = [];++ const handle = async (request: BridgeRequest, port: MessagePort) => {+ if (request.kind === "ui.resize") {+ // Clamped: a surface asking for a 10-million-pixel frame is a bug or an+ // attempt to push the rest of the page out of view.+ options.onResize?.(Math.min(Math.max(0, request.height), MAX_RESIZE_PX));+ return;+ }++ if (!isAllowedPath(request.path)) {+ port.postMessage({ id: request.id, ok: false, status: 400, error: `unsupported path ${request.path}` });+ return;+ }++ try {+ const result = await api.callPluginAction(options.installationId, {+ method: request.method,+ path: request.path,+ body: request.body,+ issueId: options.issueId,+ });+ port.postMessage({ id: request.id, ok: true, status: 200, data: result });+ } catch (error) {+ // The status matters to the surface: 403 means "the admin did not grant+ // this", which is a different thing for a plugin author to fix than 404.+ const status = typeof (error as { status?: number })?.status === "number" ? (error as { status: number }).status : 500;+ const message = error instanceof Error ? error.message : "plugin action failed";+ port.postMessage({ id: request.id, ok: false, status, error: message });+ }+ };++ return {+ connect(frame, theme) {+ if (closed) return;+ const onReady = (event: MessageEvent) => {+ if ((event.data as { type?: string } | null)?.type !== BRIDGE_READY_MESSAGE) return;+ // The only check that matters: the signal came from the window this+ // bridge owns. Origin cannot be used — every sandboxed frame reports+ // "null" — so identity is the window reference plus, from here on, the+ // private port.+ if (!frame.contentWindow || event.source !== frame.contentWindow) return;+ window.removeEventListener("message", onReady);+ if (closed) return;++ channel?.port1.close();+ channel = new MessageChannel();+ channel.port1.onmessage = (portEvent) => {+ if (!isBridgeRequest(portEvent.data)) return;+ void handle(portEvent.data, channel!.port1);+ };+ channel.port1.start();+ // targetOrigin "*" is required, not lax: an opaque origin can never+ // match a string. The message carries no secret, and the port is+ // transferred into this specific contentWindow.+ frame.contentWindow.postMessage(+ { type: BRIDGE_INIT_MESSAGE, version: BRIDGE_PROTOCOL_VERSION, theme },+ "*",+ [channel.port2],+ );+ };+ readyListeners.push(onReady);+ window.addEventListener("message", onReady);+ },+ pushTheme(theme) {+ channel?.port1.postMessage({ kind: "theme", theme });+ },+ close() {+ closed = true;+ for (const listener of readyListeners.splice(0)) window.removeEventListener("message", listener);+ channel?.port1.close();+ channel = null;+ },+ };+}diff --git a/packages/views/plugins/surface-document.test.ts b/packages/views/plugins/surface-document.test.tsnew file mode 100644index 0000000000..b5e42e2719--- /dev/null+++ b/packages/views/plugins/surface-document.test.ts@@ -0,0 +1,146 @@+// @vitest-environment node+import { describe, expect, it } from "vitest";+import type { PluginInstallation, PluginSurface } from "@multica/core/types";+import {+ buildSurfaceCSP,+ buildSurfaceDocument,+ resolveSurfaceEntry,+ surfaceConnectSources,+} from "./surface-document";++// The document the host generates IS the sandbox policy. These pin the parts a+// reviewer cannot verify by reading the component: what a surface is allowed to+// talk to, and that nothing about the plugin can escape into the markup.++const SURFACE: PluginSurface = {+ key: "hello",+ type: "issue_panel",+ name: "Hello",+ entry: "ui/main.js",+ platforms: [],+};++function installation(overrides: Partial<PluginInstallation> = {}): PluginInstallation {+ return {+ id: "installation-1",+ plugin_key: "com.example.hello",+ name: "Hello Panel",+ version: "1.0.0",+ source_url: "https://example.com/plugin/multica.plugin.json",+ enabled: true,+ granted_scopes: ["issues:read"],+ config_schema: [],+ config: {},+ configured_secrets: [],+ surfaces: [SURFACE],+ hooks: [],+ resources: [],+ created_at: "",+ updated_at: "",+ ...overrides,+ };+}++describe("surface connect-src", () => {+ it("derives the allowlist from granted net: scopes only", () => {+ expect(surfaceConnectSources(["issues:read", "net:example.com", "storage:user", "net:api.example.com"]))+ .toEqual(["https://example.com", "https://api.example.com"]);+ });++ it("gives a surface with no net: scope no third-party destination at all", () => {+ // 'none', not merely an empty allowlist. This bounds THIRD-PARTY hosts; the+ // author's own origin stays reachable through script-src, because the code+ // has to load from somewhere. Saying otherwise would overclaim.+ expect(buildSurfaceCSP(["issues:read"], "https://example.com")).toContain("connect-src 'none'");+ });++ it("keeps the cheapest side channels closed", () => {+ // <img> and webfont URLs are the two exfiltration paths that need no+ // scripting at all, so neither gets the script origin.+ const csp = buildSurfaceCSP(["net:example.com"], "https://cdn.example.com");+ expect(csp).toContain("img-src data: blob:");+ expect(csp).toContain("font-src data:");+ expect(csp).not.toContain("img-src https://cdn.example.com");+ });++ it("does not let an undeclared domain in through the script origin", () => {+ const csp = buildSurfaceCSP(["net:example.com"], "https://cdn.example.com");+ expect(csp).toContain("connect-src https://example.com");+ expect(csp).not.toContain("connect-src https://cdn.example.com");+ });++ it("denies everything by default and allows no plugin-controlled framing", () => {+ const csp = buildSurfaceCSP([], "https://example.com");+ expect(csp).toContain("default-src 'none'");+ // frame-ancestors is intentionally absent — <meta> ignores it, and the+ // sandbox already denies this document the ability to frame anything.+ expect(csp).not.toContain("frame-ancestors");+ expect(csp).toContain("base-uri 'none'");+ expect(csp).toContain("form-action 'none'");+ });+});++describe("surface entry resolution", () => {+ it("resolves the entry against the manifest URL, so the author's host serves the code", () => {+ expect(resolveSurfaceEntry(installation(), SURFACE)).toBe("https://example.com/plugin/ui/main.js");+ });++ it("refuses a local: install rather than inventing a URL", () => {+ // A local source lives on the server's filesystem; there is nothing a+ // browser could fetch, and guessing a URL would be worse than saying so.+ expect(resolveSurfaceEntry(installation({ source_url: "local:hello" }), SURFACE)).toBeNull();+ });++ it("refuses a plaintext source on a real host", () => {+ expect(resolveSurfaceEntry(installation({ source_url: "http://example.com/multica.plugin.json" }), SURFACE)).toBeNull();+ });++ it("allows plain HTTP from loopback so a surface can be developed locally", () => {+ // Browsers already treat loopback as a secure context. Without this a+ // plugin author cannot iterate on a surface at all: there is no way to+ // serve one over HTTPS from a laptop.+ expect(resolveSurfaceEntry(installation({ source_url: "http://localhost:8787/multica.plugin.json" }), SURFACE))+ .toBe("http://localhost:8787/ui/main.js");+ expect(resolveSurfaceEntry(installation({ source_url: "http://127.0.0.1:8787/multica.plugin.json" }), SURFACE))+ .toBe("http://127.0.0.1:8787/ui/main.js");+ });++ it("does not treat a hostname that merely contains localhost as loopback", () => {+ expect(resolveSurfaceEntry(installation({ source_url: "http://localhost.evil.test/multica.plugin.json" }), SURFACE)).toBeNull();+ expect(resolveSurfaceEntry(installation({ source_url: "http://notlocalhost/multica.plugin.json" }), SURFACE)).toBeNull();+ });+});++describe("surface document", () => {+ it("puts the policy before anything it governs", () => {+ const document = buildSurfaceDocument({+ entryUrl: "https://example.com/plugin/ui/main.js",+ grantedScopes: ["net:example.com"],+ theme: {},+ });+ const cspIndex = document.indexOf("Content-Security-Policy");+ const scriptIndex = document.indexOf("<script");+ expect(cspIndex).toBeGreaterThan(-1);+ expect(cspIndex).toBeLessThan(scriptIndex);+ });++ it("escapes the entry URL so a crafted manifest cannot break out of the attribute", () => {+ const document = buildSurfaceDocument({+ entryUrl: 'https://example.com/a"><script>alert(1)</script>.js',+ grantedScopes: [],+ theme: {},+ });+ expect(document).not.toContain('"><script>alert(1)');+ expect(document).toContain(""");+ });++ it("forwards theme tokens as custom properties so a surface looks native untouched", () => {+ const document = buildSurfaceDocument({+ entryUrl: "https://example.com/ui/main.js",+ grantedScopes: [],+ theme: { "--background": "oklch(1 0 0)", "--radius": "6px" },+ });+ expect(document).toContain("--background: oklch(1 0 0);");+ expect(document).toContain("--radius: 6px;");+ });+});diff --git a/packages/views/plugins/surface-document.ts b/packages/views/plugins/surface-document.tsnew file mode 100644index 0000000000..5c69e5e8f8--- /dev/null+++ b/packages/views/plugins/surface-document.ts@@ -0,0 +1,167 @@+import type { PluginInstallation, PluginSurface } from "@multica/core/types";++/**+ * The host generates the document a surface runs in. That is the point: CSP is+ * a response-header/meta decision made by whoever emits the document, so if the+ * plugin author's server emitted it, the `net:` scopes the admin approved would+ * be a claim we never check. Here they become a `connect-src` the browser+ * enforces.+ *+ * The frame is mounted with `sandbox="allow-scripts"` and NOT+ * `allow-same-origin` — the pairing the HTML spec calls out as defeating the+ * sandbox. That gives the document an opaque origin: no cookies, no+ * localStorage, no access to the embedder, and no shared storage between two+ * plugins. It is the same model `packages/views/editor/code-block-iframe.tsx`+ * already uses for untrusted HTML.+ */++/** Design tokens forwarded into the frame so a surface looks native for free. */+export const SURFACE_THEME_TOKENS = [+ "--background",+ "--foreground",+ "--muted",+ "--muted-foreground",+ "--border",+ "--primary",+ "--primary-foreground",+ "--destructive",+ "--radius",+ "--text-caption",+ "--text-body",+] as const;++export function readThemeTokens(element: Element | null): Record<string, string> {+ if (!element || typeof getComputedStyle !== "function") return {};+ const computed = getComputedStyle(element);+ const tokens: Record<string, string> = {};+ for (const name of SURFACE_THEME_TOKENS) {+ const value = computed.getPropertyValue(name).trim();+ if (value) tokens[name] = value;+ }+ return tokens;+}++/**+ * Resolves a surface entry to an absolute script URL.+ *+ * `entry` is relative to the manifest, so the plugin's own host serves its code+ * — we never proxy or re-host third-party JavaScript. A `local:` source has no+ * URL to resolve against; those installs are for developing the manifest and+ * cannot render a surface, which the panel says out loud rather than showing an+ * empty frame.+ */+export function resolveSurfaceEntry(installation: PluginInstallation, surface: PluginSurface): string | null {+ const source = installation.source_url ?? "";+ let resolved: URL;+ try {+ resolved = new URL(surface.entry, source);+ } catch {+ // A `local:` source is not a URL at all — there is nothing a browser could+ // fetch, and guessing one would be worse than saying so.+ return null;+ }+ if (resolved.protocol === "https:") return resolved.toString();+ // Plain HTTP is allowed only from loopback, matching what browsers already+ // treat as a secure context. That is what makes developing a surface possible+ // — serve it from a local static server and install by URL like any other —+ // without opening plaintext delivery on a real deployment.+ if (resolved.protocol === "http:" && isLoopbackHost(resolved.hostname)) return resolved.toString();+ return null;+}++function isLoopbackHost(hostname: string): boolean {+ return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]" || hostname === "::1";+}++function escapeAttribute(value: string): string {+ return value.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<").replace(/>/g, ">");+}++/**+ * Builds the `connect-src` list from the granted scopes only — never from the+ * manifest the source URL serves today. `net:` is an exact host by contract, so+ * a plugin that needs a subdomain declares it.+ */+export function surfaceConnectSources(grantedScopes: string[]): string[] {+ return grantedScopes+ .filter((scope) => scope.startsWith("net:"))+ .map((scope) => `https://${scope.slice("net:".length)}`);+}++export function buildSurfaceCSP(grantedScopes: string[], scriptOrigin: string): string {+ const connect = surfaceConnectSources(grantedScopes);+ return [+ "default-src 'none'",+ // The surface's own script, and nothing else executable. This origin is+ // unavoidable — the code has to load from somewhere — and it is the reason+ // `net:` bounds THIRD-PARTY destinations rather than exfiltration in+ // general: a script served by its author can always reach its author back,+ // and closing that would mean re-hosting third-party code, which this design+ // deliberately does not do.+ `script-src ${scriptOrigin} 'unsafe-inline'`,+ "style-src 'unsafe-inline'",+ // Narrowed to inline data rather than the script origin: an <img> or webfont+ // URL is the cheapest possible side channel back to the author, and a+ // surface that needs artwork can inline it. It does not make the channel+ // impossible — a dynamic import of the author's own origin remains — but it+ // removes the two that cost nothing to use.+ "img-src data: blob:",+ "font-src data:",+ // With no net: scope this is 'none', so a surface cannot reach any+ // third-party host. Its author's own origin is still reachable via+ // script-src; see above.+ `connect-src ${connect.length > 0 ? connect.join(" ") : "'none'"}`,+ // A sandboxed frame cannot navigate the top level anyway; saying so keeps+ // the policy honest if the sandbox attribute is ever loosened.+ "form-action 'none'",+ "base-uri 'none'",+ // frame-ancestors is deliberately absent: it is ignored when delivered via+ // <meta>, and the browser logs a warning for it. Nothing is lost — the+ // sandbox already denies this document the ability to frame anything.+ ].join("; ");+}++export interface SurfaceDocumentInput {+ entryUrl: string;+ grantedScopes: string[];+ theme: Record<string, string>;+}++/**+ * The srcdoc a surface iframe renders. Everything executable in it is the+ * plugin's own entry script loaded cross-origin; the inline script only forwards+ * load failures so a broken plugin reports itself instead of showing blank.+ */+export function buildSurfaceDocument({ entryUrl, grantedScopes, theme }: SurfaceDocumentInput): string {+ const scriptOrigin = new URL(entryUrl).origin;+ const csp = buildSurfaceCSP(grantedScopes, scriptOrigin);+ const themeCss = Object.entries(theme)+ .map(([name, value]) => `${name}: ${value};`)+ .join(" ");++ // The meta CSP must precede anything it governs, so it is the first child of+ // <head>. Note srcdoc documents also inherit the embedder's policy — this+ // narrows, it cannot widen.+ return `<!doctype html>+<html>+<head>+<meta http-equiv="Content-Security-Policy" content="${escapeAttribute(csp)}">+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<style>+:root { ${themeCss} color-scheme: light dark; }+* { box-sizing: border-box; }+html, body { margin: 0; padding: 0; }+body {+ background: var(--background, transparent);+ color: var(--foreground, inherit);+ font: 400 var(--text-body, 14px)/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;+}+</style>+</head>+<body>+<div id="root"></div>+<script src="${escapeAttribute(entryUrl)}" onerror="parent.postMessage({type:'multica:plugin-surface-error'},'*')"></script>+</body>+</html>`;+}diff --git a/packages/views/settings/components/plugins-tab.tsx b/packages/views/settings/components/plugins-tab.tsxindex aa23d4a5a4..d7e5690ede 100644--- a/packages/views/settings/components/plugins-tab.tsx+++ b/packages/views/settings/components/plugins-tab.tsx@@ -27,6 +27,7 @@ import {SelectValue,} from "@multica/ui/components/ui/select";import { Skeleton } from "@multica/ui/components/ui/skeleton";+import { Textarea } from "@multica/ui/components/ui/textarea";import { Switch } from "@multica/ui/components/ui/switch";import { useT } from "../../i18n";import { SettingsCard, SettingsSection, SettingsTab } from "./settings-layout";@@ -216,6 +217,17 @@ function ConfigField({onValueChange(event.target.value === "" || Number.isNaN(parsed) ? undefined : parsed);}}/>+ ) : field.multiline === true ? (+ // A field whose value is a list of lines is unreadable in a+ // single-line input — and the generated form is the one piece of+ // plugin UI the host owns, so getting it wrong is our bug.+ <Textarea+ rows={4}+ disabled={disabled}+ value={typeof value === "string" ? value : ""}+ placeholder={field.placeholder ?? ""}+ onChange={(event) => onValueChange(event.target.value)}+ />) : (<Inputdisabled={disabled}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 48141905e0..0987296e40 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -693,6 +693,18 @@ importers:specifier: ^8.35.0+ packages/plugin-sdk:+ devDependencies:+ '@multica/eslint-config':+ specifier: workspace:*+ version: link:../eslint-config+ '@multica/tsconfig':+ specifier: workspace:*+ version: link:../tsconfig+ typescript:+ specifier: 'catalog:'+ version: 5.9.3+packages/tsconfig: {}packages/ui:@@ -1002,6 +1014,9 @@ importers:'@multica/eslint-config':specifier: workspace:*version: link:../eslint-config+ '@multica/plugin-sdk':+ specifier: workspace:*+ version: link:../plugin-sdk'@multica/tsconfig':specifier: workspace:*version: link:../tsconfigdiff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 9f462b0c89..ac2b3bda9d 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -1,71 +1,43 @@packages:- - "apps/*"- - "packages/*"+ - apps/*+ - packages/*catalog:- # Core React- react: "19.2.3"- react-dom: "19.2.3"- "@types/react": "^19.2.0"- "@types/react-dom": "^19.2.0"-- # TypeScript & Node- typescript: "^5.9.3"- "@types/node": "^25.0.10"-- # State Management- zustand: "^5.0.0"- "@tanstack/react-query": "^5.96.2"- "@tanstack/react-table": "^8.21.3"-- # Runtime schema validation (defensive boundary against API drift —- # see CLAUDE.md "API Response Compatibility")- zod: "^4.1.5"-- # UI & Styling- tailwindcss: "^4"- "@tailwindcss/postcss": "^4"- postcss: "^8"- "@tailwindcss/vite": "^4"- tailwind-merge: "^3.4.0"- class-variance-authority: "^0.7.1"- clsx: "^2.1.1"- katex: "^0.16.45"- rehype-katex: "^7.0.1"- remark-math: "^6.0.0"- mermaid: "^11.14.0"-- # Icons- lucide-react: "^1.0.1"-- # i18n- i18next: "^26.0.8"- react-i18next: "^17.0.6"- "@formatjs/intl-localematcher": "^0.8.4"- eslint-plugin-i18next: "^6.1.4"-- # Loading animations (chat StatusPill)- unicode-animations: "^1.0.3"-- # QR rendering — Lark device-flow scan-to-install dialog renders the- # verification_uri_complete as a QR so users can scan it from their- # phone instead of typing the URL.- "react-qr-code": "^2.0.18"-- # Virtualized timeline (issue detail comments)- react-virtuoso: "^4.14.0"- "@tanstack/react-virtual": "^3.13.0"-- # Product analytics- posthog-js: "^1.176.1"-- # YAML parsing (skill frontmatter)- yaml: "^2.6.0"-- # Testing- vitest: "^4.1.0"- jsdom: "^29.0.1"- "@vitejs/plugin-react": "^6.0.1"- "@testing-library/react": "^16.3.2"- "@testing-library/jest-dom": "^6.9.1"- "@testing-library/user-event": "^14.6.1"+ '@formatjs/intl-localematcher': ^0.8.4+ '@tailwindcss/postcss': ^4+ '@tailwindcss/vite': ^4+ '@tanstack/react-query': ^5.96.2+ '@tanstack/react-table': ^8.21.3+ '@tanstack/react-virtual': ^3.13.0+ '@testing-library/jest-dom': ^6.9.1+ '@testing-library/react': ^16.3.2+ '@testing-library/user-event': ^14.6.1+ '@types/node': ^25.0.10+ '@types/react': ^19.2.0+ '@types/react-dom': ^19.2.0+ '@vitejs/plugin-react': ^6.0.1+ class-variance-authority: ^0.7.1+ clsx: ^2.1.1+ eslint-plugin-i18next: ^6.1.4+ i18next: ^26.0.8+ jsdom: ^29.0.1+ katex: ^0.16.45+ lucide-react: ^1.0.1+ mermaid: ^11.14.0+ postcss: ^8+ posthog-js: ^1.176.1+ react: 19.2.3+ react-dom: 19.2.3+ react-i18next: ^17.0.6+ react-qr-code: ^2.0.18+ react-virtuoso: ^4.14.0+ rehype-katex: ^7.0.1+ remark-math: ^6.0.0+ tailwind-merge: ^3.4.0+ tailwindcss: ^4+ typescript: ^5.9.3+ unicode-animations: ^1.0.3+ vitest: ^4.1.0+ yaml: ^2.6.0+ zod: ^4.1.5+ zustand: ^5.0.0diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 99c83bef37..07ef98e7e4 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -71,6 +71,8 @@ var corsAllowedHeaders = []string{"X-Client-Version","X-Client-OS","X-Client-Capabilities",+ // Sent by the host page when it relays a plugin surface's Action API call.+ "X-Multica-Plugin-Installation",}// corsExposedHeaders lists response headers browser clients are allowed to read.@@ -1242,6 +1244,26 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Use(middleware.Auth(queries, patCache, cloudPATVerifier))r.Use(middleware.RefreshCloudFrontCookies(cfSigner))+ // Plugin Action API. Called by the HOST PAGE on the signed-in user's+ // session after a surface asks for something over the postMessage+ // bridge — the iframe holds no credential and never reaches these+ // directly. Which installation is speaking arrives in a header the+ // host sets; the workspace is derived from that installation rather+ // than trusted from the client, and membership is then checked+ // against it. Sits in the user-scoped group for that reason: there is+ // no workspace in the path to gate on.+ r.Route("/api/v1/plugin", func(r chi.Router) {+ r.Get("/context", h.GetPluginContext)+ r.Get("/issues/{id}", h.GetPluginIssue)+ r.Patch("/issues/{id}", h.PatchPluginIssue)+ r.Get("/issues/{id}/comments", h.ListPluginComments)+ r.Post("/issues/{id}/comments", h.CreatePluginComment)+ r.Get("/storage/{scope}", h.ListPluginStorage)+ r.Get("/storage/{scope}/{key}", h.GetPluginStorage)+ r.Put("/storage/{scope}/{key}", h.PutPluginStorage)+ r.Delete("/storage/{scope}/{key}", h.DeletePluginStorage)+ })+// --- User-scoped routes (no workspace context required) ---r.Get("/api/me", h.GetMe)r.Patch("/api/me", h.UpdateMe)diff --git a/server/internal/handler/plugin.go b/server/internal/handler/plugin.goindex 1d2fcd5e9d..f186c3509a 100644--- a/server/internal/handler/plugin.go+++ b/server/internal/handler/plugin.go@@ -40,6 +40,8 @@ func writePluginError(w http.ResponseWriter, err error, fallback string) {writeError(w, http.StatusNotFound, pluginErr.Message)case service.PluginErrorConflict:writeError(w, http.StatusConflict, pluginErr.Message)+ case service.PluginErrorForbidden:+ writeError(w, http.StatusForbidden, pluginErr.Message)case service.PluginErrorIncompatible:writeError(w, http.StatusUnprocessableEntity, pluginErr.Message)case service.PluginErrorQuota:diff --git a/server/internal/handler/plugin_action.go b/server/internal/handler/plugin_action.gonew file mode 100644index 0000000000..11036e6091--- /dev/null+++ b/server/internal/handler/plugin_action.go@@ -0,0 +1,472 @@+package handler++import (+ "encoding/json"+ "net/http"++ "github.com/go-chi/chi/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/service"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/plugincontract"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// The Action API is what a plugin surface reaches through the host bridge.+//+// Every call passes three checks, in this order:+//+// 1. the installation exists in this workspace and is enabled;+// 2. the installation was granted the scope this endpoint needs;+// 3. the SIGNED-IN USER may touch the resource — enforced by the ordinary+// loaders, not by anything plugin-specific.+//+// Three is the one that makes the whole model safe: a plugin can never let+// someone do what they could not already do themselves. One and two are what+// bound the plugin below that ceiling.+//+// There is no plugin credential anywhere in this file. The iframe holds no+// token; it posts a message to the host page, and the host re-issues the call+// on the user's own session. That is why these routes sit under the normal+// authenticated group and read the installation from a header the iframe+// cannot set for itself.+const pluginInstallationHeader = "X-Multica-Plugin-Installation"++// pluginCaller runs checks 1 and 2 and returns the authorized caller.+func (h *Handler) pluginCaller(w http.ResponseWriter, r *http.Request, scope string) (service.PluginActionCaller, db.Member, bool) {+ if !h.requirePluginsV1(w, r) {+ return service.PluginActionCaller{}, db.Member{}, false+ }+ userID, ok := requireUserID(w, r)+ if !ok {+ return service.PluginActionCaller{}, db.Member{}, false+ }+ parsedUserID, ok := parseUUIDOrBadRequest(w, userID, "user_id")+ if !ok {+ return service.PluginActionCaller{}, db.Member{}, false+ }++ caller, err := h.PluginService.AuthorizePluginAction(r.Context(), r.Header.Get(pluginInstallationHeader), parsedUserID, scope)+ if err != nil {+ writePluginError(w, err, "failed to authorize the Plugin call")+ return service.PluginActionCaller{}, db.Member{}, false+ }++ // The workspace comes from the installation, never from a client header:+ // otherwise a caller could aim an installation at a workspace it was never+ // installed in. Membership is then checked against that workspace.+ member, ok := h.requireWorkspaceMember(w, r, uuidToString(caller.WorkspaceID), "workspace not found")+ if !ok {+ return service.PluginActionCaller{}, db.Member{}, false+ }+ return caller, member, true+}++// pluginIssueForUser is check 3. The workspace comes from the installation, not+// from a client header, and membership in that workspace was already verified+// by pluginCaller — so "the issue is in this workspace" plus "the caller is a+// member of it" is exactly the reach the user already has. An issue outside it+// is a 404 for the same reason it is on the ordinary endpoint: a plugin must+// not be able to confirm that an id it cannot read exists.+func (h *Handler) pluginIssueForUser(w http.ResponseWriter, r *http.Request, caller service.PluginActionCaller, issueID string) (db.Issue, bool) {+ if issueID == "" {+ writeError(w, http.StatusNotFound, "issue not found")+ return db.Issue{}, false+ }+ workspaceID := uuidToString(caller.WorkspaceID)+ if issue, ok := h.resolveIssueByIdentifier(r.Context(), issueID, workspaceID); ok {+ return issue, true+ }+ parsed, err := util.ParseUUID(issueID)+ if err != nil {+ writeError(w, http.StatusNotFound, "issue not found")+ return db.Issue{}, false+ }+ issue, err := h.Queries.GetIssueInWorkspace(r.Context(), db.GetIssueInWorkspaceParams{+ ID: parsed,+ WorkspaceID: caller.WorkspaceID,+ })+ if err != nil {+ writeError(w, http.StatusNotFound, "issue not found")+ return db.Issue{}, false+ }+ return issue, true+}++// GetPluginContext — GET /api/v1/plugin/context+func (h *Handler) GetPluginContext(w http.ResponseWriter, r *http.Request) {+ // No scope: this is the page the user is already looking at.+ caller, member, ok := h.pluginCaller(w, r, "")+ if !ok {+ return+ }+ workspace, err := h.Queries.GetWorkspace(r.Context(), caller.WorkspaceID)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to load the workspace")+ return+ }+ user, err := h.Queries.GetUser(r.Context(), member.UserID)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to load the user")+ return+ }++ var issue *db.Issue+ if issueID := r.URL.Query().Get("issue_id"); issueID != "" {+ loaded, ok := h.pluginIssueForUser(w, r, caller, issueID)+ if !ok {+ return+ }+ issue = &loaded+ }++ writeJSON(w, http.StatusOK, h.PluginService.BuildPluginContext(caller, workspace, user, issue))+}++// GetPluginIssue — GET /api/v1/plugin/issues/{id}+func (h *Handler) GetPluginIssue(w http.ResponseWriter, r *http.Request) {+ caller, _, ok := h.pluginCaller(w, r, plugincontract.ScopeIssuesRead)+ if !ok {+ return+ }+ issue, ok := h.pluginIssueForUser(w, r, caller, chi.URLParam(r, "id"))+ if !ok {+ return+ }+ writeJSON(w, http.StatusOK, h.pluginIssuePayload(r, caller, issue))+}++type patchPluginIssueRequest struct {+ Title *string `json:"title,omitempty"`+ Description *string `json:"description,omitempty"`+}++// PatchPluginIssue — PATCH /api/v1/plugin/issues/{id}+//+// Title and description only. Status, priority, assignee, parent, project and+// stage each carry dispatch, catalog or hierarchy semantics — a status change+// can start an agent run, and custom statuses resolve through a per-workspace+// catalog — and duplicating those rules here would give a plugin a second,+// drifting copy of them. Widening this set later is additive; getting the side+// effects wrong now is not.+func (h *Handler) PatchPluginIssue(w http.ResponseWriter, r *http.Request) {+ caller, _, ok := h.pluginCaller(w, r, plugincontract.ScopeIssuesWrite)+ if !ok {+ return+ }+ issue, ok := h.pluginIssueForUser(w, r, caller, chi.URLParam(r, "id"))+ if !ok {+ return+ }++ var req patchPluginIssueRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ if req.Title == nil && req.Description == nil {+ writeError(w, http.StatusBadRequest, "title or description is required")+ return+ }++ // Every other field is passed back unchanged: UpdateIssue treats a null+ // nargs as "clear", so omitting them here would silently unassign the issue+ // or detach it from its parent.+ params := db.UpdateIssueParams{+ ID: issue.ID,+ AssigneeType: issue.AssigneeType,+ AssigneeID: issue.AssigneeID,+ StartDate: issue.StartDate,+ DueDate: issue.DueDate,+ ParentIssueID: issue.ParentIssueID,+ ProjectID: issue.ProjectID,+ Stage: issue.Stage,+ }+ if req.Title != nil {+ title := sanitizeNullBytes(*req.Title)+ if title == "" {+ writeError(w, http.StatusBadRequest, "title must not be empty")+ return+ }+ params.Title = pgtype.Text{String: title, Valid: true}+ }+ if req.Description != nil {+ params.Description = pgtype.Text{String: sanitizeNullBytes(*req.Description), Valid: true}+ }++ updated, err := h.Queries.UpdateIssue(r.Context(), params)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to update the issue")+ return+ }+ writeJSON(w, http.StatusOK, h.pluginIssuePayload(r, caller, updated))+}++// pluginIssuePayload reuses the ordinary issue response so a surface sees the+// same shape the rest of the product does.+func (h *Handler) pluginIssuePayload(r *http.Request, caller service.PluginActionCaller, issue db.Issue) IssueResponse {+ prefix := ""+ if workspace, err := h.Queries.GetWorkspace(r.Context(), caller.WorkspaceID); err == nil {+ prefix = workspace.IssuePrefix+ }+ return issueToResponse(issue, prefix)+}++// ListPluginComments — GET /api/v1/plugin/issues/{id}/comments+func (h *Handler) ListPluginComments(w http.ResponseWriter, r *http.Request) {+ caller, _, ok := h.pluginCaller(w, r, plugincontract.ScopeCommentsRead)+ if !ok {+ return+ }+ issue, ok := h.pluginIssueForUser(w, r, caller, chi.URLParam(r, "id"))+ if !ok {+ return+ }+ comments, err := h.Queries.ListCommentsForIssue(r.Context(), db.ListCommentsForIssueParams{+ IssueID: issue.ID,+ WorkspaceID: caller.WorkspaceID,+ Limit: maxPluginCommentsPerRead,+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list comments")+ return+ }+ payload := make([]pluginCommentResponse, 0, len(comments))+ for _, comment := range comments {+ payload = append(payload, pluginCommentResponse{+ ID: uuidToString(comment.ID),+ AuthorType: comment.AuthorType,+ AuthorID: uuidToString(comment.AuthorID),+ Content: comment.Content,+ Type: comment.Type,+ ParentID: uuidToString(comment.ParentID),+ CreatedAt: comment.CreatedAt.Time.UTC().Format(timeFormatRFC3339),+ })+ }+ writeJSON(w, http.StatusOK, map[string]any{"comments": payload})+}++type pluginCommentResponse struct {+ ID string `json:"id"`+ AuthorType string `json:"author_type"`+ AuthorID string `json:"author_id"`+ Content string `json:"content"`+ Type string `json:"type"`+ ParentID string `json:"parent_id,omitempty"`+ CreatedAt string `json:"created_at"`+}++type createPluginCommentRequest struct {+ Content string `json:"content"`+ ParentID *string `json:"parent_id,omitempty"`+}++// CreatePluginComment — POST /api/v1/plugin/issues/{id}/comments+//+// The comment is authored BY THE USER and marked with the plugin that produced+// it, so the timeline can render "Jiayuan (via Hello Panel)".+//+// It deliberately does not run the @mention trigger dispatch that the ordinary+// comment endpoint does. A plugin that could post a mention could start agent+// runs — and spend the workspace's budget — from a surface the user only meant+// to click a button in. Plugins that want to start work will get an explicit+// hook for it rather than inheriting it as a side effect of posting text.+func (h *Handler) CreatePluginComment(w http.ResponseWriter, r *http.Request) {+ caller, member, ok := h.pluginCaller(w, r, plugincontract.ScopeCommentsWrite)+ if !ok {+ return+ }+ issue, ok := h.pluginIssueForUser(w, r, caller, chi.URLParam(r, "id"))+ if !ok {+ return+ }++ var req createPluginCommentRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ content := sanitizeNullBytes(req.Content)+ if content == "" {+ writeError(w, http.StatusBadRequest, "content is required")+ return+ }+ if len(content) > maxPluginCommentBytes {+ writeError(w, http.StatusBadRequest, "content is too long")+ return+ }++ var parentID pgtype.UUID+ var rootComment *db.Comment+ if req.ParentID != nil && *req.ParentID != "" {+ parsed, ok := parseUUIDOrBadRequest(w, *req.ParentID, "parent_id")+ if !ok {+ return+ }+ parent, err := h.Queries.GetComment(r.Context(), parsed)+ if err != nil || uuidToString(parent.IssueID) != uuidToString(issue.ID) {+ writeError(w, http.StatusBadRequest, "invalid parent comment")+ return+ }+ parentID = parsed+ rootComment = &parent+ }++ comment, err := h.Queries.CreateComment(r.Context(), db.CreateCommentParams{+ IssueID: issue.ID,+ WorkspaceID: caller.WorkspaceID,+ AuthorType: "member",+ AuthorID: member.UserID,+ Content: content,+ Type: "comment",+ ParentID: parentID,+ ViaPluginID: caller.Installation.ID,+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to create the comment")+ return+ }++ // The same two follow-ups every other comment path performs. Skipping them+ // made a plugin-posted comment invisible until the next refetch, and left a+ // reply into a resolved thread without re-opening it — a comment that lands+ // as the user should behave like the user's, minus only what was refused on+ // purpose (mention dispatch).+ h.publish(protocol.EventCommentCreated, uuidToString(caller.WorkspaceID), "member", uuidToString(member.UserID), map[string]any{+ "comment": commentToResponse(comment, nil, nil),+ "issue_title": issue.Title,+ "issue_assignee_type": textToPtr(issue.AssigneeType),+ "issue_assignee_id": uuidToPtr(issue.AssigneeID),+ "issue_status": issue.Status,+ })+ if rootComment != nil {+ h.TaskService.AutoUnresolveThreadOnReply(r.Context(), rootComment, uuidToString(caller.WorkspaceID), "member", uuidToString(member.UserID))+ }++ writeJSON(w, http.StatusCreated, pluginCommentResponse{+ ID: uuidToString(comment.ID),+ AuthorType: comment.AuthorType,+ AuthorID: uuidToString(comment.AuthorID),+ Content: comment.Content,+ Type: comment.Type,+ ParentID: uuidToString(comment.ParentID),+ CreatedAt: comment.CreatedAt.Time.UTC().Format(timeFormatRFC3339),+ })+}++// maxPluginCommentBytes keeps a surface from using comments as bulk storage.+const maxPluginCommentBytes = 64 * 1024++// maxPluginCommentsPerRead bounds one read. The query returns the NEWEST N in+// chronological order, so a surface on a long thread sees the recent end rather+// than a truncated beginning.+const maxPluginCommentsPerRead = 200++// --- Storage ---++func (h *Handler) pluginStorageScope(w http.ResponseWriter, r *http.Request, caller service.PluginActionCaller, member db.Member) (string, pgtype.UUID, bool) {+ scopeType := chi.URLParam(r, "scope")+ required := plugincontract.ScopeStorageWorkspace+ if scopeType == service.PluginStorageUser {+ required = plugincontract.ScopeStorageUser+ }+ if !hasGrantedScope(caller.Scopes, required) {+ writeError(w, http.StatusForbidden, "this Plugin was not granted the "+required+" scope")+ return "", pgtype.UUID{}, false+ }+ scopeID, err := service.ResolveStorageScope(scopeType, caller.WorkspaceID, member.UserID)+ if err != nil {+ writePluginError(w, err, "invalid storage scope")+ return "", pgtype.UUID{}, false+ }+ return scopeType, scopeID, true+}++func hasGrantedScope(scopes []string, want string) bool {+ for _, scope := range scopes {+ if scope == want {+ return true+ }+ }+ return false+}++// ListPluginStorage — GET /api/v1/plugin/storage/{scope}+func (h *Handler) ListPluginStorage(w http.ResponseWriter, r *http.Request) {+ caller, member, ok := h.pluginCaller(w, r, "")+ if !ok {+ return+ }+ scopeType, scopeID, ok := h.pluginStorageScope(w, r, caller, member)+ if !ok {+ return+ }+ keys, err := h.PluginService.ListStorageKeys(r.Context(), caller.Installation.ID, scopeType, scopeID)+ if err != nil {+ writePluginError(w, err, "failed to list storage")+ return+ }+ writeJSON(w, http.StatusOK, map[string]any{"keys": keys})+}++// GetPluginStorage — GET /api/v1/plugin/storage/{scope}/{key}+func (h *Handler) GetPluginStorage(w http.ResponseWriter, r *http.Request) {+ caller, member, ok := h.pluginCaller(w, r, "")+ if !ok {+ return+ }+ scopeType, scopeID, ok := h.pluginStorageScope(w, r, caller, member)+ if !ok {+ return+ }+ value, err := h.PluginService.GetStorageValue(r.Context(), caller.Installation.ID, scopeType, scopeID, chi.URLParam(r, "key"))+ if err != nil {+ writePluginError(w, err, "failed to read storage")+ return+ }+ writeJSON(w, http.StatusOK, map[string]any{"value": value})+}++type putPluginStorageRequest struct {+ Value string `json:"value"`+}++// PutPluginStorage — PUT /api/v1/plugin/storage/{scope}/{key}+func (h *Handler) PutPluginStorage(w http.ResponseWriter, r *http.Request) {+ caller, member, ok := h.pluginCaller(w, r, "")+ if !ok {+ return+ }+ scopeType, scopeID, ok := h.pluginStorageScope(w, r, caller, member)+ if !ok {+ return+ }+ var req putPluginStorageRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ if err := h.PluginService.SetStorageValue(r.Context(), caller.Installation.ID, scopeType, scopeID, chi.URLParam(r, "key"), req.Value); err != nil {+ writePluginError(w, err, "failed to write storage")+ return+ }+ w.WriteHeader(http.StatusNoContent)+}++// DeletePluginStorage — DELETE /api/v1/plugin/storage/{scope}/{key}+func (h *Handler) DeletePluginStorage(w http.ResponseWriter, r *http.Request) {+ caller, member, ok := h.pluginCaller(w, r, "")+ if !ok {+ return+ }+ scopeType, scopeID, ok := h.pluginStorageScope(w, r, caller, member)+ if !ok {+ return+ }+ if err := h.PluginService.DeleteStorageValue(r.Context(), caller.Installation.ID, scopeType, scopeID, chi.URLParam(r, "key")); err != nil {+ writePluginError(w, err, "failed to delete storage")+ return+ }+ w.WriteHeader(http.StatusNoContent)+}diff --git a/server/internal/handler/plugin_action_test.go b/server/internal/handler/plugin_action_test.gonew file mode 100644index 0000000000..5949d86683--- /dev/null+++ b/server/internal/handler/plugin_action_test.go@@ -0,0 +1,222 @@+package handler++import (+ "bytes"+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/go-chi/chi/v5"+)++// These are the Action API's security properties, not its happy path. Each one+// is a way a plugin could exceed what the person using it can do, and none of+// them is visible by reading the handler — they only hold if the three checks+// run in the right order against the right inputs.++// installPluginForAction installs the reference plugin and returns its id,+// leaving the caller free to vary scopes.+func installPluginForAction(t *testing.T, scopes []string) string {+ t.Helper()+ withPluginsV1Flag(t, testHandler, true)+ cleanupPluginInstallations(t)++ manifest := handlerTestManifest+ if scopes != nil {+ encoded, err := json.Marshal(scopes)+ if err != nil {+ t.Fatalf("encode scopes: %v", err)+ }+ manifest = strings.Replace(manifest,+ `"scopes": ["issues:read", "comments:write", "storage:user"]`,+ `"scopes": `+string(encoded), 1)+ }+ source := withLocalPluginSource(t, manifest)++ body, _ := json.Marshal(map[string]any{"source_url": source, "granted_scopes": scopes})+ recorder := httptest.NewRecorder()+ testHandler.InstallPlugin(recorder, pluginHandlerRequest(http.MethodPost, "/plugins", body, map[string]string{"id": testWorkspaceID}))+ if recorder.Code != http.StatusCreated {+ t.Fatalf("install status=%d body=%s", recorder.Code, recorder.Body.String())+ }+ var installed struct {+ ID string `json:"id"`+ }+ if err := json.Unmarshal(recorder.Body.Bytes(), &installed); err != nil {+ t.Fatalf("decode installation: %v", err)+ }+ return installed.ID+}++func pluginActionRequest(method, path, installationID string, body any, params map[string]string) *http.Request {+ var buf bytes.Buffer+ if body != nil {+ json.NewEncoder(&buf).Encode(body)+ }+ request := httptest.NewRequest(method, path, &buf)+ request.Header.Set("X-User-ID", testUserID)+ request.Header.Set("Content-Type", "application/json")+ if installationID != "" {+ request.Header.Set(pluginInstallationHeader, installationID)+ }+ routeContext := chi.NewRouteContext()+ for key, value := range params {+ routeContext.URLParams.Add(key, value)+ }+ return request.WithContext(context.WithValue(request.Context(), chi.RouteCtxKey, routeContext))+}++func TestPluginActionRequiresAGrantedScope(t *testing.T) {+ // Installed with issues:read only. Everything else must be refused, and the+ // refusal must name the missing scope so an admin can act on it.+ installationID := installPluginForAction(t, []string{"issues:read"})+ issueID := createTestIssue(t, "Plugin action scope test", "todo", "none")++ recorder := httptest.NewRecorder()+ testHandler.GetPluginIssue(recorder, pluginActionRequest(http.MethodGet, "/issues", installationID, nil,+ map[string]string{"id": issueID}))+ if recorder.Code != http.StatusOK {+ t.Fatalf("granted scope was refused: status=%d body=%s", recorder.Code, recorder.Body.String())+ }++ recorder = httptest.NewRecorder()+ testHandler.CreatePluginComment(recorder, pluginActionRequest(http.MethodPost, "/comments", installationID,+ map[string]any{"content": "hello"}, map[string]string{"id": issueID}))+ if recorder.Code != http.StatusForbidden {+ t.Fatalf("ungranted scope status=%d body=%s", recorder.Code, recorder.Body.String())+ }+ if !strings.Contains(recorder.Body.String(), "comments:write") {+ t.Fatalf("refusal does not name the missing scope: %s", recorder.Body.String())+ }+}++func TestPluginActionRefusedWithoutAnInstallation(t *testing.T) {+ installPluginForAction(t, []string{"issues:read"})+ issueID := createTestIssue(t, "Plugin action installation test", "todo", "none")++ // No header at all: the endpoint must not fall back to "any installed+ // plugin" or to an unscoped call.+ recorder := httptest.NewRecorder()+ testHandler.GetPluginIssue(recorder, pluginActionRequest(http.MethodGet, "/issues", "", nil,+ map[string]string{"id": issueID}))+ if recorder.Code != http.StatusBadRequest {+ t.Fatalf("missing installation header status=%d body=%s", recorder.Code, recorder.Body.String())+ }++ // An installation id that does not exist is a 404, never a pass-through.+ recorder = httptest.NewRecorder()+ testHandler.GetPluginIssue(recorder, pluginActionRequest(http.MethodGet, "/issues",+ "11111111-1111-1111-1111-111111111111", nil, map[string]string{"id": issueID}))+ if recorder.Code != http.StatusNotFound {+ t.Fatalf("unknown installation status=%d body=%s", recorder.Code, recorder.Body.String())+ }+}++func TestPluginActionStopsWhenTheInstallationIsDisabled(t *testing.T) {+ installationID := installPluginForAction(t, []string{"issues:read"})+ issueID := createTestIssue(t, "Plugin action disable test", "todo", "none")++ recorder := httptest.NewRecorder()+ testHandler.DisablePlugin(recorder, pluginHandlerRequest(http.MethodPost, "/plugins/disable", nil,+ map[string]string{"id": testWorkspaceID, "installationId": installationID}))+ if recorder.Code != http.StatusOK {+ t.Fatalf("disable status=%d body=%s", recorder.Code, recorder.Body.String())+ }++ // A surface left open in a stale tab keeps its bridge; disabling has to cut+ // it off server-side or "disabled" only means "hidden".+ recorder = httptest.NewRecorder()+ testHandler.GetPluginIssue(recorder, pluginActionRequest(http.MethodGet, "/issues", installationID, nil,+ map[string]string{"id": issueID}))+ if recorder.Code != http.StatusForbidden {+ t.Fatalf("disabled installation status=%d body=%s", recorder.Code, recorder.Body.String())+ }+}++func TestPluginCommentIsAuthoredByTheUserAndMarkedWithThePlugin(t *testing.T) {+ installationID := installPluginForAction(t, []string{"issues:read", "comments:write"})+ issueID := createTestIssue(t, "Plugin action attribution test", "todo", "none")++ recorder := httptest.NewRecorder()+ testHandler.CreatePluginComment(recorder, pluginActionRequest(http.MethodPost, "/comments", installationID,+ map[string]any{"content": "posted through a plugin"}, map[string]string{"id": issueID}))+ if recorder.Code != http.StatusCreated {+ t.Fatalf("create comment status=%d body=%s", recorder.Code, recorder.Body.String())+ }+ var created struct {+ ID string `json:"id"`+ AuthorType string `json:"author_type"`+ AuthorID string `json:"author_id"`+ }+ if err := json.Unmarshal(recorder.Body.Bytes(), &created); err != nil {+ t.Fatalf("decode comment: %v", err)+ }+ // Permission-wise the write is the user's...+ if created.AuthorType != "member" || created.AuthorID != testUserID {+ t.Fatalf("comment was not authored by the calling user: %+v", created)+ }+ // ...and audit-wise it stays attributable to the plugin that produced it.+ var viaPlugin *string+ if err := testPool.QueryRow(context.Background(),+ `SELECT via_plugin_id::text FROM comment WHERE id = $1`, created.ID).Scan(&viaPlugin); err != nil {+ t.Fatalf("read via_plugin_id: %v", err)+ }+ if viaPlugin == nil || *viaPlugin != installationID {+ t.Fatalf("via_plugin_id = %v, want %s", viaPlugin, installationID)+ }+}++func TestPluginActionCannotReachAnotherWorkspacesIssue(t *testing.T) {+ installationID := installPluginForAction(t, []string{"issues:read"})++ // An issue id from a workspace this user is not a member of must 404 — the+ // plugin inherits the user's reach and nothing more, so this is the same+ // answer the ordinary issue endpoint gives.+ otherWorkspaceIssue := createIssueInForeignWorkspace(t)+ recorder := httptest.NewRecorder()+ testHandler.GetPluginIssue(recorder, pluginActionRequest(http.MethodGet, "/issues", installationID, nil,+ map[string]string{"id": otherWorkspaceIssue}))+ if recorder.Code != http.StatusNotFound {+ t.Fatalf("cross-workspace read status=%d body=%s", recorder.Code, recorder.Body.String())+ }+}++// createIssueInForeignWorkspace seeds a workspace the test user is NOT a member+// of, so a cross-tenant read has something real to fail against rather than a+// made-up uuid that would 404 for the wrong reason.+func createIssueInForeignWorkspace(t *testing.T) string {+ t.Helper()+ ctx := context.Background()++ var ownerID string+ if err := testPool.QueryRow(ctx, `INSERT INTO "user" (name, email) VALUES ('Foreign Owner', $1) RETURNING id`,+ "foreign-plugin-"+testUserID+"@multica.test").Scan(&ownerID); err != nil {+ t.Fatalf("seed foreign user: %v", err)+ }+ var workspaceID string+ if err := testPool.QueryRow(ctx, `INSERT INTO workspace (name, slug) VALUES ('Foreign', $1) RETURNING id`,+ "foreign-plugin-"+testUserID).Scan(&workspaceID); err != nil {+ t.Fatalf("seed foreign workspace: %v", err)+ }+ if _, err := testPool.Exec(ctx, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'owner')`,+ workspaceID, ownerID); err != nil {+ t.Fatalf("seed foreign member: %v", err)+ }+ var issueID string+ if err := testPool.QueryRow(ctx,+ `INSERT INTO issue (workspace_id, title, status, priority, creator_type, creator_id)+ VALUES ($1, 'Foreign issue', 'todo', 'none', 'member', $2) RETURNING id`,+ workspaceID, ownerID).Scan(&issueID); err != nil {+ t.Fatalf("seed foreign issue: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM issue WHERE workspace_id = $1`, workspaceID)+ testPool.Exec(context.Background(), `DELETE FROM member WHERE workspace_id = $1`, workspaceID)+ testPool.Exec(context.Background(), `DELETE FROM workspace WHERE id = $1`, workspaceID)+ testPool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, ownerID)+ })+ return issueID+}diff --git a/server/internal/handler/plugin_test.go b/server/internal/handler/plugin_test.goindex a821ff675f..e3a90a860e 100644--- a/server/internal/handler/plugin_test.go+++ b/server/internal/handler/plugin_test.go@@ -38,6 +38,27 @@ const handlerTestManifest = `{}}`+// hookOnlyTestManifest declares a contribution kind the host does not ship yet.+// Kept separate from handlerTestManifest so flipping a surface on never silently+// changes what the capability-gate test is asserting.+const hookOnlyTestManifest = `{+ "manifest_version": 1,+ "key": "com.example.hooked",+ "name": "Hooked",+ "version": "1.0.0",+ "author": { "name": "example" },+ "scopes": ["issues:read", "net:example.com"],+ "contributes": {+ "hooks": [{+ "key": "summarize",+ "name": "Summarize",+ "description": "Compress the discussion.",+ "triggers": ["ui"],+ "transport": { "type": "http", "url": "https://example.com/hooks/summarize" }+ }]+ }+}`+func pluginHandlerRequest(method, path string, body []byte, params map[string]string) *http.Request {request := httptest.NewRequest(method, path, bytes.NewReader(body))request.Header.Set("X-User-ID", testUserID)@@ -308,25 +329,51 @@ func TestPluginInstallRejectsMalformedManifest(t *testing.T) {func TestPluginInstallRejectsUnshippedCapabilities(t *testing.T) {withPluginsV1Flag(t, testHandler, true)cleanupPluginInstallations(t)- source := withLocalPluginSource(t, handlerTestManifest)- // A declared-but-unshipped contribution must fail the install outright: a- // silently dropped surface would look installed and never render.+ // A hook is the contribution kind the host genuinely cannot run yet, so this+ // exercises the real shipped gate rather than a capability that happens to be+ // off today. Written against a still-gated kind on purpose: asserting on a+ // SHIPPED one turns every future capability flip into a test failure that+ // says nothing about the gate itself.+ source := withLocalPluginSource(t, hookOnlyTestManifest)testHandler.PluginService.Host = plugincontract.HostCapabilities()body, _ := json.Marshal(map[string]any{"source_url": source,- "granted_scopes": []string{"issues:read", "comments:write", "storage:user"},+ "granted_scopes": []string{"issues:read", "net:example.com"},})recorder := httptest.NewRecorder()testHandler.InstallPlugin(recorder, pluginHandlerRequest(http.MethodPost, "/plugins", body, map[string]string{"id": testWorkspaceID}))if recorder.Code != http.StatusUnprocessableEntity {t.Fatalf("unshipped capability status=%d body=%s", recorder.Code, recorder.Body.String())}- if !strings.Contains(recorder.Body.String(), "issue_panel") {+ // A declared-but-unrunnable contribution must fail the install outright and+ // name what is missing: silently dropping it would look installed and never+ // fire.+ if !strings.Contains(recorder.Body.String(), "hook trigger") {t.Fatalf("error does not name the missing capability: %s", recorder.Body.String())}}+func TestPluginInstallAcceptsAShippedSurface(t *testing.T) {+ withPluginsV1Flag(t, testHandler, true)+ cleanupPluginInstallations(t)+ // The other half of the gate: a contribution the host DOES ship must install+ // against the real HostCapabilities set, not only against a test set that+ // enables everything.+ source := withLocalPluginSource(t, handlerTestManifest)+ testHandler.PluginService.Host = plugincontract.HostCapabilities()++ body, _ := json.Marshal(map[string]any{+ "source_url": source,+ "granted_scopes": []string{"issues:read", "comments:write", "storage:user"},+ })+ recorder := httptest.NewRecorder()+ testHandler.InstallPlugin(recorder, pluginHandlerRequest(http.MethodPost, "/plugins", body, map[string]string{"id": testWorkspaceID}))+ if recorder.Code != http.StatusCreated {+ t.Fatalf("shipped surface was refused: status=%d body=%s", recorder.Code, recorder.Body.String())+ }+}+func TestPluginInstallationFromAnotherWorkspaceIsNotFound(t *testing.T) {withPluginsV1Flag(t, testHandler, true)recorder := httptest.NewRecorder()diff --git a/server/internal/service/plugin.go b/server/internal/service/plugin.goindex 15c54dddd2..d5a5282dc9 100644--- a/server/internal/service/plugin.go+++ b/server/internal/service/plugin.go@@ -7,9 +7,11 @@ import ("fmt""io""net/http"+ "net/url""os""path/filepath""strings"+ "time""github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgconn"@@ -37,16 +39,22 @@ type PluginService struct {Secrets *secretbox.Box// LocalDir is MULTICA_PLUGIN_DIR. Empty disables local sources.LocalDir string+ // DevOrigins is MULTICA_PLUGIN_DEV_ORIGINS: origins a plugin author may+ // serve a manifest from while building one, typically a localhost static+ // server. Empty in every deployment that has not opted in, which is the+ // only reason it is safe to skip the public-HTTPS guard for them.+ DevOrigins []string// Host gates which declared contributions this build can actually run.Host plugincontract.Capabilities}func NewPluginService(queries *db.Queries, txStarter TxStarter) *PluginService {return &PluginService{- Queries: queries,- TxStarter: txStarter,- LocalDir: strings.TrimSpace(os.Getenv("MULTICA_PLUGIN_DIR")),- Host: plugincontract.HostCapabilities(),+ Queries: queries,+ TxStarter: txStarter,+ LocalDir: strings.TrimSpace(os.Getenv("MULTICA_PLUGIN_DIR")),+ DevOrigins: parseDevOrigins(os.Getenv("MULTICA_PLUGIN_DEV_ORIGINS")),+ Host: plugincontract.HostCapabilities(),}}@@ -56,6 +64,7 @@ const (PluginErrorInvalid PluginErrorKind = "invalid"PluginErrorNotFound PluginErrorKind = "not_found"PluginErrorConflict PluginErrorKind = "conflict"+ PluginErrorForbidden PluginErrorKind = "forbidden"PluginErrorIncompatible PluginErrorKind = "incompatible"PluginErrorQuota PluginErrorKind = "quota"PluginErrorUnavailable PluginErrorKind = "unavailable"@@ -103,6 +112,7 @@ type PluginConfigField struct {Required bool `json:"required"`Options []string `json:"options,omitempty"`Placeholder string `json:"placeholder,omitempty"`+ Multiline bool `json:"multiline,omitempty"`}// ConfigFieldsForManifest flattens the manifest config schema into declaration@@ -118,6 +128,7 @@ func ConfigFieldsForManifest(manifest plugincontract.Manifest) []PluginConfigFieRequired: field.Required,Options: field.Options,Placeholder: field.Placeholder,+ Multiline: field.Multiline,})}return fields@@ -140,9 +151,16 @@ func (s *PluginService) FetchManifest(ctx context.Context, sourceURL string) (plvar raw []bytevar err error- if strings.HasPrefix(sourceURL, LocalSourcePrefix) {+ switch {+ case strings.HasPrefix(sourceURL, LocalSourcePrefix):raw, err = s.readLocalManifest(strings.TrimPrefix(sourceURL, LocalSourcePrefix))- } else {+ case s.isDevOrigin(sourceURL):+ // Explicitly opted in by the operator, so the public-HTTPS guard is+ // skipped rather than worked around. This is what makes iterating on a+ // surface possible: the author serves it from localhost and installs by+ // URL, exactly as a published plugin would be.+ raw, err = fetchDevManifest(ctx, sourceURL)+ default:raw, err = fetchRemoteManifest(ctx, sourceURL)}if err != nil {@@ -156,6 +174,70 @@ func (s *PluginService) FetchManifest(ctx context.Context, sourceURL string) (plreturn manifest, canonical, nil}+// parseDevOrigins reads the opt-in list. Anything that is not a bare origin is+// dropped rather than half-honored: a path or query here would read as a broader+// grant than it is.+func parseDevOrigins(raw string) []string {+ origins := make([]string, 0)+ for _, candidate := range strings.Split(raw, ",") {+ candidate = strings.TrimRight(strings.TrimSpace(candidate), "/")+ if candidate == "" {+ continue+ }+ parsed, err := url.Parse(candidate)+ if err != nil || parsed.Host == "" || parsed.Path != "" || parsed.RawQuery != "" {+ continue+ }+ if parsed.Scheme != "http" && parsed.Scheme != "https" {+ continue+ }+ origins = append(origins, parsed.Scheme+"://"+parsed.Host)+ }+ return origins+}++func (s *PluginService) isDevOrigin(sourceURL string) bool {+ if len(s.DevOrigins) == 0 {+ return false+ }+ parsed, err := url.Parse(sourceURL)+ if err != nil || parsed.Host == "" {+ return false+ }+ origin := parsed.Scheme + "://" + parsed.Host+ for _, allowed := range s.DevOrigins {+ if origin == allowed {+ return true+ }+ }+ return false+}++// fetchDevManifest is the opted-in path: an ordinary bounded GET with no SSRF+// guard, because the operator named this exact origin.+func fetchDevManifest(ctx context.Context, sourceURL string) ([]byte, error) {+ request, err := http.NewRequestWithContext(ctx, http.MethodGet, sourceURL, nil)+ if err != nil {+ return nil, &PluginError{Kind: PluginErrorInvalid, Message: "build manifest request", Err: err}+ }+ response, err := (&http.Client{Timeout: 10 * time.Second}).Do(request)+ if err != nil {+ return nil, &PluginError{Kind: PluginErrorUnavailable, Message: "fetch plugin manifest", Err: err}+ }+ defer response.Body.Close()+ if response.StatusCode != http.StatusOK {+ return nil, pluginErrf(PluginErrorUnavailable, "plugin manifest request returned HTTP %d", response.StatusCode)+ }+ raw, err := io.ReadAll(io.LimitReader(response.Body, plugincontract.MaxManifestSize+1))+ if err != nil {+ return nil, &PluginError{Kind: PluginErrorUnavailable, Message: "read plugin manifest", Err: err}+ }+ if len(raw) > plugincontract.MaxManifestSize {+ return nil, pluginErrf(PluginErrorInvalid, "plugin manifest exceeds %d bytes", plugincontract.MaxManifestSize)+ }+ return raw, nil+}+func (s *PluginService) readLocalManifest(name string) ([]byte, error) {if s.LocalDir == "" {return nil, pluginErrf(PluginErrorInvalid, "local plugin sources require MULTICA_PLUGIN_DIR")@@ -407,6 +489,10 @@ func pruneConfig(raw []byte, manifest plugincontract.Manifest) []byte {return encoded}+func parseUUIDValue(value string) (pgtype.UUID, error) { return util.ParseUUID(value) }++func uuidString(value pgtype.UUID) string { return util.UUIDToString(value) }+// ParseInstallationManifest reads back the consented snapshot. Callers must use// this, never a freshly fetched manifest: what the source URL serves today is// not what the administrator approved.diff --git a/server/internal/service/plugin_action.go b/server/internal/service/plugin_action.gonew file mode 100644index 0000000000..3f0e53271e--- /dev/null+++ b/server/internal/service/plugin_action.go@@ -0,0 +1,152 @@+package service++import (+ "context"+ "encoding/json"+ "errors"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/plugincontract"+)++// PluginActionCaller is one authorized Action API call: which installation is+// speaking, in which workspace, on whose behalf.+//+// The plugin never holds a credential. A surface talks to the host page over+// postMessage and the host re-issues the call with the signed-in user's own+// session, so the identity here is always a real member — a plugin cannot act+// as anyone but the person using it.+type PluginActionCaller struct {+ Installation db.PluginInstallation+ WorkspaceID pgtype.UUID+ UserID pgtype.UUID+ // Scopes is the consented set, read from the installation row rather than+ // from the manifest the source URL serves today.+ Scopes []string+}++// AuthorizePluginAction performs the two checks that belong to the plugin: the+// installation is real and enabled, and it holds the scope this call needs.+//+// It deliberately does NOT decide whether the caller may touch the resource.+// That is the third check, and it stays with the normal resource loaders so a+// plugin inherits exactly the permissions of the user behind it — no more, and+// no separate copy of the permission rules to drift.+func (s *PluginService) AuthorizePluginAction(ctx context.Context, installationID string, userID pgtype.UUID, scope string) (PluginActionCaller, error) {+ if installationID == "" {+ return PluginActionCaller{}, pluginErrf(PluginErrorInvalid, "plugin installation is required")+ }+ parsed, err := parseInstallationID(installationID)+ if err != nil {+ return PluginActionCaller{}, err+ }+ installation, err := s.Queries.GetPluginInstallation(ctx, parsed)+ if errors.Is(err, pgx.ErrNoRows) {+ return PluginActionCaller{}, pluginErrf(PluginErrorNotFound, "plugin installation not found")+ }+ if err != nil {+ return PluginActionCaller{}, &PluginError{Kind: PluginErrorUnavailable, Message: "load plugin installation", Err: err}+ }+ // A disabled plugin is off, not merely hidden: an iframe left open in a+ // stale tab must not keep working after an admin disables it.+ if !installation.Enabled {+ return PluginActionCaller{}, pluginErrf(PluginErrorForbidden, "this Plugin is disabled")+ }++ scopes := decodeScopes(installation.GrantedScopes)+ if scope != "" && !hasScope(scopes, scope) {+ return PluginActionCaller{}, &PluginError{+ Kind: PluginErrorForbidden,+ Message: "this Plugin was not granted the " + scope + " scope",+ }+ }++ return PluginActionCaller{+ Installation: installation,+ WorkspaceID: installation.WorkspaceID,+ UserID: userID,+ Scopes: scopes,+ }, nil+}++func hasScope(scopes []string, want string) bool {+ for _, scope := range scopes {+ if scope == want {+ return true+ }+ }+ return false+}++func parseInstallationID(value string) (pgtype.UUID, error) {+ parsed, err := parseUUIDValue(value)+ if err != nil {+ return pgtype.UUID{}, pluginErrf(PluginErrorNotFound, "plugin installation not found")+ }+ return parsed, nil+}++// PluginContext is what a surface gets before it has asked for anything: who is+// looking, where, and which issue the panel is mounted on. It requires no scope+// because it contains nothing the user in front of the iframe cannot already+// see on the page around it.+type PluginContext struct {+ Workspace PluginContextWorkspace `json:"workspace"`+ User PluginContextUser `json:"user"`+ Issue *PluginContextIssue `json:"issue,omitempty"`+ Config map[string]any `json:"config"`+ GrantedURLs []string `json:"granted_net_domains"`+}++type PluginContextWorkspace struct {+ ID string `json:"id"`+ Name string `json:"name"`+ Slug string `json:"slug"`+}++type PluginContextUser struct {+ ID string `json:"id"`+ Name string `json:"name"`+ // Email is deliberately absent: a surface that needs to identify a member+ // to its own backend should use the opaque id, not a mailbox.+}++type PluginContextIssue struct {+ ID string `json:"id"`+ Identifier string `json:"identifier"`+ Title string `json:"title"`+}++// BuildPluginContext assembles the context payload. Config carries only the+// non-secret installation values — secrets live in their own table and have no+// read path, so there is no way for one to reach the iframe.+func (s *PluginService) BuildPluginContext(caller PluginActionCaller, workspace db.Workspace, user db.User, issue *db.Issue) PluginContext {+ config := map[string]any{}+ if len(caller.Installation.Config) > 0 {+ _ = json.Unmarshal(caller.Installation.Config, &config)+ }++ payload := PluginContext{+ Workspace: PluginContextWorkspace{+ ID: uuidString(workspace.ID),+ Name: workspace.Name,+ Slug: workspace.Slug,+ },+ User: PluginContextUser{+ ID: uuidString(user.ID),+ Name: user.Name,+ },+ Config: config,+ GrantedURLs: plugincontract.NetDomains(caller.Scopes),+ }+ if issue != nil {+ payload.Issue = &PluginContextIssue{+ ID: uuidString(issue.ID),+ Identifier: IssueIdentifier(workspace.IssuePrefix, issue.Number),+ Title: issue.Title,+ }+ }+ return payload+}diff --git a/server/internal/service/plugin_test.go b/server/internal/service/plugin_test.goindex 0982035098..c1e4902fed 100644--- a/server/internal/service/plugin_test.go+++ b/server/internal/service/plugin_test.go@@ -262,10 +262,14 @@ func TestValidateStorageKeyEnforcesTheKeyQuota(t *testing.T) {}func TestCapabilityMessageNamesTheMissingCapabilities(t *testing.T) {+ // Asserted against an explicitly empty host set, not the shipped one: this+ // covers the message, and tying it to whatever HostCapabilities happens to+ // enable today makes every future capability flip fail a test that has+ // nothing to say about the flip.manifest := testManifest(t)- err := manifest.CheckCapabilities(plugincontract.HostCapabilities())+ err := manifest.CheckCapabilities(plugincontract.Capabilities{})if err == nil {- t.Fatal("expected the shipped host set to reject a surface contribution")+ t.Fatal("an empty host set must reject every contribution")}message := capabilityMessage(err)if !strings.Contains(message, "surface issue_panel") {@@ -273,6 +277,30 @@ func TestCapabilityMessageNamesTheMissingCapabilities(t *testing.T) {}}+func TestShippedHostCapabilitiesRunTheSurfacesTheHostMounts(t *testing.T) {+ // The gate is only meaningful if it tracks what actually renders. A surface+ // type enabled here with no mount point installs successfully and then never+ // appears — the exact silent failure the gate exists to prevent.+ shipped := plugincontract.HostCapabilities()+ if !shipped.SurfaceTypes[plugincontract.SurfaceIssuePanel] {+ t.Fatal("issue_panel is mounted by PluginPanelSection and must be shipped")+ }+ if shipped.SurfaceTypes[plugincontract.SurfaceSidebarPanel] {+ t.Fatal("sidebar_panel has no mount point yet; enabling it would install surfaces that never render")+ }+ if shipped.SurfaceTypes[plugincontract.SurfaceModal] {+ t.Fatal("modal is opened by the manual trigger, which the hook engine has not landed")+ }+ for _, trigger := range []string{plugincontract.TriggerUI, plugincontract.TriggerManual, plugincontract.TriggerAgent, plugincontract.TriggerEvent} {+ if shipped.HookTriggers[trigger] {+ t.Fatalf("hook trigger %q is enabled but the hook engine has not landed", trigger)+ }+ }+ if shipped.ResourceTypes[plugincontract.ResourceSkill] {+ t.Fatal("skill resources are enabled but the agent integration has not landed")+ }+}+func TestEnforceStorageQuota(t *testing.T) {// Canonical layer for the three storage limits. SetStorageValue only wires// the usage query to this function; plugin_storage_db_test.go covers thediff --git a/server/migrations/348_plugin_via_attribution.down.sql b/server/migrations/348_plugin_via_attribution.down.sqlnew file mode 100644index 0000000000..345e73998e--- /dev/null+++ b/server/migrations/348_plugin_via_attribution.down.sql@@ -0,0 +1 @@+ALTER TABLE comment DROP COLUMN IF EXISTS via_plugin_id;diff --git a/server/migrations/348_plugin_via_attribution.up.sql b/server/migrations/348_plugin_via_attribution.up.sqlnew file mode 100644index 0000000000..d0a7a7831a--- /dev/null+++ b/server/migrations/348_plugin_via_attribution.up.sql@@ -0,0 +1,18 @@+-- Plugin-mediated writes record which plugin mediated them.+--+-- A surface writes as the CURRENT USER — a plugin can never do more than the+-- person using it — so author_type/author_id stay exactly what they would be+-- without a plugin. This column is the missing half of that: permission-wise+-- the write is the user's, but audit-wise it must stay attributable to the+-- plugin that produced it, or an installed plugin becomes an untraceable way+-- to act as someone.+--+-- Modeled on comment.quick_action_id (migration 239) for the same two reasons:+-- adding a nullable column with no default is metadata-only and instant on a+-- hot table, and there is no request field for it — only the plugin Action API+-- sets it — so the marker cannot be forged by a member posting normally.+--+-- No FK per repository policy. The render path treats an unresolvable id as an+-- ordinary write, so uninstalling a plugin degrades old rows to plain+-- attribution instead of breaking them.+ALTER TABLE comment ADD COLUMN IF NOT EXISTS via_plugin_id UUID;diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex 38fc90d3a6..55b2ae616e 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -5197,7 +5197,7 @@ func (q *Queries) ListChatFinalizeDeferredExpired(ctx context.Context, arg ListC}const listPendingDelegatedFailureRecoveries = `-- name: ListPendingDelegatedFailureRecoveries :many-SELECT recovery.id, recovery.issue_id, recovery.author_type, recovery.author_id, recovery.content, recovery.type, recovery.created_at, recovery.updated_at, recovery.parent_id, recovery.workspace_id, recovery.resolved_at, recovery.resolved_by_type, recovery.resolved_by_id, recovery.source_task_id, recovery.quick_action_id+SELECT recovery.id, recovery.issue_id, recovery.author_type, recovery.author_id, recovery.content, recovery.type, recovery.created_at, recovery.updated_at, recovery.parent_id, recovery.workspace_id, recovery.resolved_at, recovery.resolved_by_type, recovery.resolved_by_id, recovery.source_task_id, recovery.quick_action_id, recovery.via_plugin_idFROM comment recoveryJOIN agent_task_queue failed ON failed.id = recovery.source_task_idJOIN agent_task_queue source ON source.id = failed.delegated_from_task_id@@ -5281,6 +5281,7 @@ func (q *Queries) ListPendingDelegatedFailureRecoveries(ctx context.Context, max&i.ResolvedByID,&i.SourceTaskID,&i.QuickActionID,+ &i.ViaPluginID,); err != nil {return nil, err}diff --git a/server/pkg/db/generated/comment.sql.go b/server/pkg/db/generated/comment.sql.goindex dd3dbaa5b7..c3fa131caf 100644--- a/server/pkg/db/generated/comment.sql.go+++ b/server/pkg/db/generated/comment.sql.go@@ -45,7 +45,7 @@ UPDATE comment SETWHERE comment.id IN (SELECT id FROM descendants)AND comment.id <> $1AND comment.resolved_at IS NOT NULL-RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id+RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id`type ClearOtherThreadResolutionsParams struct {@@ -89,6 +89,7 @@ func (q *Queries) ClearOtherThreadResolutions(ctx context.Context, arg ClearOthe&i.ResolvedByID,&i.SourceTaskID,&i.QuickActionID,+ &i.ViaPluginID,); err != nil {return nil, err}@@ -158,13 +159,13 @@ func (q *Queries) CountNewCommentsSince(ctx context.Context, arg CountNewCommentconst createComment = `-- name: CreateComment :oneWITH touched_issue AS (UPDATE issue SET updated_at = now()- WHERE issue.id = $8 AND issue.workspace_id = $9+ WHERE issue.id = $9 AND issue.workspace_id = $10RETURNING issue.id, issue.workspace_id)-INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, parent_id, source_task_id, quick_action_id)-SELECT ti.id, ti.workspace_id, $1, $2, $3, $4, $5, $6, $7+INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, parent_id, source_task_id, quick_action_id, via_plugin_id)+SELECT ti.id, ti.workspace_id, $1, $2, $3, $4, $5, $6, $7, $8FROM touched_issue ti-RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id+RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id`type CreateCommentParams struct {@@ -175,6 +176,7 @@ type CreateCommentParams struct {ParentID pgtype.UUID `json:"parent_id"`SourceTaskID pgtype.UUID `json:"source_task_id"`QuickActionID pgtype.UUID `json:"quick_action_id"`+ ViaPluginID pgtype.UUID `json:"via_plugin_id"`IssueID pgtype.UUID `json:"issue_id"`WorkspaceID pgtype.UUID `json:"workspace_id"`}@@ -204,6 +206,7 @@ func (q *Queries) CreateComment(ctx context.Context, arg CreateCommentParams) (Carg.ParentID,arg.SourceTaskID,arg.QuickActionID,+ arg.ViaPluginID,arg.IssueID,arg.WorkspaceID,)@@ -224,6 +227,7 @@ func (q *Queries) CreateComment(ctx context.Context, arg CreateCommentParams) (C&i.ResolvedByID,&i.SourceTaskID,&i.QuickActionID,+ &i.ViaPluginID,)return i, err}@@ -244,7 +248,7 @@ func (q *Queries) DeleteComment(ctx context.Context, arg DeleteCommentParams) er}const getComment = `-- name: GetComment :one-SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id FROM comment+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id FROM commentWHERE id = $1`@@ -267,12 +271,13 @@ func (q *Queries) GetComment(ctx context.Context, id pgtype.UUID) (Comment, erro&i.ResolvedByID,&i.SourceTaskID,&i.QuickActionID,+ &i.ViaPluginID,)return i, err}const getCommentInWorkspace = `-- name: GetCommentInWorkspace :one-SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id FROM comment+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id FROM commentWHERE id = $1 AND workspace_id = $2`@@ -300,12 +305,13 @@ func (q *Queries) GetCommentInWorkspace(ctx context.Context, arg GetCommentInWor&i.ResolvedByID,&i.SourceTaskID,&i.QuickActionID,+ &i.ViaPluginID,)return i, err}const getDelegatedFailureRecoveryComment = `-- name: GetDelegatedFailureRecoveryComment :one-SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id FROM comment+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id FROM commentWHERE issue_id = $1AND workspace_id = $2AND author_type = 'system'@@ -344,12 +350,13 @@ func (q *Queries) GetDelegatedFailureRecoveryComment(ctx context.Context, arg Ge&i.ResolvedByID,&i.SourceTaskID,&i.QuickActionID,+ &i.ViaPluginID,)return i, err}const getDelegatedFailureRecoveryExhaustionComment = `-- name: GetDelegatedFailureRecoveryExhaustionComment :one-SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id FROM comment+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id FROM commentWHERE issue_id = $1AND workspace_id = $2AND author_type = 'system'@@ -388,12 +395,13 @@ func (q *Queries) GetDelegatedFailureRecoveryExhaustionComment(ctx context.Conte&i.ResolvedByID,&i.SourceTaskID,&i.QuickActionID,+ &i.ViaPluginID,)return i, err}const getLatestMemberCommentForIssueSince = `-- name: GetLatestMemberCommentForIssueSince :one-SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id FROM comment+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id FROM commentWHERE issue_id = $1AND author_type = 'member'AND created_at > $2@@ -434,6 +442,7 @@ func (q *Queries) GetLatestMemberCommentForIssueSince(ctx context.Context, arg G&i.ResolvedByID,&i.SourceTaskID,&i.QuickActionID,+ &i.ViaPluginID,)return i, err}@@ -448,7 +457,7 @@ WITH RECURSIVE root_of AS (FROM comment pJOIN root_of r ON p.id = r.parent_id)-SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type, c.created_at, c.updated_at, c.parent_id, c.workspace_id, c.resolved_at, c.resolved_by_type, c.resolved_by_id, c.source_task_id, c.quick_action_id FROM comment c+SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type, c.created_at, c.updated_at, c.parent_id, c.workspace_id, c.resolved_at, c.resolved_by_type, c.resolved_by_id, c.source_task_id, c.quick_action_id, c.via_plugin_id FROM comment cWHERE c.id = (SELECT id FROM root_of WHERE parent_id IS NULL LIMIT 1)`@@ -481,6 +490,7 @@ func (q *Queries) GetThreadRoot(ctx context.Context, arg GetThreadRootParams) (C&i.ResolvedByID,&i.SourceTaskID,&i.QuickActionID,+ &i.ViaPluginID,)return i, err}@@ -529,7 +539,7 @@ func (q *Queries) HasAgentRepliedInThread(ctx context.Context, arg HasAgentRepli}const listChildCommentsForParents = `-- name: ListChildCommentsForParents :many-SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id FROM comment+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id FROM commentWHERE parent_id = ANY($1::uuid[])AND issue_id = $2AND workspace_id = $3@@ -588,6 +598,7 @@ func (q *Queries) ListChildCommentsForParents(ctx context.Context, arg ListChild&i.ResolvedByID,&i.SourceTaskID,&i.QuickActionID,+ &i.ViaPluginID,); err != nil {return nil, err}@@ -600,7 +611,7 @@ func (q *Queries) ListChildCommentsForParents(ctx context.Context, arg ListChild}const listCommentsByIDsForIssue = `-- name: ListCommentsByIDsForIssue :many-SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id FROM comment+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id FROM commentWHERE id = ANY($1::uuid[])AND issue_id = $2AND workspace_id = $3@@ -647,6 +658,7 @@ func (q *Queries) ListCommentsByIDsForIssue(ctx context.Context, arg ListComment&i.ResolvedByID,&i.SourceTaskID,&i.QuickActionID,+ &i.ViaPluginID,); err != nil {return nil, err}@@ -659,8 +671,8 @@ func (q *Queries) ListCommentsByIDsForIssue(ctx context.Context, arg ListComment}const listCommentsForIssue = `-- name: ListCommentsForIssue :many-SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id FROM (- SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id FROM comment+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id FROM (+ SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id FROM commentWHERE issue_id = $1 AND workspace_id = $2ORDER BY created_at DESC, id DESCLIMIT $3@@ -716,6 +728,7 @@ func (q *Queries) ListCommentsForIssue(ctx context.Context, arg ListCommentsForI&i.ResolvedByID,&i.SourceTaskID,&i.QuickActionID,+ &i.ViaPluginID,); err != nil {return nil, err}@@ -728,7 +741,7 @@ func (q *Queries) ListCommentsForIssue(ctx context.Context, arg ListCommentsForI}const listCommentsSinceForIssue = `-- name: ListCommentsSinceForIssue :many-SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id FROM comment+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id FROM commentWHERE issue_id = $1 AND workspace_id = $2 AND created_at > $3ORDER BY created_at ASC, id ASCLIMIT $4@@ -773,6 +786,7 @@ func (q *Queries) ListCommentsSinceForIssue(ctx context.Context, arg ListComment&i.ResolvedByID,&i.SourceTaskID,&i.QuickActionID,+ &i.ViaPluginID,); err != nil {return nil, err}@@ -930,7 +944,7 @@ func (q *Queries) ListRecentThreadCommentsForIssue(ctx context.Context, arg List}const listReconcilableCommentsForIssueSince = `-- name: ListReconcilableCommentsForIssueSince :many-SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id FROM comment+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id FROM commentWHERE issue_id = $1AND ((@@ -1010,6 +1024,7 @@ func (q *Queries) ListReconcilableCommentsForIssueSince(ctx context.Context, arg&i.ResolvedByID,&i.SourceTaskID,&i.QuickActionID,+ &i.ViaPluginID,); err != nil {return nil, err}@@ -1412,7 +1427,7 @@ UPDATE comment SETresolved_by_id = COALESCE(resolved_by_id, $3),updated_at = CASE WHEN resolved_at IS NULL THEN now() ELSE updated_at ENDWHERE id = $1-RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id+RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id`type ResolveCommentParams struct {@@ -1442,6 +1457,7 @@ func (q *Queries) ResolveComment(ctx context.Context, arg ResolveCommentParams)&i.ResolvedByID,&i.SourceTaskID,&i.QuickActionID,+ &i.ViaPluginID,)return i, err}@@ -1453,7 +1469,7 @@ UPDATE comment SETresolved_by_id = NULL,updated_at = CASE WHEN resolved_at IS NOT NULL THEN now() ELSE updated_at ENDWHERE id = $1-RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id+RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id`// Idempotent: a no-op clear (already unresolved) just returns the row.@@ -1476,6 +1492,7 @@ func (q *Queries) UnresolveComment(ctx context.Context, id pgtype.UUID) (Comment&i.ResolvedByID,&i.SourceTaskID,&i.QuickActionID,+ &i.ViaPluginID,)return i, err}@@ -1486,7 +1503,7 @@ UPDATE comment SETsource_task_id = $3,updated_at = now()WHERE id = $1-RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id+RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id`type UpdateCommentParams struct {@@ -1514,6 +1531,7 @@ func (q *Queries) UpdateComment(ctx context.Context, arg UpdateCommentParams) (C&i.ResolvedByID,&i.SourceTaskID,&i.QuickActionID,+ &i.ViaPluginID,)return i, err}diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex 2e2405ec2e..6128db4775 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -467,6 +467,7 @@ type Comment struct {ResolvedByID pgtype.UUID `json:"resolved_by_id"`SourceTaskID pgtype.UUID `json:"source_task_id"`QuickActionID pgtype.UUID `json:"quick_action_id"`+ ViaPluginID pgtype.UUID `json:"via_plugin_id"`}type CommentReaction struct {diff --git a/server/pkg/db/queries/comment.sql b/server/pkg/db/queries/comment.sqlindex f135bd156e..0d7d07f049 100644--- a/server/pkg/db/queries/comment.sql+++ b/server/pkg/db/queries/comment.sql@@ -442,8 +442,8 @@ WITH touched_issue AS (WHERE issue.id = sqlc.arg(issue_id) AND issue.workspace_id = sqlc.arg(workspace_id)RETURNING issue.id, issue.workspace_id)-INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, parent_id, source_task_id, quick_action_id)-SELECT ti.id, ti.workspace_id, sqlc.arg(author_type), sqlc.arg(author_id), sqlc.arg(content), sqlc.arg(type), sqlc.narg(parent_id), sqlc.narg(source_task_id), sqlc.narg(quick_action_id)+INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, parent_id, source_task_id, quick_action_id, via_plugin_id)+SELECT ti.id, ti.workspace_id, sqlc.arg(author_type), sqlc.arg(author_id), sqlc.arg(content), sqlc.arg(type), sqlc.narg(parent_id), sqlc.narg(source_task_id), sqlc.narg(quick_action_id), sqlc.narg(via_plugin_id)FROM touched_issue tiRETURNING *;diff --git a/server/pkg/plugincontract/capabilities.go b/server/pkg/plugincontract/capabilities.goindex 55988975cd..ba20e84352 100644--- a/server/pkg/plugincontract/capabilities.go+++ b/server/pkg/plugincontract/capabilities.go@@ -27,7 +27,11 @@ type Capabilities struct {// resources land with the agent integration.func HostCapabilities() Capabilities {return Capabilities{- SurfaceTypes: map[string]bool{},+ // issue_panel only: PluginPanelSection is the one mount point that exists.+ // sidebar_panel has no host location yet, and enabling a surface the host+ // cannot render installs a plugin that silently never appears — precisely+ // what this gate exists to prevent.+ SurfaceTypes: map[string]bool{SurfaceIssuePanel: true},HookTriggers: map[string]bool{},HookTransport: map[string]bool{},ResourceTypes: map[string]bool{},diff --git a/server/pkg/plugincontract/manifest.go b/server/pkg/plugincontract/manifest.goindex 45787a9c4f..4d83ce5621 100644--- a/server/pkg/plugincontract/manifest.go+++ b/server/pkg/plugincontract/manifest.go@@ -204,6 +204,10 @@ type ConfigField struct {Required bool `json:"required,omitempty"`Options []string `json:"options,omitempty"`Placeholder string `json:"placeholder,omitempty"`+ // Multiline asks the host to render a textarea. Only meaningful for string+ // fields; without it a value that is a list of lines is unreadable in the+ // generated form, which is the one thing the host owns rendering for.+ Multiline bool `json:"multiline,omitempty"`}// ConfigSchema keeps declaration order so the generated form is stable across@@ -246,7 +250,8 @@ func (c ConfigSchema) MarshalJSON() ([]byte, error) {Required bool `json:"required,omitempty"`Options []string `json:"options,omitempty"`Placeholder string `json:"placeholder,omitempty"`- }{field.Type, field.Label, field.Description, field.Required, field.Options, field.Placeholder})+ Multiline bool `json:"multiline,omitempty"`+ }{field.Type, field.Label, field.Description, field.Required, field.Options, field.Placeholder, field.Multiline})if err != nil {return nil, err}@@ -452,6 +457,9 @@ func (m Manifest) validateConfig() error {if len(field.Options) > 0 {return fmt.Errorf("%s.options is only valid for enum fields", label)}+ if field.Multiline && field.Type != ConfigString {+ return fmt.Errorf("%s.multiline is only valid for string fields", label)+ }case ConfigEnum:if len(field.Options) == 0 {return fmt.Errorf("%s.options must not be empty for enum fields", label)@@ -472,6 +480,9 @@ func (m Manifest) validateConfig() error {default:return fmt.Errorf("%s.type is unsupported: %q", label, field.Type)}+ if field.Multiline && field.Type != ConfigString {+ return fmt.Errorf("%s.multiline is only valid for string fields", label)+ }if err := validateDisplayText(label+".label", field.Label, 160); err != nil {return err}diff --git a/server/pkg/plugincontract/manifest_test.go b/server/pkg/plugincontract/manifest_test.goindex d1c092017d..5d96855ce1 100644--- a/server/pkg/plugincontract/manifest_test.go+++ b/server/pkg/plugincontract/manifest_test.go@@ -378,7 +378,8 @@ func TestCheckCapabilitiesReportsEveryUnavailableContribution(t *testing.T) {// The shipped host set is what gates a staged rollout: a manifest naming a// capability this build cannot run must fail loudly, never install- // half-working.+ // half-working. Surfaces ship with the surface runtime; hooks and skill+ // resources are still ahead, so they are what must be reported here.err = manifest.CheckCapabilities(HostCapabilities())if err == nil {t.Fatal("CheckCapabilities accepted contributions the host cannot run")@@ -387,11 +388,16 @@ func TestCheckCapabilitiesReportsEveryUnavailableContribution(t *testing.T) {if !asCapabilityError(err, &unavailable) {t.Fatalf("error type = %T, want *ErrCapabilityUnavailable", err)}- for _, want := range []string{"surface issue_panel", "hook trigger ui", "hook transport http", "resource skill"} {+ for _, want := range []string{"hook trigger ui", "hook transport http", "resource skill"} {if !containsString(unavailable.Missing, want) {t.Fatalf("missing = %v, want it to include %q", unavailable.Missing, want)}}+ // A shipped capability must NOT be reported, or every install of a plain+ // panel plugin would fail on a capability the host can actually run.+ if containsString(unavailable.Missing, "surface "+SurfaceIssuePanel) {+ t.Fatalf("missing = %v, want it to exclude the shipped issue_panel surface", unavailable.Missing)+ }full := Capabilities{SurfaceTypes: map[string]bool{SurfaceIssuePanel: true, SurfaceSidebarPanel: true, SurfaceModal: true},