Skip to content

Commit 7ddc786

Browse files
committed
fix(web): keep windows drive paths clickable in chat markdown
A markdown destination like `D:/tmp/example.md` rendered as styled but dead text, and it failed differently on each of the two pipelines chat uses. Assistant messages leave `parseRawHtml` at its default of true, so they run `rehype-sanitize`, which reads `D:` as an unknown protocol and removes the href before `urlTransform` is reached. User messages pass false, skip the sanitizer, and React Markdown's `defaultUrlTransform` blanks the same destination for the same reason. Either way the anchor arrives without an href and cannot match an entry in `markdownFileLinkMetaByHref`, even though that map has already resolved the path from the raw message text. Both pipelines run remark, so the destination is normalized there: `toFilesystemLinkUrl` maps a drive path to the `file:` URL the sanitizer already allows, and `rewriteMarkdownFileUriHref` maps it back on the way out. `resolveMarkdownFileLinkTarget` already handled these paths, so this is only about getting them that far. Link keys go through the same function, so `M:\dir\file.md` in the source and the `M:/dir/file.md` the renderer receives resolve to one key rather than missing each other on the separator. The anchor resolves a drive destination itself when the metadata map misses. That map is built by scanning the message text for inline links with a plain destination, so balanced parentheses, nested brackets and bracketed destinations with spaces are absent from it; without the fallback those would render as ordinary anchors pointing at a drive path with no file action. The sanitize schema is exported so the tests can render both pipelines with the real configuration; that needs an explicit type annotation because its inferred type is not nameable outside the module. This covers markdown destinations only. A bare `M:\dir\file.md` written as plain text is still not linked, because GFM does not autolink filesystem paths and adding that is a separate change.
1 parent 4cb676c commit 7ddc786

5 files changed

Lines changed: 214 additions & 4 deletions

File tree

‎apps/web/src/components/ChatMarkdown.tsx‎

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -73,11 +73,13 @@ import {
7373
serializeTableElementToMarkdown,
7474
} from "../markdown-clipboard";
7575
import { remarkNormalizeListItemIndentation } from "../markdown-list-indentation";
76+
import { remarkFilesystemLinkDestinations } from "../markdown-filesystem-links";
7677
import {
7778
normalizeMarkdownLinkDestination,
7879
resolveInlineCodeFileLinkMeta,
7980
resolveMarkdownFileLinkMeta,
8081
rewriteMarkdownFileUriHref,
82+
toFilesystemLinkUrl,
8183
type MarkdownFileLinkMeta,
8284
} from "../markdown-links";
8385
import { readLocalApi } from "../localApi";
@@ -175,7 +177,7 @@ export function orderedListGutterStyle(
175177
return { "--list-gutter": `${digits + 1}ch` };
176178
}
177179

178-
const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
180+
export const CHAT_MARKDOWN_SANITIZE_SCHEMA: NonNullable<Parameters<typeof rehypeSanitize>[0]> = {
179181
...defaultSchema,
180182
attributes: {
181183
...defaultSchema.attributes,
@@ -187,12 +189,13 @@ const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
187189
...defaultSchema.protocols,
188190
href: [...(defaultSchema.protocols?.href ?? []), "file"],
189191
},
190-
} satisfies Parameters<typeof rehypeSanitize>[0];
192+
};
191193

192194
const CHAT_MARKDOWN_REMARK_PLUGINS = [
193195
remarkGfm,
194196
remarkGithubAlerts,
195197
remarkNormalizeListItemIndentation,
198+
remarkFilesystemLinkDestinations,
196199
remarkPreserveCodeMeta,
197200
remarkTagInlineCode,
198201
] satisfies NonNullable<ReactMarkdownOptions["remarkPlugins"]>;
@@ -202,6 +205,7 @@ const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS = [
202205
remarkGithubAlerts,
203206
remarkNormalizeListItemIndentation,
204207
remarkBreaks,
208+
remarkFilesystemLinkDestinations,
205209
remarkPreserveCodeMeta,
206210
remarkTagInlineCode,
207211
] satisfies NonNullable<ReactMarkdownOptions["remarkPlugins"]>;
@@ -915,7 +919,10 @@ function extractMarkdownLinkHrefs(text: string): string[] {
915919
}
916920

