Skip to content

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

fix(plugins): align workspace discovery with invoking sessions

鱼骨头TO89c2921083b3
diff --git a/apps/desktop/electron/main/plugin-runtime.ts b/apps/desktop/electron/main/plugin-runtime.ts
index da553c4fa..b55aad147 100644
--- a/apps/desktop/electron/main/plugin-runtime.ts
+++ b/apps/desktop/electron/main/plugin-runtime.ts
@@ -121,6 +121,7 @@ import {
import { desktopDataDir } from "./data-paths";
import { McpServerClient, type McpServerClientOptions } from "./plugin-mcp";
import { PluginToolInvocations, type PluginToolInvocation } from "./plugin-tool-invocations";
+import { pluginWorkspaceForCall, pluginWorkspacePath } from "./plugin-workspace-context";
import { McpCallRegistry } from "./mcp-call-registry";
import {
RendererCallRelay,
@@ -331,7 +332,7 @@ export type PluginHostServices = {
* The workspace plus the project group behind it, when the caller can supply
* it. Additive: `workspace.get` falls back to `getWorkspacePath` alone.
*/
- getWorkspaceInfo?: () => PluginWorkspaceInfo | null;
+ getWorkspaceInfo?: (workspacePath?: string | null) => PluginWorkspaceInfo | null;
/** Durable project metadata only; unavailable hosts resolve to an empty list. */
listProjects?: () => Promise<PluginProjectInfo[]>;
/**
@@ -5129,10 +5130,7 @@ export class PluginRuntime {
private fsRoot(loaded: LoadedPlugin, rule: PluginFsRule): string | null {
if (rule.root === "userSelected") return loaded.userRoot ?? null;
const sessionId = this.inFlightTool(loaded.manifest.id)?.sessionId.trim() || undefined;
- const scoped = sessionId
- ? (this.services.getWorkspacePathForSession?.(sessionId) ?? null)
- : null;
- return scoped ?? this.services.getWorkspacePath();
+ return pluginWorkspacePath(this.services, sessionId);
}
private remoteFsRead(loaded: LoadedPlugin, operation: "list" | "preview", ref: string, options?: PluginFsReadOptions) {
@@ -5299,7 +5297,7 @@ export class PluginRuntime {
if (!isAbsolute(String(requestPath ?? ""))) return null;
const rule: PluginFsRule = loaded.fsPolicy.read ?? { root: "workspace", scope: [] };
if (rule.root !== "workspace") return null;
- const roots = (this.services.getWorkspaceInfo?.()?.roots ?? [])
+ const roots = (pluginWorkspaceForCall(this.services, this.inFlightTool(loaded.manifest.id)?.sessionId.trim() || undefined)?.roots ?? [])
.map((entry) => entry?.path)
.filter((path): path is string => Boolean(path));
if (roots.length === 0) return null;
@@ -5779,14 +5777,7 @@ export class PluginRuntime {
},
workspace: {
get: async () => {
- // The enriched payload carries the project group behind the visible
- // workspace (ADR 0263); the path-only fallback keeps `get` working for
- // any caller whose services never bound the richer provider.
- const info = this.services.getWorkspaceInfo?.();
- if (info !== undefined) return info;
- const path = this.services.getWorkspacePath();
- if (!path) return null;
- return { path, name: path.split(/[\\/]/).filter(Boolean).at(-1) || path };
+ return pluginWorkspaceForCall(this.services, this.inFlightTool(pluginId)?.sessionId.trim() || undefined);
},
},
projects: {
diff --git a/apps/desktop/electron/main/plugin-workspace-context.ts b/apps/desktop/electron/main/plugin-workspace-context.ts
new file mode 100644
index 000000000..2d345c56c
--- /dev/null
+++ b/apps/desktop/electron/main/plugin-workspace-context.ts
@@ -0,0 +1,29 @@
+import type { PluginWorkspaceInfo } from "@pi-desktop/shared";
+
+export type PluginWorkspaceServices = {
+ getWorkspacePath: () => string | null;
+ getWorkspacePathForSession?: (sessionId: string) => string | null;
+ getWorkspaceInfo?: (workspacePath?: string | null) => PluginWorkspaceInfo | null;
+};
+
+/** The same host-owned project identity drives discovery and filesystem roots. */
+export function pluginWorkspacePath(services: PluginWorkspaceServices, sessionId?: string): string | null {
+ const scoped = sessionId ? services.getWorkspacePathForSession?.(sessionId) : null;
+ return scoped ?? services.getWorkspacePath();
+}
+
+const singleRoot = (path: string | null): PluginWorkspaceInfo | null => path
+ ? { path, name: path.split(/[\\/]/).filter(Boolean).at(-1) || path }
+ : null;
+
+export function pluginWorkspaceForCall(services: PluginWorkspaceServices, sessionId?: string): PluginWorkspaceInfo | null {
+ const scoped = sessionId ? services.getWorkspacePathForSession?.(sessionId) : null;
+ if (scoped != null) {
+ const info = services.getWorkspaceInfo?.(scoped);
+ // Older providers may ignore the path argument. Never project the visible
+ // project's group metadata onto a different background tool session.
+ return info?.path === scoped ? info : singleRoot(scoped);
+ }
+ const info = services.getWorkspaceInfo?.();
+ return info !== undefined ? info : singleRoot(services.getWorkspacePath());
+}
diff --git a/apps/desktop/electron/main/services/plugin-services.ts b/apps/desktop/electron/main/services/plugin-services.ts
index 5e78660eb..213917c63 100644
--- a/apps/desktop/electron/main/services/plugin-services.ts
+++ b/apps/desktop/electron/main/services/plugin-services.ts
@@ -732,7 +732,7 @@ export function createPluginServices({
* `workspace:changed` event both expose the open project's folder roots
* (ADR 0263) instead of the bare primary path.
*/
- getWorkspaceInfo: () => pluginWorkspaceInfo(getWorkspacePath()),
+ getWorkspaceInfo: (path = getWorkspacePath()) => pluginWorkspaceInfo(path),
listProjects: createPluginProjectLister(getHost, (operation) => {
logger.app("plugin", "warn", "plugin.projects.unavailable", {
code: "HOST_UNAVAILABLE", data: { operation },
diff --git a/apps/desktop/test/plugin-workspace-session.test.mjs b/apps/desktop/test/plugin-workspace-session.test.mjs
new file mode 100644
index 000000000..0397d023e
--- /dev/null
+++ b/apps/desktop/test/plugin-workspace-session.test.mjs
@@ -0,0 +1,97 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { fork } from "node:child_process";
+import { mkdtempSync, writeFileSync, rmSync, realpathSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { register } from "node:module";
+import { fileURLToPath } from "node:url";
+
+const data = mkdtempSync(join(tmpdir(), "pi-plugin-workspace-context-"));
+process.env.PI_DESKTOP_DATA_DIR = join(data, "data");
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+const { PluginRuntime } = await import("../electron/main/plugin-runtime.ts");
+const hostEntry = fileURLToPath(new URL("../electron/main/plugin-host-process.mjs", import.meta.url));
+
+async function fixture(t) {
+ const root = mkdtempSync(join(data, "fixture-"));
+ const { mkdirSync } = await import("node:fs");
+ const a = join(root, "alpha"), b = join(root, "beta"), c = join(root, "visible");
+ const sibling = join(root, "alpha-sibling"), revealed = [];
+ for (const [dir, marker] of [[a,"alpha"],[b,"beta"],[c,"visible"],[sibling,"own-sibling"]]) {
+ mkdirSync(dir); writeFileSync(join(dir,"marker.txt"), marker);
+ }
+ const plugin = join(root,"plugin"); mkdirSync(plugin);
+ const permissions = ["agent.tool.register", "fs.read"];
+ writeFileSync(join(plugin,"manifest.json"), JSON.stringify({ schemaVersion:1,
+ id:"test.workspace.context", name:"Context", version:"0.0.1", main:"main.cjs", permissions,
+ fs:{read:{root:"workspace",scope:["marker.txt"]}} }));
+ writeFileSync(join(plugin,"main.cjs"), `
+ async function inspect(args) { if (args?.reveal) await pi.fs.reveal(args.reveal); const workspace = await pi.workspace.get();
+ return { workspace, marker: workspace && !workspace.path.startsWith('remote-project:') ? await pi.fs.readText('marker.txt') : null }; }
+ module.exports = { onLoad: async () => pi.agent.registerTool({name:'inspect',description:'Inspect current project',schema:{type:'object'},execute:inspect}),
+ onPanelInvoke:inspect };
+ `);
+ let visible = c, info = path => path == null ? null : ({ path, name:path.split('/').at(-1),
+ projectId:path===a?'project-a':path===b?'project-b':'project-c',
+ roots:[{path,name:path.split('/').at(-1),primary:true},...(path===a?[{path:sibling,name:'Sibling',primary:false}]:[])] });
+ const sessions = new Map([['a',a],['b',b]]);
+ const runtime = new PluginRuntime({ hostEntry, getWorkspacePath:()=>visible,
+ getWorkspacePathForSession:id=>sessions.get(id) ?? null,
+ getWorkspaceInfo:(path=visible)=>info(path),
+ revealPath:async path=>{revealed.push(path);},
+ spawnProcess({entry}) { const child = fork(entry,[],{stdio:['ignore','pipe','pipe','ipc']});
+ return {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()}; },
+ });
+ t.after(async()=>{await runtime.unload('test.workspace.context');rmSync(root,{recursive:true,force:true});});
+ await runtime.loadFromPath(plugin,permissions);
+ const tool=runtime.getTools().find(tool=>tool.name==='inspect');assert.ok(tool);
+ return {a,b,c,sibling,revealed,sessions,runtime,tool,setVisible:path=>{visible=path;},setInfo:fn=>{info=fn;}};
+}
+
+test('workspace metadata and filesystem agree for concurrent background project sessions', async t=>{
+ const f=await fixture(t);
+ const [a,b]=await Promise.all([f.tool.execute({sessionId:'b'},{sessionId:'a'}),f.tool.execute({sessionId:'a'},{sessionId:'b'})]);
+ assert.equal(a.workspace.path,f.a);assert.equal(a.workspace.projectId,'project-a');assert.equal(a.marker,'alpha');
+ assert.equal(b.workspace.path,f.b);assert.equal(b.workspace.projectId,'project-b');assert.equal(b.marker,'beta');
+ assert.deepEqual(a.workspace.roots.map(root=>root.path),[f.a,f.sibling]);
+ assert.deepEqual(b.workspace.roots.map(root=>root.path),[f.b]);
+ f.setVisible(f.b);
+ const again=await f.tool.execute({},{sessionId:'a'});assert.equal(again.workspace.path,f.a);assert.equal(again.marker,'alpha');
+});
+
+test('a tracked background project remains discoverable without a visible project',async t=>{
+ const f=await fixture(t);f.setVisible(null);
+ const a=await f.tool.execute({},{sessionId:'a'});assert.equal(a.workspace.path,f.a);assert.equal(a.marker,'alpha');
+ assert.deepEqual(await f.runtime.invokePanelBridge('test.workspace.context','inspect'),{workspace:null,marker:null});
+});
+
+test('panel and unknown-session discovery preserve the visible workspace fallback',async t=>{
+ const f=await fixture(t);
+ for(const value of [await f.tool.execute({},{sessionId:'unknown'}),await f.runtime.invokePanelBridge('test.workspace.context','inspect')]){
+ assert.equal(value.workspace.path,f.c);assert.equal(value.workspace.projectId,'project-c');assert.equal(value.marker,'visible');
+ }
+});
+
+test('a legacy metadata provider cannot leak another project group into a tool workspace',async t=>{
+ const f=await fixture(t);f.setInfo(()=>({path:f.c,name:'Visible',projectId:'wrong',roots:[{path:f.c,name:'Visible',primary:true}]}));
+ const a=await f.tool.execute({},{sessionId:'a'});assert.deepEqual(a.workspace,{path:f.a,name:'alpha'});assert.equal(a.marker,'alpha');
+});
+
+test('remote session identity never becomes the visible local workspace',async t=>{
+ const f=await fixture(t);const remote='remote-project:remote-alpha';f.sessions.set('remote',remote);
+ f.setInfo(path=>path===remote?{path:remote,name:'Remote alpha',remote:{path:'/remote/alpha',readOnly:true}}:{path:f.c,name:'Visible'});
+ const value=await f.tool.execute({},{sessionId:'remote'});
+ assert.equal(value.workspace.path,remote);assert.equal(value.workspace.remote.path,'/remote/alpha');assert.equal(value.marker,null);
+});
+
+test('absolute reveal uses only the invoking project registered roots',async t=>{
+ const f=await fixture(t);
+ await f.tool.execute({reveal:join(f.sibling,'marker.txt')},{sessionId:'a'});
+ assert.deepEqual(f.revealed,[realpathSync(join(f.sibling,'marker.txt'))]);
+ await assert.rejects(f.tool.execute({reveal:join(f.c,'marker.txt')},{sessionId:'a'}));
+ assert.equal(f.revealed.length,1);
+});
+
+test.after(()=>rmSync(data,{recursive:true,force:true}));
diff --git a/docs/adr/0266-plugin-fs-root-follows-the-calling-session.md b/docs/adr/0266-plugin-fs-root-follows-the-calling-session.md
index 583924ad1..66f0f40e8 100644
--- a/docs/adr/0266-plugin-fs-root-follows-the-calling-session.md
+++ b/docs/adr/0266-plugin-fs-root-follows-the-calling-session.md
@@ -58,6 +58,27 @@ scope/consent -- were correct; only the directory they measured against was wron
with a session project they keep working per session. A panel call in that
state still fails closed, because it has nothing else to resolve.
+### Workspace metadata consistency amendment
+
+The initial implementation scoped ordinary file calls but left `workspace.get`
+and registered-folder action metadata tied to the visible project. A plugin
+could discover project B while its session-rooted file calls reached A, causing
+knowledge-library guards to reject otherwise valid saves. Absolute open/reveal
+actions could also select the visible project's registered roots.
+
+Discovery and registered-folder actions now use the same host-owned session
+mapping as `fsRoot`, through one internal resolver. The existing group snapshot
+is queried for that path; a legacy metadata provider answering a different path
+cannot attach its roots to the session. Panel and untracked-session fallbacks
+remain unchanged. `workspace:changed` remains a foreground event, while a
+background tool's pull describes its invoking session. No SDK shape, permission,
+process boundary, persistent state or migration is added.
+
+Plugins that enqueue callbacks must preserve the caller's async context for
+each job; executing every job in the queue pump's original context would retain
+the wrong invocation authority. Invocation IDs still expire on completion or
+cancellation and may not be dropped to recover through a foreground fallback.
+
## Consequences
- Two sessions on two projects no longer cross-talk: a plugin agent tool reads and
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 285429a01..dd779e880 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -18083,6 +18083,26 @@ command, a delegate, and an explicit Stop. Accepted input is delivered once.
project. The two-live-sessions desktop journey and the panel step are Draft
(run only in a capable environment when this surface changes)
+##### Workspace discovery consistency and project-isolated queues
+
+- Run `node --experimental-strip-types --test
+ apps/desktop/test/plugin-workspace-session.test.mjs` on Node 22, together with
+ the existing session-root, invocation, filesystem-scope and workspace-root
+ suites. The real plugin child process checks concurrent A/B workspace
+ discovery against actual marker reads, foreground switching, no visible
+ workspace, legacy provider mismatch, remote identity, and absolute reveal
+ limited to the caller's registered roots. Only the OS reveal boundary is stubbed.
+- A companion knowledge-plugin process test runs the real PluginRuntime, actual
+ plugin entry point, project queues and temporary files. Hold A's read at an
+ explicit RPC gate; B must save before A is released. A second caller in A
+ queues behind A and must retain its own invocation after the first finishes.
+ Switch or clear the visible project, reject an A invocation targeting B,
+ cancel A while B searches, and verify both original bodies and B's saved
+ revision. No live provider, installed user instance or `verify:ui:*` is used.
+- The full two-live-session shell journey remains separate; the child-process
+ tests establish the actual host/plugin/filesystem boundary without requiring
+ a foreground Electron app or changing permission semantics.
+
#### E2E-MODEL-catalog-window-correction-reaches-saved-bindings
- **Goal**: a models.dev limit correction — the context window or the output cap —
diff --git a/docs/spec/07-plugins/03-plugin-api.md b/docs/spec/07-plugins/03-plugin-api.md
index b04cdd64d..20e7656ce 100644
--- a/docs/spec/07-plugins/03-plugin-api.md
+++ b/docs/spec/07-plugins/03-plugin-api.md
@@ -409,15 +409,21 @@ This read-only metadata needs no permission and is also available through the
panel bridge channel `projects.list`. It never creates, opens, switches, or
grants access to a project. Filesystem and session permissions are unchanged.
-`workspace.get` answers with the primary root — `path` and its leaf `name`,
-both unchanged — plus, when that folder belongs to a project group (ADR 0249),
-`projectId` and `roots`: every registered folder of the group in its own order,
-primary first, each `{ path, name, primary }` (ADR 0263). `workspace:changed`
-carries the same object, and main answers both from the host-owned group
-records, so the event and the pull cannot disagree. A host that cannot resolve
-the group omits `projectId` and `roots` — the same `{ path, name }` a plugin
-already handles — and reading this metadata needs no new permission and adds no
-SDK method.
+`workspace.get` uses the same trusted tool-session project as workspace-rooted
+filesystem calls (ADR 0266). A background session therefore receives its own
+`path`, `name`, `projectId`, group `roots`, and remote metadata even when another
+project is visible or no project is selected. Tool arguments do not select a
+workspace or impersonate a session. Panel calls and untracked sessions retain
+the visible-workspace fallback; `workspace:changed` continues to describe that
+visible workspace, so a background tool's pull can intentionally differ from
+the foreground event.
+
+Group metadata is resolved from the host-owned group snapshot for the selected
+path. An older metadata provider that answers for a different path is discarded
+in favor of the session's `{ path, name }`, without copying another group's
+roots or remote identity. The existing return shape, SDK method, permissions,
+and storage schema do not change. Absolute `openDefault`, `openInBrowser`, and
+`reveal` requests use the same invoking project's registered roots.
`fs.readPreview` classifies one existing readable file for in-app display. It
uses the same `fs.read` checks as `fs.readText`, rejects directories, and