Skip to content

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

fix(plugins): use session scratch path for scaffolding

koeria3bbf76f24938
diff --git a/apps/desktop/electron/main/runtime/sidecar.ts b/apps/desktop/electron/main/runtime/sidecar.ts
index f6a40058f..c3aa983e2 100644
--- a/apps/desktop/electron/main/runtime/sidecar.ts
+++ b/apps/desktop/electron/main/runtime/sidecar.ts
@@ -374,7 +374,7 @@ export function createSidecarRuntime({
const s = new AgentSidecar((text) => logger.child("agent", text));
wireSidecar(s);
// The directory a session's file tools work in: its isolated worktree
- // (ADR 0329), resolved by host-core from its own registry, or its project.
+ // (ADR 0329), project, or host-owned scratch directory (ADR 0124).
const sessionFileRoot = async (sessionId: string): Promise<string | null> => {
const host = runtimeState.host;
if (!host) return null;
@@ -385,7 +385,11 @@ export function createSidecarRuntime({
const location = await host.call<{ path?: string }>("worktree.location", { sessionId });
return location.path?.trim() || null;
}
- return res?.session?.projectPath?.trim() || null;
+ if (!res?.session) return null;
+ const projectPath = res.session.projectPath?.trim();
+ if (projectPath) return projectPath;
+ const scratch = await host.call<{ path: string }>("session.getScratchPath", { sessionId });
+ return scratch.path?.trim() || null;
};
s.setProjectInstructionResolver(async ({ sessionId, projectPath, path }) => {
// The root is registered by Electron main from the host-owned session
@@ -685,13 +689,7 @@ export function createSidecarRuntime({
// Plugin authoring (D171): scaffold, validate and package a plugin without
// leaving the session. Paths stay inside the open workspace.
registerPluginDevTools(s, {
- resolveWorkspace: async (sessionId) => {
- try {
- return await sessionFileRoot(sessionId);
- } catch {
- return null;
- }
- },
+ resolveWorkspace: sessionFileRoot,
registerDevPlugin: async (path) => {
if (!runtimeState.host) throw new Error("host unavailable");
const loaded = await runtimeState.host.call<{ plugin?: { permissions?: string[] } }>(
diff --git a/apps/desktop/test/plugin-dev-workspace.test.mjs b/apps/desktop/test/plugin-dev-workspace.test.mjs
new file mode 100644
index 000000000..a7d2ee3fb
--- /dev/null
+++ b/apps/desktop/test/plugin-dev-workspace.test.mjs
@@ -0,0 +1,178 @@
+import assert from "node:assert/strict";
+import { mkdtemp, readFile, rm } from "node:fs/promises";
+import { readFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { createRequire } from "node:module";
+import test from "node:test";
+import ts from "typescript";
+import * as devkit from "@pi-desktop/plugin-devkit";
+
+const require = createRequire(import.meta.url);
+const compile = (source) => ts.transpileModule(source, {
+ compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS, esModuleInterop: true },
+}).outputText;
+
+function loadModule(url, dependencies = {}) {
+ const module = { exports: {} };
+ new Function("require", "exports", "module", compile(readFileSync(url, "utf8")))(
+ (id) => dependencies[id] ?? require(id), module.exports, module,
+ );
+ return module.exports;
+}
+
+const { resolveWithinRoot } = loadModule(
+ new URL("../../../packages/host-runtime/src/workspace-files.ts", import.meta.url),
+);
+const { registerPluginDevTools } = loadModule(
+ new URL("../electron/main/plugin-dev-tools.ts", import.meta.url),
+ { "@pi-desktop/plugin-devkit": devkit, "@pi-desktop/host-runtime": { resolveWithinRoot } },
+);
+
+// Execute the production root resolver and its real DI wiring, not a copy of
+// their behavior. Only Host RPC and the Electron plugin loader are external edges.
+const source = readFileSync(new URL("../electron/main/runtime/sidecar.ts", import.meta.url), "utf8");
+const tree = ts.createSourceFile("sidecar.ts", source, ts.ScriptTarget.Latest, true);
+let rootDeclaration;
+let registration;
+function visit(node) {
+ if (ts.isVariableDeclaration(node) && node.name.getText(tree) === "sessionFileRoot") {
+ rootDeclaration = node.getText(tree);
+ }
+ if (ts.isCallExpression(node) && node.expression.getText(tree) === "registerPluginDevTools") {
+ registration = node.getText(tree);
+ }
+ ts.forEachChild(node, visit);
+}
+visit(tree);
+assert.ok(rootDeclaration && registration, "production plugin workspace wiring must exist");
+
+function toolsFor(host) {
+ const tools = new Map();
+ const loaded = [];
+ new Function("runtimeState", "s", "registerPluginDevTools", "plugins", "sendToRenderer", "IPC",
+ compile(`const ${rootDeclaration}; ${registration};`),
+ )(
+ { host }, { setLocalTool: (name, handler) => tools.set(name, handler) }, registerPluginDevTools,
+ {
+ loadFromPath: async (path) => { loaded.push(path); return { id: "test.plugin" }; },
+ watchDevPlugin: () => {}, drainToasts: () => [],
+ }, () => {}, { event: { pluginChanged: "pluginChanged" } },
+ );
+ return { tools, loaded };
+}
+
+function hostFor(sessions, scratchRoot) {
+ const calls = [];
+ return {
+ calls,
+ async call(method, input) {
+ calls.push({ method, input });
+ if (method === "session.get") return { session: sessions[input.id] ?? null };
+ if (method === "session.getScratchPath") return { path: join(scratchRoot, input.sessionId) };
+ if (method === "worktree.location") return { path: sessions[input.sessionId].worktreePath };
+ if (method === "plugins.loadDev") return { plugin: { permissions: [] } };
+ throw new Error(`Unexpected RPC: ${method}`);
+ },
+ };
+}
+
+const invoke = (tools, name, sessionId, directory = "word-to-pdf") => tools.get(name)({
+ sessionId, args: { directory, template: "panel-basic" },
+});
+
+test("temporary session scaffolds, checks and packs in its own host-owned scratch directory", async () => {
+ const scratch = await mkdtemp(join(tmpdir(), "plugin-workspace-"));
+ try {
+ const host = hostFor({ temporary: {} }, scratch);
+ const { tools, loaded } = toolsFor(host);
+ const created = await invoke(tools, "PluginScaffold", "temporary");
+ assert.equal(created.ok, true, created.content);
+ const target = join(scratch, "temporary", "word-to-pdf");
+ assert.ok(JSON.parse(await readFile(join(target, "manifest.json"), "utf8")).id);
+ assert.deepEqual(loaded, [target]);
+ assert.equal((await invoke(tools, "PluginCheck", "temporary")).ok, true);
+ assert.equal((await invoke(tools, "PluginPack", "temporary")).ok, true);
+ assert.ok(host.calls.some(({ method, input }) =>
+ method === "session.getScratchPath" && input.sessionId === "temporary"));
+ } finally {
+ await rm(scratch, { recursive: true, force: true });
+ }
+});
+
+for (const kind of ["project", "worktree"]) {
+ test(`${kind} sessions retain their authoritative root without requesting scratch`, async () => {
+ const root = await mkdtemp(join(tmpdir(), "plugin-project-"));
+ try {
+ const session = kind === "worktree"
+ ? { projectPath: join(root, "project"), worktree: {}, worktreePath: join(root, "worktree") }
+ : { projectPath: ` ${root} ` };
+ const host = hostFor({ bound: session }, join(root, "scratch"));
+ const { tools, loaded } = toolsFor(host);
+ const result = await invoke(tools, "PluginScaffold", "bound");
+ assert.equal(result.ok, true, result.content);
+ assert.deepEqual(loaded, [join(kind === "worktree" ? session.worktreePath : root, "word-to-pdf")]);
+ assert.ok(!host.calls.some(({ method }) => method === "session.getScratchPath"));
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+ });
+}
+
+for (const name of ["PluginScaffold", "PluginCheck", "PluginPack"]) {
+ test(`${name} rejects traversal outside the calling session scratch root`, async () => {
+ const host = hostFor({ first: {}, second: {} }, tmpdir());
+ const { tools, loaded } = toolsFor(host);
+ const result = await invoke(tools, name, "first", "../second/plugin");
+ assert.equal(result.ok, false);
+ assert.match(result.content, /outside the workspace/);
+ assert.deepEqual(loaded, []);
+ assert.ok(!host.calls.some(({ method }) => method === "plugins.loadDev"));
+ });
+}
+
+test("different temporary sessions resolve independently rather than using a visible project", async () => {
+ const scratch = await mkdtemp(join(tmpdir(), "plugin-isolation-"));
+ try {
+ const host = hostFor({ first: {}, second: { projectPath: " " } }, scratch);
+ const { tools, loaded } = toolsFor(host);
+ for (const id of ["first", "second"]) {
+ const result = await invoke(tools, "PluginScaffold", id);
+ assert.equal(result.ok, true, result.content);
+ }
+ assert.deepEqual(loaded, ["first", "second"].map((id) => resolve(scratch, id, "word-to-pdf")));
+ } finally {
+ await rm(scratch, { recursive: true, force: true });
+ }
+});
+
+for (const host of [null, hostFor({}, tmpdir())]) {
+ test(`missing ${host ? "session" : "host"} fails closed without allocating scratch`, async () => {
+ const { tools } = toolsFor(host);
+ const result = await invoke(tools, "PluginScaffold", "missing");
+ assert.equal(result.ok, false);
+ assert.match(result.content, /no workspace is open/);
+ assert.ok(!host?.calls.some(({ method }) => method === "session.getScratchPath"));
+ });
+}
+
+test("an unresolved isolated worktree does not fall back to a project or scratch", async () => {
+ const host = hostFor({ isolated: { worktree: {}, projectPath: "/must-not-use" } }, tmpdir());
+ const { tools } = toolsFor(host);
+ const result = await invoke(tools, "PluginScaffold", "isolated");
+ assert.equal(result.ok, false);
+ assert.ok(!host.calls.some(({ method }) => method === "session.getScratchPath"));
+});
+
+for (const method of ["session.get", "session.getScratchPath", "worktree.location"]) {
+ test(`${method} errors remain observable instead of becoming no-workspace errors`, async () => {
+ const host = hostFor({ temporary: method === "worktree.location" ? { worktree: {} } : {} }, tmpdir());
+ const call = host.call.bind(host);
+ host.call = async (name, input) => {
+ if (name === method) throw new Error(`RPC failed: ${method}`);
+ return call(name, input);
+ };
+ const { tools } = toolsFor(host);
+ await assert.rejects(invoke(tools, "PluginScaffold", "temporary"), { message: `RPC failed: ${method}` });
+ });
+}
diff --git a/docs/spec/06-delivery/e2e/plugins-and-extensions.md b/docs/spec/06-delivery/e2e/plugins-and-extensions.md
index b9e64928d..9d30bad01 100644
--- a/docs/spec/06-delivery/e2e/plugins-and-extensions.md
+++ b/docs/spec/06-delivery/e2e/plugins-and-extensions.md
@@ -3946,6 +3946,22 @@ same-name definitions with different IDs do not prevent saving to A. A real
duplicate name or ID in A still blocks creation; a real duplicate name blocks
editing. Cover both creating and editing before changing the page selection.
+## E2E-ISSUE-2399
+
+In an unbound Agent conversation, call `PluginScaffold` with `panel-basic` and
+`word-to-pdf`, then `PluginCheck` and `PluginPack` on that directory. Files and the
+package must stay under that session's host-owned scratch root, and development
+registration/loading must receive that same plugin path. A second temporary
+session must not share the first session's directory. Project/worktree sessions
+must retain their own root; missing sessions and escaping paths must fail closed.
+Host lookup failures must remain observable. Scratch sources retain the existing
+temporary cleanup lifecycle, not a persistent project guarantee.
+
+Offline coverage: `node --test apps/desktop/test/plugin-dev-workspace.test.mjs`
+executes the production resolver, DI wiring, tool handlers and devkit filesystem
+operations. Host RPC and Electron plugin loading are boundary fixtures; rendered
+Electron and real-host lifecycle verification remain manual/CI coverage.
+
## E2E-ISSUE-2184
Load the actual bundled plugin in an isolated workspace. Create a file and Unicode directory, rename and move the file; verify disk entries and response metadata. Invalid create/rename names fail before writing, and duplicate destinations are refused. Coverage: apps/desktop/test/file-manager-mutations.test.mjs. Existing Electron directory-location path also passes.
diff --git a/docs/spec/07-plugins/10-plugin-devex.md b/docs/spec/07-plugins/10-plugin-devex.md
index 0bdadab98..e06204aee 100644
--- a/docs/spec/07-plugins/10-plugin-devex.md
+++ b/docs/spec/07-plugins/10-plugin-devex.md
@@ -28,7 +28,12 @@ The first step has three entry points, all calling the same
the file panel read. If the folder cannot be opened as a project the plugin
still stays loaded, and the toast says only that it was created and loaded.
- **Agent** — `PluginScaffold`, in a conversation ("write me a plugin that …").
- It writes inside the current workspace, which is already open.
+ It writes inside the calling session's worktree or project, or its host-owned
+ scratch directory for a temporary conversation. It never inherits the visible
+ project's directory. Scratch plugins use the same development registration and
+ loading flow, but their sources remain temporary: session deletion or the
+ scratch cleanup policy can remove them. Copy sources to a persistent project
+ before relying on development reload across cleanup.
- **CLI** — `pnpm pi-plugin init <template> <dir>`.
## 3. Template types
@@ -133,7 +138,9 @@ must never be built with `zip` or another shell tool.
Three tools are served from Electron main (host-core never sees them), each
resolving its `directory` argument against the session's workspace root and
-refusing to escape it:
+refusing to escape it. A persisted temporary session uses `session.getScratchPath`;
+missing sessions fail closed, and Host RPC failures remain errors rather than
+being reported as an absent workspace:
| Tool | Modes | Effect |
|---|---|---|