Skip to content

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

fix: 修复 native Pi 会话文件访问来源路由

geng yuea5e3b3626cf1
diff --git a/apps/desktop/electron/main/ipc/workspace-ipc.ts b/apps/desktop/electron/main/ipc/workspace-ipc.ts
index af0888438..fb2bd6cab 100644
--- a/apps/desktop/electron/main/ipc/workspace-ipc.ts
+++ b/apps/desktop/electron/main/ipc/workspace-ipc.ts
@@ -21,7 +21,7 @@ import {
loadComposerTemplates,
type ComposerTemplate,
} from "@pi-desktop/agent-runtime";
-import { remoteWorkspaceForFiles } from "../remote/workspace-file-scope";
+import { remoteWorkspaceForFiles, sessionForFiles } from "../remote/workspace-file-scope";
import { getActiveRemoteHostsBoot } from "../bootstrap/remote-hosts";
import { cloneGitRepository } from "../git-clone";
import {
@@ -676,7 +676,7 @@ handleWithEvent(
},
);
- const remoteFileWorkspace = (sessionId?: string) => remoteWorkspaceForFiles(getHost, sessionId);
+ const remoteFileWorkspace = (sessionId?: string) => remoteWorkspaceForFiles(getHost, sessionId, getSidecar);
const readRemoteFiles = (remote: RemoteWorkspace, operation: WorkspaceFilesRequest["operation"], ref?: string, mimeType?: string) => {
const boot = getActiveRemoteHostsBoot();
if (!boot) throw new Error("remote hosts unavailable");
@@ -830,9 +830,7 @@ handleWithEvent(
let worktree: string | undefined;
let parent: string | undefined;
if (sessionId) {
- const { session } = await owner.call<{ session?: { projectPath?: string; worktree?: unknown } }>(
- "session.get", { id: sessionId, messageLimit: 1 },
- );
+ const session = await sessionForFiles(getHost, sessionId, getSidecar);
const projectPath = session?.projectPath?.trim();
if (session?.worktree) {
// Chat references and source reads must see the same files as the
@@ -918,7 +916,7 @@ handleWithEvent(
sessionId: string | undefined,
): Promise<string | null> => {
const id = String(sessionId ?? "").trim();
- if (!id || !host) return null;
+ if (!id || id.startsWith("native-pi:") || !host) return null;
try {
const result = await host.call<{ path: string }>("session.getScratchPath", {
sessionId: id,
diff --git a/apps/desktop/electron/main/remote/workspace-file-scope.ts b/apps/desktop/electron/main/remote/workspace-file-scope.ts
index d3b96a058..435755808 100644
--- a/apps/desktop/electron/main/remote/workspace-file-scope.ts
+++ b/apps/desktop/electron/main/remote/workspace-file-scope.ts
@@ -2,14 +2,30 @@ import type { ProjectGroupRecord, RemoteWorkspace } from "@pi-desktop/shared";
type FileHost = { call<T>(method: string, input?: unknown): Promise<T> };
+export async function sessionForFiles(
+ getHost: () => FileHost | null,
+ sessionId: string,
+ getSidecar?: () => FileHost | null,
+): Promise<{ projectPath?: string; worktree?: unknown }> {
+ const native = sessionId.startsWith("native-pi:");
+ const getOwner = native ? getSidecar : getHost;
+ const owner = getOwner?.();
+ if (!owner) throw Object.assign(new Error("session source unavailable"), { errorCode: "HOST_UNAVAILABLE" });
+ const { session } = await owner.call<{ session?: { projectPath?: string; worktree?: unknown } }>(
+ native ? "native.session.get" : "session.get", { id: sessionId, messageLimit: 1 },
+ );
+ if (getOwner?.() !== owner) throw Object.assign(new Error("session source replaced"), { errorCode: "HOST_UNAVAILABLE" });
+ if (!session) throw Object.assign(new Error("session not found"), { errorCode: "NOT_FOUND" });
+ return session;
+}
+
/** Retained file views authorize against their own durable session, not the selected project. */
-export async function remoteWorkspaceForFiles(getHost: () => FileHost | null, sessionId?: string): Promise<RemoteWorkspace | null> {
+export async function remoteWorkspaceForFiles(getHost: () => FileHost | null, sessionId?: string, getSidecar?: () => FileHost | null): Promise<RemoteWorkspace | null> {
const owner = getHost();
if (!owner) throw new Error("host unavailable");
let path: string | undefined;
if (sessionId) {
- const { session } = await owner.call<{ session?: { projectPath?: string } }>("session.get", { id: sessionId, messageLimit: 1 });
- if (!session) throw Object.assign(new Error("session not found"), { errorCode: "NOT_FOUND" });
+ const session = await sessionForFiles(getHost, sessionId, getSidecar);
path = session.projectPath;
} else {
const { workspace } = await owner.call<{ workspace?: { path: string } }>("workspace.get");
diff --git a/apps/desktop/test/native-workspace-files.test.mjs b/apps/desktop/test/native-workspace-files.test.mjs
new file mode 100644
index 000000000..b173dc779
--- /dev/null
+++ b/apps/desktop/test/native-workspace-files.test.mjs
@@ -0,0 +1,31 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { register } from "node:module";
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+const { remoteWorkspaceForFiles } = await import("../electron/main/remote/workspace-file-scope.ts");
+
+test("native file views resolve the sidecar session instead of the selected Desktop workspace", async () => {
+ const host = { call: () => assert.fail("native identity reached Desktop storage") };
+ const sidecar = { async call(method, input) {
+ assert.equal(method, "native.session.get");
+ assert.equal(input.id, "native-pi:fixture");
+ return { session: { projectPath: "C:/fixture/native-project", source: "pi-native" } };
+ } };
+ assert.equal(await remoteWorkspaceForFiles(() => host, "native-pi:fixture", () => sidecar), null);
+});
+
+test("unavailable native sources fail closed without Desktop workspace fallback", async () => {
+ const host = { call: () => assert.fail("native identity reached Desktop storage") };
+ await assert.rejects(remoteWorkspaceForFiles(() => host, "native-pi:missing", () => null), { errorCode: "HOST_UNAVAILABLE" });
+ const sidecar = { call: async () => ({ session: null }) };
+ await assert.rejects(remoteWorkspaceForFiles(() => host, "native-pi:missing", () => sidecar), { errorCode: "NOT_FOUND" });
+});
+
+test("a replaced sidecar cannot publish a stale native file root", async () => {
+ let finish;
+ let sidecar = { call: () => new Promise(resolve => { finish = resolve; }) };
+ const pending = remoteWorkspaceForFiles(() => ({ call() {} }), "native-pi:fixture", () => sidecar);
+ sidecar = null;
+ finish({ session: { projectPath: "C:/fixture" } });
+ await assert.rejects(pending, { errorCode: "HOST_UNAVAILABLE" });
+});
diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.md
index 184989401..1ab21f082 100644
--- a/docs/spec/04-ux/08-component-spec.md
+++ b/docs/spec/04-ux/08-component-spec.md
@@ -4767,3 +4767,7 @@ While a checkpoint estimate supplies context occupancy, use its recorded provide
### File Manager mutation validation (#2184)
The bundled File Manager validates each create/rename name before filesystem writes. Valid names return canonical entry metadata after create, rename or move. Empty names, dot segments, separators, control characters, Windows-reserved names and trailing dots fail with INVALID_NAME. Existing destinations fail with EXISTS; containment and protected-path gates remain enforced.
+
+### Native Pi file references (#1853)
+
+User-initiated file reads, directory listings, reference resolution and file search use the native session's sidecar-projected project path. Native identities never query Desktop session storage or fall back to the selected workspace. Missing/replaced sources fail closed. Existing local file containment and explicit external-file rules still apply; this grants no model tools or attachments. Native sessions have no Desktop scratch directory.
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 6b73f1bfb..acdd43410 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -20416,3 +20416,9 @@ Use synthetic Darwin x64/arm64 uname responses through production SSH bootstrap,
#### 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.
+
+### E2E-NATIVE-workspace-file-routing
+
+Run
+ode scripts/e2e-native-workspace-files.mjs: isolated Electron Main, production workspace IPC, synthetic sidecar session metadata and real fixture files. Select an unrelated Desktop workspace; list, read and resolve a native file, then reject a missing native session. The test asserts no native session or scratch RPC reaches Desktop storage.
+ative-workspace-files.test.mjs additionally rejects replaced sidecars. No provider execution or native user session data is used.
diff --git a/docs/zh-CN/spec/04-ux/08-component-spec.md b/docs/zh-CN/spec/04-ux/08-component-spec.md
index 07b6adced..564b4425c 100644
--- a/docs/zh-CN/spec/04-ux/08-component-spec.md
+++ b/docs/zh-CN/spec/04-ux/08-component-spec.md
@@ -3115,3 +3115,7 @@ default nor provider configuration. OAuth accounts remain in their separate sect
### 文件管理器名称校验(#2184)
新建和重命名前校验名称,创建、重命名和移动后返回正确条目信息。空名称、点路径、分隔符、控制字符、Windows 保留名及尾点返回 INVALID_NAME;已有目标返回 EXISTS。路径边界和受保护路径检查保持生效。
+
+### Native Pi 文件引用(#1853)
+
+用户发起的文件读取、目录列表、引用解析和文件搜索使用 sidecar 投影的 native 会话项目路径。Native 身份不查询 Desktop 会话存储,也不回退到当前选中的工作区。来源丢失或更换时拒绝请求。现有本地文件范围和显式外部文件规则继续生效,不增加模型工具或附件权限。Native 会话没有 Desktop scratch 目录。
diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
index d5ea19d98..ebb186d04 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
@@ -10435,3 +10435,9 @@ MCP All 在创建、导入、安装时使用所选项目,无项目才回退全
#### E2E-ISSUE-2184
隔离项目加载真实内置插件,创建文件和中文目录,重命名并移动文件,核查磁盘与返回元数据;非法名称及重复目标拒绝。覆盖 file-manager-mutations.test.mjs 和原有 Electron 目录定位路径。
+
+### E2E-NATIVE-workspace-file-routing
+
+运行
+ode scripts/e2e-native-workspace-files.mjs:使用隔离 Electron Main、生产 workspace IPC、合成 sidecar 会话元数据和真实测试文件。选中无关的 Desktop 工作区后,列出、读取和解析 native 文件,再拒绝不存在的 native 会话。断言 native 会话及 scratch 请求不会进入 Desktop 存储。
+ative-workspace-files.test.mjs 另验证 sidecar 更换后拒绝旧响应。不执行模型或访问用户 native 会话。
diff --git a/scripts/e2e-native-workspace-files.mjs b/scripts/e2e-native-workspace-files.mjs
new file mode 100644
index 000000000..8ec526ddf
--- /dev/null
+++ b/scripts/e2e-native-workspace-files.mjs
@@ -0,0 +1,71 @@
+import assert from "node:assert/strict";
+import { createRequire } from "node:module";
+import { spawn } from "node:child_process";
+import { mkdtemp, mkdir, writeFile, rm } from "node:fs/promises";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { resolveElectronBinary } from "./e2e/boot.mjs";
+
+const root = dirname(dirname(fileURLToPath(import.meta.url)));
+const { build } = createRequire(join(root, "packages/agent-runtime/package.json"))("esbuild");
+const temporary = await mkdtemp(join(root, "apps/desktop/.native-file-e2e-"));
+try {
+ const project = join(temporary, "native-project");
+ await mkdir(project);
+ await writeFile(join(project, "note.md"), "NATIVE FILE CONTENT");
+ await build({ entryPoints: [join(root, "apps/desktop/electron/main/ipc/workspace-ipc.ts")], outfile: join(temporary, "workspace.mjs"), bundle: true, platform: "node", format: "esm", packages: "external", nodePaths: [join(root, "apps/desktop/node_modules")] });
+ await writeFile(join(temporary, "main.cjs"), `
+const assert = require("node:assert/strict");
+const { app } = require("electron");
+const { join } = require("node:path");
+
+
+app.setPath("userData", join(__dirname, "profile"));
+app.whenReady().then(async () => {
+ const { IPC } = await import("@pi-desktop/shared");
+ const { registerWorkspaceIpc } = await import("./workspace.mjs");
+ const handlers = new Map();
+ const host = { async call(method) {
+ assert.ok(!method.startsWith("session."), "native request reached Desktop session storage");
+ if (method === "project.groups.list") return { groups: [] };
+ assert.fail("Unexpected Host request: " + method);
+ } };
+ const sidecar = { async call(method, input) {
+ assert.equal(method, "native.session.get");
+ if (input.id === "native-pi:missing") return { session: null };
+ assert.equal(input.id, "native-pi:fixture");
+ return { session: { projectPath: join(__dirname, "native-project"), source: "pi-native" } };
+ } };
+ registerWorkspaceIpc({
+ registrar: { handle: (name, fn) => handlers.set(name, fn), handleWithEvent: (name, fn) => handlers.set(name, fn), assertMainWindowSender() {} },
+ getHost: () => host, getSidecar: () => sidecar, dataDir: join(__dirname, "data"),
+ plugins: {}, browserHost: {}, currentWorkspacePath: () => "C:/unrelated-selected-project",
+ });
+ const sessionId = "native-pi:fixture";
+ const listing = await handlers.get(IPC.invoke.fsList)({ sessionId });
+ assert.ok(listing.entries.some(entry => entry.name === "note.md"));
+ const file = await handlers.get(IPC.invoke.fsRead)({ sessionId, path: "note.md" });
+ assert.equal(file.content, "NATIVE FILE CONTENT");
+ const resolved = await handlers.get(IPC.invoke.fsResolveRef)({ sessionId, ref: "note.md" });
+ assert.equal(resolved.match.absolutePath, join(__dirname, "native-project", "note.md"));
+ await assert.rejects(handlers.get(IPC.invoke.fsRead)({ sessionId: "native-pi:missing", path: "note.md" }), { errorCode: "NOT_FOUND" });
+ console.log("NATIVE_WORKSPACE_FILES_E2E_OK");
+ app.exit(0);
+}).catch(error => { console.error(error); app.exit(1); });
+`);
+ const binary = resolveElectronBinary(root).electronBinary;
+ const env = { ...process.env };
+ delete env.ELECTRON_RUN_AS_NODE;
+ const child = spawn(binary, [join(temporary, "main.cjs")], { windowsHide: true, env, stdio: ["ignore", "pipe", "pipe"] });
+ let output = "";
+ child.stdout.on("data", chunk => { output += chunk; });
+ child.stderr.on("data", chunk => { output += chunk; });
+ const timer = setTimeout(() => child.kill(), 60_000);
+ const code = await new Promise((resolve, reject) => { child.on("error", reject); child.on("exit", resolve); });
+ clearTimeout(timer);
+ assert.equal(code, 0, output);
+ assert.match(output, /NATIVE_WORKSPACE_FILES_E2E_OK/);
+ console.log("Native workspace file IPC E2E passed");
+} finally {
+ await rm(temporary, { recursive: true, force: true });
+}