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(desktop): open chat file refs to absolute paths outside project roots
zszz31fa498caf79b
diff --git a/apps/desktop/electron/main/chat-ref-resolve.ts b/apps/desktop/electron/main/chat-ref-resolve.tsindex eccea42ac..34e25f5ff 100644--- a/apps/desktop/electron/main/chat-ref-resolve.ts+++ b/apps/desktop/electron/main/chat-ref-resolve.ts@@ -1,2 +1,2 @@-export { isChatRefOutsideRoots, parseChatRef, resolveChatFileRef } from "@pi-desktop/host-runtime";+export { isChatRefOutsideRoots, parseChatRef, resolveChatFileRef, resolveExternalChatRef } from "@pi-desktop/host-runtime";export type { ChatRefRoots, ChatRefContainmentRoot, ParsedChatRef } from "@pi-desktop/host-runtime";diff --git a/apps/desktop/electron/main/ipc/workspace-ipc.ts b/apps/desktop/electron/main/ipc/workspace-ipc.tsindex 0c4526614..047d7f176 100644--- a/apps/desktop/electron/main/ipc/workspace-ipc.ts+++ b/apps/desktop/electron/main/ipc/workspace-ipc.ts@@ -36,10 +36,12 @@ import {listDir,readOpenableFile,readOpenableImage,+ readUserOpenableFile,resolveRealOpenablePath,+ resolveUserOpenablePath,} from "@pi-desktop/host-runtime";import { openableMp4Path } from "../open-attachment-video";-import { isChatRefOutsideRoots, resolveChatFileRef } from "../chat-ref-resolve";+import { isChatRefOutsideRoots, resolveChatFileRef, resolveExternalChatRef } from "../chat-ref-resolve";import { rebaseWorktreeRef, type WorktreeRefContext } from "../worktree-ref";import { getWorkspaceFileIndex, searchWorkspaceFiles } from "../fs-index";import {@@ -932,7 +934,7 @@ export function registerWorkspaceIpc({throw error;}}- return readOpenableFile(+ return readUserOpenableFile(requested,workspaceRoot,await fsExtraRoots(workspaceRoot),@@ -973,7 +975,7 @@ export function registerWorkspaceIpc({throw error;}}- const target = await resolveRealOpenablePath(+ const target = await resolveUserOpenablePath(requested,workspaceRoot,await fsExtraRoots(workspaceRoot),@@ -992,7 +994,7 @@ export function registerWorkspaceIpc({if (remote && !(await isLocalStoredFile(String(input.path ?? "")))) throw Object.assign(new Error("remote paths cannot be opened on this computer"), { errorCode: ErrorCodes.INVALID_ARGUMENT });const workspaceRoot = await optionalWorkspaceRoot(input.sessionId);const requested = String(input.path ?? "").trim();- const target = await resolveRealOpenablePath(+ const target = await resolveUserOpenablePath(requested,workspaceRoot,await fsExtraRoots(workspaceRoot),@@ -1076,7 +1078,9 @@ export function registerWorkspaceIpc({attachments: join(dataDir, "attachments"),};if (await isChatRefOutsideRoots(ref, roots)) {- return { match: null, reason: "outside-allowed-roots" };+ // An exact absolute path outside the managed roots opens when it names+ // an existing regular file (ADR 0339).+ return resolveExternalChatRef(ref);}return { match: await resolveChatFileRef(ref, roots) };},diff --git a/apps/desktop/src/components/Markdown.tsx b/apps/desktop/src/components/Markdown.tsxindex e34ca6550..9093a36d3 100644--- a/apps/desktop/src/components/Markdown.tsx+++ b/apps/desktop/src/components/Markdown.tsx@@ -77,6 +77,7 @@ import {} from "../hooks/use-chat-file-menu";import {handleMarkdownFileLinkClick,+ markdownLinkFileTarget,remarkChatFileLinks,resolvePreviewTarget,safeDecodeUri,@@ -624,9 +625,7 @@ function Anchor({action on the file's folder. `./` and `../` resolve against the markdownfile on screen, which is the base this row already holds.*/- const decoded = safeDecodeUri(href);- const target = resolvePreviewTarget(decoded, root, baseDir);- const ref = target?.kind === "file" ? target.path : toWorkspaceRel(decoded, root, baseDir);+ const ref = markdownLinkFileTarget(href, root, baseDir)?.path;if (!ref || !openFileMenu) return;openFileMenu(event, { path: ref, baseDir });return;diff --git a/apps/desktop/src/lib/chat-links.ts b/apps/desktop/src/lib/chat-links.tsindex 83496ee92..59fc399c5 100644--- a/apps/desktop/src/lib/chat-links.ts+++ b/apps/desktop/src/lib/chat-links.ts@@ -289,19 +289,41 @@ export function handleMarkdownFileLinkClick(openFileRef: (path: string, baseDir?: string, mimeType?: string,position?: { line?: number; column?: number }) => void,): boolean {- const decoded = safeDecodeUri(href);- const target = resolvePreviewTarget(decoded, root, baseDir);- const ref = target?.kind === "file" ? target.path : toWorkspaceRel(decoded, root, baseDir);- if (!ref) return false;+ const target = markdownLinkFileTarget(href, root, baseDir);+ if (!target) return false;event.preventDefault();- if (target?.kind === "file" && target.line !== undefined) {- openFileRef(ref, baseDir, undefined, { line: target.line, column: target.column });+ if (target.line !== undefined) {+ openFileRef(target.path, baseDir, undefined, { line: target.line, column: target.column });} else {- openFileRef(ref, baseDir);+ openFileRef(target.path, baseDir);}return true;}+/**+ * The file a local Markdown link destination names, shared by click and the+ * context menu. A link destination is an explicit reference, so an absolute+ * path counts even without a file extension (`/etc/hosts`, `.../Makefile`):+ * the extension heuristic only keeps prose from turning into chips. The main+ * process still decides whether the file exists and may open (ADR 0339).+ */+export function markdownLinkFileTarget(+ href: string,+ root: string | null | undefined,+ baseDir: string | null | undefined,+): { path: string; line?: number; column?: number } | null {+ const decoded = safeDecodeUri(href);+ const target = resolvePreviewTarget(decoded, root, baseDir);+ if (target?.kind === "file") return target;+ const rel = toWorkspaceRel(decoded, root, baseDir);+ if (rel) return { path: rel };+ const trimmed = decoded.trim();+ const path = stripLineRef(trimmed);+ if (!path || /[\n\0]/.test(path) || /[\\/]$/.test(path) || !isAbsoluteFilePath(path)) return null;+ const position = path === trimmed ? null : parseFileRefPosition(trimmed);+ return { path, ...(position ?? {}) };+}+/** Tool-call args → preview target (Read/Write/Edit paths, fetch URLs). */export function getToolPreviewTarget(args: unknown,diff --git a/apps/desktop/test/chat-links.test.mjs b/apps/desktop/test/chat-links.test.mjsindex ea04b6db6..2f5b0299b 100644--- a/apps/desktop/test/chat-links.test.mjs+++ b/apps/desktop/test/chat-links.test.mjs@@ -957,3 +957,32 @@ test("session links segment as their own target", () => {assert.equal(resolvePreviewTarget("pi-desktop://session/remote:abc", ROOT), null);assert.equal(resolvePreviewTarget("pi-desktop://session/", ROOT), null);});++test("an absolute Markdown link to an extensionless file still reaches the file opener", () => {+ // The link destination is explicit, so the extension heuristic that keeps+ // prose from turning into chips does not apply. The main process decides+ // whether the file exists and may open (ADR 0339).+ for (const [source, root, expected] of [+ ["[config](</Users/me/.ssh/config>)", null, ["/Users/me/.ssh/config", undefined]],+ ["[Makefile](</tmp/build dir/Makefile>)", "/Users/me/project", ["/tmp/build dir/Makefile", undefined]],+ ["[LICENSE](<D:/vendor/LICENSE>)", "D:/person", ["D:/vendor/LICENSE", undefined]],+ ["[notes](</tmp/notes:4>)", null, ["/tmp/notes", undefined, undefined, { line: 4, column: undefined }]],+ ]) {+ const markup = renderSanitizedMarkdown(source);+ const href = markup.match(/<a href="([^"]+)"/)?.[1];+ assert.ok(href, source);+ const calls = [];+ let prevented = false;+ const handled = handleMarkdownFileLinkClick(+ { preventDefault: () => { prevented = true; } }, href, root, undefined,+ (...args) => calls.push(args));+ assert.equal(handled, true, source);+ assert.equal(prevented, true, source);+ assert.deepEqual(calls, [expected], source);+ }+ // A home path is not an absolute link destination and opens nothing.+ const calls = [];+ assert.equal(handleMarkdownFileLinkClick({ preventDefault() {} }, "~/.ssh/config", null, undefined,+ (...args) => calls.push(args)), false);+ assert.deepEqual(calls, []);+});diff --git a/apps/desktop/test/chat-ref-external.test.mjs b/apps/desktop/test/chat-ref-external.test.mjsnew file mode 100644index 000000000..3f692adaa--- /dev/null+++ b/apps/desktop/test/chat-ref-external.test.mjs@@ -0,0 +1,128 @@+import assert from "node:assert/strict";+import test from "node:test";+import { mkdirSync, mkdtempSync, realpathSync, symlinkSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { register } from "node:module";+import { fileURLToPath, pathToFileURL } from "node:url";++const here = dirname(fileURLToPath(import.meta.url));+register(pathToFileURL(join(here, "helpers/ts-import-hooks.mjs")));+const { isChatRefOutsideRoots, resolveChatFileRef, resolveExternalChatRef } = await import(+ "../../../packages/host-runtime/src/chat-ref-resolve.ts"+);+const { readUserOpenableFile, resolveExternalFile, resolveUserOpenablePath } =+ await import("../../../packages/host-runtime/src/external-files.ts");++/**+ * Issue #1837 / ADR 0339: the agent names a file by its exact absolute path+ * outside the open project (a download, a chat client's folder, the temp+ * directory) and the user clicks it. That click must open that exact file, and+ * no same-name file is looked up anywhere else.+ */++function tempTree(name, files) {+ const root = realpathSync(mkdtempSync(join(tmpdir(), `pi-ext-ref-${name}-`)));+ for (const file of files) {+ const target = join(root, ...file.split("/"));+ mkdirSync(dirname(target), { recursive: true });+ writeFileSync(target, `${file}\n`);+ }+ return root;+}++function projectRoots(workspace, extra = {}) {+ return { project: [{ path: workspace, name: "ws", primary: true }], ...extra };+}++test("an exact absolute path outside every root resolves to that file", async () => {+ const workspace = tempTree("ws", ["src/a.ts"]);+ const outside = tempTree("outside", ["专业实践 考核.txt", "notes/report.md"]);+ const target = join(outside, "专业实践 考核.txt");+ const roots = projectRoots(workspace);++ assert.equal(await isChatRefOutsideRoots(target, roots), true);+ assert.equal(await resolveChatFileRef(target, roots), null);+ const result = await resolveExternalChatRef(target);+ assert.deepEqual(result, {+ match: {+ root: "external",+ relativePath: "专业实践 考核.txt",+ absolutePath: target,+ matchedBy: "exact-absolute",+ },+ });++ const withLine = await resolveExternalChatRef(`${join(outside, "notes", "report.md")}:3`);+ assert.equal(withLine.match?.absolutePath, join(outside, "notes", "report.md"));+ const withAnchor = await resolveExternalChatRef(`${join(outside, "notes", "report.md")}#L2-L4`);+ assert.equal(withAnchor.match?.absolutePath, join(outside, "notes", "report.md"));+});++test("a missing external file is a miss, not an access limit", async () => {+ const outside = tempTree("missing", ["here.txt"]);+ assert.deepEqual(await resolveExternalChatRef(join(outside, "gone.txt")), { match: null });+ assert.deepEqual(await resolveExternalChatRef(join(outside)), { match: null });+});++test("a shorthand never resolves outside the managed roots", async () => {+ const workspace = tempTree("ws-short", ["src/a.ts"]);+ const roots = projectRoots(workspace);+ assert.equal(await isChatRefOutsideRoots("report.md", roots), false);+ assert.equal(await resolveChatFileRef("report.md", roots), null);+ assert.equal((await resolveExternalChatRef("report.md")).match, null);+ assert.equal((await resolveExternalChatRef("~/report.md")).match, null);+ assert.equal((await resolveExternalFile("notes/report.md")).kind, "notAbsolute");+});++test("dotfiles and credential-looking paths open like any other file", async () => {+ // A click only shows the file to the user on this machine; nothing reaches+ // the model or the network, so no path shape is withheld (ADR 0339).+ const outside = tempTree("dot", [".ssh/config", "app/.env", "keys/server.pem", "repo/.git/config"]);+ for (const file of [".ssh/config", "app/.env", "keys/server.pem", "repo/.git/config"]) {+ const target = join(outside, ...file.split("/"));+ assert.deepEqual(await resolveExternalChatRef(target), {+ match: {+ root: "external",+ relativePath: file.split("/").pop(),+ absolutePath: target,+ matchedBy: "exact-absolute",+ },+ }, file);+ }+});++test("symlinks and dot-dot spellings resolve to the real file", async () => {+ const outside = tempTree("link", ["data/real.txt", "plain/readme.txt"]);+ const link = join(outside, "plain", "alias.txt");+ symlinkSync(join(outside, "data", "real.txt"), link);+ assert.equal((await resolveExternalChatRef(link)).match?.absolutePath, join(outside, "data", "real.txt"));+ const dotted = `${join(outside, "plain")}/../data/real.txt`;+ assert.deepEqual(await resolveExternalFile(dotted), { kind: "file", path: join(outside, "data", "real.txt") });+ const dangling = join(outside, "plain", "dangling.txt");+ symlinkSync(join(outside, "data", "gone.txt"), dangling);+ assert.deepEqual(await resolveExternalFile(dangling), { kind: "missing" });+});++test("scratch keeps answering through containment before the external rule", async () => {+ const dataDir = tempTree("data", ["scratch/s1/out.md"]);+ const scratch = join(dataDir, "scratch");+ assert.equal(+ await resolveUserOpenablePath(join(scratch, "s1", "out.md"), null, [scratch]),+ join(scratch, "s1", "out.md"),+ );+});++test("fs/read admits an exact absolute external file but never a shorthand", async () => {+ const workspace = tempTree("ws-read", ["src/a.ts"]);+ const outside = tempTree("read", ["report.md", ".ssh/config"]);+ const preview = await readUserOpenableFile(join(outside, "report.md"), workspace, []);+ assert.equal(preview.kind, "text");+ assert.equal(preview.content, "report.md\n");+ const dotfile = await readUserOpenableFile(join(outside, ".ssh", "config"), workspace, []);+ assert.equal(dotfile.content, ".ssh/config\n");+ await assert.rejects(readUserOpenableFile(outside, workspace, []), /path outside allowed roots/);+ await assert.rejects(readUserOpenableFile("report.md", workspace, []), /path outside allowed roots/);+ const inside = await readUserOpenableFile("src/a.ts", workspace, []);+ assert.equal(inside.content, "src/a.ts\n");+});diff --git a/apps/desktop/test/markdown-prose-style.test.mjs b/apps/desktop/test/markdown-prose-style.test.mjsindex 6d963da9c..32e80434b 100644--- a/apps/desktop/test/markdown-prose-style.test.mjs+++ b/apps/desktop/test/markdown-prose-style.test.mjs@@ -66,7 +66,7 @@ test("markdown resolves relative file links against a base directory", () => {markdownSource,/toWorkspaceRel\(decoded, root, baseDir\)/,);- assert.match(markdownSource, /safeDecodeUri\(href\)/);+ assert.match(markdownSource, /markdownLinkFileTarget\(href, root, baseDir\)/);assert.match(filesTabSource, /baseDir=\{fileDirOf\(selected\)\}/);});diff --git a/docs/adr/0262-chat-file-refs-open-in-the-file-view.md b/docs/adr/0262-chat-file-refs-open-in-the-file-view.mdindex 2dd41f3c0..9d09e2158 100644--- a/docs/adr/0262-chat-file-refs-open-in-the-file-view.md+++ b/docs/adr/0262-chat-file-refs-open-in-the-file-view.md@@ -92,6 +92,11 @@ work-panel tab already carries was honoured by main for `pi.browser` only.This is deliberate and is why the plugin's `safetyNotes` states the exceptioninstead of claiming the project-root containment still covers everything itreads.+ ADR 0339 drops root containment for the host as well: `fs/resolveRef`,+ `fs/read`, `fs/reveal`, and `fs/open` open an exact absolute path outside the+ managed roots when it names an existing regular file. The host applies no+ deny list, because its file view only shows the file to the user who clicked+ it; the plugin keeps its own, since plugin code receives the bytes.5. **The bundled copy moves to v0.4.0** through ADR 0241's re-sync procedure, andthe same release is published to the plugin center: the marketplace and thebundled copy ship the same bytes.diff --git a/docs/adr/0339-chat-file-refs-open-absolute-files-outside-managed-roots.md b/docs/adr/0339-chat-file-refs-open-absolute-files-outside-managed-roots.mdnew file mode 100644index 000000000..b12112a61--- /dev/null+++ b/docs/adr/0339-chat-file-refs-open-absolute-files-outside-managed-roots.md@@ -0,0 +1,87 @@+# ADR 0339: Chat file references open absolute files outside the managed roots++- Status: Accepted+- Date: 2026-11-03+- Deciders: PI-Desktop maintainers+- Related: ADR 0262 (chat file refs open in the file view), ADR 0172 (fs read+ containment), ADR 0249 / ADR 0263 (project folder groups),+ `docs/spec/03-runtime/01-ipc-protocol.md` § fs, issue #1837+- Amends: ADR 0262 §4++## Context++The agent is instructed to reference files by their exact absolute path, and+it routinely works on files outside the open project: a download, a chat+client's folder, the system temporary directory, or any path in a session with+no project at all. The main process answered `fs/resolveRef`, `fs/read`,+`fs/reveal`, and `fs/open` by **root containment** — the project folders, the+session scratch store, the whole scratch store, and the attachment store. Every+correctly written absolute link to a file outside those roots therefore+reported "outside the locations this app can access" and could not be opened+(#1722 follow-up, #1837).++The restriction protected nothing. The agent reads and writes those files with+its own tools, and a renderer that can issue arbitrary IPC already controls the+agent. Opening a file the user clicked shows it to that same user on this+machine: the bytes reach neither the model nor the network. A credential deny+list was considered to stop a prompt-injected link to+`~/.ssh/id_ed25519`, but such a click only shows the user their own file — there+is no disclosure to defend against. Comparable agent desktops (ZCode 3.16)+open any clicked local file, dotfiles included, and hand any file to the OS+default application without a deny list.++## Decision++1. For a **user-initiated open of an exact absolute path** outside every+ managed root, the host replaces containment with one shape check: the path+ is absolute (no `~`, no relative shorthand, no `attachments/<sha256>`) and+ its real path is an existing regular file. No path is withheld, dotfile+ folders such as `.ssh` included.+2. The rule lives in one module, `packages/host-runtime/src/external-files.ts`+ (`resolveExternalFile`, `resolveUserOpenablePath`, `readUserOpenableFile`),+ and is applied by `fs/read`, `fs/reveal`, and `fs/open`. Containment still+ answers first, unchanged. `fs/resolveRef` answers an absolute outside+ reference with `resolveExternalChatRef`: a match with the new+ `root: "external"`, `matchedBy: "exact-absolute"`, or `match: null` when no+ regular file is there.+3. A shorthand never resolves outside the managed roots, and an outside+ absolute path never falls back to a same-name file inside a root.+4. A Markdown link whose destination is an absolute path reaches the opener+ even without a file extension (`/etc/hosts`, `.ssh/config`); the host, not a+ renderer filename heuristic, decides. Bare prose tokens keep the extension+ heuristic that decides which of them become chips.+5. Unchanged: `fs/list` (project only), `fs/readImageDataUrl` (inline chat+ images load without a click, so a model-written image reference must not+ render an arbitrary local image), remote and headless-host file reads+ (`apps/pi-host`), the `pi.file-manager` plugin's own deny list (plugin code+ receives the bytes), and the renderer routing, which already sends a+ non-project match to the host `file:` tab. An external `.html` file opens as+ source there, never in the side browser.++## Consequences++- Clicking a correct absolute link to an ordinary file anywhere on the machine+ opens it; sessions without a project and temporary directories work.+- An exact absolute path to an existing outside file now verifies as a chip in+ user messages too.+- `fs/open` can hand any such file to its OS default application, including a+ script or application bundle that the OS runs when "opened". That is the same+ capability the agent already has through its shell and that project files+ already had, and it still requires the user to choose the default-app+ destination.+- `FsChatRefRoot` gains `"external"`. Consumers that switch on the root treat+ any value other than `workspace` as an absolute-path file, so no consumer+ changes. `reason: "outside-allowed-roots"` keeps its shape and remains only+ for an outside reference that is not an exact absolute path.++## Alternatives considered++- **Credential deny list on the host.** Rejected: showing a user their own file+ discloses nothing, the agent can already read it, and the list made correct+ links to dotfiles fail.+- **Ask the user to grant each outside folder.** Rejected: the user asked for+ links that simply open, and `fs/resolveRef` also runs automatically for chip+ verification, so a grant prompt would fire without a click.+- **Keep containment and add the temp directory and downloads as roots.**+ Rejected: it fixes only the reported folders and leaves every other location+ (chat clients, mounted drives) broken.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 8f3d83276..c3393540a 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -396,5 +396,6 @@ Each ADR includes:| gen-ui-inline-visualization | [Inline generative UI visualizations](gen-ui-inline-visualization.md) | Accepted (D671) || 0337 | [Keep the request prefix stable across delegation settlements](0337-stable-prompt-prefix-across-delegation.md) | Accepted (supersedes ADR 0279 §9) || 0338 | [A user-supplied video owns the boot surface, served over a host-owned scheme](0338-user-supplied-startup-animation.md) | Accepted (D679) |+| 0339 | [Chat file references open absolute files outside the managed roots](0339-chat-file-refs-open-absolute-files-outside-managed-roots.md) | Accepted (amends ADR 0262 §4) || model-reasoning-effort-override | [Model reasoning effort override](model-reasoning-effort-override.md) | Proposed |diff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.mdindex c6a1811f7..ec7ccfe78 100644--- a/docs/spec/03-runtime/01-ipc-protocol.md+++ b/docs/spec/03-runtime/01-ipc-protocol.md@@ -1921,16 +1921,22 @@ Renderer IPC kept for the Plan-safe preview facade and URL fallback:accepted after a realpath check (D334 / ADR 0172), as is an absolute path inanother folder of the same project group (ADR 0249 §5, ADR 0263). A knownimage extension wins over `mimeType`; extension-less blobs accept only the- image MIME allowlist. Traversal, `~`, and other escapes are rejected+ image MIME allowlist. An exact absolute path outside every one of those+ roots is also accepted when its real path is an existing regular file+ (ADR 0339); no path is withheld, since the file is only shown to the user who+ clicked it. Relative traversal, `~`, and other escapes are rejected(`INVALID_ARGUMENT`).- `fs/readImageDataUrl({ref, mimeType?})` → `FsImageDataUrlResult`- (`image` with `dataUrl`, or `missing` / `notImage` / `tooLarge`). Same- containment as `fs/read`. Never returns non-image bytes. Renderer-only;+ (`image` with `dataUrl`, or `missing` / `notImage` / `tooLarge`). Root+ containment only: the ADR 0339 external-file rule does not apply, so a+ model-written image reference cannot render an arbitrary local image. Never returns non-image bytes. Renderer-only;not a plugin host API.-- `fs/reveal({path})` → reveal in Finder. Same containment as `fs/read`.+- `fs/reveal({path})` → reveal in Finder. Same rules as `fs/read`,+ including the ADR 0339 external-file rule.- `fs/open({path, mimeType?})` → open an existing regular file with the OS- default application. It uses the same realpath containment as `fs/read`,- including rejection of symlink escapes. For a content-addressed+ default application. It uses the same rules as `fs/read` — realpath+ containment, including rejection of symlink escapes, plus the ADR 0339+ external-file rule. For a content-addressed`attachments/<sha256>` blob declared as `video/mp4`, the host creates a`.mp4` symlink inside its private app-data directory before the OS handoff,so the extensionless blob has a media association without copying its bytes.@@ -1941,8 +1947,8 @@ Renderer IPC kept for the Plan-safe preview facade and URL fallback: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+ (`workspace` / `scratch` / `attachments` / `external`), the `relativePath`+ relative to that root (the file name for `external`), optional `sessionScratch: true` for the current session's own scratch(not the wider read-only scratch containment store), the absolute`absolutePath`, `matchedBy` (`exact-relative` /`exact-absolute` / `path-suffix` / `basename`), and — for a `workspace` match@@ -1972,9 +1978,14 @@ Renderer IPC kept for the Plan-safe preview facade and URL fallback:`fs/open`, the image reader) already accept it, so such a path completesinstead of reporting a restriction. A shorthand never completes from thatwider store; it still searches the session's own one. A reference that matches- 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).+ nothing returns `match: null`. An exact absolute path outside every allowed+ root never tries a same-name file inside a root; it is answered by the+ `fs/read` external-file rule instead (ADR 0339): an existing regular file+ that passes it returns `root: "external"` with `matchedBy: "exact-absolute"`+ and its real path, a path with no regular file behind it returns+ `match: null`; `reason: "outside-allowed-roots"` remains only for a reference+ outside the roots that is not such an exact absolute path. 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 0e83a4709..6605ac57d 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -1926,21 +1926,24 @@ Single message render — either user (plaintext) or assistant (markdown streamiany of these discards old results and cancels queued work. Newly createdfiles are reconsidered when the message remounts or its scope changes, notby 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.+ remain whole candidates. An exact absolute path to an existing file outside+ the managed roots verifies like an in-root one (ADR 0339), dotfile folders+ such as `.ssh` included. Home paths stay plain. A Markdown link whose destination is an absolute path+ reaches the opener even without a file extension (`/etc/hosts`); the+ extension heuristic only decides which bare prose tokens become chips.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-panelview (the host `file:` tab when that view is unavailable), a session-scratch- or attachment file in the host `file:` tab, and a `.html`/`.htm` page of the+ or attachment file — or an `external` file named by its exact absolute path+ outside every managed root (ADR 0339) — in the host `file:` tab, which shows+ an external `.html`/`.htm` page as source, and a `.html`/`.htm` page of theprimary folder in the side browser. A primary-folder file is addressed to theview 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 chip resolves and opens the same way. A chip whose reference- matches nothing opens nothing and reports itself; an absolute path outside- every allowed root reports the access limit separately. The OS default application+ matches nothing opens nothing and reports itself. 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 8eb8b9859..8124e0b61 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -5311,19 +5311,26 @@ window; opening a normal panel afterward must still work.primary project HTML, secondary project-folder HTML, project scratch HTMLand an isolated session's worktree HTML. Repeat with a `file:` URL containingUnicode/spaces. Interact with each rendered page using native pointer input.- Try a missing file, an outside file and a positioned HTML- source reference. Send a prompt that invokes BrowserPreview through the real+ Try a missing file, an outside HTML file, an outside text file whose folder+ and name contain spaces and CJK characters, an outside file under a `.ssh`+ folder, an outside extensionless file and the extensionless `.ssh/config`,+ and a positioned HTML source reference. Send a prompt that invokes BrowserPreview through the realsidecar in ordinary, project and isolated conversations. Disable Browser and clickagain. Switch conversations between cases.- **Expected**: Valid pages render and execute in the side browser at their- canonical path. Missing/restricted files report errors without guest loads.+ canonical path. A missing file reports an error without a guest load. The+ outside HTML, text, `.ssh`, and extensionless files open in the host file+ view (HTML as source, never executed) (ADR 0339).A line reference opens source, not execution. Disabled Browser remainsdisabled and reports an error. BrowserPreview uses its originating session'sroots and delivers a valid resource tab. No visible-project fallback.- **Automation**: `node scripts/e2e-chat-html-artifacts.mjs`, after buildingHost, runtime and Electron. Captures and synthetic profiles are retained in`PI_TEST_OUTPUT` (or the OS temporary directory).-- **Status**: Electron user-path covered on Windows; other OSes pending.+- **Status**: Electron user-path covered on Windows and macOS (on macOS set+ `PI_TEST_OUTPUT` to a real-path directory such as `/private/tmp/...`; the+ `/var` → `/private/var` alias of the default temporary directory makes guest+ URL matching miss); Linux pending.#### E2E-BROWSER-capture-resize: Capture preserves live placement and restores the latest viewport@@ -14275,8 +14282,8 @@ are withdrawn with ADR 0165.side file view; no path is truncated to its suffix or redirected to thesame-name file. The Windows Markdown link keeps a valid sanitized addressand reaches the existing file opener with the original drive path. The outside- path opens nothing and reports the access limit, while a missing in-root file- reports that no file matches.+ path opens that exact file in the host file view (ADR 0339), dotfile folders+ such as `.ssh` included, while a missing 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), Qualitydiff --git a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.mdindex bc48726d4..4b5292bd2 100644--- a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md+++ b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md@@ -1442,11 +1442,11 @@ Chrome 和代理 CDP 位于随应用打包的 `pi.browser` 插件中,通过 `p- `fs/list({path})` → 条目首先按目录排序;忽略 `.git`,`node_modules`,默认忽略子集[15-工作区-忽略-规则](/zh-CN/spec/03-runtime/15-workspace-ignore-rules)-- `fs/read({path, mimeType?})` → 文本 (≤512KB) / 图像数据 URL (≤5MB) / 二进制 / 太大。相对路径在工作区根内解析;`attachments/<sha256>` 以及已位于工作区、`<data_dir>/scratch/` 或 `<data_dir>/attachments/` 下的绝对路径在 realpath 校验后也可读(D334 / ADR 0172);同一项目组中其他文件夹里的绝对路径同样可读(ADR 0249 §5、ADR 0263)。已知图片扩展名优先于 `mimeType`;无扩展名 blob 只接受图片 MIME 白名单。穿越、`~` 和其他逃逸被拒绝(`INVALID_ARGUMENT`)。-- `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` 决定查哪个会话的临时目录。隔离会话以 `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/read({path, mimeType?})` → 文本 (≤512KB) / 图像数据 URL (≤5MB) / 二进制 / 太大。相对路径在工作区根内解析;`attachments/<sha256>` 以及已位于工作区、`<data_dir>/scratch/` 或 `<data_dir>/attachments/` 下的绝对路径在 realpath 校验后也可读(D334 / ADR 0172);同一项目组中其他文件夹里的绝对路径同样可读(ADR 0249 §5、ADR 0263)。已知图片扩展名优先于 `mimeType`;无扩展名 blob 只接受图片 MIME 白名单。位于这些根之外的精确绝对路径,只要真实路径是存在的普通文件,同样可读(ADR 0339);文件只展示给点击它的用户本人,因此不按路径扣留。相对穿越、`~` 和其他逃逸被拒绝(`INVALID_ARGUMENT`)。+- `fs/readImageDataUrl({ref, mimeType?})` → `FsImageDataUrlResult`(`image` 带 `dataUrl`,或 `missing` / `notImage` / `tooLarge`)。只做根包含检查,不适用 ADR 0339 外部文件规则,因此模型写出的图片引用无法渲染任意本地图片。从不返回非图片字节。仅渲染器使用,不是插件宿主 API。+- `fs/reveal({path})` → 在 Finder 中显示。规则与 `fs/read` 相同,包括 ADR 0339 外部文件规则。+- `fs/open({path, mimeType?})` → 用系统默认应用打开已有的普通文件。与 `fs/read` 规则相同:校验真实路径包含范围、拒绝通过符号链接逃逸,并适用 ADR 0339 外部文件规则。对于声明为 `video/mp4` 的无后缀 `attachments/<sha256>` blob,宿主在私有应用数据目录建立 `.mp4` 符号链接后再交给系统,不复制视频字节。+- `fs/resolveRef({ref, sessionId?})` → `FsChatRefResolveResult`(`{ match: FsChatRefMatch | null }`,match 指出应答的 `root`(`workspace` / `scratch` / `attachments` / `external`)、相对该应答根的 `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 0339):指向存在的普通文件时返回 `root: "external"`(`matchedBy: "exact-absolute"`,`relativePath` 为文件名);没有文件时返回 `match: null`;`reason: "outside-allowed-roots"` 只留给位于受管根之外、又不是精确绝对路径的引用。`fs/read`、`fs/reveal`、`fs/open` 采用同一规则,`fs/readImageDataUrl` 仍只做根包含检查。解析本身不打开任何东西(ADR 0262)。- `fs/list` 仍只限工作区;外面的遍历被拒绝(`INVALID_ARGUMENT`)。## 13b. 桌面菜单和窗口 APIdiff --git a/docs/zh-CN/spec/04-ux/08-component-spec.md b/docs/zh-CN/spec/04-ux/08-component-spec.mdindex 7a209656a..69203d8a0 100644--- a/docs/zh-CN/spec/04-ux/08-component-spec.md+++ b/docs/zh-CN/spec/04-ux/08-component-spec.md@@ -2417,7 +2417,7 @@ Live Voice 受现有开发者模式和开发构建门控约束,包含四种展切换会话或项目、删除正在查看的附件时关闭预览;晚到的读取结果不得覆盖新图片。- 发送的模板调用在记录中呈现为等宽命令来自消息的 `command` 字段的芯片而不是扩展的正文。-- 已发送的 `@path` 文件引用(带引号或不带引号)画成与草稿相同的叶子名芯片。点击芯片先经 `pi-desktop/fs/resolveRef` 补全引用——搜索整个打开的项目,按项目组文件夹顺序、主文件夹优先(ADR 0263)——再按解析结果打开:项目文件在随应用打包的 `pi.file-manager` 视图中打开(该视图不可用时退回宿主 `file:` 选项卡),会话临时目录或附件文件在宿主 `file:` 选项卡中打开,主文件夹中的 `.html`/`.htm` 在侧边浏览器打开。交给该视图的地址跟随应答的文件夹:主文件夹中的文件用项目内相对路径传递,同一项目的同级文件夹中的文件用绝对路径传递,与会话临时目录和附件文件一致。什么都没匹配到时既不打开任何东西,也会自己报告出来,右键该芯片也一样;引用菜单除了在系统文件管理器中显示该文件,还提供复制完整地址与复制相对地址,发送的 `@path` 芯片、消息 Markdown 中的行内代码、本地链接与本地图片、工具行自己的文件路径、工具结果的文件列表或匹配列表中的路径、图片附件缩略图都提供同样的几项,并同样经这次补全与这套寻址规则;项目外的文件没有相对地址,会直接说明。系统默认应用不再由这次点击触发。HTTP(S) URL 仍是侧边浏览器的文本链接。+- 已发送的 `@path` 文件引用(带引号或不带引号)画成与草稿相同的叶子名芯片。点击芯片先经 `pi-desktop/fs/resolveRef` 补全引用——搜索整个打开的项目,按项目组文件夹顺序、主文件夹优先(ADR 0263)——再按解析结果打开:项目文件在随应用打包的 `pi.file-manager` 视图中打开(该视图不可用时退回宿主 `file:` 选项卡),会话临时目录或附件文件——以及以精确绝对路径指向、位于所有受管根之外的 `external` 文件(ADR 0339)——在宿主 `file:` 选项卡中打开(外部 `.html`/`.htm` 显示源码;目标为绝对路径的 Markdown 链接即使没有扩展名也会交给打开流程,例如 `/etc/hosts`),主文件夹中的 `.html`/`.htm` 在侧边浏览器打开。交给该视图的地址跟随应答的文件夹:主文件夹中的文件用项目内相对路径传递,同一项目的同级文件夹中的文件用绝对路径传递,与会话临时目录和附件文件一致。什么都没匹配到时既不打开任何东西,也会自己报告出来,右键该芯片也一样;引用菜单除了在系统文件管理器中显示该文件,还提供复制完整地址与复制相对地址,发送的 `@path` 芯片、消息 Markdown 中的行内代码、本地链接与本地图片、工具行自己的文件路径、工具结果的文件列表或匹配列表中的路径、图片附件缩略图都提供同样的几项,并同样经这次补全与这套寻址规则;项目外的文件没有相对地址,会直接说明。系统默认应用不再由这次点击触发。HTTP(S) URL 仍是侧边浏览器的文本链接。带行号的 `path:line` 引用使用宿主只读 `file:` 选项卡,并将目标行滚动到可见区域。- 状态:键盘活动行使用共享 `kb-active` 处理;空的diff --git a/packages/host-runtime/src/chat-ref-resolve.ts b/packages/host-runtime/src/chat-ref-resolve.tsindex 54ace884d..03fd1854d 100644--- a/packages/host-runtime/src/chat-ref-resolve.ts+++ b/packages/host-runtime/src/chat-ref-resolve.ts@@ -5,8 +5,10 @@ import type {FsChatRefMatchKind,FsChatRefProjectRoot,FsChatRefRoot,+ FsChatRefResolveResult,} from "@pi-desktop/shared";import { isAttachmentBlobRef, isIgnoredName, resolveRealPathWithinRoot } from "./workspace-files.js";+import { resolveExternalFile } from "./external-files.js";import { getWorkspaceFileIndex } from "./fs-index.js";/**@@ -244,6 +246,33 @@ export async function isChatRefOutsideRoots(ref: string, roots: ChatRefRoots): P);}+/**+ * Complete an absolute reference that `isChatRefOutsideRoots` placed outside+ * every managed root (ADR 0339). It names that exact file or nothing: a path+ * with no regular file behind it reports a miss, and no same-name file is ever+ * looked up anywhere else. A reference that is not an exact absolute path keeps+ * reporting the access limit, since shorthand never searches outside the roots.+ */+export async function resolveExternalChatRef(ref: string): Promise<FsChatRefResolveResult> {+ const parsed = parseChatRef(ref);+ const cleaned = cleanRef(ref);+ if (!parsed?.absolute || !isAbsolute(cleaned)) {+ return { match: null, reason: "outside-allowed-roots" };+ }+ const external = await resolveExternalFile(cleaned);+ if (external.kind === "file") {+ return {+ match: {+ root: "external",+ relativePath: basename(external.path),+ absolutePath: external.path,+ matchedBy: "exact-absolute",+ },+ };+ }+ return { match: null };+}+function segmentsOf(path: string): string[] {return toPosix(path).split("/").filter(Boolean);}diff --git a/packages/host-runtime/src/external-files.ts b/packages/host-runtime/src/external-files.tsnew file mode 100644index 000000000..9ac4bad30--- /dev/null+++ b/packages/host-runtime/src/external-files.ts@@ -0,0 +1,71 @@+import { realpath, stat } from "node:fs/promises";+import { isAbsolute, resolve } from "node:path";+import type { FsReadResult } from "@pi-desktop/shared";+import { isAttachmentBlobRef, previewFile, resolveRealOpenablePath } from "./workspace-files.js";++/**+ * A file the user explicitly clicked that lives outside every root the app+ * manages (ADR 0339).+ *+ * The agent names files by their exact absolute path, and it works on files+ * anywhere the user points it: a download, a chat client's folder, the system+ * temp directory. Root containment cannot cover those locations. Opening a file+ * the user clicked only shows it to that same user on this machine — nothing+ * reaches the model or the network — so no path is withheld. The shape stays+ * narrow: an exact absolute path whose real target is an existing regular file.+ */++export type ExternalFileResolution =+ | { kind: "file"; path: string }+ /** Absolute, but no regular file exists there. */+ | { kind: "missing" }+ /** Not an absolute path; external resolution does not apply. */+ | { kind: "notAbsolute" };++/**+ * Resolve an absolute path to the real path of an existing regular file. A+ * home shorthand, an attachment blob reference, and any relative path are not+ * external references; directories and other non-files count as missing.+ */+export async function resolveExternalFile(path: string): Promise<ExternalFileResolution> {+ const raw = String(path ?? "").trim();+ if (!raw || raw.includes("\0") || raw.startsWith("~") || isAttachmentBlobRef(raw) || !isAbsolute(raw)) {+ return { kind: "notAbsolute" };+ }+ try {+ const real = await realpath(resolve(raw));+ if (!(await stat(real)).isFile()) return { kind: "missing" };+ return { kind: "file", path: real };+ } catch {+ return { kind: "missing" };+ }+}++/**+ * The real path a user-initiated open may act on: a path contained in the+ * managed roots answers first, and otherwise an absolute external regular file.+ */+export async function resolveUserOpenablePath(+ path: string,+ workspaceRoot: string | null | undefined,+ extraRoots: readonly string[],+): Promise<string | null> {+ const contained = await resolveRealOpenablePath(path, workspaceRoot, extraRoots);+ if (contained) return contained;+ const external = await resolveExternalFile(path);+ return external.kind === "file" ? external.path : null;+}++/** `readOpenableFile`, widened to absolute external files (ADR 0339). */+export async function readUserOpenableFile(+ path: string,+ workspaceRoot: string | null | undefined,+ extraRoots: readonly string[],+ mimeType?: string,+): Promise<FsReadResult> {+ const target = await resolveUserOpenablePath(path, workspaceRoot, extraRoots);+ if (!target) throw new Error("path outside allowed roots");+ const info = await stat(target);+ if (!info.isFile()) throw new Error("not a file");+ return previewFile(target, path, mimeType);+}diff --git a/packages/host-runtime/src/index.ts b/packages/host-runtime/src/index.tsindex 35b11b7dd..8f2e645a8 100644--- a/packages/host-runtime/src/index.ts+++ b/packages/host-runtime/src/index.ts@@ -11,6 +11,7 @@ export * from "./turn-events.js";export * from "./runtime-service.js";export * from "./plan-dispatch.js";export * from "./workspace-files.js";+export * from "./external-files.js";export * from "./workspace-diff.js";export * from "./live-work/operation-ledger.js";export * from "./live-work/intent.js";diff --git a/packages/shared/src/types/filesystem.ts b/packages/shared/src/types/filesystem.tsindex 4d66474a4..b4c3867fc 100644--- a/packages/shared/src/types/filesystem.ts+++ b/packages/shared/src/types/filesystem.ts@@ -101,8 +101,12 @@ export type FsChatRefProjectRoot = {* file is expressed to the work panel as a path relative to the project's* **primary** folder, while any other project folder — and every scratch or* attachment file — can only be addressed by its absolute path.+ *+ * `external` is an existing regular file the reference named by its exact+ * absolute path outside every managed root (ADR 0339). It is never produced by+ * a shorthand, and its `relativePath` is the file name.*/-export type FsChatRefRoot = "workspace" | "scratch" | "attachments";+export type FsChatRefRoot = "workspace" | "scratch" | "attachments" | "external";/** Which rule produced the match; the shallow tiers are informational. */export type FsChatRefMatchKind =@@ -130,6 +134,10 @@ export type FsChatRefMatch = {export type FsChatRefResolveResult = {match: FsChatRefMatch | null;- /** The supplied absolute path is not inside a project, scratch, or attachment root. */+ /**+ * The reference lies outside the managed roots and is not an exact absolute+ * path, so it cannot be opened from there. An exact absolute path to an+ * existing file outside the roots opens instead (ADR 0339).+ */reason?: "outside-allowed-roots";};diff --git a/scripts/e2e-chat-html-artifacts.mjs b/scripts/e2e-chat-html-artifacts.mjsindex d9d836621..55eb2f0b4 100644--- a/scripts/e2e-chat-html-artifacts.mjs+++ b/scripts/e2e-chat-html-artifacts.mjs@@ -23,7 +23,7 @@ const binary = resolveHostBinary();const host = new Host(binary, data, { quiet: true });const model = await startHtmlPreviewModel();const cases = [];-let outside;+let outside, outsideNote, outsideDotfile, outsideBare, outsideBareDotfile;const html = '<!doctype html><meta charset="utf-8"><title>Pelican animation</title><style>body{background:#f5f5f5;color:#222;font:20px system-ui;padding:28px}svg{width:240px}circle{animation:ride 2s infinite alternate}@keyframes ride{to{transform:translateX(80px)}}</style><h1>Pelican bicycle animation</h1><svg viewBox="0 0 240 80"><circle cx="40" cy="40" r="24" fill="#222"/></svg><p id="result">Ready</p><button onclick="document.querySelector(\'#result\').textContent=\'Animation opened\'">Run animation</button>';try {await host.start();@@ -82,8 +82,25 @@ try {} });outside = join(output, "outside.html");await writeFile(outside, html);+ // ADR 0339: an exact absolute path outside every managed root opens the file+ // the user clicked, dotfile folders included.+ await mkdir(join(output, "outside notes"), { recursive: true });+ outsideNote = join(output, "outside notes", "考核 notes.txt");+ await writeFile(outsideNote, "External note body\n");+ await mkdir(join(output, ".ssh"), { recursive: true });+ outsideDotfile = join(output, ".ssh", "notes.txt");+ await writeFile(outsideDotfile, "Host fixture\n");+ // Extensionless files are still explicit link destinations.+ outsideBare = join(output, "outside notes", "build-log");+ await writeFile(outsideBare, "Bare file body\n");+ outsideBareDotfile = join(output, ".ssh", "config");+ await writeFile(outsideBareDotfile, "Bare dotfile body\n");for (const [label, content] of [["Outside HTML", "[Outside HTML](<" + outside.replaceAll("\\", "/") + ">)"],+ ["Outside note", "[Outside note](<" + outsideNote.replaceAll("\\", "/") + ">)"],+ ["Outside dotfile", "[Outside dotfile](<" + outsideDotfile.replaceAll("\\", "/") + ">)"],+ ["Outside bare", "[Outside bare](<" + outsideBare.replaceAll("\\", "/") + ">)"],+ ["Outside bare dotfile", "[Outside bare dotfile](<" + outsideBareDotfile.replaceAll("\\", "/") + ">)"],["Source line", "Source: Ordinary-scratch.html:1"],]) {for (const [role, text] of [["user", "Inspect " + label], ["assistant", content]]) {@@ -168,13 +185,25 @@ try {await page.getByRole("link", { name: "Missing HTML", exact: true }).click();await page.getByText("No file matches missing.html", { exact: true }).waitFor();results.push("missing file reports its failure");+ for (const dismiss of await page.locator(".toast-dismiss").all()) await dismiss.click();+ await page.locator(".toast").first().waitFor({ state: "hidden" });await page.getByRole("link", { name: "Outside HTML", exact: true }).click();- await page.getByText(/is outside the locations this app can access/).waitFor();+ await page.locator(".file-viewer").getByText(/Pelican bicycle animation/).waitFor();assert.equal(await app.evaluate(({ webContents }, url) =>webContents.getAllWebContents().some(wc => wc.getURL() === url), pathToFileURL(outside).href), false);- results.push("outside HTML is rejected without guest navigation");- for (const dismiss of await page.locator(".toast-dismiss").all()) await dismiss.click();- await page.locator(".toast").first().waitFor({ state: "hidden" });+ results.push("outside HTML opens its source without guest navigation");+ await page.getByRole("link", { name: "Outside note", exact: true }).click();+ await page.locator(".file-viewer").getByText("External note body").waitFor();+ results.push("outside absolute file opens in the file viewer");+ await page.getByRole("link", { name: "Outside dotfile", exact: true }).click();+ await page.locator(".file-viewer").getByText("Host fixture").waitFor();+ results.push("outside dotfile folder opens in the file viewer");+ await page.getByRole("link", { name: "Outside bare", exact: true }).click();+ await page.locator(".file-viewer").getByText("Bare file body").waitFor();+ results.push("outside extensionless file opens in the file viewer");+ await page.getByRole("link", { name: "Outside bare dotfile", exact: true }).click();+ await page.locator(".file-viewer").getByText("Bare dotfile body").waitFor();+ results.push("outside extensionless dotfile opens in the file viewer");await page.getByText("Ordinary-scratch.html:1", { exact: true }).click();await page.locator(".file-viewer").waitFor();results.push("positioned HTML opens source, not execution");