Skip to content

Commit 91b520e

Browse files
committed
fix(web): Markdown images and links render when a Windows path contains a space
CommonMark ends a bare link destination at its first space, so an agent's ![shot](C:\Users\First Last\shot.png) rendered as plain text, and the backslash before .claude in the path was eaten as an escape. Agents write Windows paths unwrapped, and every user whose home folder has a space hits it. Before parsing, a space inside a destination that starts with a drive path becomes a placeholder of the same length, so source offsets do not move; the parser restores the spaces in the tree it returns. Code spans and fenced code are left as written. Fixes #26685.
1 parent 80a2351 commit 91b520e

4 files changed

Lines changed: 125 additions & 2 deletions

File tree

‎packages/shared/src/markdownLinks.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,10 @@ describe("extractMarkdownLinkHrefs", () => {
9999
["[".repeat(32_000), []],
100100
["[a](<foo)bar> invalid [b](ok)", ["<foo", "ok"]],
101101
["[[[nested](src/main.ts) [unfinished", ["src/main.ts"]],
102+
[
103+
String.raw`[a](C:\Users\Jo Doe\.t3\a.png) [b](C:\Jo Doe\b.html "B")`,
104+
[String.raw`C:\Users\Jo Doe\.t3\a.png`, String.raw`C:\Jo Doe\b.html`],
105+
],
102106
])("extracts links from incomplete and nested text", (markdown, hrefs) => {
103107
expect(extractMarkdownLinkHrefs(markdown)).toEqual(hrefs);
104108
});

‎packages/shared/src/markdownLinks.ts‎

Lines changed: 60 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -380,8 +380,66 @@ function markdownLinkDestinationScanner(markdown: string) {
380380
};
381381
}
382382

