Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(plugins): enforce command registration ownership
Seraph-xf0a77bb7b994
diff --git a/apps/desktop/electron/main/plugin-runtime.ts b/apps/desktop/electron/main/plugin-runtime.tsindex 3d1c31727..f82a55257 100644--- a/apps/desktop/electron/main/plugin-runtime.ts+++ b/apps/desktop/electron/main/plugin-runtime.ts@@ -2748,6 +2748,10 @@ export class PluginRuntime {};const id = String(descriptor.id ?? "");if (!id) throw apiError("INVALID_ARGUMENT", "command.id is required");+ const existing = this.commands.get(id);+ if (existing && existing.pluginId !== pluginId) {+ throw apiError("CONFLICT", `command is registered by another plugin: ${id}`);+ }this.commands.set(id, {id,title: String(descriptor.title ?? id),@@ -2767,7 +2771,12 @@ export class PluginRuntime {return { ok: true };}case "commands.unregister": {- this.commands.delete(String(args[0] ?? ""));+ const id = String(args[0] ?? "");+ const command = this.commands.get(id);+ if (command && command.pluginId !== pluginId) {+ throw apiError("PERMISSION_DENIED", `command belongs to another plugin: ${id}`);+ }+ this.commands.delete(id);return { ok: true };}case "keyboard.registerGlobalShortcut": {diff --git a/apps/desktop/test/plugin-command-ownership.test.mjs b/apps/desktop/test/plugin-command-ownership.test.mjsnew file mode 100644index 000000000..37865de68--- /dev/null+++ b/apps/desktop/test/plugin-command-ownership.test.mjs@@ -0,0 +1,134 @@+import assert from "node:assert/strict";+import { fork } from "node:child_process";+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { register } from "node:module";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import test from "node:test";+import { fileURLToPath } from "node:url";++register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));+const { PluginRuntime } = await import("../electron/main/plugin-runtime.ts");+const hostEntry = join(dirname(fileURLToPath(import.meta.url)), "../electron/main/plugin-host-process.mjs");++function createRuntime(t) {+ const folders = [];+ const runtime = new PluginRuntime({+ hostEntry,+ spawnProcess: ({ entry }) => {+ const child = fork(entry, [], { stdio: ["ignore", "pipe", "pipe", "ipc"] });+ return {+ postMessage: (message) => child.send(message),+ onMessage: (handler) => child.on("message", handler),+ onExit: (handler) => child.on("exit", (code) => handler(code ?? 0)),+ kill: () => child.kill(),+ };+ },+ });+ t.after(async () => {+ for (const loaded of runtime.listLoaded()) await runtime.unload(loaded.manifest.id);+ for (const folder of folders) rmSync(folder, { recursive: true, force: true });+ });+ const load = async (id, commandId) => {+ const folder = mkdtempSync(join(tmpdir(), "pi-command-owner-"));+ folders.push(folder);+ writeFileSync(join(folder, "manifest.json"), JSON.stringify({+ schemaVersion: 1, id, name: id, version: "0.0.1", main: "main.js", permissions: [],+ }));+ writeFileSync(join(folder, "main.js"), `+ const initialId = ${JSON.stringify(commandId ?? null)};+ const registerCommand = (id, marker) => pi.commands.register({+ id, title: marker, run: () => pi.ui.showToast(marker),+ });+ module.exports = {+ async onLoad() {+ if (initialId) await registerCommand(initialId, ${JSON.stringify(id)});+ },+ async onPanelInvoke(channel, input) {+ if (channel === "command.register") return registerCommand(input.id, input.marker);+ if (channel === "command.unregister") return pi.commands.unregister(input.id);+ throw new Error("unknown test operation: " + channel);+ },+ };+ `);+ await runtime.loadFromPath(folder);+ };+ return { runtime, load };+}++async function runCommand(runtime, id, marker) {+ const command = runtime.getCommands().find((candidate) => candidate.id === id);+ assert.ok(command, `missing command: ${id}`);+ await command.run();+ assert.deepEqual(runtime.drainToasts(), [marker]);+}++test("another plugin cannot replace a registered command", { timeout: 60_000 }, async (t) => {+ const { runtime, load } = createRuntime(t);+ await load("audit.owner", "shared-command");+ await load("audit.other");+ await assert.rejects(+ runtime.invokePanelBridge("audit.other", "command.register", { id: "shared-command", marker: "replacement" }),+ { code: "CONFLICT" },+ );+ assert.equal(runtime.getCommands()[0].pluginId, "audit.owner");+ await runCommand(runtime, "shared-command", "audit.owner");+ await runtime.invokePanelBridge("audit.other", "command.register", { id: "other-command", marker: "other" });+ await runCommand(runtime, "other-command", "other");+});++test("another plugin cannot unregister a registered command", { timeout: 60_000 }, async (t) => {+ const { runtime, load } = createRuntime(t);+ await load("audit.owner", "shared-command");+ await load("audit.other");+ await assert.rejects(+ runtime.invokePanelBridge("audit.other", "command.unregister", { id: "shared-command" }),+ { code: "PERMISSION_DENIED" },+ );+ await runCommand(runtime, "shared-command", "audit.owner");+});++test("the owner can update its command without changing a legacy ID", { timeout: 60_000 }, async (t) => {+ const { runtime, load } = createRuntime(t);+ await load("audit.owner", "legacy-command");+ await runtime.invokePanelBridge("audit.owner", "command.register", { id: "legacy-command", marker: "updated" });+ assert.equal(runtime.getCommands().length, 1);+ assert.equal(runtime.getCommands()[0].id, "legacy-command");+ await runCommand(runtime, "legacy-command", "updated");+});++test("owner removal is idempotent and releases the ID for another plugin", { timeout: 60_000 }, async (t) => {+ const { runtime, load } = createRuntime(t);+ await load("audit.owner", "shared-command");+ await load("audit.other");+ await runtime.invokePanelBridge("audit.owner", "command.unregister", { id: "shared-command" });+ await runtime.invokePanelBridge("audit.owner", "command.unregister", { id: "shared-command" });+ assert.deepEqual(runtime.getCommands(), []);+ await runtime.invokePanelBridge("audit.other", "command.register", { id: "shared-command", marker: "new owner" });+ await runCommand(runtime, "shared-command", "new owner");+});++test("a conflicting command during plugin load leaves the existing owner running", { timeout: 60_000 }, async (t) => {+ const { runtime, load } = createRuntime(t);+ await load("audit.owner", "shared-command");+ await assert.rejects(load("audit.other", "shared-command"), { code: "CONFLICT" });+ assert.deepEqual(runtime.listLoaded().map((loaded) => loaded.manifest.id), ["audit.owner"]);+ await runCommand(runtime, "shared-command", "audit.owner");+});++test("concurrent registrations admit only one owner", { timeout: 60_000 }, async (t) => {+ const { runtime, load } = createRuntime(t);+ await load("audit.first");+ await load("audit.second");+ const results = await Promise.allSettled(["audit.first", "audit.second"].map((pluginId) =>+ runtime.invokePanelBridge(pluginId, "command.register", { id: "shared-command", marker: pluginId }),+ ));+ assert.equal(results.filter((result) => result.status === "fulfilled").length, 1);+ const rejected = results.find((result) => result.status === "rejected");+ assert.equal(rejected.reason.code, "CONFLICT");+ const command = runtime.getCommands()[0];+ await runCommand(runtime, "shared-command", command.pluginId);+ const loser = command.pluginId === "audit.first" ? "audit.second" : "audit.first";+ await runtime.unload(loser);+ await runCommand(runtime, "shared-command", command.pluginId);+});diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex d1d973d13..247fbb134 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -3880,6 +3880,24 @@ identify the platform validation still needed.- **Milestone**: M4- **Status**: Draft+#### E2E-PLUGIN-command-ownership: Command registration respects plugin ownership++- **Preconditions**: Two plugins run in separate plugin host processes.+- **Steps**: 1) Register a command from one plugin. 2) Attempt to replace and+ unregister it from the other plugin. 3) Update and unregister it from the+ owner. 4) Repeat with a load-time collision and concurrent registrations.+- **Expected**: Cross-plugin replacement rejects with `CONFLICT`; cross-plugin+ removal rejects with `PERMISSION_DENIED`. Rejected calls leave the original+ handler runnable. Same-owner updates preserve the ID; repeated removal is+ harmless; released IDs can be reused. A failed plugin load or unloading a+ losing registrant does not remove the winning command. Concurrent calls+ admit exactly one owner.+- **Specs linked**: `07-plugins/03-plugin-api.md`, `07-plugins/12-plugin-ipc-and-host-services.md`+- **Acceptance**: G (plugin command isolation)+- **Milestone**: M4+- **Status**: Automated — `pnpm test:e2e:plugin-command-ownership` exercises+ the public plugin API through real plugin host processes and the host broker.+#### E2E-024: Plugin registers and calls agent tool- **Preconditions**: Plugin loaded; plugin declares an agent tool.diff --git a/docs/spec/07-plugins/03-plugin-api.md b/docs/spec/07-plugins/03-plugin-api.mdindex 5d8a29245..d11a1f77b 100644--- a/docs/spec/07-plugins/03-plugin-api.md+++ b/docs/spec/07-plugins/03-plugin-api.md@@ -130,6 +130,13 @@ pi.commands.register(def: {pi.commands.unregister(id: string): Promise<void>```+Command IDs are stored as supplied; the host does not add a prefix. Use a+plugin-specific namespace to avoid collisions. A plugin may replace its own+command, but registering an ID owned by another loaded plugin rejects with+`CONFLICT`. Unregistering another plugin's command rejects with+`PERMISSION_DENIED`. Unregistering an absent ID succeeds without changes.+Disabling or unloading a plugin removes its commands and releases their IDs.+### Composer text transforms (`composer.transform`)A plugin may contribute explicit, user-invoked text actions throughdiff --git a/docs/spec/07-plugins/12-plugin-ipc-and-host-services.md b/docs/spec/07-plugins/12-plugin-ipc-and-host-services.mdindex 2df66f9cd..0ceea6933 100644--- a/docs/spec/07-plugins/12-plugin-ipc-and-host-services.md+++ b/docs/spec/07-plugins/12-plugin-ipc-and-host-services.md@@ -114,7 +114,11 @@ handler is logged, never fatal. This is the same channel that finally makes### Registration- key must be unique-- Plugin commands share the prefix: `plugin.<pluginId>.<commandId>`+- Command IDs are preserved as supplied; `plugin.<pluginId>.<commandId>` is+ a naming convention, not an enforced prefix. The host rejects registration+ of another plugin's command ID with `CONFLICT` and rejects removal of+ another plugin's command with `PERMISSION_DENIED`. Same-owner updates and+ unregistering an absent ID remain valid.- Plugin tool prefix policy: `plugin_<pluginIdSafe>_<toolName>` (fixed in the implementation)### Querydiff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.mdindex 6507da796..3be4d8aeb 100644--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md@@ -1574,6 +1574,21 @@ task-candidate E2E 从请求工作树运行,但使用主工作区已经准备- **里程碑**:M4- **状态**:草案+#### E2E-PLUGIN-command-ownership:命令注册遵循插件归属++- **前提条件**:两个插件分别运行在独立的插件宿主进程中。+- **步骤**:1)由一个插件注册命令。2)尝试通过另一个插件覆盖并注销该命令。+ 3)由所属插件更新并注销命令。4)验证加载期间发生 ID 冲突和并发注册的情况。+- **预期**:跨插件覆盖命令返回 `CONFLICT` 错误,跨插件注销返回 `PERMISSION_DENIED`+ 错误;调用被拒绝后,原命令仍可正常执行。所属插件更新命令时保留原 ID,重复注销不产生+ 副作用,释放后的 ID 可被重新使用。插件加载失败或未成功注册命令的插件被卸载时,不会+ 移除已成功注册的命令。并发注册同一 ID 时,仅一个插件能够成功取得该命令的归属权。+- **关联规范**:`07-plugins/03-plugin-api.md`、`07-plugins/12-plugin-ipc-and-host-services.md`+- **验收项**:G(插件命令隔离)+- **里程碑**:M4+- **状态**:已自动化;`pnpm test:e2e:plugin-command-ownership` 通过真实插件宿主进程和+ 宿主代理,验证公开插件 API 的调用行为。+#### E2E-024:插件注册并调用代理工具- **先决条件**:插件已加载;插件声明一个代理工具。diff --git a/docs/zh-CN/spec/07-plugins/03-plugin-api.md b/docs/zh-CN/spec/07-plugins/03-plugin-api.mdindex d726db7c9..04dc7d074 100644--- a/docs/zh-CN/spec/07-plugins/03-plugin-api.md+++ b/docs/zh-CN/spec/07-plugins/03-plugin-api.md@@ -108,6 +108,12 @@ pi.commands.register(def: {pi.commands.unregister(id: string): Promise<void>```+宿主按原值保存命令 ID,不会自动添加前缀。建议使用插件专属命名空间,避免 ID 冲突。+插件可以更新自己注册的命令;若 ID 已由另一个已加载的插件占用,注册操作将以+`CONFLICT` 错误拒绝。注销其他插件的命令将以 `PERMISSION_DENIED` 错误拒绝。+注销不存在的 ID 会成功返回,不产生任何变更。禁用或卸载插件时,宿主会移除该插件的+命令,并释放相应 ID。+### 输入框文本转换(`composer.transform`)插件可通过 `manifest.contributes.composerTransforms` 声明由用户主动触发的文本操作。diff --git a/docs/zh-CN/spec/07-plugins/12-plugin-ipc-and-host-services.md b/docs/zh-CN/spec/07-plugins/12-plugin-ipc-and-host-services.mdindex 092778bb6..b052355c0 100644--- a/docs/zh-CN/spec/07-plugins/12-plugin-ipc-and-host-services.md+++ b/docs/zh-CN/spec/07-plugins/12-plugin-ipc-and-host-services.md@@ -101,7 +101,9 @@ PluginManager### 注册- 密钥必须是唯一的-- 插件命令共享前缀:`plugin.<pluginId>.<commandId>`+- 命令 ID 按原值保存;`plugin.<pluginId>.<commandId>` 是命名约定,宿主不会强制添加该前缀。+ 注册其他插件已占用的命令 ID 时,宿主返回 `CONFLICT` 错误;注销其他插件的命令时,+ 宿主返回 `PERMISSION_DENIED` 错误。插件仍可更新自己的命令,也可注销不存在的 ID。- 插件工具前缀策略:`plugin_<pluginIdSafe>_<toolName>`(在实现中修复)### 查询diff --git a/package.json b/package.jsonindex 827c6e51c..e579253ae 100644--- a/package.json+++ b/package.json@@ -98,6 +98,7 @@"test:e2e:market-retry": "node scripts/e2e-market-retry.mjs","test:e2e:capability-move": "node scripts/e2e-capability-move.mjs","test:e2e:plugin-fetch-redirect": "node --test apps/desktop/test/plugin-fetch-redirect.test.mjs",+ "test:e2e:plugin-command-ownership": "node --test --test-timeout=60000 apps/desktop/test/plugin-command-ownership.test.mjs","test:e2e:plugin-projects": "node scripts/e2e-plugin-projects.mjs","test:e2e:plugin-import-deps": "node scripts/e2e-plugin-import-deps.mjs","test:e2e:trusted-extensions": "node scripts/e2e-trusted-extensions.mjs",