Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(scope): resolve durable session projects for desktop reads

koeria9903eb871cd2
diff --git a/apps/desktop/electron/main/plugin-runtime.ts b/apps/desktop/electron/main/plugin-runtime.ts
index f9c37917b..d2da02c27 100644
--- a/apps/desktop/electron/main/plugin-runtime.ts
+++ b/apps/desktop/electron/main/plugin-runtime.ts
@@ -341,6 +341,8 @@ export type PluginHostServices = {
* visible workspace -- for a panel call or an unknown session.
*/
getWorkspacePathForSession?: (sessionId: string) => string | null;
+ /** Authoritative durable session metadata for desktop-control scope checks. */
+ resolveSessionProjectPath?: (sessionId: string) => Promise<string | null>;
/**
* Whether a plugin's activation scope covers `projectPath` — the same
* project-aware check the UI surfaces apply (#2377). Optional so a headless
@@ -5038,24 +5040,24 @@ export class PluginRuntime {
/**
* #2377: refuse a targeted desktop.control session read whose target session
* belongs to a project the caller's activation scope excludes. Resolved from
- * the live session-project map when available; an unresolvable project is
- * allowed through, matching the workspace-relative fallback the event
- * fan-out uses. A no-op without a scope service (headless hosts, global
- * plugins always pass through `pluginActiveInProject` anyway).
+ * durable metadata rather than the live runtime map. Unknown metadata is
+ * checked as null so project-scoped callers fail closed. Hosts without a
+ * scope service retain their existing global behavior.
*/
- private assertDesktopSessionScope(
+ private async assertDesktopSessionScope(
pluginId: string,
operation: string,
args: readonly unknown[],
- ): void {
+ ): Promise<void> {
if (operation === SESSION_LIST_DESKTOP_OPERATION) return;
if (!SESSION_READ_DESKTOP_OPERATIONS.has(operation)) return;
const activeInProject = this.services.pluginActiveInProject;
if (!activeInProject) return;
const sessionId = desktopSessionTargetId(args);
if (!sessionId) return;
- const projectPath = this.services.getWorkspacePathForSession?.(sessionId);
- if (projectPath === undefined) return;
+ const projectPath = this.services.resolveSessionProjectPath
+ ? await this.services.resolveSessionProjectPath(sessionId)
+ : this.services.getWorkspacePathForSession?.(sessionId) ?? null;
if (activeInProject(pluginId, projectPath)) return;
this.services.audit?.({
pluginId,
@@ -5944,7 +5946,7 @@ export class PluginRuntime {
const operationInfo = this.services.desktopControl.operations.find(
(candidate) => candidate.id === operation,
);
- this.assertDesktopSessionScope(pluginId, operation, args);
+ await this.assertDesktopSessionScope(pluginId, operation, args);
// The controller's `confirm` flag is an acknowledgement by the
// caller, not a decision by the user. A plugin can set it at will,
// so a dangerous operation additionally needs the host's native
diff --git a/apps/desktop/electron/main/services/plugin-services.ts b/apps/desktop/electron/main/services/plugin-services.ts
index 5eef7caf7..90f632967 100644
--- a/apps/desktop/electron/main/services/plugin-services.ts
+++ b/apps/desktop/electron/main/services/plugin-services.ts
@@ -60,6 +60,7 @@ import type { TurnEndedPayload } from "../runtime/session-coordination";
import type { HostProcess } from "../host-process";
import { createPluginSessionContext } from "./plugin-session-context";
import { createPluginProjectLister } from "./plugin-projects";
+import { createPluginSessionProjectResolver } from "./plugin-session-project";
import { createComposerSuggestionRelay } from "./composer-suggestion";
import type { Logger } from "../logger";
import type { PluginAppearance } from "../../shared/plugin-panel-chrome";
@@ -748,6 +749,7 @@ export function createPluginServices({
* runtime has not launched yet, which falls back to the visible workspace.
*/
getWorkspacePathForSession: (sessionId) => sessionProjects.get(sessionId) ?? null,
+ resolveSessionProjectPath: createPluginSessionProjectResolver(getHost),
agentExtensionsChanged: () =>
sendToRenderer(IPC.event.pluginChanged, { reason: "agentExtensions" }),
/** `pi.session.getActive`: the selected session as the shell shows it. */
diff --git a/apps/desktop/electron/main/services/plugin-session-project.ts b/apps/desktop/electron/main/services/plugin-session-project.ts
new file mode 100644
index 000000000..f42f0028d
--- /dev/null
+++ b/apps/desktop/electron/main/services/plugin-session-project.ts
@@ -0,0 +1,26 @@
+import type { GroupHost } from "../workspace-roots";
+
+/** Resolve scope from durable metadata, including sessions with no live runtime. */
+export function createPluginSessionProjectResolver(
+ getHost: () => GroupHost | null,
+): (sessionId: string) => Promise<string | null> {
+ return async (sessionId) => {
+ const host = getHost();
+ if (!host?.isAvailable()) return null;
+ try {
+ const result = (await host.call(
+ "session.get",
+ { id: sessionId, messageLimit: 1 },
+ 5_000,
+ )) as {
+ session?: { projectPath?: string | null } | null;
+ } | null;
+ if (getHost() !== host || !host.isAvailable()) return null;
+ const path = result?.session?.projectPath;
+ return typeof path === "string" && path.trim() ? path : null;
+ } catch {
+ // Missing/invalid metadata and unavailable hosts never widen activation scope.
+ return null;
+ }
+ };
+}
diff --git a/apps/desktop/test/plugin-desktop-control.test.mjs b/apps/desktop/test/plugin-desktop-control.test.mjs
index c88b901c0..f9bc6309d 100644
--- a/apps/desktop/test/plugin-desktop-control.test.mjs
+++ b/apps/desktop/test/plugin-desktop-control.test.mjs
@@ -11,11 +11,15 @@ const here = dirname(fileURLToPath(import.meta.url));
const hostProcessEntry = join(here, "../electron/main/plugin-host-process.mjs");
register(pathToFileURL(join(here, "helpers/ts-import-hooks.mjs")));
const { PluginRuntime } = await import("../electron/main/plugin-runtime.ts");
+const { createPluginSessionProjectResolver } =
+ await import("../electron/main/services/plugin-session-project.ts");
function forkPluginProcess({ entry }) {
const child = fork(entry, [], { stdio: ["ignore", "pipe", "pipe", "ipc"] });
return {
- postMessage: (message) => { if (child.connected) child.send(message); },
+ postMessage: (message) => {
+ if (child.connected) child.send(message);
+ },
onMessage: (handler) => child.on("message", handler),
onExit: (handler) => child.on("exit", (code) => handler(code ?? 0)),
kill: () => child.kill(),
@@ -24,14 +28,18 @@ function forkPluginProcess({ entry }) {
function writePlugin(id, permissions, main) {
const dir = mkdtempSync(join(tmpdir(), "pi-desktop-control-plugin-"));
- writeFileSync(join(dir, "manifest.json"), JSON.stringify({
- schemaVersion: 1,
- id,
- name: id,
- version: "0.0.1",
- main: "main.js",
- permissions,
- }), "utf8");
+ writeFileSync(
+ join(dir, "manifest.json"),
+ JSON.stringify({
+ schemaVersion: 1,
+ id,
+ name: id,
+ version: "0.0.1",
+ main: "main.js",
+ permissions,
+ }),
+ "utf8",
+ );
writeFileSync(join(dir, "main.js"), main, "utf8");
return dir;
}
@@ -42,9 +50,24 @@ function createRuntime(t, calls, extraServices = {}) {
spawnProcess: forkPluginProcess,
desktopControl: {
operations: [
- { id: "project/set", channel: "projectSet", description: "Open a project", risk: "write" },
- { id: "session/create", channel: "sessionCreate", description: "Create a durable session", risk: "write" },
- { id: "session/delete", channel: "sessionDelete", description: "Delete a session", risk: "dangerous" },
+ {
+ id: "project/set",
+ channel: "projectSet",
+ description: "Open a project",
+ risk: "write",
+ },
+ {
+ id: "session/create",
+ channel: "sessionCreate",
+ description: "Create a durable session",
+ risk: "write",
+ },
+ {
+ id: "session/delete",
+ channel: "sessionDelete",
+ description: "Delete a session",
+ risk: "dangerous",
+ },
],
invoke: async (input) => {
calls.push(input);
@@ -54,7 +77,8 @@ function createRuntime(t, calls, extraServices = {}) {
...extraServices,
});
t.after(async () => {
- for (const loaded of runtime.listLoaded()) await runtime.unload(loaded.manifest.id);
+ for (const loaded of runtime.listLoaded())
+ await runtime.unload(loaded.manifest.id);
});
return runtime;
}
@@ -74,12 +98,24 @@ const DANGEROUS_PLUGIN = `
test("dangerous desktop operations are refused without a host consent service", async (t) => {
const calls = [];
const runtime = createRuntime(t, calls);
- const dir = writePlugin("demo.dangerous.headless", ["desktop.control"], DANGEROUS_PLUGIN);
+ const dir = writePlugin(
+ "demo.dangerous.headless",
+ ["desktop.control"],
+ DANGEROUS_PLUGIN,
+ );
await runtime.loadFromPath(dir, ["desktop.control"]);
- const result = await runtime.invokePanelBridge("demo.dangerous.headless", "desktop.test", {});
+ const result = await runtime.invokePanelBridge(
+ "demo.dangerous.headless",
+ "desktop.test",
+ {},
+ );
assert.equal(result.ok, false);
assert.equal(result.code, "PERMISSION_DENIED");
- assert.deepEqual(calls, [], "the controller must never see an unconfirmed dangerous call");
+ assert.deepEqual(
+ calls,
+ [],
+ "the controller must never see an unconfirmed dangerous call",
+ );
});
test("dangerous desktop operations need the user's native consent, not just confirm=true", async (t) => {
@@ -92,10 +128,18 @@ test("dangerous desktop operations need the user's native consent, not just conf
return answer;
},
});
- const dir = writePlugin("demo.dangerous", ["desktop.control"], DANGEROUS_PLUGIN);
+ const dir = writePlugin(
+ "demo.dangerous",
+ ["desktop.control"],
+ DANGEROUS_PLUGIN,
+ );
await runtime.loadFromPath(dir, ["desktop.control"]);
- const declined = await runtime.invokePanelBridge("demo.dangerous", "desktop.test", {});
+ const declined = await runtime.invokePanelBridge(
+ "demo.dangerous",
+ "desktop.test",
+ {},
+ );
assert.equal(declined.ok, false);
assert.equal(declined.code, "PERMISSION_DENIED");
assert.deepEqual(calls, []);
@@ -106,41 +150,87 @@ test("dangerous desktop operations need the user's native consent, not just conf
assert.deepEqual(prompts[0].args, ["s1"]);
answer = true;
- const granted = await runtime.invokePanelBridge("demo.dangerous", "desktop.test", {});
+ const granted = await runtime.invokePanelBridge(
+ "demo.dangerous",
+ "desktop.test",
+ {},
+ );
assert.equal(granted.ok, true, JSON.stringify(granted));
- assert.deepEqual(calls, [{ operation: "session/delete", args: ["s1"], confirm: true, source: "plugin", pluginContext: { pluginId: "demo.dangerous" } }]);
+ assert.deepEqual(calls, [
+ {
+ operation: "session/delete",
+ args: ["s1"],
+ confirm: true,
+ source: "plugin",
+ pluginContext: { pluginId: "demo.dangerous" },
+ },
+ ]);
// A plugin that does not even acknowledge the risk never reaches the user.
- const unacknowledged = await runtime.invokePanelBridge("demo.dangerous", "desktop.test", { confirm: false });
+ const unacknowledged = await runtime.invokePanelBridge(
+ "demo.dangerous",
+ "desktop.test",
+ { confirm: false },
+ );
assert.equal(unacknowledged.code, "CONFIRMATION_REQUIRED");
- assert.equal(prompts.length, 2, "no consent prompt for an unacknowledged call");
+ assert.equal(
+ prompts.length,
+ 2,
+ "no consent prompt for an unacknowledged call",
+ );
});
test("desktop control is permission-gated and uses the shared controller", async (t) => {
const calls = [];
const runtime = createRuntime(t, calls);
- const dir = writePlugin("demo.desktop", ["desktop.control"], `
+ const dir = writePlugin(
+ "demo.desktop",
+ ["desktop.control"],
+ `
module.exports = {
onPanelInvoke: async () => ({
operations: await pi.desktop.listOperations(),
result: await pi.desktop.invoke({ operation: "project/set", args: ["/tmp/project"] }),
}),
};
- `);
+ `,
+ );
await runtime.loadFromPath(dir, ["desktop.control"]);
- const result = await runtime.invokePanelBridge("demo.desktop", "desktop.test");
+ const result = await runtime.invokePanelBridge(
+ "demo.desktop",
+ "desktop.test",
+ );
assert.deepEqual(result.operations, [
{ id: "project/set", description: "Open a project", risk: "write" },
- { id: "session/create", description: "Create a durable session", risk: "write" },
- { id: "session/delete", description: "Delete a session", risk: "dangerous" },
+ {
+ id: "session/create",
+ description: "Create a durable session",
+ risk: "write",
+ },
+ {
+ id: "session/delete",
+ description: "Delete a session",
+ risk: "dangerous",
+ },
+ ]);
+ assert.deepEqual(calls, [
+ {
+ operation: "project/set",
+ args: ["/tmp/project"],
+ confirm: false,
+ source: "plugin",
+ pluginContext: { pluginId: "demo.desktop" },
+ },
]);
- assert.deepEqual(calls, [{ operation: "project/set", args: ["/tmp/project"], confirm: false, source: "plugin", pluginContext: { pluginId: "demo.desktop" } }]);
});
test("permission inheritance is bound to the current plugin tool session", async (t) => {
const calls = [];
const runtime = createRuntime(t, calls);
- const dir = writePlugin("demo.inheritance", ["agent.tool.register", "desktop.control"], `
+ const dir = writePlugin(
+ "demo.inheritance",
+ ["agent.tool.register", "desktop.control"],
+ `
module.exports = {
onLoad: async () => pi.agent.registerTool({
name: "create_worker",
@@ -153,9 +243,12 @@ test("permission inheritance is bound to the current plugin tool session", async
}),
}),
};
- `);
+ `,
+ );
await runtime.loadFromPath(dir, ["agent.tool.register", "desktop.control"]);
- const tool = runtime.getTools().find((entry) => entry.name === "create_worker");
+ const tool = runtime
+ .getTools()
+ .find((entry) => entry.name === "create_worker");
assert.ok(tool);
await assert.rejects(
@@ -173,7 +266,11 @@ test("permission inheritance is bound to the current plugin tool session", async
args: [{ inheritPermissionFromSessionId: "parent" }],
confirm: false,
source: "plugin",
- pluginContext: { pluginId: "demo.inheritance", sessionId: "parent", invocationId: calls[0].pluginContext.invocationId },
+ pluginContext: {
+ pluginId: "demo.inheritance",
+ sessionId: "parent",
+ invocationId: calls[0].pluginContext.invocationId,
+ },
signal: calls[0].signal,
},
]);
@@ -181,11 +278,15 @@ test("permission inheritance is bound to the current plugin tool session", async
test("desktop control fails closed without its permission", async (t) => {
const runtime = createRuntime(t, []);
- const dir = writePlugin("demo.denied", [], `
+ const dir = writePlugin(
+ "demo.denied",
+ [],
+ `
module.exports = {
onPanelInvoke: async () => pi.desktop.listOperations(),
};
- `);
+ `,
+ );
await runtime.loadFromPath(dir, []);
await assert.rejects(
() => runtime.invokePanelBridge("demo.denied", "desktop.test"),
@@ -198,7 +299,12 @@ test("project-scoped plugins get session/list filtered by activation scope", asy
const runtime = createRuntime(t, calls, {
desktopControl: {
operations: [
- { id: "session/list", channel: "sessionList", description: "List durable sessions", risk: "read" },
+ {
+ id: "session/list",
+ channel: "sessionList",
+ description: "List durable sessions",
+ risk: "read",
+ },
],
invoke: async (input) => {
calls.push(input);
@@ -211,16 +317,26 @@ test("project-scoped plugins get session/list filtered by activation scope", asy
};
},
},
- pluginActiveInProject: (pluginId, projectPath) => projectPath === "/workspace/allowed",
+ pluginActiveInProject: (pluginId, projectPath) =>
+ projectPath === "/workspace/allowed",
});
- const dir = writePlugin("demo.scoped.list", ["desktop.control"], `
+ const dir = writePlugin(
+ "demo.scoped.list",
+ ["desktop.control"],
+ `
module.exports = {
onPanelInvoke: async () => pi.desktop.invoke({ operation: "session/list", args: [] }),
};
- `);
+ `,
+ );
await runtime.loadFromPath(dir, ["desktop.control"]);
- const result = await runtime.invokePanelBridge("demo.scoped.list", "desktop.test");
- assert.deepEqual(result.sessions, [{ id: "in-scope", projectPath: "/workspace/allowed" }]);
+ const result = await runtime.invokePanelBridge(
+ "demo.scoped.list",
+ "desktop.test",
+ );
+ assert.deepEqual(result.sessions, [
+ { id: "in-scope", projectPath: "/workspace/allowed" },
+ ]);
});
test("project-scoped plugins cannot read an out-of-scope session via desktop.control", async (t) => {
@@ -228,17 +344,27 @@ test("project-scoped plugins cannot read an out-of-scope session via desktop.con
const runtime = createRuntime(t, calls, {
desktopControl: {
operations: [
- { id: "session/get", channel: "sessionGet", description: "Read a session", risk: "read" },
+ {
+ id: "session/get",
+ channel: "sessionGet",
+ description: "Read a session",
+ risk: "read",
+ },
],
invoke: async (input) => {
calls.push(input);
return { session: { id: "secret", projectPath: "/workspace/other" } };
},
},
- pluginActiveInProject: (pluginId, projectPath) => projectPath !== "/workspace/other",
- getWorkspacePathForSession: (sessionId) => sessionId === "secret" ? "/workspace/other" : null,
+ pluginActiveInProject: (pluginId, projectPath) =>
+ projectPath !== "/workspace/other",
+ getWorkspacePathForSession: (sessionId) =>
+ sessionId === "secret" ? "/workspace/other" : null,
});
- const dir = writePlugin("demo.scoped.get", ["desktop.control"], `
+ const dir = writePlugin(
+ "demo.scoped.get",
+ ["desktop.control"],
+ `
module.exports = {
onPanelInvoke: async () => {
try {
@@ -251,12 +377,108 @@ test("project-scoped plugins cannot read an out-of-scope session via desktop.con
}
},
};
- `);
+ `,
+ );
await runtime.loadFromPath(dir, ["desktop.control"]);
- const result = await runtime.invokePanelBridge("demo.scoped.get", "desktop.test");
+ const result = await runtime.invokePanelBridge(
+ "demo.scoped.get",
+ "desktop.test",
+ );
assert.equal(result.ok, false);
assert.equal(result.code, "PERMISSION_DENIED");
- assert.deepEqual(calls, [], "an out-of-scope targeted read never reaches the controller");
+ assert.deepEqual(
+ calls,
+ [],
+ "an out-of-scope targeted read never reaches the controller",
+ );
+});
+
+test("cold durable sessions keep list to get and revisions scope parity", async (t) => {
+ const sessions = [
+ { id: "cold-allowed", projectPath: "/workspace/allowed" },
+ { id: "cold-other", projectPath: "/workspace/other" },
+ { id: "unknown" },
+ ];
+ const calls = [];
+ const metadataReads = [];
+ const host = {
+ isAvailable: () => true,
+ call: async (method, input) => {
+ assert.equal(method, "session.get");
+ metadataReads.push(input.id);
+ return { session: sessions.find((s) => s.id === input.id) ?? null };
+ },
+ };
+ const runtime = createRuntime(t, calls, {
+ getWorkspacePathForSession: () => null,
+ resolveSessionProjectPath: createPluginSessionProjectResolver(() => host),
+ pluginActiveInProject: (_, path) => path === "/workspace/allowed",
+ desktopControl: {
+ operations: ["session/list", "session/get", "session/listRevisions"].map(
+ (id) => ({
+ id,
+ channel: id,
+ description: id,
+ risk: "read",
+ }),
+ ),
+ invoke: async (input) => {
+ calls.push(input);
+ if (input.operation === "session/list") return { sessions };
+ if (input.operation === "session/listRevisions")
+ return { revisions: ["r1"] };
+ return {
+ session: sessions.find((s) => s.id === input.args[0].sessionId),
+ };
+ },
+ },
+ });
+ const id = "demo.scoped.cold";
+ const dir = writePlugin(
+ id,
+ ["desktop.control"],
+ `
+ module.exports = { onPanelInvoke: async (_, input) => {
+ try { return { ok: true, result: await pi.desktop.invoke(input) }; }
+ catch (error) { return { ok: false, code: error.code }; }
+ } };
+ `,
+ );
+ await runtime.loadFromPath(dir, ["desktop.control"]);
+ const invoke = (operation, args = []) =>
+ runtime.invokePanelBridge(id, "desktop.test", { operation, args });
+ const listed = await invoke("session/list");
+ assert.deepEqual(listed.result.sessions, [sessions[0]]);
+ for (const session of listed.result.sessions) {
+ assert.deepEqual(
+ (await invoke("session/get", [{ sessionId: session.id }])).result.session,
+ session,
+ );
+ assert.deepEqual(
+ (await invoke("session/listRevisions", [{ sessionId: session.id }]))
+ .result.revisions,
+ ["r1"],
+ );
+ }
+ for (const target of ["cold-other", "unknown", "missing"]) {
+ for (const operation of ["session/get", "session/listRevisions"]) {
+ assert.deepEqual(await invoke(operation, [{ sessionId: target }]), {
+ ok: false,
+ code: "PERMISSION_DENIED",
+ });
+ }
+ }
+ assert.equal(calls.length, 3, "denied targets never reach the controller");
+ assert.deepEqual(metadataReads, [
+ "cold-allowed",
+ "cold-allowed",
+ "cold-other",
+ "cold-other",
+ "unknown",
+ "unknown",
+ "missing",
+ "missing",
+ ]);
});
test("an unscoped plugin keeps full desktop.control session reads", async (t) => {
@@ -264,7 +486,12 @@ test("an unscoped plugin keeps full desktop.control session reads", async (t) =>
const runtime = createRuntime(t, calls, {
desktopControl: {
operations: [
- { id: "session/list", channel: "sessionList", description: "List durable sessions", risk: "read" },
+ {
+ id: "session/list",
+ channel: "sessionList",
+ description: "List durable sessions",
+ risk: "read",
+ },
],
invoke: async (input) => {
calls.push(input);
@@ -273,12 +500,19 @@ test("an unscoped plugin keeps full desktop.control session reads", async (t) =>
},
pluginActiveInProject: () => true,
});
- const dir = writePlugin("demo.global.list", ["desktop.control"], `
+ const dir = writePlugin(
+ "demo.global.list",
+ ["desktop.control"],
+ `
module.exports = {
onPanelInvoke: async () => pi.desktop.invoke({ operation: "session/list", args: [] }),
};
- `);
+ `,
+ );
await runtime.loadFromPath(dir, ["desktop.control"]);
- const result = await runtime.invokePanelBridge("demo.global.list", "desktop.test");
+ const result = await runtime.invokePanelBridge(
+ "demo.global.list",
+ "desktop.test",
+ );
assert.deepEqual(result.sessions, [{ id: "any", projectPath: "/anywhere" }]);
});