917921
function normalizeMarkdownLinkHrefKey(href: string): string {
918-
const normalizedHref = normalizeMarkdownLinkDestination(href);
922+
// Drive destinations are keyed through the same `file:` form the remark plugin
923+
// rewrites them to, so a `M:\dir\file.md` in the source text and the
924+
// `M:/dir/file.md` the renderer receives resolve to one key.
925+
const normalizedHref = toFilesystemLinkUrl(href) ?? normalizeMarkdownLinkDestination(href);
919926
return rewriteMarkdownFileUriHref(normalizedHref) ?? normalizedHref;
920927
}
921928

@@ -1627,7 +1634,16 @@ function ChatMarkdown({
16271634
},
16281635
a({ node, href, children, title: _title, ...props }) {
16291636
const normalizedHref = href ? normalizeMarkdownLinkHrefKey(href) : "";
1630-
const fileLinkMeta = normalizedHref ? markdownFileLinkMetaByHref.get(normalizedHref) : null;
1637+
// The map is keyed off a scan of the message text, which only reads
1638+
// inline links with a plain destination. A drive path is resolved here
1639+
// when that scan missed it, so a link shape the scan cannot read still
1640+
// opens the file rather than rendering as an ordinary dead link.
1641+
const fileLinkMeta = normalizedHref
1642+
? (markdownFileLinkMetaByHref.get(normalizedHref) ??
1643+
(toFilesystemLinkUrl(normalizedHref)
1644+
? resolveMarkdownFileLinkMeta(normalizedHref, cwd)
1645+
: null))
1646+
: null;
16311647
if (!fileLinkMeta) {
16321648
const faviconHost = resolveExternalWebLinkHost(href);
16331649
const isSameDocumentLink = href?.startsWith("#") ?? false;
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
import { describe, expect, it } from "vite-plus/test";
2+
import { renderToStaticMarkup } from "react-dom/server";
3+
import ReactMarkdown, { defaultUrlTransform } from "react-markdown";
4+
import rehypeRaw from "rehype-raw";
5+
import rehypeSanitize from "rehype-sanitize";
6+
import remarkGfm from "remark-gfm";
7+
8+
import { CHAT_MARKDOWN_SANITIZE_SCHEMA } from "./components/ChatMarkdown";
9+
import { remarkFilesystemLinkDestinations } from "./markdown-filesystem-links";
10+
import { rewriteMarkdownFileUriHref } from "./markdown-links";
11+
12+
/**
13+
* Renders through the same two pipelines the chat does: assistant messages parse
14+
* raw HTML and therefore run `rehype-sanitize`, user messages do not.
15+
*/
16+
function renderChatMarkdown(markdown: string, options: { readonly parseRawHtml: boolean }): string {
17+
return renderToStaticMarkup(
18+
<ReactMarkdown
19+
remarkPlugins={[remarkGfm, remarkFilesystemLinkDestinations]}
20+
rehypePlugins={
21+
options.parseRawHtml
22+
? [rehypeRaw, [rehypeSanitize, CHAT_MARKDOWN_SANITIZE_SCHEMA]]
23+
: undefined
24+
}
25+
skipHtml={false}
26+
// Mirrors the component's own transform, so an unsafe scheme is still
27+
// rejected by React Markdown exactly as it is in the app.
28+
urlTransform={(href) => rewriteMarkdownFileUriHref(href) ?? defaultUrlTransform(href)}
29+
>
30+
{markdown}
31+
</ReactMarkdown>,
32+
);
33+
}
34+
35+
describe("remarkFilesystemLinkDestinations", () => {
36+
// #6418: both pipelines dropped the destination, so the anchor rendered
37+
// without an href and could not be matched to a resolved file link.
38+
for (const parseRawHtml of [true, false]) {
39+
it(`keeps a drive destination with parseRawHtml=${parseRawHtml}`, () => {
40+
expect(renderChatMarkdown("[Open](D:/tmp/example.md)", { parseRawHtml })).toContain(
41+
'href="D:/tmp/example.md"',
42+
);
43+
});
44+
45+
it(`keeps a backslash drive destination with parseRawHtml=${parseRawHtml}`, () => {
46+
expect(
47+
renderChatMarkdown("[Open](M:\\batches\\docs\\prompt.md)", { parseRawHtml }),
48+
).toContain('href="M:/batches/docs/prompt.md"');
49+
});
50+
51+
it(`keeps a reference definition destination with parseRawHtml=${parseRawHtml}`, () => {
52+
expect(
53+
renderChatMarkdown("[Open][ref]\n\n[ref]: D:/tmp/example.md", { parseRawHtml }),
54+
).toContain('href="D:/tmp/example.md"');
55+
});
56+
57+
// Link shapes the metadata scan's regex cannot read - balanced parentheses,
58+
// nested brackets, a bracketed destination with spaces. The anchor resolves
59+
// these itself, so the destination still has to survive the pipeline.
60+
it(`keeps destinations the metadata scan misses with parseRawHtml=${parseRawHtml}`, () => {
61+
expect(renderChatMarkdown("[Open](D:/tmp/example(1).md)", { parseRawHtml })).toContain(
62+
'href="D:/tmp/example(1).md"',
63+
);
64+
// A space survives percent-encoded, the form the `file:` URL carries it
65+
// in; `resolveMarkdownFileLinkTarget` decodes it again when it resolves.
66+
expect(
67+
renderChatMarkdown("[Open](<D:/Program Files/example.md>)", { parseRawHtml }),
68+
).toContain('href="D:/Program%20Files/example.md"');
69+
});
70+
71+
it(`still drops an unsafe scheme with parseRawHtml=${parseRawHtml}`, () => {
72+
const html = renderChatMarkdown("[Click](javascript:alert(1))", { parseRawHtml });
73+
expect(html).not.toContain("javascript:");
74+
});
75+
76+
it(`leaves ordinary destinations alone with parseRawHtml=${parseRawHtml}`, () => {
77+
expect(renderChatMarkdown("[Docs](https://example.com/docs)", { parseRawHtml })).toContain(
78+
'href="https://example.com/docs"',
79+
);
80+
});
81+
}
82+
});
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import { toFilesystemLinkUrl } from "./markdown-links";
2+
3+
interface MarkdownAstNode {
4+
readonly type: string;
5+
url?: unknown;
6+
children?: MarkdownAstNode[];
7+
}
8+
9+
/**
10+
* Rewrite Windows drive link destinations to the `file:` URLs they can survive
11+
* the rest of the pipeline as.
12+
*
13+
* `[open](D:/src/main.ts)` renders as styled but dead text otherwise: with raw
14+
* HTML parsing on, `rehype-sanitize` reads `D:` as an unknown protocol and
15+
* removes the href before `urlTransform` ever sees it, and with it off
16+
* `defaultUrlTransform` returns an empty string for the same reason. Rewriting
17+
* at the syntax-tree stage covers both, because remark plugins run either way.
18+
*
19+
* The renderer still receives a plain path: `rewriteMarkdownFileUriHref` maps
20+
* the `file:` URL back on the way out, which is the form the resolved file
21+
* links are keyed by.
22+
*/
23+
export function remarkFilesystemLinkDestinations() {
24+
return (tree: MarkdownAstNode): void => {
25+
const visit = (node: MarkdownAstNode): void => {
26+
// Reference definitions carry a destination too, so `[a][ref]` behaves the
27+
// same as the inline form.
28+
if ((node.type === "link" || node.type === "definition") && typeof node.url === "string") {
29+
const fileUrl = toFilesystemLinkUrl(node.url);
30+
if (fileUrl !== null) {
31+
node.url = fileUrl;
32+
}
33+
}
34+
node.children?.forEach(visit);
35+
};
36+
visit(tree);
37+
};
38+
}

‎apps/web/src/markdown-links.test.ts‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
resolveMarkdownFileLinkMeta,
66
resolveMarkdownFileLinkTarget,
77
rewriteMarkdownFileUriHref,
8+
toFilesystemLinkUrl,
89
} from "./markdown-links";
910

1011
describe("rewriteMarkdownFileUriHref", () => {
@@ -35,6 +36,60 @@ describe("rewriteMarkdownFileUriHref", () => {
3536
});
3637
});
3738

39+
describe("toFilesystemLinkUrl", () => {
40+
it("maps a drive destination to a file url", () => {
41+
expect(toFilesystemLinkUrl("D:/tmp/example.md")).toBe("file:///D:/tmp/example.md");
42+
});
43+
44+
it("normalizes separators so backslash and slash forms share one key", () => {
45+
expect(toFilesystemLinkUrl("M:\\batches\\docs\\prompt.md")).toBe(
46+
"file:///M:/batches/docs/prompt.md",
47+
);
48+
expect(toFilesystemLinkUrl("M:\\batches\\docs\\prompt.md")).toBe(
49+
toFilesystemLinkUrl("M:/batches/docs/prompt.md"),
50+
);
51+
});
52+
53+
it("round-trips back to the path the renderer receives", () => {
54+
const fileUrl = toFilesystemLinkUrl("D:/tmp/example.md");
55+
expect(fileUrl).not.toBeNull();
56+
expect(rewriteMarkdownFileUriHref(fileUrl!)).toBe("D:/tmp/example.md");
57+
});
58+
59+
it("unwraps angle-bracketed drive destinations", () => {
60+
expect(toFilesystemLinkUrl(" <D:/Programme/t3code/AGENTS.md> ")).toBe(
61+
"file:///D:/Programme/t3code/AGENTS.md",
62+
);
63+
});
64+
65+
it("leaves everything that is not a drive destination alone", () => {
66+
expect(toFilesystemLinkUrl("https://example.com")).toBeNull();
67+
expect(toFilesystemLinkUrl("./relative.md")).toBeNull();
68+
expect(toFilesystemLinkUrl("/Users/julius/project/AGENTS.md")).toBeNull();
69+
expect(toFilesystemLinkUrl("file:///D:/tmp/example.md")).toBeNull();
70+
expect(toFilesystemLinkUrl(undefined)).toBeNull();
71+
});
72+
73+
it("resolves the shapes the link scan misses, which the anchor falls back to", () => {
74+
// Balanced parentheses and spaced destinations never reach the metadata map,
75+
// so the anchor resolves them directly; that only works if these resolve.
76+
expect(resolveMarkdownFileLinkMeta("D:/tmp/example(1).md")).toMatchObject({
77+
basename: "example(1).md",
78+
});
79+
expect(resolveMarkdownFileLinkMeta("D:/Program Files/example.md")).toMatchObject({
80+
basename: "example.md",
81+
});
82+
});
83+
84+
it("does not take a multi-letter scheme", () => {
85+
// A drive letter is one character, so nothing that could carry script
86+
// matches; those stay with the transform that already rejects them.
87+
expect(toFilesystemLinkUrl("javascript:alert(1)")).toBeNull();
88+
expect(toFilesystemLinkUrl("data:text/html,<script>")).toBeNull();
89+
expect(toFilesystemLinkUrl("D:alert(1)")).toBeNull();
90+
});
91+
});
92+
3893
describe("resolveMarkdownFileLinkTarget", () => {
3994
it("resolves absolute posix file paths", () => {
4095
expect(resolveMarkdownFileLinkTarget("/Users/julius/project/AGENTS.md")).toBe(

‎apps/web/src/markdown-links.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,25 @@ export function rewriteMarkdownFileUriHref(href: string | undefined): string | n
108108
return `${target.path}${target.hash}`;
109109
}
110110

111+
/**
112+
* The `file:` URL for a Windows drive destination, or null for anything else.
113+
*
114+
* A destination like `D:/src/main.ts` cannot reach the anchor renderer as
115+
* written: `D:` reads as an unknown protocol, so `rehype-sanitize` drops the
116+
* href and React Markdown's `defaultUrlTransform` blanks it. Both already allow
117+
* `file:`, and `rewriteMarkdownFileUriHref` turns that back into a plain path,
118+
* so this is the one form a drive path can travel in.
119+
*
120+
* Separators are normalized because a `file:` URL cannot carry backslashes;
121+
* link keys go through here too, so both sides of the lookup agree.
122+
*/
123+
export function toFilesystemLinkUrl(destination: string | undefined): string | null {
124+
if (!destination) return null;
125+
const normalized = normalizeMarkdownLinkDestination(destination);
126+
if (!WINDOWS_DRIVE_PATH_PATTERN.test(normalized)) return null;
127+
return `file:///${normalized.replaceAll("\\", "/")}`;
128+
}
129+
111130
function looksLikePosixFilesystemPath(path: string): boolean {
112131
if (!path.startsWith("/")) return false;
113132
if (POSIX_FILE_ROOT_PREFIXES.some((prefix) => path.startsWith(prefix))) return true;

0 commit comments

Comments
 (0)