383-
export function extractMarkdownLinkHrefs(markdown: string): string[] {
383+
// Stands in for a space inside a drive path destination while CommonMark parses it. One UTF-16
384+
// unit, so every source offset the renderers read stays where it was.
385+
const DESTINATION_SPACE = "\uE020";
386+
387+
// `](C:\Users\Jo Doe\shot.png)` or with a title. Parentheses inside the path must balance.
388+
const SPACED_DRIVE_DESTINATION =
389+
/\]\([ \t]*([A-Za-z]:[\\/](?:[^()\n]|\([^()\n]*\))*?)(?=(?:[ \t]+"[^"\n]*")?[ \t]*\))/g;
390+
const HAS_SPACED_DRIVE_DESTINATION = /\]\([ \t]*[A-Za-z]:[\\/][^)\n]* [^)\n]*\)/;
391+
const CODE_FENCE = /^ {0,3}(`{3,}|~{3,})/;
392+
const INLINE_CODE = /(`+)[^`]*?\1/g;
393+
394+
function protectDestinationsOutsideInlineCode(line: string): string {
395+
let result = "";
396+
let cursor = 0;
397+
const protect = (segment: string) =>
398+
segment.replace(
399+
SPACED_DRIVE_DESTINATION,
400+
(match: string, destination: string) =>
401+
match.slice(0, match.length - destination.length) +
402+
destination.replaceAll(" ", DESTINATION_SPACE),
403+
);
404+
for (const code of line.matchAll(INLINE_CODE)) {
405+
result += protect(line.slice(cursor, code.index)) + code[0];
406+
cursor = code.index + code[0].length;
407+
}
408+
return result + protect(line.slice(cursor));
409+
}
410+
411+
/**
412+
* CommonMark ends a bare destination at its first space, so `![shot](C:\Users\Jo Doe\a.png)`
413+
* renders as text. Agents write Windows paths that way, so a drive path destination keeps its
414+
* spaces until the parser has read it. Code stays as written.
415+
*/
416+
export function protectSpacedWindowsDestinations(markdown: string): string {
417+
if (!HAS_SPACED_DRIVE_DESTINATION.test(markdown)) return markdown;
418+
let fence: string | null = null;
419+
return markdown
420+
.split("\n")
421+
.map((line) => {
422+
const marker = CODE_FENCE.exec(line)?.[1];
423+
if (fence !== null) {
424+
if (marker && marker[0] === fence[0] && marker.length >= fence.length) fence = null;
425+
return line;
426+
}
427+
if (marker) {
428+
fence = marker;
429+
return line;
430+
}
431+
return line.includes("](") ? protectDestinationsOutsideInlineCode(line) : line;
432+
})
433+
.join("\n");
434+
}
435+
436+
export function restoreWindowsDestinationSpaces(value: string): string {
437+
return value.includes(DESTINATION_SPACE) ? value.replaceAll(DESTINATION_SPACE, " ") : value;
438+
}
439+
440+
export function extractMarkdownLinkHrefs(source: string): string[] {
384441
const hrefs: string[] = [];
442+
const markdown = protectSpacedWindowsDestinations(source);
385443
const scanDestination = markdownLinkDestinationScanner(markdown);
386444
let cursor = 0;
387445
while (cursor < markdown.length) {
@@ -396,7 +454,7 @@ export function extractMarkdownLinkHrefs(markdown: string): string[] {
396454
if (!destination) continue;
397455
cursor = destination.end;
398456
const href = markdown.slice(destination.hrefStart, destination.hrefEnd).trim();
399-
if (href) hrefs.push(href);
457+
if (href) hrefs.push(restoreWindowsDestinationSpaces(href));
400458
}
401459
return hrefs;
402460
}

‎packages/shared/src/markdownPipeline.test.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,42 @@ it("keeps backslashes that CommonMark would read as escapes in prose Windows pat
118118
);
119119
});
120120

121+
it("reads Windows drive path destinations that contain spaces", () => {
122+
const processor = unified()
123+
.use(remarkParse)
124+
.use(CHAT_MARKDOWN_REMARK_PLUGINS)
125+
.use(remarkRehype, { allowDangerousHtml: true })
126+
.use(CHAT_MARKDOWN_REHYPE_PLUGINS);
127+
type Node = {
128+
type: string;
129+
value?: string;
130+
tagName?: string;
131+
properties?: { href?: string; dataLocalSrc?: string };
132+
children?: Node[];
133+
};
134+
const shape = (node: Node): string =>
135+
node.type === "text"
136+
? (node.value ?? "")
137+
: node.tagName === "img"
138+
? `<img ${decodeURIComponent(node.properties?.dataLocalSrc ?? "")}>`
139+
: node.tagName === "a"
140+
? `<a ${decodeURIComponent(node.properties?.href ?? "")}>`
141+
: (node.children ?? []).map(shape).join("");
142+
const render = (markdown: string) => shape(processor.runSync(processor.parse(markdown)) as Node);
143+
144+
expect(render(String.raw`![Nell's line](C:\Users\Jo Doe\.claude\shot.png)`)).toBe(
145+
String.raw`<img C:\Users\Jo Doe\.claude\shot.png>`,
146+
);
147+
expect(render(String.raw`[balance.html](C:\Program Files (x86)\a b\balance.html "Run")`)).toBe(
148+
"<a file:///C:/Program Files (x86)/a b/balance.html>",
149+
);
150+
expect(
151+
render(
152+
"`[a](C:\\Jo Doe\\a.png)`\n\n```md\n![a](C:\\Jo Doe\\a.png)\n```\n\n[a](C:\\Jo Doe\\a.png",
153+
),
154+
).toBe("[a](C:\\Jo Doe\\a.png)\n![a](C:\\Jo Doe\\a.png)\n\n[a](C:\\Jo Doe\\a.png");
155+
});
156+
121157
it("keeps an image on its own line under a label but leaves inline images inline", () => {
122158
const processor = unified()
123159
.use(remarkParse)

‎packages/shared/src/markdownWindowsPaths.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,22 @@
11
import type { Processor } from "unified";
2+
import {
3+
protectSpacedWindowsDestinations,
4+
restoreWindowsDestinationSpaces,
5+
} from "./markdownLinks.ts";
26
import { isWindowsAbsolutePath } from "./path.ts";
37

8+
interface RestorableNode {
9+
value?: unknown;
10+
url?: unknown;
11+
children?: RestorableNode[];
12+
}
13+
14+
function restoreTreeDestinationSpaces(node: RestorableNode) {
15+
if (typeof node.url === "string") node.url = restoreWindowsDestinationSpaces(node.url);
16+
if (typeof node.value === "string") node.value = restoreWindowsDestinationSpaces(node.value);
17+
node.children?.forEach(restoreTreeDestinationSpaces);
18+
}
19+
420
interface DestinationCompileContext {
521
readonly stack: ReadonlyArray<{ readonly type: string; url?: string }>;
622
resume(): string;
@@ -64,4 +80,13 @@ export function remarkKeepWindowsPaths(this: Processor) {
6480
characterEscape: keepWindowsPathEscape,
6581
},
6682
});
83+
const parse = this.parser;
84+
if (!parse) return;
85+
// Restore before returning, so parsers that cache this tree (streaming) keep the real spaces.
86+
this.parser = (document, file) => {
87+
const protectedDocument = protectSpacedWindowsDestinations(document);
88+
const tree = parse(protectedDocument, file);
89+
if (protectedDocument !== document) restoreTreeDestinationSpaces(tree as RestorableNode);
90+
return tree;
91+
};
6792
}

0 commit comments

Comments
 (0)