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(markdown): preserve Windows file links (#1470)
Lan27da36b03e96
diff --git a/apps/desktop/src/components/Markdown.tsx b/apps/desktop/src/components/Markdown.tsxindex 77bb7591e..a629c5602 100644--- a/apps/desktop/src/components/Markdown.tsx+++ b/apps/desktop/src/components/Markdown.tsx@@ -75,6 +75,7 @@ import {type ChatFileMenuTarget,} from "../hooks/use-chat-file-menu";import {+ handleMarkdownFileLinkClick,remarkChatFileLinks,resolvePreviewTarget,safeDecodeUri,@@ -666,13 +667,7 @@ function Anchor({openHttpUrl(href);return;}- 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(ref, baseDir);- }+ handleMarkdownFileLinkClick(e, href, root, baseDir, openFileRef);};return (<>diff --git a/apps/desktop/src/lib/chat-links.ts b/apps/desktop/src/lib/chat-links.tsindex 40991b27f..26f31ac38 100644--- a/apps/desktop/src/lib/chat-links.ts+++ b/apps/desktop/src/lib/chat-links.ts@@ -95,6 +95,22 @@ function isAbsoluteFilePath(path: string): boolean {return path.startsWith("/") || /^[A-Za-z]:[\\/]/.test(path) || path.startsWith("\\\\");}+function encodeWindowsPathForHref(path: string): string {+ return /^[A-Za-z]:[\\/]/.test(path) || path.startsWith("\\\\")+ ? encodeURIComponent(path)+ : path;+}++function normalizeMarkdownWindowsPath(url: string): string {+ // Keep a drive letter from being interpreted as a URI scheme by the+ // renderer and sanitizer; the anchor decodes this back before file lookup.+ const decoded = safeDecodeUri(url);+ if (!/^[A-Za-z]:[\\/]/.test(decoded)) return url;+ const path = parseFileRef(decoded);+ if (path !== decoded) return url;+ return encodeWindowsPathForHref(path);+}+/*** Returns the cleaned path when `text` plausibly names a file (trailing* `:line[:col]` refs are stripped), otherwise null. A leading `@` — the@@ -241,6 +257,23 @@ export function resolvePreviewTarget(return rel ? { kind: "file", path: rel, ...(position ?? {}) } : null;}+/** Route a plain click on a local Markdown link through the existing file opener. */+export function handleMarkdownFileLinkClick(+ event: { preventDefault(): void },+ href: string,+ root: string | null | undefined,+ baseDir: string | undefined,+ openFileRef: (path: string, baseDir?: string) => 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;+ event.preventDefault();+ openFileRef(ref, baseDir);+ return true;+}+/** Tool-call args → preview target (Read/Write/Edit paths, fetch URLs). */export function getToolPreviewTarget(args: unknown,@@ -381,6 +414,12 @@ const SKIP_MDAST = new Set(["html",]);+function normalizeMarkdownLinkDestination(node: MdastNode): void {+ if ((node.type === "link" || node.type === "definition") && typeof node.url === "string") {+ node.url = normalizeMarkdownWindowsPath(node.url);+ }+}+/*** Turn bare file/URL tokens in markdown phrasing into link nodes so the* existing markdown Anchor handler can preview them. Skips fenced code,@@ -411,6 +450,7 @@ export function linkifyMdastTree(function walk(node: MdastNode | null | undefined, skip: boolean) {if (!node || typeof node.type !== "string") return;inputNodeCount += 1;+ normalizeMarkdownLinkDestination(node);if ((node.type === "text" || node.type === "inlineCode") && typeof node.value === "string") {sourceLength += node.value.length;}@@ -449,9 +489,7 @@ export function linkifyMdastTree(? target.url: target.kind === "session"? formatSessionLink(target.sessionId)- : /^[A-Za-z]:[\\/]/.test(target.path) || target.path.startsWith("\\\\")- ? encodeURIComponent(target.path)- : target.path;+ : encodeWindowsPathForHref(target.path);next.push({type: "link",url,@@ -476,9 +514,7 @@ export function linkifyMdastTree(? segment.target.url: segment.target.kind === "session"? formatSessionLink(segment.target.sessionId)- : (/^[A-Za-z]:[\\/]/.test(segment.target.path) || segment.target.path.startsWith("\\\\"))- ? encodeURIComponent(segment.target.path)- : segment.target.path;+ : encodeWindowsPathForHref(segment.target.path);next.push({type: "link",url,diff --git a/apps/desktop/test/chat-links.test.mjs b/apps/desktop/test/chat-links.test.mjsindex 805574cdd..02d071c58 100644--- a/apps/desktop/test/chat-links.test.mjs+++ b/apps/desktop/test/chat-links.test.mjs@@ -3,9 +3,13 @@ import test from "node:test";import * as React from "react";import { renderToStaticMarkup } from "react-dom/server";import ReactMarkdown from "react-markdown";+import rehypeRaw from "rehype-raw";+import rehypeSanitize from "rehype-sanitize";+import remarkGfm from "remark-gfm";import {fileDirOf,getToolPreviewTarget,+ handleMarkdownFileLinkClick,isHttpUrl,linkifyMdastTree,parseFileRef,@@ -18,6 +22,104 @@ import {const ROOT = "/Users/dev/project";+function renderSanitizedMarkdown(source, root = "D:\\person") {+ return renderToStaticMarkup(+ React.createElement(ReactMarkdown, {+ remarkPlugins: [remarkGfm, remarkChatFileLinks(root)],+ rehypePlugins: [rehypeRaw, rehypeSanitize],+ children: source,+ }),+ );+}++function assertMarkdownLinkClick(markup, expectedPath) {+ const href = markup.match(/<a href="([^"]+)"/)?.[1];+ assert.ok(href, `rendered Markdown link has no href: ${markup}`);+ const calls = [];+ let prevented = false;+ const handled = handleMarkdownFileLinkClick(+ { preventDefault: () => { prevented = true; } },+ href,+ "D:\\person",+ undefined,+ (...args) => calls.push(args),+ );+ assert.equal(handled, true);+ assert.equal(prevented, true);+ assert.deepEqual(calls, [[expectedPath, undefined]]);+}++test("Windows Markdown file links survive parsing and sanitization without changing their paths", () => {+ const paths = [+ String.raw`D:\person\test.js`,+ "D:/person/test.js",+ String.raw`D:\person\dir name\报告 2026.js`,+ "D:/person/dir name/报告 2026.js",+ ];++ for (const path of paths) {+ const source = `[file](<${path}>)`;+ const markup = renderSanitizedMarkdown(source);+ const href = markup.match(/<a href="([^"]+)"/)?.[1];+ assert.ok(href, `sanitized Markdown link lost href for ${path}: ${markup}`);+ assert.equal(decodeURIComponent(href), path);+ assertMarkdownLinkClick(markup, path);+ }++ const plainMarkdown = String.raw`[test.js](D:\person\test.js)`;+ const plainMarkup = renderSanitizedMarkdown(plainMarkdown);+ assert.match(plainMarkup, /<a href="D%3A%5Cperson%5Ctest\.js">test\.js<\/a>/);+ assertMarkdownLinkClick(plainMarkup, String.raw`D:\person\test.js`);++ const referencePath = String.raw`D:\person\dir name\报告 2026.js`;+ const referenceMarkup = renderSanitizedMarkdown(+ `[file][local]\n\n[local]: <${referencePath}>`,+ );+ const referenceHref = referenceMarkup.match(/<a href="([^"]+)"/)?.[1];+ assert.ok(referenceHref, `reference-style link lost href: ${referenceMarkup}`);+ assert.equal(decodeURIComponent(referenceHref), referencePath);+ assertMarkdownLinkClick(referenceMarkup, referencePath);++ const encodedPath = "D%3A%5Cperson%5Cdir%20name%5C%E6%8A%A5%E5%91%8A.js";+ const encodedMarkup = renderSanitizedMarkdown(`[file](${encodedPath})`);+ const encodedHref = encodedMarkup.match(/<a href="([^"]+)"/)?.[1];+ assert.ok(encodedHref, `encoded path link lost href: ${encodedMarkup}`);+ assert.equal(decodeURIComponent(encodedHref), String.raw`D:\person\dir name\报告.js`);+ assert.equal(encodedHref, encodedPath, "normalization must not double-encode an existing URI path");+ assertMarkdownLinkClick(encodedMarkup, String.raw`D:\person\dir name\报告.js`);++ const encodedSlashPath = "D%3A%2Fperson%2Fdir%20name%2F%E6%8A%A5%E5%91%8A.js";+ const encodedSlashMarkup = renderSanitizedMarkdown(`[file](${encodedSlashPath})`);+ const encodedSlashHref = encodedSlashMarkup.match(/<a href="([^"]+)"/)?.[1];+ assert.ok(encodedSlashHref, `encoded forward-slash link lost href: ${encodedSlashMarkup}`);+ assert.equal(decodeURIComponent(encodedSlashHref), "D:/person/dir name/报告.js");+ assert.equal(encodedSlashHref, encodedSlashPath);+ assertMarkdownLinkClick(encodedSlashMarkup, "D:/person/dir name/报告.js");+});++test("Markdown link normalization leaves web, relative, automatic, and unsafe links alone", () => {+ const httpMarkup = renderSanitizedMarkdown("[web](https://example.com/a%20b)");+ assert.match(httpMarkup, /href="https:\/\/example\.com\/a%20b"/);++ const relativeMarkup = renderSanitizedMarkdown("[relative](../docs/readme.md)");+ assert.match(relativeMarkup, /href="\.\.\/docs\/readme\.md"/);++ const autoPath = String.raw`D:\person\test.js`;+ const autoMarkup = renderSanitizedMarkdown(`Open ${autoPath}`);+ assert.match(autoMarkup, /href="D%3A%5Cperson%5Ctest\.js"/);++ for (const destination of [+ "javascript:alert%281%29",+ "data:text/html,unsafe",+ "file:///C:/secret.txt",+ "ms-msdt:/diagnostics",+ "custom:payload",+ ]) {+ const unsafeMarkup = renderSanitizedMarkdown(`[unsafe](${destination})`);+ assert.doesNotMatch(unsafeMarkup, /href=/, destination);+ }+});+test("parseFileRef accepts pathy tokens and strips line refs", () => {assert.equal(parseFileRef("apps/desktop/src/App.tsx"), "apps/desktop/src/App.tsx");assert.equal(parseFileRef("src/main.rs:42"), "src/main.rs");diff --git a/apps/desktop/test/transcript-file-chips.test.mjs b/apps/desktop/test/transcript-file-chips.test.mjsindex ae133e087..8d510060c 100644--- a/apps/desktop/test/transcript-file-chips.test.mjs+++ b/apps/desktop/test/transcript-file-chips.test.mjs@@ -7,6 +7,7 @@ import { readFile } from "node:fs/promises";import test from "node:test";const read = (path) => readFile(new URL(path, import.meta.url), "utf8");+const markdown = await read("../src/components/Markdown.tsx");const [transcript, styles, hook, api, toolDetails, toolRow, filesTab] = await Promise.all([readTranscriptSource(),@@ -68,6 +69,10 @@ test("a file chip is routed by where the reference resolved, never optimisticallassert.match(api, /fsOpen: \(path: string, mimeType\?: string\) =>\s*invoke\(IPC\.invoke\.fsOpen, \{ path, mimeType \}\)/);});+test("Markdown file anchors route clicks through the existing file opener", () => {+ assert.match(markdown, /handleMarkdownFileLinkClick\(e, href, root, baseDir, openFileRef\)/);+});+test("a tool row and a tool result row open a file where the message body does", () => {// One opener serves every transcript surface that names a file. It completes// the reference the same way a chat chip does instead of handing the raw pathdiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 76a5df735..48e734ee8 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -12746,14 +12746,18 @@ are withdrawn with ADR 0165.every allowed root. Repeat the path-recognition checks with a POSIX projectpath 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+ path as inline code and as ordinary text in the assistant reply. On Windows,+ also click it as a Markdown link with an angle-bracketed destination, for+ example `[readme.md](<C:\workspace with spaces\readme.md>)`. 3) Click arelative path whose middle directory contains a space, then a first-segmentspaced path using an explicit `@"..."` reference. 4) Click the outsideabsolute path.- **Expected**: Every allowed reference opens the exact file in the existingside 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.+ same-name file. The Windows Markdown link keeps a valid sanitized address+ and 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.- **Specs linked**: `03-runtime/01-ipc-protocol.md` § fs,`04-ux/08-component-spec.md` §8.3.- **Acceptance**: C (conversation & stream), D (workspace), Quality