Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(chat): preserve full network refs and canonical roots
cauliflower4f0f84650332
diff --git a/apps/desktop/electron/main/chat-ref-resolve.ts b/apps/desktop/electron/main/chat-ref-resolve.tsindex b56f3aeec..208973527 100644--- a/apps/desktop/electron/main/chat-ref-resolve.ts+++ b/apps/desktop/electron/main/chat-ref-resolve.ts@@ -1,5 +1,5 @@-import { readdir, stat } from "node:fs/promises";-import { isAbsolute, join, relative, resolve, sep } from "node:path";+import { readdir, realpath, stat } from "node:fs/promises";+import { basename, dirname, isAbsolute, join, parse, relative, resolve, sep } from "node:path";import type {FsChatRefMatch,FsChatRefMatchKind,@@ -48,6 +48,8 @@ type ChatRefRootEntry = {projectRoot?: FsChatRefProjectRoot;};+type CanonicalChatRefRoot = ChatRefRootEntry & { realPath: string | null };+const MAX_REF_LENGTH = 512;const ATTACHMENT_HASH_PATTERN = /^[0-9a-f]{64}$/i;/** A tail longer than this is a user quoting a full path, not a shorthand. */@@ -162,13 +164,52 @@ function relativeInside(rootPath: string, absolute: string): string | null {return toPosix(rel);}-export function isChatRefOutsideRoots(ref: string, roots: ChatRefRoots): boolean {+async function canonicalRoots(roots: ChatRefRootEntry[]): Promise<CanonicalChatRefRoot[]> {+ return Promise.all(roots.map(async (root) => {+ try {+ return { ...root, realPath: await realpath(root.path) };+ } catch {+ return { ...root, realPath: null };+ }+ }));+}++function couldShareVolume(target: string, roots: CanonicalChatRefRoot[]): boolean {+ if (process.platform !== "win32") return true;+ const volume = parse(target).root.toLowerCase();+ return roots.some((root) => [root.path, root.realPath].some(+ (path) => path && parse(path).root.toLowerCase() === volume,+ ));+}++async function canonicalPathOrMissingTail(path: string): Promise<string | null> {+ let ancestor = path;+ const tail: string[] = [];+ for (;;) {+ try {+ return resolve(await realpath(ancestor), ...tail);+ } catch {+ const parent = dirname(ancestor);+ if (parent === ancestor) return null;+ tail.unshift(basename(ancestor));+ ancestor = parent;+ }+ }+}++export async function isChatRefOutsideRoots(ref: string, roots: ChatRefRoots): Promise<boolean> {const parsed = parseChatRef(ref);if (!parsed?.absolute) return false;const cleaned = cleanRef(ref);if (!isAbsolute(cleaned)) return true;const absolutePath = resolve(cleaned);- return !orderedRoots(roots).some((root) => relativeInside(root.path, absolutePath) !== null);+ const rootList = await canonicalRoots(orderedRoots(roots));+ if (!couldShareVolume(absolutePath, rootList)) return true;+ const targetPath = await canonicalPathOrMissingTail(absolutePath);+ if (!targetPath) return !rootList.some((root) => relativeInside(root.path, absolutePath) !== null);+ return !rootList.some((root) =>+ root.realPath && relativeInside(root.realPath, targetPath) !== null,+ );}function segmentsOf(path: string): string[] {@@ -291,18 +332,25 @@ export async function resolveChatFileRef(const cleaned = cleanRef(ref);if (!isAbsolute(cleaned)) return null;const absolutePath = resolve(cleaned);- for (const root of rootList) {- const relativePath = relativeInside(root.path, absolutePath);+ const canonicalRootList = await canonicalRoots(rootList);+ if (!couldShareVolume(absolutePath, canonicalRootList)) return null;+ let targetPath: string;+ try {+ targetPath = await realpath(absolutePath);+ } catch {+ return null;+ }+ if (!(await isRegularFile(targetPath))) return null;+ for (const root of canonicalRootList) {+ const relativePath = root.realPath ? relativeInside(root.realPath, targetPath) : null;if (!relativePath) continue;- if (await isRegularFile(absolutePath)) {- return {- root: root.kind,- relativePath,- absolutePath,- matchedBy: "exact-absolute",- ...(root.projectRoot ? { projectRoot: root.projectRoot } : {}),- };- }+ return {+ root: root.kind,+ relativePath,+ absolutePath,+ matchedBy: "exact-absolute",+ ...(root.projectRoot ? { projectRoot: root.projectRoot } : {}),+ };}return null;}diff --git a/apps/desktop/electron/main/ipc/workspace-ipc.ts b/apps/desktop/electron/main/ipc/workspace-ipc.tsindex ec395dedb..3e5c4663b 100644--- a/apps/desktop/electron/main/ipc/workspace-ipc.ts+++ b/apps/desktop/electron/main/ipc/workspace-ipc.ts@@ -921,7 +921,7 @@ export function registerWorkspaceIpc({scratch: await sessionScratchRoot(input.sessionId),attachments: join(dataDir, "attachments"),};- if (isChatRefOutsideRoots(ref, roots)) {+ if (await isChatRefOutsideRoots(ref, roots)) {return { match: null, reason: "outside-allowed-roots" };}return { match: await resolveChatFileRef(ref, roots) };diff --git a/apps/desktop/src/lib/chat-links.ts b/apps/desktop/src/lib/chat-links.tsindex 767250629..ad355a1ed 100644--- a/apps/desktop/src/lib/chat-links.ts+++ b/apps/desktop/src/lib/chat-links.ts@@ -35,7 +35,7 @@ const KNOWN_BARE_NAMES = new Set([]);const FILE_TOKEN_RE =- /^(?:(?:[A-Za-z]:[\\/]|~[\\/]|[\\/])|(?:\.{1,2}[\\/])?)[\p{L}\p{N}_@+. -]+(?:[\\/][\p{L}\p{N}_@+. -]+)*(?::\d+(?::\d+)?)?$/u;+ /^(?:(?:[A-Za-z]:[\\/]|~[\\/]|\\\\|\/\/|[\\/])|(?:\.{1,2}[\\/])?)[\p{L}\p{N}_@+. -]+(?:[\\/][\p{L}\p{N}_@+. -]+)*(?::\d+(?::\d+)?)?$/u;const AT_QUOTED_RE = /^@"([^"\n]+)"$/;const AT_UNQUOTED_RE = /^@(\/?[^\s]+)$/;@@ -252,6 +252,7 @@ const PATH_WORD = String.raw`[\p{L}\p{N}_@+.-]+`;const PATH_SEGMENT = String.raw`[\p{L}\p{N}_@+. -]+`;const FILE_END = String.raw`\.[A-Za-z0-9]{1,8}(?::\d+(?::\d+)?)?(?![A-Za-z0-9_]|\.[A-Za-z0-9])`;const FILE_NAME = String.raw`${PATH_SEGMENT}?${FILE_END}`;+const UNC_PREFIX = String.raw`(?:\\\\[^\\/\s]+[\\/]|\/\/[^/\s]+\/)`;const SPACED_START = String.raw`(?<![\p{L}\p{N}_@+.-])[A-Za-z][\p{L}\p{N}_+-]*(?: [\p{L}\p{N}_+-]+)+`;// Unmarked first-segment spaces cannot be distinguished from prose. Retry// after common introducers so ordinary bare file links still work.@@ -266,7 +267,7 @@ const SCAN_RE = new RegExp([String.raw`@"[^"\n]+"`,String.raw`@[^\s]+`,String.raw`https?:\/\/(?=[^\s<>"'()[\]{}])`,- String.raw`(?:[A-Za-z]:[\\/]|\/)(?:${PATH_SEGMENT}[\\/])*?${FILE_NAME}`,+ String.raw`(?:[A-Za-z]:[\\/]|${UNC_PREFIX}|\/)(?:${PATH_SEGMENT}[\\/])*?${FILE_NAME}`,String.raw`${SPACED_START}[\\/](?:${PATH_SEGMENT}[\\/])*?${FILE_NAME}`,String.raw`${SPACED_START}(?:\.[A-Za-z0-9_-]+)*${FILE_END}`,String.raw`(?:${PATH_WORD}[\\/])+(?:${PATH_SEGMENT}[\\/])*?${FILE_NAME}`,@@ -320,6 +321,8 @@ export function splitChatText(? scanUrl(text, start): match[0];scanner.lastIndex = start + raw.length;+ if ((text[start - 1] === "~" && /^[\\/]/u.test(raw)) ||+ ["~/", "~\\"].includes(text.slice(start - 2, start))) continue;const disposition = spacedRefDisposition(raw);if (disposition === "skip") continue;if (disposition === "retry") {@@ -389,7 +392,7 @@ export function linkifyMdastTree(const url =segment.target.kind === "url"? segment.target.url- : /^[A-Za-z]:[\\/]/.test(segment.target.path)+ : (/^[A-Za-z]:[\\/]/.test(segment.target.path) || segment.target.path.startsWith("\\\\"))? encodeURIComponent(segment.target.path): segment.target.path;next.push({diff --git a/apps/desktop/test/chat-links.test.mjs b/apps/desktop/test/chat-links.test.mjsindex e96679c37..c48ead3e2 100644--- a/apps/desktop/test/chat-links.test.mjs+++ b/apps/desktop/test/chat-links.test.mjs@@ -425,6 +425,22 @@ test("splitChatText keeps outside absolute paths whole and home paths plain", ());assert.deepEqual(outside.filter((segment) => segment.kind === "target").map((segment) => segment.text), ["/elsewhere/a.ts"]);assert.equal(outside.map((segment) => segment.text).join(""), "see /elsewhere/a.ts and ~/Downloads/x.png here");+ for (const source of ["~/my project/page.md", "see ~/my project/page.md here", "~\\my project\\page.md"]) {+ assert.deepEqual(splitChatText(source, ROOT), [{ kind: "text", text: source }]);+ }+ const unc = "\\\\server\\my share\\page.md";+ const segments = splitChatText(`Open ${unc} now`, ROOT);+ assert.deepEqual(segments.filter((segment) => segment.kind === "target").map((segment) => segment.text), [unc]);+ assert.deepEqual(segments.filter((segment) => segment.kind === "target").map((segment) => segment.target), [+ { kind: "file", path: unc },+ ]);+ const forwardUnc = "//server/my share/page.md";+ assert.deepEqual(+ splitChatText(`Open ${forwardUnc} now`, ROOT)+ .filter((segment) => segment.kind === "target")+ .map((segment) => segment.text),+ [forwardUnc],+ );});test("markdown linkification encodes a Windows file path without losing its source text", () => {@@ -441,6 +457,12 @@ test("markdown linkification encodes a Windows file path without losing its sour}),);assert.match(markup, /href="C%3A%5Cdemo%20project%5Creadme.md"/);+ const unc = "\\\\server\\my share\\page.md";+ const uncTree = { type: "root", children: [{ type: "paragraph", children: [{ type: "text", value: `Open ${unc}` }] }] };+ linkifyMdastTree(uncTree, ROOT);+ const uncLink = uncTree.children[0].children.find((node) => node.type === "link");+ assert.equal(uncLink.url, encodeURIComponent(unc));+ assert.equal(uncLink.children[0].value, unc);});test("splitChatText keeps unknown extensions literal", () => {diff --git a/apps/desktop/test/chat-ref-resolve.test.mjs b/apps/desktop/test/chat-ref-resolve.test.mjsindex 1444f0db1..2a99363cc 100644--- a/apps/desktop/test/chat-ref-resolve.test.mjs+++ b/apps/desktop/test/chat-ref-resolve.test.mjs@@ -1,6 +1,6 @@import assert from "node:assert/strict";import test from "node:test";-import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";+import { mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { dirname, join } from "node:path";import { register } from "node:module";@@ -84,6 +84,10 @@ test("an absolute path outside the project cannot select a same-name file by taiconst workspace = tempTree("ws", ["src/dir/openimage.js"]);const match = await resolve("/root/dir/openimage.js", { workspace });assert.equal(match, null);+ const unc = "\\\\server\\my share\\openimage.js";+ assert.equal(parseChatRef(unc)?.absolute, true);+ assert.equal(await isChatRefOutsideRoots(unc, roots({ workspace })), true);+ assert.equal(await resolve(unc, { workspace }), null);});test("an exact absolute path with spaces resolves only inside an allowed root", async () => {@@ -93,8 +97,35 @@ test("an exact absolute path with spaces resolves only inside an allowed root",assert.equal(match?.matchedBy, "exact-absolute");assert.equal(match?.absolutePath, absolute);assert.equal(await resolve(join(dirname(workspace), "page.md"), { workspace }), null);- assert.equal(isChatRefOutsideRoots(absolute, roots({ workspace })), false);- assert.equal(isChatRefOutsideRoots(join(dirname(workspace), "page.md"), roots({ workspace })), true);+ assert.equal(await isChatRefOutsideRoots(absolute, roots({ workspace })), false);+ assert.equal(await isChatRefOutsideRoots(join(dirname(workspace), "page.md"), roots({ workspace })), true);+});++test("an absolute realpath alias resolves under the same registered root", async () => {+ const workspace = tempTree("alias-target", ["my project/page.md"]);+ const aliasParent = mkdtempSync(join(tmpdir(), "pi-chat-ref-alias-"));+ const alias = join(aliasParent, "linked-project");+ symlinkSync(workspace, alias, process.platform === "win32" ? "junction" : "dir");+ const target = join(workspace, "my project", "page.md");+ const project = [folder(alias)];+ assert.equal(await isChatRefOutsideRoots(target, { project }), false);+ const match = await resolveChatFileRef(target, { project });+ assert.equal(match?.matchedBy, "exact-absolute");+ assert.equal(match?.relativePath, "my project/page.md");+ assert.equal(match?.absolutePath, target);+ const missing = join(workspace, "my project", "missing.md");+ assert.equal(await isChatRefOutsideRoots(missing, { project }), false);+ assert.equal(await resolveChatFileRef(missing, { project }), null);+});++test("an in-root symlink cannot resolve a file outside the registered root", async () => {+ const workspace = tempTree("symlink-root", ["safe.md"]);+ const outside = tempTree("symlink-outside", ["page.md"]);+ symlinkSync(outside, join(workspace, "linked"), process.platform === "win32" ? "junction" : "dir");+ const ref = join(workspace, "linked", "page.md");+ assert.equal(await isChatRefOutsideRoots(ref, roots({ workspace })), true);+ assert.equal(await resolve(ref, { workspace }), null);+ assert.equal(await isChatRefOutsideRoots(join(workspace, "linked", "missing.md"), roots({ workspace })), true);});test("a longer matching tail beats a bare leaf name", async () => {diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex b0dec7248..44a3b2eed 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -11761,7 +11761,9 @@ are withdrawn with ADR 0165.path containing a space on macOS or Linux.- **Steps**: 1) Click the full path in the Write row. 2) Click the same fullpath as inline code and as ordinary text in the assistant reply. 3) Click a- relative path containing a space. 4) Click the outside absolute path.+ relative path whose middle directory contains a space, then a first-segment+ spaced path using an explicit `@"..."` reference. 4) Click the outside+ absolute path.- **Expected**: Every allowed reference opens the exact file in the existingside file view; no path is truncated to its suffix or redirected to thesame-name file. The outside path opens nothing and reports the access limit,