Skip to content

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

fix(chat): open worktree references from the branch copy

zszz31b1032c28794
diff --git a/apps/desktop/electron/main/ipc/workspace-ipc.ts b/apps/desktop/electron/main/ipc/workspace-ipc.ts
index 57d7b5979..15dac8b68 100644
--- a/apps/desktop/electron/main/ipc/workspace-ipc.ts
+++ b/apps/desktop/electron/main/ipc/workspace-ipc.ts
@@ -40,6 +40,7 @@ import {
} from "@pi-desktop/host-runtime";
import { openableMp4Path } from "../open-attachment-video";
import { isChatRefOutsideRoots, resolveChatFileRef } from "../chat-ref-resolve";
+import { rebaseWorktreeRef, type WorktreeRefContext } from "../worktree-ref";
import { getWorkspaceFileIndex } from "../fs-index";
import {
projectFolderPaths,
@@ -768,27 +769,58 @@ export function registerWorkspaceIpc({
return browserHost.getState();
});
- const requireWorkspaceRoot = async (sessionId?: string) => {
+ type WorkspaceRootInfo = {
+ root: string;
+ /** Present only for an isolated session's worktree checkout. */
+ worktree?: string;
+ /** The parent checkout a worktree session's project identity points at. */
+ parent?: string;
+ };
+
+ const workspaceRootInfo = async (
+ sessionId?: string,
+ ): Promise<WorkspaceRootInfo> => {
const owner = getHost();
if (!owner) throw new Error("host unavailable");
let root: string | undefined;
+ 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 },
);
- // Chat references and source reads must see the same files as the
- // session's tools, not a same-named file in the parent checkout.
- root = session?.worktree
- ? (await owner.call<{ path?: string }>("worktree.location", { sessionId })).path
- : session?.projectPath;
+ const projectPath = session?.projectPath?.trim();
+ if (session?.worktree) {
+ // Chat references and source reads must see the same files as the
+ // session's tools, not a same-named file in the parent checkout.
+ worktree =
+ (await owner.call<{ path?: string }>("worktree.location", { sessionId })).path?.trim() ||
+ undefined;
+ root = worktree;
+ // A reference captured from this checkout rebases onto the worktree
+ // (issue #1747); the opaque remote identity is never a local parent.
+ parent =
+ projectPath && !projectPath.startsWith("remote-project:")
+ ? projectPath
+ : undefined;
+ } else {
+ root = projectPath;
+ }
} else {
root = (await owner.call<{ workspace?: { path: string } }>("workspace.get")).workspace?.path;
}
if (getHost() !== owner) throw Object.assign(new Error("host replaced"), { errorCode: ErrorCodes.HOST_UNAVAILABLE });
if (!root) throw Object.assign(new Error("workspace required"), { errorCode: ErrorCodes.INVALID_ARGUMENT });
- return root;
+ return {
+ root,
+ ...(worktree ? { worktree } : {}),
+ ...(parent ? { parent } : {}),
+ };
};
+ const requireWorkspaceRoot = async (sessionId?: string) =>
+ (await workspaceRootInfo(sessionId)).root;
+
handle(IPC.invoke.fsList, async (input: { path?: string; sessionId?: string } = {}) => {
const remote = await remoteFileWorkspace(input.sessionId);
if (remote) return readRemoteFiles(remote, "list", input.path);
@@ -997,11 +1029,29 @@ export function registerWorkspaceIpc({
async (
input: { ref?: string; sessionId?: string } = {},
): Promise<FsChatRefResolveResult> => {
- const ref = String(input.ref ?? "").trim();
- if (!ref) return { match: null };
+ const rawRef = String(input.ref ?? "").trim();
+ if (!rawRef) return { match: null };
const remote = await remoteFileWorkspace(input.sessionId);
- if (remote && !(await isLocalStoredFile(ref))) return await readRemoteFiles(remote, "resolve", ref) as FsChatRefResolveResult;
- const workspaceRoot = await optionalWorkspaceRoot(input.sessionId);
+ if (remote && !(await isLocalStoredFile(rawRef))) return await readRemoteFiles(remote, "resolve", rawRef) as FsChatRefResolveResult;
+ // A reference captured from the parent checkout names the same relative
+ // file the session's worktree holds; resolve the branch copy instead of
+ // rejecting the path as outside the isolated roots (issue #1747).
+ let rootInfo: WorkspaceRootInfo | undefined;
+ try {
+ rootInfo = await workspaceRootInfo(input.sessionId);
+ } catch {
+ rootInfo = undefined;
+ }
+ const ref = await rebaseWorktreeRef(
+ rawRef,
+ rootInfo?.worktree && rootInfo.parent
+ ? ({
+ worktree: rootInfo.worktree,
+ parent: rootInfo.parent,
+ } satisfies WorktreeRefContext)
+ : null,
+ );
+ const workspaceRoot = rootInfo?.root ?? null;
const roots = {
project: projectRootsFor(workspaceRoot),
scratch: await sessionScratchRoot(input.sessionId),
diff --git a/apps/desktop/electron/main/worktree-ref.ts b/apps/desktop/electron/main/worktree-ref.ts
new file mode 100644
index 000000000..dd56df3b9
--- /dev/null
+++ b/apps/desktop/electron/main/worktree-ref.ts
@@ -0,0 +1,59 @@
+import { stat } from "node:fs/promises";
+import { isAbsolute, resolve } from "node:path";
+
+/**
+ * The two roots a chat reference can mean for an isolated session: the checkout
+ * the user sees (the worktree) and the parent checkout the project identity
+ * still points at (ADR 0329).
+ */
+export type WorktreeRefContext = { worktree: string; parent: string };
+
+/**
+ * Rewrite an absolute chat reference that points into the parent checkout onto
+ * the same relative path inside the session's worktree.
+ *
+ * References can be produced before isolation or by producers that only know
+ * the project path (project instructions, MCP tools, an attachment captured
+ * from the parent checkout). The session's files live in the worktree, so the
+ * original path is outside the allowed roots and the click fails even though
+ * the branch has the same file. Relative references, paths already inside the
+ * worktree, and paths with no worktree counterpart are returned unchanged so
+ * the caller keeps reporting the accurate reason.
+ */
+export async function rebaseWorktreeRef(
+ ref: string,
+ context: WorktreeRefContext | null,
+ isFile: (path: string) => Promise<boolean> = defaultIsFile,
+): Promise<string> {
+ if (!context || !isAbsolute(ref)) return ref;
+ if (relativeWithin(context.worktree, ref) !== null) return ref;
+ const relativePath = relativeWithin(context.parent, ref);
+ if (!relativePath) return ref;
+ const candidate = resolve(context.worktree, ...relativePath.split("/"));
+ return (await isFile(candidate)) ? candidate : ref;
+}
+
+/**
+ * The project UI treats Windows and macOS paths as case-insensitive, and a
+ * reference may use either separator. Compare in normalized form without
+ * changing the spelling returned to the caller.
+ */
+function relativeWithin(root: string, candidate: string): string | null {
+ const rootPath = root.replaceAll("\\", "/").replace(/\/+$/, "");
+ const candidatePath = candidate.replaceAll("\\", "/");
+ const caseInsensitive = process.platform !== "linux";
+ const normalizedRoot = caseInsensitive ? rootPath.toLowerCase() : rootPath;
+ const normalizedCandidate = caseInsensitive
+ ? candidatePath.toLowerCase()
+ : candidatePath;
+ if (!normalizedCandidate.startsWith(`${normalizedRoot}/`)) return null;
+ return candidatePath.slice(rootPath.length + 1);
+}
+
+async function defaultIsFile(path: string): Promise<boolean> {
+ try {
+ return (await stat(path)).isFile();
+ } catch {
+ return false;
+ }
+}
diff --git a/apps/desktop/src/hooks/use-preview-target.ts b/apps/desktop/src/hooks/use-preview-target.ts
index 93f613337..9af9e25a7 100644
--- a/apps/desktop/src/hooks/use-preview-target.ts
+++ b/apps/desktop/src/hooks/use-preview-target.ts
@@ -190,6 +190,10 @@ function useResolveChatFileRef() {
showToast(t("chat.fileRefLookupFailed"), { variant: "error" });
return null;
}
+ // An isolated session's files live in its worktree, which is outside the
+ // plugin's project roots. A relative path would be resolved by the file
+ // view against the parent checkout, so the branch copy stays absolute.
+ const isolated = Boolean(session?.worktree);
const match = result.match;
if (!match) {
const key = result.reason === "outside-allowed-roots"
@@ -213,7 +217,7 @@ function useResolveChatFileRef() {
// absolute path and the file view switches to that folder (ADR 0263).
const primary = match.projectRoot ? match.projectRoot.primary : true;
return {
- path: primary ? match.relativePath : match.absolutePath,
+ path: primary && !isolated ? match.relativePath : match.absolutePath,
absolutePath: match.absolutePath,
relativePath: match.relativePath,
inProject: true,
diff --git a/apps/desktop/test/transcript-file-chips.test.mjs b/apps/desktop/test/transcript-file-chips.test.mjs
index 3cff0bce9..f49837574 100644
--- a/apps/desktop/test/transcript-file-chips.test.mjs
+++ b/apps/desktop/test/transcript-file-chips.test.mjs
@@ -49,7 +49,13 @@ test("a file chip is routed by where the reference resolved, never optimisticall
// follows the folder that answered: relative for the primary one, absolute
// for its siblings, and the file view switches to the folder it is given.
assert.match(hook, /match\.projectRoot \? match\.projectRoot\.primary : true/);
- assert.match(hook, /path: primary \? match\.relativePath : match\.absolutePath/);
+ // An isolated session's worktree is outside the plugin's project roots, so
+ // the branch copy travels by its absolute path (issue #1747).
+ assert.match(hook, /const isolated = Boolean\(session\?\.worktree\)/);
+ assert.match(
+ hook,
+ /path: primary && !isolated \? match\.relativePath : match\.absolutePath/,
+ );
// Project and scratch HTML run at the exact path resolved by main.
assert.match(hook, /resolved\.inProject \|\| resolved\.scratch/);
assert.match(hook, /isHtmlFilePath\(resolved\.absolutePath\)/);
diff --git a/apps/desktop/test/worktree-ref-rebase.test.mjs b/apps/desktop/test/worktree-ref-rebase.test.mjs
new file mode 100644
index 000000000..054711645
--- /dev/null
+++ b/apps/desktop/test/worktree-ref-rebase.test.mjs
@@ -0,0 +1,96 @@
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import test from "node:test";
+
+import { rebaseWorktreeRef } from "../electron/main/worktree-ref.ts";
+
+async function fixture() {
+ const root = await mkdtemp(join(tmpdir(), "pi-worktree-ref-"));
+ const parent = join(root, "main");
+ const worktree = join(root, "worktree");
+ await mkdir(join(parent, "docs"), { recursive: true });
+ await mkdir(join(worktree, "docs"), { recursive: true });
+ await writeFile(join(parent, "docs", "branch-note.md"), "parent\n");
+ await writeFile(join(worktree, "docs", "branch-note.md"), "branch\n");
+ await writeFile(join(parent, "docs", "parent-only.md"), "parent only\n");
+ return { root, parent, worktree };
+}
+
+test("a reference without a worktree context is unchanged", async () => {
+ assert.equal(
+ await rebaseWorktreeRef("/repo/docs/a.md", null),
+ "/repo/docs/a.md",
+ );
+});
+
+test("relative references stay relative", async () => {
+ const { root, parent, worktree } = await fixture();
+ try {
+ assert.equal(
+ await rebaseWorktreeRef("docs/branch-note.md", { parent, worktree }),
+ "docs/branch-note.md",
+ );
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("a reference already inside the worktree is unchanged", async () => {
+ const { root, parent, worktree } = await fixture();
+ try {
+ const ref = join(worktree, "docs", "branch-note.md");
+ assert.equal(await rebaseWorktreeRef(ref, { parent, worktree }), ref);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("a parent-checkout path resolves to the branch copy in the worktree", async () => {
+ const { root, parent, worktree } = await fixture();
+ try {
+ assert.equal(
+ await rebaseWorktreeRef(join(parent, "docs", "branch-note.md"), {
+ parent,
+ worktree,
+ }),
+ join(worktree, "docs", "branch-note.md"),
+ );
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("a parent-only file keeps its original path when the branch lacks it", async () => {
+ const { root, parent, worktree } = await fixture();
+ try {
+ const ref = join(parent, "docs", "parent-only.md");
+ assert.equal(await rebaseWorktreeRef(ref, { parent, worktree }), ref);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("a sibling directory sharing the parent prefix is not rebased", async () => {
+ const { root, parent, worktree } = await fixture();
+ try {
+ const sibling = join(`${parent}-other`, "docs", "branch-note.md");
+ assert.equal(await rebaseWorktreeRef(sibling, { parent, worktree }), sibling);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("a worktree nested inside the parent is not rebased onto itself", async () => {
+ const { root, worktree } = await fixture();
+ try {
+ const nested = join(worktree, ".worktrees", "branch");
+ await mkdir(join(nested, "docs"), { recursive: true });
+ await writeFile(join(nested, "docs", "branch-note.md"), "branch\n");
+ const ref = join(nested, "docs", "branch-note.md");
+ assert.equal(await rebaseWorktreeRef(ref, { parent: worktree, worktree: nested }), ref);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.md
index 64c0fa905..1f81a9c0e 100644
--- a/docs/spec/03-runtime/01-ipc-protocol.md
+++ b/docs/spec/03-runtime/01-ipc-protocol.md
@@ -1926,7 +1926,10 @@ Renderer IPC kept for the Plan-safe preview facade and URL fallback:
so the extensionless blob has a media association without copying its bytes.
- `fs/resolveRef({ref, sessionId?})` → `FsChatRefResolveResult`
(for isolated sessions, lookup and file reads use `worktree.location` rather
- than the parent project checkout)
+ than the parent project checkout; an absolute reference under the parent
+ checkout is rebased onto the same relative path in the worktree when that
+ file exists, so the branch copy opens instead of reporting
+ `outside-allowed-roots`)
(`{ match: FsChatRefMatch | null, reason?: "outside-allowed-roots" }`, the match naming the answering `root`
(`workspace` / `scratch` / `attachments`), the `relativePath` relative to that
root, optional `sessionScratch: true` for the current session's own scratch
diff --git a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md
index 79a7716a2..8fdf8921d 100644
--- a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md
+++ b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md
@@ -1439,7 +1439,7 @@ Chrome 和代理 CDP 位于随应用打包的 `pi.browser` 插件中,通过 `p
- `fs/readImageDataUrl({ref, mimeType?})` → `FsImageDataUrlResult`(`image` 带 `dataUrl`,或 `missing` / `notImage` / `tooLarge`)。包含范围与 `fs/read` 相同。从不返回非图片字节。仅渲染器使用,不是插件宿主 API。
- `fs/reveal({path})` → 在 Finder 中显示。包含范围与 `fs/read` 相同。
- `fs/open({path, mimeType?})` → 用系统默认应用打开已有的普通文件。与 `fs/read` 一样校验真实路径包含范围,拒绝通过符号链接逃逸。对于声明为 `video/mp4` 的无后缀 `attachments/<sha256>` blob,宿主在私有应用数据目录建立 `.mp4` 符号链接后再交给系统,不复制视频字节。
-- `fs/resolveRef({ref, sessionId?})` → `FsChatRefResolveResult`(`{ match: FsChatRefMatch | null }`,match 指出应答的 `root`(`workspace` / `scratch` / `attachments`)、相对该应答根的 `relativePath`、绝对路径 `absolutePath` 与 `matchedBy`(`exact-relative` / `exact-absolute` / `path-suffix` / `basename`),以及在 `workspace` 命中时给出的 `projectRoot`(`{ path, name, primary }`,指出是哪个文件夹应答的));`sessionId` 决定查哪个会话的临时目录。它补全智能体在聊天里打印的文件引用,因为渲染器看不到会话自己的临时目录:已经在某个已知根内指向真实文件的绝对引用直接胜出,`attachments/<sha256>` blob 直接对附件库解析;否则按优先级顺序搜索各根——整个打开的项目、再会话自己的临时目录(`<data_dir>/scratch/<sessionId>/`,ADR 0124)、最后附件库——第一个给出结果的根胜出。项目指的是打开的工作区背后的文件夹组(ADR 0249):主文件夹先应答,其余文件夹随后按项目组自身顺序搜索(ADR 0263),因此简写落在同级文件夹里和落在主文件夹里一样自然,命中结果也指出是哪个文件夹应答的。同一个根内精确路径优先于简写;简写之间最长匹配尾优先,其次路径更浅者。文件面板的忽略集合同样生效。什么都没匹配到时返回 `match: null`;解析本身不打开任何东西(ADR 0262)。
+- `fs/resolveRef({ref, sessionId?})` → `FsChatRefResolveResult`(`{ match: FsChatRefMatch | null }`,match 指出应答的 `root`(`workspace` / `scratch` / `attachments`)、相对该应答根的 `relativePath`、绝对路径 `absolutePath` 与 `matchedBy`(`exact-relative` / `exact-absolute` / `path-suffix` / `basename`),以及在 `workspace` 命中时给出的 `projectRoot`(`{ path, name, primary }`,指出是哪个文件夹应答的));`sessionId` 决定查哪个会话的临时目录。隔离会话以 `worktree.location` 而不是父项目 checkout 作为查找与读取的根;落在父 checkout 内的绝对引用会先映射到 worktree 中的同一相对路径(该文件存在时),从而打开分支上的副本,而不是报 `outside-allowed-roots`。它补全智能体在聊天里打印的文件引用,因为渲染器看不到会话自己的临时目录:已经在某个已知根内指向真实文件的绝对引用直接胜出,`attachments/<sha256>` blob 直接对附件库解析;否则按优先级顺序搜索各根——整个打开的项目、再会话自己的临时目录(`<data_dir>/scratch/<sessionId>/`,ADR 0124)、最后附件库——第一个给出结果的根胜出。项目指的是打开的工作区背后的文件夹组(ADR 0249):主文件夹先应答,其余文件夹随后按项目组自身顺序搜索(ADR 0263),因此简写落在同级文件夹里和落在主文件夹里一样自然,命中结果也指出是哪个文件夹应答的。同一个根内精确路径优先于简写;简写之间最长匹配尾优先,其次路径更浅者。文件面板的忽略集合同样生效。什么都没匹配到时返回 `match: null`;解析本身不打开任何东西(ADR 0262)。
- `fs/list` 仍只限工作区;外面的遍历被拒绝(`INVALID_ARGUMENT`)。
## 13b. 桌面菜单和窗口 API