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): resolve complete file paths in transcripts
cauliflower211de72a644d
diff --git a/apps/desktop/electron/main/chat-ref-resolve.ts b/apps/desktop/electron/main/chat-ref-resolve.tsindex 10fe041e9..b56f3aeec 100644--- a/apps/desktop/electron/main/chat-ref-resolve.ts+++ b/apps/desktop/electron/main/chat-ref-resolve.ts@@ -19,8 +19,7 @@ import { getWorkspaceFileIndex } from "./fs-index.js";** Resolution order is the product contract:*- * 1. an absolute reference that already names a real file inside a known- * root wins outright — that is path equality, not a guess;+ * 1. an absolute reference only names that exact file inside a known root;* 2. an `attachments/<sha256>` blob names a stored file by hash rather than* by path, so it resolves against the attachment store directly;* 3. otherwise the roots are searched in priority order — the open project@@ -163,6 +162,15 @@ function relativeInside(rootPath: string, absolute: string): string | null {return toPosix(rel);}+export function isChatRefOutsideRoots(ref: string, roots: ChatRefRoots): 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);+}+function segmentsOf(path: string): string[] {return toPosix(path).split("/").filter(Boolean);}@@ -278,12 +286,11 @@ export async function resolveChatFileRef(const cleanedPosixRef = toPosix(cleanRef(ref));const isAttachmentRef = /^attachments(?:\/|$)/i.test(cleanedPosixRef);- // 1. An absolute reference that already names a real path inside a known root- // is unambiguous evidence, so it outranks every shorthand rule below. A- // POSIX-style path on Windows finds nothing here, which is correct: step 2- // then treats its tail as the shorthand it is.+ // Absolute references must not select an unrelated in-root file by suffix.if (parsed.absolute) {- const absolutePath = resolve(cleanRef(ref));+ const cleaned = cleanRef(ref);+ if (!isAbsolute(cleaned)) return null;+ const absolutePath = resolve(cleaned);for (const root of rootList) {const relativePath = relativeInside(root.path, absolutePath);if (!relativePath) continue;@@ -297,6 +304,7 @@ export async function resolveChatFileRef(};}}+ return null;}// 2. A content-addressed attachment blob (`attachments/<sha256>`) is not a@@ -333,17 +341,15 @@ export async function resolveChatFileRef(tails.push(parsed.segments.slice(parsed.segments.length - length));}for (const root of rootList) {- if (!parsed.absolute) {- const absolutePath = join(root.path, ...parsed.segments);- if (await isRegularFile(absolutePath)) {- return {- root: root.kind,- relativePath: parsed.segments.join("/"),- absolutePath,- matchedBy: "exact-relative",- ...(root.projectRoot ? { projectRoot: root.projectRoot } : {}),- };- }+ const absolutePath = join(root.path, ...parsed.segments);+ if (await isRegularFile(absolutePath)) {+ return {+ root: root.kind,+ relativePath: parsed.segments.join("/"),+ absolutePath,+ matchedBy: "exact-relative",+ ...(root.projectRoot ? { projectRoot: root.projectRoot } : {}),+ };}const candidate = bestFuzzyCandidate(await listRootFiles(root.kind, root.path),diff --git a/apps/desktop/electron/main/ipc/workspace-ipc.ts b/apps/desktop/electron/main/ipc/workspace-ipc.tsindex 94015c57c..ec395dedb 100644--- a/apps/desktop/electron/main/ipc/workspace-ipc.ts+++ b/apps/desktop/electron/main/ipc/workspace-ipc.ts@@ -35,7 +35,7 @@ import {resolveRealOpenablePath,} from "@pi-desktop/host-runtime";import { openableMp4Path } from "../open-attachment-video";-import { resolveChatFileRef } from "../chat-ref-resolve";+import { isChatRefOutsideRoots, resolveChatFileRef } from "../chat-ref-resolve";import { getWorkspaceFileIndex } from "../fs-index";import {projectFolderPaths,@@ -916,13 +916,15 @@ export function registerWorkspaceIpc({const ref = String(input.ref ?? "").trim();if (!ref) return { match: null };const workspaceRoot = await optionalWorkspaceRoot();- return {- match: await resolveChatFileRef(ref, {- project: projectRootsFor(workspaceRoot),- scratch: await sessionScratchRoot(input.sessionId),- attachments: join(dataDir, "attachments"),- }),+ const roots = {+ project: projectRootsFor(workspaceRoot),+ scratch: await sessionScratchRoot(input.sessionId),+ attachments: join(dataDir, "attachments"),};+ if (isChatRefOutsideRoots(ref, roots)) {+ return { match: null, reason: "outside-allowed-roots" };+ }+ return { match: await resolveChatFileRef(ref, roots) };},);diff --git a/apps/desktop/src/components/Markdown.tsx b/apps/desktop/src/components/Markdown.tsxindex d21389b67..b425cc122 100644--- a/apps/desktop/src/components/Markdown.tsx+++ b/apps/desktop/src/components/Markdown.tsx@@ -574,9 +574,11 @@ function Anchor({action on the file's folder. `./` and `../` resolve against the markdownfile on screen, which is the base this row already holds.*/- const rel = toWorkspaceRel(safeDecodeUri(href), root, baseDir);- if (!rel || !openFileMenu) return;- openFileMenu(event, { path: rel, baseDir });+ const decoded = safeDecodeUri(href);+ const target = resolvePreviewTarget(decoded, root, baseDir);+ const ref = target?.kind === "file" ? target.path : toWorkspaceRel(decoded, root, baseDir);+ if (!ref || !openFileMenu) return;+ openFileMenu(event, { path: ref, baseDir });return;}const target = href;@@ -622,10 +624,12 @@ function Anchor({openHttpUrl(href);return;}- const rel = toWorkspaceRel(safeDecodeUri(href), root, baseDir);- if (rel) {+ const decoded = safeDecodeUri(href);+ const target = resolvePreviewTarget(decoded, root, baseDir);+ const ref = target?.kind === "file" ? target.path : toWorkspaceRel(decoded, root, baseDir);+ if (ref) {e.preventDefault();- openFileRef(rel, baseDir);+ openFileRef(ref, baseDir);}};return (diff --git a/apps/desktop/src/hooks/use-preview-target.ts b/apps/desktop/src/hooks/use-preview-target.tsindex 7f6839289..2cbac818b 100644--- a/apps/desktop/src/hooks/use-preview-target.ts+++ b/apps/desktop/src/hooks/use-preview-target.ts@@ -87,14 +87,19 @@ function useResolveChatFileRef() {const anchored = isDotRelative(raw)? toWorkspaceRel(raw, workspacePath, baseDir): null;- let match = null;+ let result;try {- match = (await api.fsResolveRef(anchored ?? raw, sessionId)).match;+ result = await api.fsResolveRef(anchored ?? raw, sessionId);} catch {- match = null;+ showToast(t("chat.fileRefLookupFailed"), { variant: "error" });+ return null;}+ const match = result.match;if (!match) {- showToast(t("chat.fileRefMissing", { name: raw }), { variant: "error" });+ const key = result.reason === "outside-allowed-roots"+ ? "chat.fileRefRestricted"+ : "chat.fileRefMissing";+ showToast(t(key, { name: raw }), { variant: "error" });return null;}if (match.root !== "workspace") {diff --git a/apps/desktop/src/lib/chat-links.ts b/apps/desktop/src/lib/chat-links.tsindex 8dc8e2bc6..c13ceda91 100644--- a/apps/desktop/src/lib/chat-links.ts+++ b/apps/desktop/src/lib/chat-links.ts@@ -8,12 +8,9 @@* prose (`store.messages`) stay plain text. Explicit `@path` tokens from the* composer (D124 / D320) are accepted even when quoted or absolute.*- * Path tokens recognize Unicode letters and digits, so non-ASCII filenames- * (CJK above all) link exactly like ASCII ones. Absolute and `~/` tokens are- * captured whole and then resolved by the same workspace rules: a path under- * the root resolves normally, and one outside it — or any home path — stays- * plain text instead of rendering a chip that could never open. Links still- * cannot escape the workspace (D322).+ * Path tokens recognize Unicode letters and digits, spaces, and Windows drive+ * paths. Absolute candidates stay whole for main-process resolution, which+ * checks the allowed roots before opening anything. Home paths stay plain.** Relative paths are workspace-rooted unless they start with `./` or `../`,* in which case they resolve against an optional markdown-file directory and@@ -38,7 +35,7 @@ const KNOWN_BARE_NAMES = new Set([]);const FILE_TOKEN_RE =- /^(?:~\/|\/)?(?:\.{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]+)$/;@@ -61,10 +58,11 @@ function leafName(path: string): string {}function isLikelyFilePath(path: string): boolean {- const base = path.split("/").pop() ?? "";+ const normalized = path.replaceAll("\\", "/");+ const base = normalized.split("/").pop() ?? "";const dotIndex = base.lastIndexOf(".");const ext = dotIndex > 0 ? base.slice(dotIndex + 1).toLowerCase() : "";- if (path.includes("/")) {+ if (normalized.includes("/")) {if (ext && ext.length <= 8) return true;if (KNOWN_BARE_NAMES.has(base)) return true;return false;@@ -73,6 +71,10 @@ function isLikelyFilePath(path: string): boolean {return KNOWN_EXTS.has(ext);}+function isAbsoluteFilePath(path: string): boolean {+ return path.startsWith("/") || /^[A-Za-z]:[\\/]/.test(path) || path.startsWith("\\\\");+}+/*** Returns the cleaned path when `text` plausibly names a file (trailing* `:line[:col]` refs are stripped), otherwise null. A leading `@` — the@@ -118,7 +120,7 @@ export function fileDirOf(path: string): string {export function safeDecodeUri(value: string): string {try {- return decodeURI(value);+ return decodeURIComponent(value);} catch {return value;}@@ -163,19 +165,22 @@ export function toWorkspaceRel(): string | null {if (!path) return null;if (path.startsWith("~")) return null;+ const normalizedPath = path.replaceAll("\\", "/");let rel: string;- if (path.startsWith("/")) {+ if (isAbsoluteFilePath(path)) {if (!root) return null;- const cleanRoot = root.replace(/\/+$/, "");- if (path === cleanRoot) return null;- if (!path.startsWith(cleanRoot + "/")) return null;- rel = path.slice(cleanRoot.length + 1);- } else if (isDotRelative(path)) {+ const cleanRoot = root.replaceAll("\\", "/").replace(/\/+$/, "");+ const windowsPath = /^[A-Za-z]:\//.test(normalizedPath);+ const comparisonPath = windowsPath ? normalizedPath.toLowerCase() : normalizedPath;+ const comparisonRoot = windowsPath ? cleanRoot.toLowerCase() : cleanRoot;+ if (!comparisonPath.startsWith(comparisonRoot + "/")) return null;+ rel = normalizedPath.slice(cleanRoot.length + 1);+ } else if (isDotRelative(normalizedPath)) {const base = (baseDir ?? "").replaceAll("\\", "/").replace(/\/+$/, "");- rel = base ? `${base}/${path}` : path;+ rel = base ? `${base}/${normalizedPath}` : normalizedPath;} else {- rel = path;+ rel = normalizedPath;}return normalizeWorkspaceRel(rel);@@ -195,13 +200,13 @@ export function resolvePreviewTarget(if (isHttpUrl(trimmed)) return { kind: "url", url: trimmed };const at = unwrapAtFileRef(trimmed);if (at) {- // Scratch/attachment @refs stay absolute so fs/open can contain them.- if (at.startsWith("/")) return { kind: "file", path: at };+ if (isAbsoluteFilePath(at)) return { kind: "file", path: at };const rel = toWorkspaceRel(at, root, baseDir);return rel ? { kind: "file", path: rel } : null;}const file = parseFileRef(trimmed);if (!file) return null;+ if (isAbsoluteFilePath(file)) return { kind: "file", path: file };const rel = toWorkspaceRel(file, root, baseDir);return rel ? { kind: "file", path: rel } : null;}@@ -216,7 +221,9 @@ export function getToolPreviewTarget(for (const key of ["path", "file_path", "filePath"]) {const value = record[key];if (typeof value === "string" && value.trim()) {- const rel = toWorkspaceRel(value.trim(), root);+ const raw = value.trim();+ if (isAbsoluteFilePath(raw)) return { kind: "file", path: raw };+ const rel = toWorkspaceRel(raw, root);if (rel) return { kind: "file", path: rel };return null;}@@ -238,14 +245,12 @@ export type ChatTextSegment =target: ChatPreviewTarget;};-// Unicode-aware scan (#235). `~`- and `/`-prefixed paths are captured whole-// so the resolver sees the real anchor: under-root absolutes resolve, while-// outside absolutes and home paths fail resolution and stay plain text-// instead of chipping a suffix that could never open. The extension tail+// Unicode-aware scan (#235). Absolute paths are captured whole so a failed+// lookup never turns a suffix into a different file reference. The extension tail// uses `(?![A-Za-z0-9_])` rather than `\b`: in unicode mode `\b` treats CJK// letters as word characters, which would stop `App.tsx文件` from linking.const SCAN_RE =- /@"[^"\n]+"|@[^\s]+|https?:\/\/(?=[^\s<>"'()[\]{}])|(?:~\/)?\/?\.{1,2}\/(?:[\p{L}\p{N}_@+.-]+\/)*[\p{L}\p{N}_@+.-]+(?::\d+(?::\d+)?)?|(?:~\/)?\/?(?:[\p{L}\p{N}_@+.-]+\/)+[\p{L}\p{N}_@+.-]+(?::\d+(?::\d+)?)?|[\p{L}\p{N}_@+-][\p{L}\p{N}_@+.-]*\.[A-Za-z0-9]{1,8}(?![A-Za-z0-9_])/gu;+ /@"[^"\n]+"|@[^\s]+|https?:\/\/(?=[^\s<>"'()[\]{}])|(?:[A-Za-z]:[\\/]|\/)(?:[\p{L}\p{N}_@+. -]+[\\/])*?[\p{L}\p{N}_@+. -]+?\.[A-Za-z0-9]{1,8}(?::\d+(?::\d+)?)?(?![A-Za-z0-9_])|(?:[\p{L}\p{N}_@+.-]+[\\/])+(?:[\p{L}\p{N}_@+. -]+[\\/])*?[\p{L}\p{N}_@+. -]+?\.[A-Za-z0-9]{1,8}(?::\d+(?::\d+)?)?(?![A-Za-z0-9_])|(?:~\/)?\/?\.{1,2}\/(?:[\p{L}\p{N}_@+.-]+\/)*[\p{L}\p{N}_@+.-]+(?::\d+(?::\d+)?)?|(?:~\/)?\/?(?:[\p{L}\p{N}_@+.-]+\/)+[\p{L}\p{N}_@+.-]+(?::\d+(?::\d+)?)?|[\p{L}\p{N}_@+-][\p{L}\p{N}_@+.-]*\.[A-Za-z0-9]{1,8}(?![A-Za-z0-9_])/gu;/** Scan once, keeping URL parentheses but stopping at a closing prose wrapper. */function scanUrl(text: string, start: number): string {@@ -347,7 +352,9 @@ export function linkifyMdastTree(const url =segment.target.kind === "url"? segment.target.url- : segment.target.path;+ : /^[A-Za-z]:[\\/]/.test(segment.target.path)+ ? encodeURIComponent(segment.target.path)+ : segment.target.path;next.push({type: "link",url,diff --git a/apps/desktop/test/chat-file-reveal-menu.test.mjs b/apps/desktop/test/chat-file-reveal-menu.test.mjsindex 1292c90b8..3d9c9718c 100644--- a/apps/desktop/test/chat-file-reveal-menu.test.mjs+++ b/apps/desktop/test/chat-file-reveal-menu.test.mjs@@ -366,7 +366,7 @@ test("every transcript surface that names a file opens that item", () => {// Inline code, a file link, and a local image each hand their own reference// to that surface; `./` and `../` keep the markdown base beside the path.assert.match(markdown, /openFileMenu\(event, \{ path: text \?\? target\.path, baseDir \}\)/);- assert.match(markdown, /openFileMenu\(event, \{ path: rel, baseDir \}\)/);+ assert.match(markdown, /openFileMenu\(event, \{ path: ref, baseDir \}\)/);assert.match(markdown, /openFileMenu\(event, \{ path: localRef, baseDir \}\)/);assert.match(markdown, /onContextMenu=\{onLocalContextMenu\}/);// A local image that cannot be shown inline keeps a chip, and both carry thediff --git a/apps/desktop/test/chat-links.test.mjs b/apps/desktop/test/chat-links.test.mjsindex baa302d98..bea0c8f44 100644--- a/apps/desktop/test/chat-links.test.mjs+++ b/apps/desktop/test/chat-links.test.mjs@@ -1,5 +1,8 @@import assert from "node:assert/strict";import test from "node:test";+import * as React from "react";+import { renderToStaticMarkup } from "react-dom/server";+import ReactMarkdown from "react-markdown";import {fileDirOf,getToolPreviewTarget,@@ -23,6 +26,10 @@ test("parseFileRef accepts pathy tokens and strips line refs", () => {assert.equal(parseFileRef("docs/Makefile"), "docs/Makefile");assert.equal(parseFileRef("./README.md"), "./README.md");assert.equal(parseFileRef("../adr/0163.md"), "../adr/0163.md");+ assert.equal(parseFileRef("/Users/me/my project/page.md"), "/Users/me/my project/page.md");+ assert.equal(parseFileRef("C:\\demo project\\readme.md"), "C:\\demo project\\readme.md");+ assert.equal(parseFileRef("C:/demo project/readme.md"), "C:/demo project/readme.md");+ assert.equal(parseFileRef("docs/my project/page.md"), "docs/my project/page.md");});test("parseFileRef accepts bare names only with known extensions", () => {@@ -51,6 +58,9 @@ test("toWorkspaceRel maps absolute paths under the root and rejects escapes", ()assert.equal(toWorkspaceRel("../outside.ts", ROOT), null);assert.equal(toWorkspaceRel("~/anything.ts", ROOT), null);assert.equal(toWorkspaceRel("apps/../docs/foo.md", ROOT), "docs/foo.md");+ assert.equal(toWorkspaceRel("C:\\demo project\\readme.md", "C:\\demo project"), "readme.md");+ assert.equal(toWorkspaceRel("c:/DEMO PROJECT/readme.md", "C:\\demo project"), "readme.md");+ assert.equal(toWorkspaceRel("C:\\elsewhere\\readme.md", "C:\\demo project"), null);});test("toWorkspaceRel resolves ./ and ../ against a markdown file directory", () => {@@ -98,27 +108,61 @@ test("resolvePreviewTarget classifies urls and workspace files", () => {});assert.deepEqual(resolvePreviewTarget(`${ROOT}/src/a.ts`, ROOT), {kind: "file",- path: "src/a.ts",+ path: `${ROOT}/src/a.ts`,+ });+ assert.deepEqual(resolvePreviewTarget("/outside/root.ts", ROOT), {+ kind: "file",+ path: "/outside/root.ts",});- assert.equal(resolvePreviewTarget("/outside/root.ts", ROOT), null);assert.equal(isHttpUrl("ftp://example.com"), false);});test("getToolPreviewTarget reads path-like args and fetch urls", () => {assert.deepEqual(getToolPreviewTarget({ path: `${ROOT}/src/a.ts` }, ROOT),- { kind: "file", path: "src/a.ts" },+ { kind: "file", path: `${ROOT}/src/a.ts` },);assert.deepEqual(getToolPreviewTarget({ file_path: "src/b.ts" }, ROOT),{ kind: "file", path: "src/b.ts" },);- assert.equal(getToolPreviewTarget({ path: "/outside/a.ts" }, ROOT), null);+ assert.deepEqual(getToolPreviewTarget({ path: "/outside/a.ts" }, ROOT), {+ kind: "file", path: "/outside/a.ts",+ });assert.deepEqual(getToolPreviewTarget({ url: "https://example.com" }, ROOT),{ kind: "url", url: "https://example.com" },);assert.equal(getToolPreviewTarget({ command: "ls" }, ROOT), null);+ assert.deepEqual(+ getToolPreviewTarget({ path: "C:\\demo project\\readme.md" }, "C:\\demo project"),+ { kind: "file", path: "C:\\demo project\\readme.md" },+ );+});++test("complete spaced and Windows paths are scanned without linking their suffixes", () => {+ const posix = "/Users/me/my project/page.md";+ const windows = "C:\\demo project\\readme.md";+ for (const [path, root] of [[posix, "/Users/me/my project"], [windows, "C:\\demo project"]]) {+ const segments = splitChatText(`Open ${path} now`, root);+ const links = segments.filter((segment) => segment.kind === "target");+ assert.equal(links.length, 1);+ assert.equal(links[0].text, path);+ assert.equal(segments.map((segment) => segment.text).join(""), `Open ${path} now`);+ }+ assert.deepEqual(+ splitChatText("Open /Users/me/my project/page.md now", ROOT)+ .filter((segment) => segment.kind === "target")+ .map((segment) => segment.text),+ [posix],+ );+ const relative = splitChatText("Open docs/my project/page.md now", ROOT);+ assert.deepEqual(relative.filter((segment) => segment.kind === "target").map((segment) => segment.text), ["docs/my project/page.md"]);+ const forward = splitChatText("Open C:/demo project/readme.md now", "C:/demo project");+ assert.deepEqual(forward.filter((segment) => segment.kind === "target").map((segment) => segment.text), ["C:/demo project/readme.md"]);+ assert.deepEqual(resolvePreviewTarget('@"C:\\demo project\\readme.md"', "C:/demo project"), {+ kind: "file", path: "C:\\demo project\\readme.md",+ });});test("splitChatText linkifies embedded refs and keeps literals", () => {@@ -243,20 +287,33 @@ test("splitChatText resolves a unicode absolute path under the root", () => {segments.filter((s) => s.kind === "target" && s.target.kind === "file").map((s) => s.target.path),- ["src/报告.md"],+ [`${ROOT}/src/报告.md`],);});-test("splitChatText leaves outside absolute and home paths as plain text", () => {- // #235: the scanner used to drop the leading "/" (or "~") and chip the- // suffix as a workspace-relative path that could never open.+test("splitChatText keeps outside absolute paths whole and home paths plain", () => {const outside = splitChatText("see /elsewhere/a.ts and ~/Downloads/x.png here",ROOT,);- assert.deepEqual(outside, [- { kind: "text", text: "see /elsewhere/a.ts and ~/Downloads/x.png here" },- ]);+ 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");+});++test("markdown linkification encodes a Windows file path without losing its source text", () => {+ const path = "C:\\demo project\\readme.md";+ const tree = { type: "root", children: [{ type: "paragraph", children: [{ type: "text", value: `Open ${path}` }] }] };+ linkifyMdastTree(tree, "C:\\demo project");+ const link = tree.children[0].children.find((node) => node.type === "link");+ assert.equal(link.url, encodeURIComponent(path));+ assert.equal(link.children[0].value, path);+ const markup = renderToStaticMarkup(+ React.createElement(ReactMarkdown, {+ remarkPlugins: [remarkChatFileLinks("C:\\demo project")],+ children: `Open ${path}`,+ }),+ );+ assert.match(markup, /href="C%3A%5Cdemo%20project%5Creadme.md"/);});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 fe4750a65..1444f0db1 100644--- a/apps/desktop/test/chat-ref-resolve.test.mjs+++ b/apps/desktop/test/chat-ref-resolve.test.mjs@@ -8,7 +8,7 @@ import { fileURLToPath, pathToFileURL } from "node:url";const here = dirname(fileURLToPath(import.meta.url));register(pathToFileURL(join(here, "helpers/ts-import-hooks.mjs")));-const { parseChatRef, resolveChatFileRef } = await import(+const { isChatRefOutsideRoots, parseChatRef, resolveChatFileRef } = await import("../electron/main/chat-ref-resolve.ts");@@ -80,14 +80,21 @@ test("a bare leaf name resolves through the workspace index", async () => {assert.equal(match?.relativePath, "src/dir/openimage.js");});-test("the reported case: a POSIX absolute path from a tool call is completed by tail", async () => {- // The agent printed `/root/dir/openimage.js`; on this machine the real file- // only ever existed as `src/dir/openimage.js` inside the project.+test("an absolute path outside the project cannot select a same-name file by tail", async () => {const workspace = tempTree("ws", ["src/dir/openimage.js"]);const match = await resolve("/root/dir/openimage.js", { workspace });- assert.equal(match?.root, "workspace");- assert.equal(match?.matchedBy, "path-suffix");- assert.equal(match?.relativePath, "src/dir/openimage.js");+ assert.equal(match, null);+});++test("an exact absolute path with spaces resolves only inside an allowed root", async () => {+ const workspace = tempTree("spaced ws", ["my project/page.md", "other/page.md"]);+ const absolute = join(workspace, "my project", "page.md");+ const match = await resolve(absolute, { workspace });+ 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);});test("a longer matching tail beats a bare leaf name", async () => {diff --git a/apps/desktop/test/markdown-prose-style.test.mjs b/apps/desktop/test/markdown-prose-style.test.mjsindex b83cb64a5..226e40fff 100644--- a/apps/desktop/test/markdown-prose-style.test.mjs+++ b/apps/desktop/test/markdown-prose-style.test.mjs@@ -62,8 +62,9 @@ test("markdown resolves relative file links against a base directory", () => {assert.match(markdownSource, /remarkChatFileLinks/);assert.match(markdownSource,- /toWorkspaceRel\(safeDecodeUri\(href\), root, baseDir\)/,+ /toWorkspaceRel\(decoded, root, baseDir\)/,);+ assert.match(markdownSource, /safeDecodeUri\(href\)/);assert.match(filesTabSource, /baseDir=\{fileDirOf\(selected\)\}/);});diff --git a/apps/desktop/test/tool-row-file-refs.test.mjs b/apps/desktop/test/tool-row-file-refs.test.mjsindex 4da37f78f..be3b235de 100644--- a/apps/desktop/test/tool-row-file-refs.test.mjs+++ b/apps/desktop/test/tool-row-file-refs.test.mjs@@ -56,6 +56,7 @@ const state = {/** What the next `fs.resolveRef` reply is; each case sets it. */let nextMatch = null;+let nextReason = null;let resolveFails = false;const workPanelTabs = loadModule("../src/lib/work-panel-tabs.ts", {});@@ -68,7 +69,7 @@ const { useOpenPreviewTarget } = loadModule("../src/hooks/use-preview-target.ts"fsResolveRef: async (ref) => {calls.resolved.push(ref);if (resolveFails) throw new Error("host unavailable");- return { match: nextMatch };+ return { match: nextMatch, ...(nextReason ? { reason: nextReason } : {}) };},},},@@ -85,6 +86,7 @@ function reset({ pluginView = false } = {}) {? [{ pluginId: "pi.file-manager", viewId: "manager" }]: [];nextMatch = null;+ nextReason = null;resolveFails = false;}@@ -135,6 +137,16 @@ test("a project file a tool surface names opens in the bundled file view", asyncassert.deepEqual(calls.toasts, []);});+test("a Windows tool path reaches resolution intact and opens its exact project file", async () => {+ reset({ pluginView: true });+ const path = "C:\\demo project\\readme.md";+ nextMatch = projectMatch({ relativePath: "readme.md", absolutePath: path, matchedBy: "exact-absolute" });+ await click({ kind: "file", path });+ assert.deepEqual(calls.resolved, [path]);+ assert.equal(calls.tabs[0].location, "readme.md");+ assert.deepEqual(calls.toasts, []);+});+test("without the file view a project file keeps falling back to the host file tab", async () => {reset();nextMatch = projectMatch();@@ -186,13 +198,22 @@ test("a reference nothing answers reports itself and opens nothing", async () =>assert.equal(calls.toasts[0][0], "chat.fileRefMissing:missing-helper.js");});+test("an absolute tool path outside allowed roots reports the access limit", async () => {+ reset({ pluginView: true });+ nextReason = "outside-allowed-roots";+ await click({ kind: "file", path: "C:\\elsewhere\\readme.md" });+ assert.deepEqual(calls.resolved, ["C:\\elsewhere\\readme.md"]);+ assert.deepEqual(calls.tabs, []);+ assert.equal(calls.toasts[0][0], "chat.fileRefRestricted:C:\\elsewhere\\readme.md");+});+test("a failing resolve is reported instead of opening a panel", async () => {reset({ pluginView: true });resolveFails = true;await click({ kind: "file", path: "src/dir/a.ts" });assert.deepEqual(calls.tabs, []);assert.deepEqual(calls.files, []);- assert.equal(calls.toasts[0][0], "chat.fileRefMissing:src/dir/a.ts");+ assert.equal(calls.toasts[0][0], "chat.fileRefLookupFailed:");});test("a URL target keeps the embedded browser and never reaches file resolution", async () => {diff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.mdindex cd7b15617..10cfe62bf 100644--- a/docs/spec/03-runtime/01-ipc-protocol.md+++ b/docs/spec/03-runtime/01-ipc-protocol.md@@ -1790,7 +1790,7 @@ Renderer IPC kept for the Plan-safe preview facade and URL fallback:`.mp4` symlink inside its private app-data directory before the OS handoff,so the extensionless blob has a media association without copying its bytes.- `fs/resolveRef({ref, sessionId?})` → `FsChatRefResolveResult`- (`{ match: FsChatRefMatch | null }`, the match naming the answering `root`+ (`{ match: FsChatRefMatch | null, reason?: "outside-allowed-roots" }`, the match naming the answering `root`(`workspace` / `scratch` / `attachments`), the `relativePath` relative to thatroot, the absolute `absolutePath`, `matchedBy` (`exact-relative` /`exact-absolute` / `path-suffix` / `basename`), and — for a `workspace` match@@ -1798,8 +1798,8 @@ Renderer IPC kept for the Plan-safe preview facade and URL fallback:that answered); `sessionId` selects thesession whose scratch store is searched. Completes a file reference the agentprinted in chat, because the renderer cannot see the session's own scratch- store: an absolute reference that already names a real file inside a known- root wins outright, and an `attachments/<sha256>` blob resolves against the+ store: an absolute reference only matches that exact file inside a known+ root, and an `attachments/<sha256>` blob resolves against theattachment store directly; otherwise the roots are searched in priority order— the open project first, the session's own scratch store(`<data_dir>/scratch/<sessionId>/`, ADR 0124) second, the attachment store@@ -1810,7 +1810,9 @@ Renderer IPC kept for the Plan-safe preview facade and URL fallback:and the match names the folder that answered. Inside one root an exact pathbeats a shorthand; among shorthands the longest matching tail wins, then theshallowest path. The files-panel ignore set applies. A reference that matches- nothing returns `match: null`; resolving never opens anything (ADR 0262).+ nothing returns `match: null`; an absolute path outside every allowed root+ also returns `reason: "outside-allowed-roots"`, without trying a same-name+ file inside a root. Resolving never opens anything (ADR 0262).- `fs/list` stays workspace-only; traversal outside is rejected(`INVALID_ARGUMENT`).diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex f51e0a2b6..c42218364 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -1716,10 +1716,11 @@ Single message render — either user (plaintext) or assistant (markdown streamiConfirmation is scoped to the message text, workspace path, and session; changingany of these discards old results and cancels queued work. Newly createdfiles are reconsidered when the message remounts or its scope changes, not- by polling. Non-ASCII filenames remain supported. Absolute and `~/` tokens are matched whole,- and one outside the workspace (or any home path) stays plain text rather- than rendering a chip that could never open — containment is unchanged- (D322). Clicking a chip+ by polling. Non-ASCII filenames, spaces, and Windows drive/backslash paths+ remain whole candidates. User-message paths outside the allowed roots stay+ plain after verification, while assistant references and tool paths remain+ clickable so the opener can explain the access limit. Home paths stay plain.+ Clicking a chipcompletes the reference through `pi-desktop/fs/resolveRef` — the whole openproject is searched, its group's folders primary first (ADR 0263) — and openswhere it resolved: a project file in the bundled `pi.file-manager` work-panel@@ -1729,7 +1730,8 @@ Single message render — either user (plaintext) or assistant (markdown streamiview as a project-relative path and a sibling-folder file as an absolute one,which is also how scratch and attachment files are addressed. A resolvedimage thumbnail resolves and opens the same way. A chip whose reference- matches nothing opens nothing and reports itself; the OS default application+ matches nothing opens nothing and reports itself; an absolute path outside+ every allowed root reports the access limit separately. The OS default applicationis no longer what this click does.HTTP(S) URLs remain inline text links. Bare URLs preserve balanced parenthesesin paths, queries, and fragments; an unmatched closing parenthesis wrappingdiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex d81b99fbb..b0dec7248 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -11752,6 +11752,27 @@ are withdrawn with ADR 0165.(`apps/desktop/test/chat-ref-resolve.test.mjs`); full UI journey Draft (runonly in a capable environment when this surface changes)+#### E2E-CHAT-spaced-absolute-file-paths++- **Preconditions**: On Windows, open a project rooted at a directory whose+ name contains a space. Create `readme.md` there through a chat Write tool+ call; keep a same-name file in another project directory and one file outside+ every allowed root. Repeat the path-recognition checks with a POSIX project+ path containing a space on macOS or Linux.+- **Steps**: 1) Click the full path in the Write row. 2) Click the same full+ path 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.+- **Expected**: Every allowed reference opens the exact file in the existing+ side file view; no path is truncated to its suffix or redirected to the+ same-name file. The outside path opens nothing and reports the access limit,+ while a missing in-root file reports that no file matches.+- **Specs linked**: `03-runtime/01-ipc-protocol.md` § fs,+ `04-ux/08-component-spec.md` §8.3.+- **Acceptance**: C (conversation & stream), D (workspace), Quality+- **Milestone**: M5+- **Status**: Unit/component-covered (`chat-links.test.mjs`,+ `chat-ref-resolve.test.mjs`, `tool-row-file-refs.test.mjs`); full UI journey Draft.+#### E2E-CHAT-file-ref-opens-the-surface-that-owns-it- **Preconditions**: The bundled File Manager plugin is loaded and enabled anddiff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.tsindex cb867c419..04ba2765d 100644--- a/packages/i18n/src/locales/de/index.ts+++ b/packages/i18n/src/locales/de/index.ts@@ -328,6 +328,8 @@ export const de = {"errorModel": "Modell","previewFile": "Vorschau im Seitenbereich","fileRefMissing": "Keine Datei entspricht {{name}}",+ "fileRefRestricted": "{{name}} liegt außerhalb der für die App zugänglichen Orte",+ "fileRefLookupFailed": "Dieser Dateiverweis konnte nicht geprüft werden.","revealFileInFolder": "Im Ordner anzeigen","fileRevealFailed": "Die Datei konnte nicht im Ordner angezeigt werden.","copyFullPath": "Vollständigen Pfad kopieren",diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex bdaf1bc7d..6ed19ac0d 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -335,6 +335,8 @@ export const en = {errorModel: "Model",previewFile: "Preview in the side panel",fileRefMissing: "No file matches {{name}}",+ fileRefRestricted: "{{name}} is outside the locations this app can access",+ fileRefLookupFailed: "Could not check this file reference.",revealFileInFolder: "Show in folder",fileRevealFailed: "Could not show the file in its folder.",copyFullPath: "Copy full path",diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.tsindex 7d9acfe17..a206ab72f 100644--- a/packages/i18n/src/locales/es/index.ts+++ b/packages/i18n/src/locales/es/index.ts@@ -328,6 +328,8 @@ export const es = {"errorModel": "Modelo","previewFile": "Vista previa en el panel lateral","fileRefMissing": "Ningún archivo coincide con {{name}}",+ "fileRefRestricted": "{{name}} está fuera de las ubicaciones a las que puede acceder la aplicación",+ "fileRefLookupFailed": "No se pudo comprobar esta referencia de archivo.","revealFileInFolder": "Mostrar en carpeta","fileRevealFailed": "No se pudo mostrar el archivo en su carpeta.","copyFullPath": "Copiar ruta completa",diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.tsindex 724e751a3..970526ed2 100644--- a/packages/i18n/src/locales/fr/index.ts+++ b/packages/i18n/src/locales/fr/index.ts@@ -328,6 +328,8 @@ export const fr = {"errorModel": "Modèle","previewFile": "Aperçu dans le panneau latéral","fileRefMissing": "Aucun fichier ne correspond à {{name}}",+ "fileRefRestricted": "{{name}} se trouve hors des emplacements accessibles à l'application",+ "fileRefLookupFailed": "Impossible de vérifier cette référence de fichier.","revealFileInFolder": "Afficher dans le dossier","fileRevealFailed": "Impossible d'afficher le fichier dans son dossier.","copyFullPath": "Copier le chemin complet",diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.tsindex f4d96e985..1310add2b 100644--- a/packages/i18n/src/locales/ko/index.ts+++ b/packages/i18n/src/locales/ko/index.ts@@ -337,6 +337,8 @@ export const ko = {errorModel: "모델",previewFile: "사이드 패널에서 미리 보기",fileRefMissing: "{{name}}과(와) 일치하는 파일이 없습니다",+ fileRefRestricted: "{{name}}은(는) 앱이 접근할 수 있는 위치 밖에 있습니다",+ fileRefLookupFailed: "이 파일 참조를 확인할 수 없습니다.",revealFileInFolder: "폴더에서 보기",fileRevealFailed: "폴더에서 파일을 표시할 수 없습니다.",copyFullPath: "전체 경로 복사",diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.tsindex 452502bb8..4f6848f6d 100644--- a/packages/i18n/src/locales/pt-BR/index.ts+++ b/packages/i18n/src/locales/pt-BR/index.ts@@ -326,6 +326,8 @@ export const ptBR = {errorModel: "Modelo",previewFile: "Pré-visualizar no painel lateral",fileRefMissing: "Nenhum arquivo corresponde a {{name}}",+ fileRefRestricted: "{{name}} está fora dos locais que o aplicativo pode acessar",+ fileRefLookupFailed: "Não foi possível verificar esta referência de arquivo.",revealFileInFolder: "Mostrar na pasta",fileRevealFailed: "Não foi possível mostrar o arquivo na pasta.",copyFullPath: "Copiar caminho completo",diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.tsindex 35f54ab25..e0a0deadb 100644--- a/packages/i18n/src/locales/tr/index.ts+++ b/packages/i18n/src/locales/tr/index.ts@@ -337,6 +337,8 @@ export const tr = {errorModel: "Model",previewFile: "Yan panelde önizle",fileRefMissing: "{{name}} ile eşleşen dosya yok",+ fileRefRestricted: "{{name}} uygulamanın erişebildiği konumların dışında",+ fileRefLookupFailed: "Bu dosya başvurusu denetlenemedi.",revealFileInFolder: "Klasörde göster",fileRevealFailed: "Dosya klasörde gösterilemedi.",copyFullPath: "Tam yolu kopyala",diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex ec16c49a1..558c99d01 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -329,6 +329,8 @@ export const zhCN = {errorModel: "模型",previewFile: "在侧边面板预览",fileRefMissing: "没有匹配 {{name}} 的文件",+ fileRefRestricted: "{{name}} 不在应用允许访问的范围内",+ fileRefLookupFailed: "无法检查此文件引用。",revealFileInFolder: "在文件夹中显示",fileRevealFailed: "无法在文件夹中打开该文件。",copyFullPath: "复制完整地址",diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.tsindex b3b055ddb..6aa169131 100644--- a/packages/i18n/src/locales/zh-TW/index.ts+++ b/packages/i18n/src/locales/zh-TW/index.ts@@ -329,6 +329,8 @@ export const zhTW = {errorModel: "模型",previewFile: "在側邊面板預覽",fileRefMissing: "沒有匹配 {{name}} 的檔案",+ fileRefRestricted: "{{name}} 不在應用程式允許存取的範圍內",+ fileRefLookupFailed: "無法檢查此檔案參照。",revealFileInFolder: "在資料夾中顯示",fileRevealFailed: "無法在資料夾中開啟該檔案。",copyFullPath: "複製完整位址",diff --git a/packages/shared/src/types/filesystem.ts b/packages/shared/src/types/filesystem.tsindex 3264edc59..6bbf03e8a 100644--- a/packages/shared/src/types/filesystem.ts+++ b/packages/shared/src/types/filesystem.ts@@ -128,4 +128,6 @@ export type FsChatRefMatch = {export type FsChatRefResolveResult = {match: FsChatRefMatch | null;+ /** The supplied absolute path is not inside a project, scratch, or attachment root. */+ reason?: "outside-allowed-roots";};