Open History to see the last commit
1import { expect, it } from "vite-plus/test";
2import { type PluggableList, unified } from "unified";
3import rehypeRaw from "rehype-raw";
4import remarkGfm from "remark-gfm";
5import remarkParse from "remark-parse";
6import remarkRehype from "remark-rehype";
7import type { Link, Root, RootContent } from "mdast";
8import {
9 CHAT_MARKDOWN_REHYPE_PLUGINS,
10 CHAT_MARKDOWN_REMARK_PLUGINS,
11 CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS,
12 CHAT_USER_MARKDOWN_REMARK_PLUGINS,
13 chatMarkdownImageSources,
14 remarkAssistantInsights,
15 remarkEnableOrderedListNumbers,
16} from "./markdownPipeline.ts";
17
18it.each([
19 ["default", CHAT_MARKDOWN_REMARK_PLUGINS],
20 ["with breaks", CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS],
21] as const)("preserves bare URL boundaries (%s)", (_, plugins) => {
22 const processor = unified().use(remarkParse).use(plugins);
23 const shape = (node: Root | RootContent): string => {
24 if (node.type === "text") return node.value;
25 if (node.type === "inlineCode") return `\`${node.value}\``;
26 if (node.type === "code") return `\`\`\`${node.value}\`\`\``;
27 const children = "children" in node ? node.children.map(shape).join("") : "";
28 if (node.type === "link") return `[${children}](${node.url})`;
29 if (node.type === "linkReference") return `[${children}][${node.identifier}]`;
30 if (node.type === "emphasis") return `*${children}*`;
31 if (node.type === "strong") return `**${children}**`;
32 if (node.type === "delete") return `~~${children}~~`;
33 return children;
34 };
35 const link = (url: string) => `[${url}](${/^www\./i.test(url) ? `http://${url}` : url})`;
36 for (const url of [
37 "https://x.com/dimasike_",
38 "http://example.com/name__",
39 "HTTPS://example.com/name_",
40 "https://example.com/a_(b)_",
41 "https://example.com/?name=value_",
42 "https://example.com/#section_",
43 "https://example.com/a_?name=value_#section_",
44 "https://example.com/name~",
45 "https://example.com/name~~",
46 "https://example.com/name_~",
47 "https://example.com/name~_",
48 "https://example.com/name__~~_",
49 "https://example.com/?name=value~",
50 "https://example.com/#section~",
51 "www.example.com/name_",
52 "www.example.com/name~_",
53 "WWW.example.com/name~~",
54 "https://example.com/name-",
55 "https://example.com/name/",
56 "https://example.com/name%5F",
57 "https://example.com/name%7E",
58 ]) {
59 for (const punctuation of ["", ".", ",", "!", "?", ":", ";", ")", "]", '"']) {
60 const markdown = `See ${url}${punctuation} next`;
61 expect(shape(processor.runSync(processor.parse(markdown), markdown) as Root), markdown).toBe(
62 `See ${link(url)}${punctuation} next`,
63 );
64 }
65 }
66 for (const [markdown, expected] of [
67 ["*https://x.com/dimasike_*", `*${link("https://x.com/dimasike_")}*`],
68 ["**https://x.com/dimasike_**", `**${link("https://x.com/dimasike_")}**`],
69 ["_https://x.com/dimasike_", `*${link("https://x.com/dimasike")}*`],
70 ["__https://x.com/dimasike__", `**${link("https://x.com/dimasike")}**`],
71 ["~~https://example.com/name_~~", `~~${link("https://example.com/name_")}~~`],
72 ["~~https://example.com/name~~", `~~${link("https://example.com/name")}~~`],
73 ["~https://example.com/name~", `~~${link("https://example.com/name")}~~`],
74 ["*https://example.com/name~*", `*${link("https://example.com/name~")}*`],
75 ["_https://example.com/name~_", `*${link("https://example.com/name~")}*`],
76 ["[test](https://example.com/name~)", "[test](https://example.com/name~)"],
77 ["[https://x.com/a](https://x.com/a)~_", `${link("https://x.com/a")}~_`],
78 ["<https://x.com/a>~_", `${link("https://x.com/a")}~_`],
79 ["[test][ref]~_\n\n[ref]: https://x.com/a~_", "[test][ref]~_"],
80 ["`https://example.com/name~_`", "`https://example.com/name~_`"],
81 ["```\nhttps://example.com/name~_\n```", "```https://example.com/name~_```"],
82 ["https\\://example.com/name~_", link("https://example.com/name~_")],
83 ["https://example.com/name. _~", `${link("https://example.com/name")}. _~`],
84 ["Mail person@example.com_", "Mail person@example.com_"],
85 ["Mail person@example.com ~_", "Mail [person@example.com](mailto:person@example.com) ~_"],
86 ["[test](https://x.com/dimasike_)", "[test](https://x.com/dimasike_)"],
87 ["[https://x.com/a](https://x.com/a)_", `${link("https://x.com/a")}_`],
88 ["<https://x.com/a>_", `${link("https://x.com/a")}_`],
89 ["[test][ref]_\n\n[ref]: https://x.com/a_", "[test][ref]_"],
90 ["`https://x.com/dimasike_`", "`https://x.com/dimasike_`"],
91 ["```\nhttps://x.com/dimasike_\n```", "```https://x.com/dimasike_```"],
92 ["https://x.com/a. _", `${link("https://x.com/a")}. _`],
93 ["https\\://x.com/dimasike_", link("https://x.com/dimasike_")],
94 ["https://x.com/a\\_", link("https://x.com/a\\_")],
95 ["https://x.com/a_", `${link("https://x.com/a_")};`],
96 [
97 "可以看了:**http://localhost:18780**(已重启)。",
98 `可以看了:**${link("http://localhost:18780")}**(已重启)。`,
99 ],
100 ["打开 http://localhost:18780,然后刷新", `打开 ${link("http://localhost:18780")},然后刷新`],
101 ["URL:https://example.com/a。下一句", `URL:${link("https://example.com/a")}。下一句`],
102 ["(预览:http://localhost:18780)", `(预览:${link("http://localhost:18780")})`],
103 [
104 "能打开 http://localhost:3000?见 http://localhost:3001;「www.example.com」",
105 `能打开 ${link("http://localhost:3000")}?见 ${link("http://localhost:3001")};「${link("www.example.com")}」`,
106 ],
107 [
108 "__http://localhost:18780__,*http://localhost:3000*,~~http://localhost:3001~~。",
109 `**${link("http://localhost:18780")}**,*${link("http://localhost:3000")}*,~~${link("http://localhost:3001")}~~。`,
110 ],
111 [
112 "foo**http://localhost:18780**(bar)***http://localhost:3000***。",
113 `foo**${link("http://localhost:18780")}**(bar)***${link("http://localhost:3000")}***。`,
114 ],
115 [
116 "http://a.com。http://b.com,www.c.com、person@example.com。",
117 `${link("http://a.com")}。${link("http://b.com")},${link("www.c.com")}、[person@example.com](mailto:person@example.com)。`,
118 ],
119 [
120 "**http://localhost:18780**(重启)。 https://example.com/a。结束",
121 `**${link("http://localhost:18780")}**(重启)。 ${link("https://example.com/a")}。结束`,
122 ],
123 ["# **http://localhost:3000**,刷新", `**${link("http://localhost:3000")}**,刷新`],
124 [
125 "| a |\n| - |\n| **http://localhost:3000**,刷新 |",
126 `a**${link("http://localhost:3000")}**,刷新`,
127 ],
128 ["www.example.com/preview。下一句", `${link("www.example.com/preview")}。下一句`],
129 ["https://example.com/a_。下一句", `${link("https://example.com/a_")}。下一句`],
130 ["https://example.com/a.,下一句", `${link("https://example.com/a")}.,下一句`],
131 [
132 "https://example.com/search?q=hello,world",
133 `${link("https://example.com/search?q=hello")},world`,
134 ],
135 ["https://example.com/日本語,続き", link("https://example.com/日本語,続き")],
136 [
137 "https://zh.wikipedia.org/wiki/北京(城市)",
138 link("https://zh.wikipedia.org/wiki/北京(城市)"),
139 ],
140 ["https://example.com/a%EF%BC%8Cb", link("https://example.com/a%EF%BC%8Cb")],
141 ["<https://example.com/日本語,続き>", link("https://example.com/日本語,続き")],
142 ["[記事](https://example.com/a,b)", "[記事](https://example.com/a,b)"],
143 ["[http://example.com/a,b](http://example.com/a,b)", link("http://example.com/a,b")],
144 ["`https://example.com/a。次`", "`https://example.com/a。次`"],
145 [
146 "منشور على https://example.com/report، ونسخته",
147 `منشور على ${link("https://example.com/report")}، ونسخته`,
148 ],
149 [
150 "هل يعمل **http://localhost:3000**؟ نعم؛ www.example.com۔",
151 `هل يعمل **${link("http://localhost:3000")}**؟ نعم؛ ${link("www.example.com")}۔`,
152 ],
153 [
154 "https://x.com/a_ https://x.com/b_",
155 `${link("https://x.com/a_")} ${link("https://x.com/b_")}`,
156 ],
157 ] as const) {
158 expect(shape(processor.runSync(processor.parse(markdown), markdown) as Root), markdown).toBe(
159 expected,
160 );
161 }
162 for (const url of ["https://x.com/dimasike_", "www.example.com/name~_"]) {
163 const markdown = `${url}, next`;
164 const boundary = { line: 1, column: url.length + 1, offset: url.length };
165 expect(processor.runSync(processor.parse(markdown), markdown)).toMatchObject({
166 children: [
167 {
168 children: [
169 {
170 type: "link",
171 url: /^www\./i.test(url) ? `http://${url}` : url,
172 position: { end: boundary },
173 children: [{ type: "text", value: url, position: { end: boundary } }],
174 },
175 { type: "text", value: ", next", position: { start: boundary } },
176 ],
177 },
178 ],
179 });
180 }
181});
182
183it("ends bare URLs at CJK and Arabic punctuation with source positions", () => {
184 const processor = unified().use(remarkParse).use(CHAT_MARKDOWN_REMARK_PLUGINS);
185 const parse = (markdown: string) => processor.runSync(processor.parse(markdown), markdown);
186 const at = (line: number, column: number, offset: number) => ({ line, column, offset });
187 const url = "http://localhost:18780";
188 expect(parse(`第一行\n可以看了:**${url}**(已重启)。`)).toMatchObject({
189 children: [
190 {
191 children: [
192 { type: "text", value: "第一行\n可以看了:", position: { end: at(2, 6, 9) } },
193 {
194 type: "strong",
195 position: { start: at(2, 6, 9), end: at(2, 32, 35) },
196 children: [
197 {
198 type: "link",
199 url,
200 position: { start: at(2, 8, 11), end: at(2, 30, 33) },
201 children: [{ type: "text", value: url, position: { end: at(2, 30, 33) } }],
202 },
203 ],
204 },
205 {
206 type: "text",
207 value: "(已重启)。",
208 position: { start: at(2, 32, 35), end: at(2, 38, 41) },
209 },
210 ],
211 },
212 ],
213 });
214 // Markup the URL swallowed comes back once the URL ends.
215 expect(parse(`打开 ${url},然后运行\`pnpm dev\``)).toMatchObject({
216 children: [
217 {
218 children: [
219 { type: "text", value: "打开 " },
220 { type: "link", url },
221 { type: "text", value: ",然后运行" },
222 { type: "inlineCode", value: "pnpm dev" },
223 ],
224 },
225 ],
226 });
227 // Every URL in one paragraph ends at its mark, with positions on its own line.
228 const lines = Array.from({ length: 300 }, (_, index) => `接口:http://localhost:${index},`);
229 const [paragraph] = (parse(lines.join("\n")) as Root).children;
230 const links =
231 paragraph?.type === "paragraph"
232 ? paragraph.children.filter((node): node is Link => node.type === "link")
233 : [];
234 expect(links.map((node) => node.url)).toEqual(
235 lines.map((_, index) => `http://localhost:${index}`),
236 );
237 const lastLine = lines.slice(0, -1).join("\n").length + 1;
238 expect(links.at(-1)).toMatchObject({
239 position: { start: at(300, 4, lastLine + 3), end: at(300, 24, lastLine + 23) },
240 });
241 // Only a table unescapes `\|` in code, so that cell keeps its parse and the URL is cut.
242 const descendants = (node: Root | RootContent): RootContent[] =>
243 "children" in node
244 ? (node.children as RootContent[]).flatMap((child) => [child, ...descendants(child)])
245 : [];
246 const cell = descendants(parse("| a |\n| - |\n| http://example.com, `a\\|b` |") as Root);
247 expect(cell.flatMap((node) => (node.type === "link" ? [node.url] : []))).toEqual([
248 "http://example.com",
249 ]);
250 expect(cell.flatMap((node) => (node.type === "inlineCode" ? [node.value] : []))).toEqual(["a|b"]);
251 // A task item's checkbox is not part of its paragraph's text.
252 const task = descendants(parse("- [x] http://example.com,刷新") as Root);
253 expect(task.flatMap((node) => (node.type === "text" ? [node.value] : []))).toEqual([
254 "http://example.com",
255 ",刷新",
256 ]);
257 // A list item's indentation stays out of a code span that crosses lines.
258 const code = descendants(parse("- `echo\n hello` http://example.com,结束") as Root);
259 expect(code.flatMap((node) => (node.type === "link" ? [node.url] : []))).toEqual([
260 "http://example.com",
261 ]);
262 expect(code.flatMap((node) => (node.type === "inlineCode" ? [node.value] : []))).toEqual([
263 "echo\nhello",
264 ]);
265 // A list item's continuation line parses the same on its own.
266 expect(parse(`- 第一行\n **${url}**(已重启)`)).toMatchObject({
267 children: [
268 {
269 children: [
270 {
271 children: [
272 {
273 children: [
274 { type: "text", value: "第一行\n" },
275 { type: "strong", children: [{ type: "link", url }] },
276 { type: "text", value: "(已重启)" },
277 ],
278 },
279 ],
280 },
281 ],
282 },
283 ],
284 });
285 // A quote's continuation line does not, so the URL ends and the asterisks stay as text.
286 expect(parse(`> 第一行\n> **${url}**(已重启)`)).toMatchObject({
287 children: [
288 {
289 children: [
290 {
291 children: [
292 { type: "text", value: "第一行\n**" },
293 { type: "link", url, position: { end: at(2, 27, 32) } },
294 { type: "text", value: "**(已重启)", position: { start: at(2, 27, 32) } },
295 ],
296 },
297 ],
298 },
299 ],
300 });
301});
302
303const insightRule = "─".repeat(20);
304const insightFence = (body: string, wrap = "") =>
305 [`${wrap}★ Insight ${insightRule}${wrap}`, body, `${wrap}${insightRule}${wrap}`].join("\n");
306
307it.each(["", "`"])("groups %j insight fences while preserving surrounding markdown", (wrap) => {
308 const markdown = [
309 "Before **bold** and [reference][src].",
310 "",
311 insightFence("- Also [reference][src].", wrap),
312 "",
313 "After.",
314 "",
315 '[src]:\n https://example.com\n "Source"',
316 ].join("\n");
317 const processor = unified()
318 .use(remarkParse)
319 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
320 .use(remarkAssistantInsights)
321 .use(remarkRehype)
322 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
323 const tree = processor.runSync(processor.parse(markdown), markdown);
324 expect(
325 tree.children.filter((node) => node.type === "element").map((node) => node.tagName),
326 ).toEqual(["p", "blockquote", "p"]);
327 expect(
328 tree.children.find((node) => node.type === "element" && node.tagName === "blockquote"),
329 ).toMatchObject({ properties: { dataAlert: "insight" } });
330 expect(JSON.stringify(tree).match(/"href":"https:\/\/example.com"/g)).toHaveLength(2);
331 expect(JSON.stringify(tree)).toContain('"tagName":"strong"');
332 expect(JSON.stringify(tree)).not.toContain(insightRule);
333});
334
335it.each([
336 ["```text", "★ Insight " + insightRule, "literal", insightRule, "```"].join("\n"),
337 ["- ```text", " ★ Insight " + insightRule, " literal", " " + insightRule, " ```"].join("\n"),
338 [" ★ Insight " + insightRule, " literal", " " + insightRule].join("\n"),
339 ["Paragraph.", " ★ Insight " + insightRule, " literal", " " + insightRule].join("\n"),
340 ["`example", "★ Insight " + insightRule, "literal", insightRule, "`"].join("\n"),
341 insightFence("quoted")
342 .split("\n")
343 .map((line) => "> " + line)
344 .join("\n"),
345])("leaves literal and nested insight examples unchanged: %s", (markdown) => {
346 const processor = unified().use(remarkParse).use(remarkAssistantInsights);
347 const tree = processor.parse(markdown);
348 expect(processor.runSync(structuredClone(tree), markdown)).toEqual(tree);
349});
350
351it("groups streaming bodies and several insights without losing code or headings", () => {
352 const markdown = [
353 "## Setup",
354 "",
355 insightFence("```text\n" + insightRule + "\n```"),
356 "",
357 "## Setup",
358 "",
359 "★ Insight " + insightRule,
360 "Still **streaming**",
361 ].join("\n");
362 const processor = unified().use(remarkParse).use(remarkAssistantInsights);
363 const tree = processor.parse(markdown);
364 processor.runSync(tree, markdown);
365 expect(tree.children.map((node) => node.type)).toEqual([
366 "heading",
367 "blockquote",
368 "heading",
369 "blockquote",
370 ]);
371 expect(tree.children[1]).toMatchObject({ children: [{ type: "code", value: insightRule }] });
372 expect(tree.children[3]).toMatchObject({
373 children: [
374 { type: "paragraph", children: [{ type: "text", value: "Still " }, { type: "strong" }] },
375 ],
376 });
377});
378
379it("keeps reference definitions out of unfinished streaming code", () => {
380 const markdown = `[src]: https://example.com\n\n★ Insight ${insightRule}\n\`\`\`ts\nconst value = 1`;
381 const processor = unified().use(remarkParse).use(remarkAssistantInsights);
382 const tree = processor.parse(markdown);
383 processor.runSync(tree, markdown);
384 expect(tree.children.find((node) => node.type === "blockquote")).toMatchObject({
385 children: [{ type: "code", value: "const value = 1" }],
386 });
387});
388
389it("preserves footnotes and original code positions across a callout", () => {
390 const code = "```sh\necho hello\n```";
391 const markdown = ["Before[^n].", "", insightFence(code), "", "[^n]: Footnote."].join("\n");
392 const processor = unified()
393 .use(remarkParse)
394 .use(remarkAssistantInsights)
395 .use(CHAT_MARKDOWN_REMARK_PLUGINS);
396 const tree = processor.parse(markdown);
397 processor.runSync(tree, markdown);
398 expect(tree.children[0]).toMatchObject({
399 children: [
400 { type: "text", value: "Before" },
401 { type: "footnoteReference", identifier: "n" },
402 { type: "text", value: "." },
403 ],
404 });
405 expect(tree.children.at(-1)).toMatchObject({ type: "footnoteDefinition", identifier: "n" });
406 const note = tree.children.find((node) => node.type === "blockquote");
407 const block = note?.children[0];
408 expect(markdown.slice(block?.position?.start.offset, block?.position?.end.offset)).toBe(code);
409});
410
411it("preserves in-app thread links through the shared Markdown sanitizer", () => {
412 const processor = unified()
413 .use(remarkParse)
414 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
415 .use(remarkRehype, { allowDangerousHtml: true })
416 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
417 const tree = processor.runSync(
418 processor.parse(
419 '[Open thread](t3-thread://v1/thread)\n\n<t3-thread://v2/environment/thread:a%3A1>\n\n<a href="javascript:alert(1)">Unsafe</a>',
420 ),
421 );
422 expect(tree.children[0]).toMatchObject({
423 tagName: "p",
424 children: [
425 {
426 tagName: "a",
427 properties: { href: "t3-thread://v1/thread" },
428 children: [{ type: "text", value: "Open thread" }],
429 },
430 ],
431 });
432 expect(tree.children[2]).toMatchObject({
433 tagName: "p",
434 children: [
435 {
436 tagName: "a",
437 properties: { href: "t3-thread://v2/environment/thread:a%3A1" },
438 children: [{ type: "text", value: "t3-thread://v2/environment/thread:a%3A1" }],
439 },
440 ],
441 });
442 expect(JSON.stringify(tree)).not.toContain("javascript:");
443});
444
445it("builds the tree rehype-raw builds for markdown without HTML", () => {
446 type Node = {
447 type: string;
448 tagName?: string;
449 value?: string;
450 position?: unknown;
451 data?: unknown;
452 children?: Node[];
453 };
454 // What the round trip changes that renders the same; see `needsHtmlParser`.
455 const comparable = (node: Node): Node => {
456 const { position, children, data, ...rest } = node;
457 const result: Node =
458 node.type === "text" || node.type === "root" ? rest : { ...rest, position, data };
459 if (!children) return result;
460 const merged: Node[] = [];
461 for (const child of children.map(comparable)) {
462 const last = merged.at(-1);
463 if (child.type === "text" && last?.type === "text") last.value += child.value ?? "";
464 else merged.push(child);
465 }
466 // Blank text inside a table moves in front of it; the JSX runtime drops it in tables.
467 const inTable = /^(?:table|thead|tbody|tfoot|tr)$/.test(node.tagName ?? "");
468 result.children = merged.filter(
469 (child, index) =>
470 child.type !== "text" ||
471 child.value?.trim() ||
472 !(inTable || merged[index + 1]?.tagName === "table"),
473 );
474 return result;
475 };
476 const tree = (rehypePlugins: typeof CHAT_MARKDOWN_REHYPE_PLUGINS, markdown: string) => {
477 const processor = unified()
478 .use(remarkParse)
479 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
480 .use(remarkRehype, { allowDangerousHtml: true })
481 .use(rehypePlugins);
482 return comparable(processor.runSync(processor.parse(markdown)) as Node);
483 };
484 const [first, , ...rest] = CHAT_MARKDOWN_REHYPE_PLUGINS;
485 const withRaw = [first!, rehypeRaw, ...rest];
486 for (const markdown of [
487 "- [ ] open\n- [x] done\n\nNote[^1]\n\n[^1]: The note.",
488 "| a | b |\n| :- | -: |\n| `c` |  |\n\n```ts title=x\nconst a = 1;\n```",
489 // The HTML parser moves the footnote's link out of the label's link.
490 "[note[^x]](https://example.com)\n\n[^x]: text",
491 "**a** **b**\r\n> - | a |\r\n> | - |\r\n> | b |\r\n\n-\tx\n\n y",
492 ]) {
493 expect(tree(CHAT_MARKDOWN_REHYPE_PLUGINS, markdown)).toEqual(tree(withRaw, markdown));
494 }
495});
496
497it("keeps local editor file links but not other schemes through the shared Markdown sanitizer", () => {
498 const processor = unified()
499 .use(remarkParse)
500 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
501 .use(remarkRehype, { allowDangerousHtml: true })
502 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
503 const tree = processor.runSync(
504 processor.parse(
505 [
506 "[cursor](cursor://file/Users/me/repo/file.md:3)",
507 "[code](vscode://file/Users/me/repo/file.md:3:7)",
508 "[insiders](vscode-insiders://file/Users/me/repo/file.md)",
509 "[unknown](foo://file/Users/me/repo/file.md)",
510 "[zed](zed://file/Users/me/repo/file.md)",
511 ].join(" "),
512 ),
513 );
514 type Node = { tagName?: string; properties?: { href?: string }; children?: Node[] };
515 const hrefs = ((tree.children[0] as Node).children ?? [])
516 .filter((node) => node.tagName === "a")
517 .map((node) => node.properties?.href);
518 expect(hrefs).toEqual([
519 "cursor://file/Users/me/repo/file.md:3",
520 "vscode://file/Users/me/repo/file.md:3:7",
521 "vscode-insiders://file/Users/me/repo/file.md",
522 undefined,
523 undefined,
524 ]);
525});
526
527it("keeps mixed-case local editor file links by lowercasing the scheme before sanitizing", () => {
528 const processor = unified()
529 .use(remarkParse)
530 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
531 .use(remarkRehype, { allowDangerousHtml: true })
532 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
533 const tree = processor.runSync(
534 processor.parse(
535 [
536 "[upper](VSCODE://file/Users/me/repo/file.md:3:7)",
537 "[mixed](Cursor://file/Users/me/repo/file.md:3)",
538 "[other](FOO://file/Users/me/repo/file.md)",
539 ].join(" "),
540 ),
541 );
542 type Node = { tagName?: string; properties?: { href?: string }; children?: Node[] };
543 const hrefs = ((tree.children[0] as Node).children ?? [])
544 .filter((node) => node.tagName === "a")
545 .map((node) => node.properties?.href);
546 expect(hrefs).toEqual([
547 "vscode://file/Users/me/repo/file.md:3:7",
548 "cursor://file/Users/me/repo/file.md:3",
549 undefined,
550 ]);
551});
552
553it("keeps uppercase HTTP(S) link and image URLs by lowercasing the scheme before sanitizing", () => {
554 const processor = unified()
555 .use(remarkParse)
556 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
557 .use(remarkRehype, { allowDangerousHtml: true })
558 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
559 type Node = { tagName?: string; properties?: object; children?: Node[] };
560 const elements = (node: Node): Node[] => [
561 ...(node.tagName === "a" || node.tagName === "img" ? [node] : []),
562 ...(node.children ?? []).flatMap(elements),
563 ];
564 const tree = processor.runSync(
565 processor.parse(
566 [
567 "[upper](HTTPS://Example.com/A?Key=Value#Part) [mixed](hTtP://Example.com/B) [js](JAVASCRIPT:alert(1))",
568 "",
569 "",
570 "",
571 '<picture><source media="(prefers-color-scheme: dark)" srcset="HTTPS://Example.com/Dark.png"><img src="HTTP://Example.com/Light.png"></picture>',
572 ].join("\n"),
573 ),
574 ) as Node;
575 expect(elements(tree).map((node) => node.properties)).toEqual([
576 { href: "https://Example.com/A?Key=Value#Part" },
577 { href: "http://Example.com/B" },
578 {},
579 { src: "https://Example.com/Shot.png", alt: "shot", dataStandalone: true },
580 {
581 src: "http://Example.com/Light.png",
582 dataDarkSrc: "https://Example.com/Dark.png",
583 dataStandalone: true,
584 },
585 ]);
586});
587
588it("keeps uppercase FILE link and image URLs by lowercasing the scheme before sanitizing", () => {
589 const processor = unified()
590 .use(remarkParse)
591 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
592 .use(remarkRehype, { allowDangerousHtml: true })
593 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
594 type Node = { tagName?: string; properties?: object; children?: Node[] };
595 const elements = (node: Node): Node[] => [
596 ...(node.tagName === "a" || node.tagName === "img" ? [node] : []),
597 ...(node.children ?? []).flatMap(elements),
598 ];
599 const markdown = [
600 '[upper](FILE:///tmp/A.md) <a href="FiLe:///C:/Demo%20A.md">raw</a>',
601 "",
602 "",
603 "",
604 '<picture><source media="(prefers-color-scheme: dark)" srcset="FILE:///tmp/Dark.png"><source media="(prefers-color-scheme: light)" srcset="FILE:///tmp/Light.png"><img src="FILE://host/tmp/Fallback.png"></picture>',
605 ].join("\n");
606 const tree = processor.runSync(processor.parse(markdown)) as Node;
607 expect(elements(tree).map((node) => node.properties)).toEqual([
608 { href: "file:///tmp/A.md" },
609 { href: "file:///C:/Demo%20A.md" },
610 { src: "file:///tmp/Shot.png", alt: "shot", dataStandalone: true },
611 {
612 src: "file://host/tmp/Fallback.png",
613 dataDarkSrc: "file:///tmp/Dark.png",
614 dataLightSrc: "file:///tmp/Light.png",
615 dataStandalone: true,
616 },
617 ]);
618 expect(chatMarkdownImageSources(markdown)).toHaveLength(4);
619});
620
621it("keeps raw and percent-encoded Windows drive file links through the shared Markdown sanitizer", () => {
622 const processor = unified()
623 .use(remarkParse)
624 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
625 .use(remarkRehype, { allowDangerousHtml: true })
626 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
627 type Node = { tagName?: string; properties?: { href?: string }; children?: Node[] };
628 const hrefs = (node: Node): Array<string | undefined> => [
629 ...(node.tagName === "a" ? [node.properties?.href] : []),
630 ...(node.children ?? []).flatMap(hrefs),
631 ];
632 const tree = processor.runSync(
633 processor.parse(
634 [
635 "[report.md](<C:%5CUsers%5Ctest%5Creport.md#L7>)",
636 "[lower](c:%5cUsers/test%5creport.md)",
637 "[raw](C:\\Users\\test\\report.md)",
638 "[ref][win]",
639 "",
640 "[win]: <D:%5Cwork%5Creport.md#L12>",
641 ].join("\n"),
642 ),
643 ) as Node;
644 expect(hrefs(tree)).toEqual([
645 "file:///C:/Users/test/report.md#L7",
646 "file:///c:/Users/test/report.md",
647 "file:///C:/Users/test/report.md",
648 "file:///D:/work/report.md#L12",
649 ]);
650});
651
652it("keeps backslashes that CommonMark would read as escapes in prose Windows paths", () => {
653 const processor = unified()
654 .use(remarkParse)
655 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
656 .use(remarkRehype, { allowDangerousHtml: true })
657 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
658 type Node = { type: string; value?: string; tagName?: string; children?: Node[] };
659 const text = (node: Node): string =>
660 node.type === "text"
661 ? (node.value ?? "")
662 : node.tagName === "code"
663 ? `<code>${(node.children ?? []).map(text).join("")}</code>`
664 : (node.children ?? []).map(text).join("");
665 const render = (markdown: string) => text(processor.runSync(processor.parse(markdown)) as Node);
666
667 expect(
668 render(String.raw`Saved to C:\Users\me\.t3\_build and (C:\.scratch) and C:/work\.config.`),
669 ).toBe(String.raw`Saved to C:\Users\me\.t3\_build and (C:\.scratch) and C:/work\.config.`);
670 expect(render(String.raw`Escaped C:\\Users\\me`)).toBe(String.raw`Escaped C:\\Users\\me`);
671 expect(render(String.raw`See C:\x and \*this\* and Note:\*that\*.`)).toBe(
672 String.raw`See C:\x and *this* and Note:*that*.`,
673 );
674 expect(render(String.raw`${"`"}C:\me\.t3${"`"} and C:\me\.t3`)).toBe(
675 String.raw`<code>C:\me\.t3</code> and C:\me\.t3`,
676 );
677});
678
679it("keeps an image on its own line under a label but leaves inline images inline", () => {
680 const processor = unified()
681 .use(remarkParse)
682 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
683 .use(remarkRehype, { allowDangerousHtml: true })
684 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
685 type Node = { type: string; value?: string; tagName?: string; children?: Node[] };
686 const shape = (node: Node): string =>
687 node.type === "text"
688 ? (node.value ?? "")
689 : node.tagName === "br" || node.tagName === "img"
690 ? `<${node.tagName}>`
691 : (node.children ?? []).map(shape).join("");
692 const render = (markdown: string) => shape(processor.runSync(processor.parse(markdown)) as Node);
693
694 expect(
695 render("**Palette**\n\n**Hero** (dark)\n"),
696 ).toBe("Palette<br>\n<img><br>\nHero (dark)<br>\n<img>");
697 expect(render("Built [](/ci)\nand wrapped")).toBe("Built <img>\nand wrapped");
698 expect(render("**Dialog** (native)  ")).toBe(
699 "Dialog (native)<br>\n<img> <img>",
700 );
701 expect(render("Hard-wrapped\nprose")).toBe("Hard-wrapped\nprose");
702});
703
704it("keeps the number written on each ordered list item only when enabled", () => {
705 type Node = { tagName?: string; properties?: { value?: unknown }; children?: Node[] };
706 const values = (node: Node): unknown[] => [
707 ...(node.tagName === "li" ? [node.properties?.value] : []),
708 ...(node.children ?? []).flatMap(values),
709 ];
710 const renderer = (plugins: PluggableList) => {
711 const processor = unified()
712 .use(remarkParse)
713 .use(plugins)
714 .use(remarkRehype, { allowDangerousHtml: true });
715 return (markdown: string) =>
716 values(processor.runSync(processor.parse(markdown), markdown) as Node);
717 };
718 const render = renderer([
719 ...CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS,
720 remarkEnableOrderedListNumbers,
721 ]);
722
723 expect(render("3. first\n5. second\n6. third")).toEqual([undefined, "5", undefined]);
724 expect(render("1. one\n1. one again")).toEqual([undefined, "1"]);
725 expect(render("> 1. quoted\n> 4. skipped")).toEqual([undefined, "4"]);
726 expect(render("1. outer\n 1. nested\n 7. jump\n9. back")).toEqual([
727 undefined,
728 undefined,
729 "7",
730 "9",
731 ]);
732 expect(render("1. one\n2. two\n- bullet")).toEqual([undefined, undefined, undefined]);
733 expect(render("- first block\n\n 3. first\n 5. second")).toEqual([
734 undefined,
735 undefined,
736 "5",
737 ]);
738 expect(
739 renderer(CHAT_MARKDOWN_REMARK_PLUGINS)(
740 "3. first\n5. second\n\n- first block\n\n 3. first\n 5. second",
741 ),
742 ).toEqual([undefined, undefined, undefined, undefined, undefined]);
743});
744
745type ShownNode = {
746 type: string;
747 tagName?: string;
748 value?: string;
749 properties?: Record<string, unknown>;
750 children?: ShownNode[];
751};
752const SHOWN_BLOCKS = new Set([
753 "p",
754 "li",
755 "blockquote",
756 "ul",
757 "ol",
758 "pre",
759 "h1",
760 "h2",
761 "table",
762 "tr",
763]);
764
765/** The text a browser shows, by line: whitespace collapses except in `pre` and kept whitespace. */
766function shownText(tree: ShownNode): string {
767 let out = "";
768 const visit = (node: ShownNode, keep: boolean) => {
769 if (node.type === "text") {
770 const value = node.value ?? "";
771 // Only spaces, tabs and line endings collapse; a no-break space shows.
772 out += keep
773 ? value.replace(/ /g, "\u0001").replace(/\t/g, "\u0002")
774 : value.replace(/[ \t\r\n]/g, " ");
775 }
776 // An image shows as something, which its alt text stands in for.
777 if (node.properties?.alt !== undefined) out += String(node.properties.alt);
778 if (node.tagName === "br" || SHOWN_BLOCKS.has(node.tagName ?? "")) out += "\n";
779 const inner =
780 keep || node.tagName === "pre" || node.properties?.dataLeadingWhitespace !== undefined;
781 node.children?.forEach((child) => visit(child, inner));
782 if (SHOWN_BLOCKS.has(node.tagName ?? "")) out += "\n";
783 };
784 visit(tree, false);
785 return out
786 .split("\n")
787 .map((line) => line.replace(/ +/g, " ").replace(/^ | $/g, ""))
788 .filter(Boolean)
789 .join("\n")
790 .replace(/\u0001/g, " ")
791 .replace(/\u0002/g, "\t");
792}
793
794const hastRenderer = (plugins: PluggableList) => {
795 const processor = unified()
796 .use(remarkParse)
797 .use(plugins)
798 .use(remarkRehype, { allowDangerousHtml: true });
799 return (markdown: string) => processor.runSync(processor.parse(markdown), markdown) as ShownNode;
800};
801const userMessage = hastRenderer([
802 ...CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS,
803 ...CHAT_USER_MARKDOWN_REMARK_PLUGINS,
804]);
805// The user pipeline as it was before leading whitespace was kept.
806const commonMarkUserMessage = hastRenderer([
807 ...CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS,
808 [remarkGfm, { singleTilde: false }],
809]);
810/** The tree with the restored indentation taken out, with the empty texts and positions it leaves. */
811const withoutRestoredWhitespace = ({
812 position: _position,
813 ...node
814}: ShownNode & { position?: unknown }): ShownNode => ({
815 ...node,
816 ...(node.children && {
817 children: node.children
818 .filter(
819 (child) =>
820 child.properties?.dataLeadingWhitespace === undefined &&
821 !(child.type === "text" && child.value === ""),
822 )
823 .map(withoutRestoredWhitespace),
824 }),
825});
826/** Each link's text and where it goes. */
827const linkTargets = (node: ShownNode): [string, unknown][] =>
828 node.properties?.href === undefined
829 ? (node.children ?? []).flatMap(linkTargets)
830 : [[shownText(node), node.properties.href]];
831
832it("shows the spaces and tabs typed at the start of each line of a user message", () => {
833 const shown = (markdown: string) => shownText(userMessage(markdown));
834 const outline = "Plan\n Step one\n Step two\n Detail a\n Detail b";
835 expect(shown(outline)).toBe(outline);
836 expect(shown(outline.replaceAll("\n", "\r\n"))).toBe(outline);
837 expect(shown(" First line\nnext\n\n New paragraph")).toBe(
838 " First line\nnext\n New paragraph",
839 );
840 expect(shown("Plan\n\tTabbed\n \t Mixed")).toBe("Plan\n\tTabbed\n \t Mixed");
841 expect(shown("Plan \n After a hard break\\\n and an escaped one")).toBe(
842 "Plan\n After a hard break\n and an escaped one",
843 );
844 // In a container, only whitespace past its own structure counts.
845 expect(shown("- item\n continued")).toBe("item\ncontinued");
846 expect(shown("- item\n more")).toBe("item\n more");
847 expect(shown("- item\ncontinued")).toBe("item\ncontinued");
848 expect(shown("- item\n continued")).toBe("item\ncontinued");
849 expect(shown("1. one\n two")).toBe("one\n two");
850 expect(shown("- item\n\tsplit tab")).toBe("item\n split tab");
851 expect(shown("- item\n\n second paragraph")).toBe("item\n second paragraph");
852 // An item's content starts after its marker and the marker's spacing. A task's checkbox is
853 // content, so it does not move where continuation lines start, however the task begins.
854 expect(shown("- [ ] task\n under the task")).toBe("task\n under the task");
855 for (const task of ["task", "**task**", "[task](https://example.com)", "`task`"]) {
856 expect(shown(`- [ ] ${task}\n detail`), task).toBe("task\n detail");
857 }
858 expect(shown("- x\n y")).toBe("x\n y");
859 expect(shown("- x\n y")).toBe("x\n y");
860 expect(shown("-\tx\n\t y")).toBe("x\n y");
861 expect(shown("10. x\n y")).toBe("x\n y");
862 expect(shown("> a\n> b")).toBe("a\n b");
863 expect(shown("> first")).toBe(" first");
864 expect(shown("> a\n lazy")).toBe("a\nlazy");
865 expect(shown("> - item\n> more")).toBe("item\n more");
866 expect(shown("- > a\n > b")).toBe("a\n b");
867 expect(shown("- a\n - b\n c")).toBe("a\nb\n c");
868 // List recovery reparses over-indented content; its first line sets the indentation.
869 expect(shown("- first block\n continued\n deeper")).toBe(
870 "first block\ncontinued\n deeper",
871 );
872
873 // A space or tab written as a character reference after the indentation is dropped, as it is
874 // without the indentation; only the typed indentation is added.
875 for (const reference of [" ", " ", "	", "	"]) {
876 expect(shown(`a\n ${reference}b`), reference).toBe("a\n b");
877 expect(shown(`a \n\t${reference}b`), reference).toBe("a\n\tb");
878 expect(shown(`a\\\r\n ${reference}${reference}b`), reference).toBe("a\n b");
879 }
880 // Converting to HTML also drops the spaces that start code or a link's text after a line break.
881 expect(shown("a\n ` npm i`")).toBe("a\n npm i");
882 expect(shown("a\n [ docs](https://example.com)")).toBe("a\n docs");
883 // A line whose text starts with whitespace the browser hides keeps no indentation, as without it.
884 expect(shown("  b")).toBe("b");
885 expect(shown("a\n *** b***")).toBe("a\nb");
886
887 // Only the indentation is added: formatting, code, links and alerts render as without it.
888 const inline = "Plan\n **bold** [link](https://example.com) `code` ~/a and ~~gone~~ /tmp/a.ts";
889 const alert = "> [!NOTE]\n> indented body";
890 expect(shown(inline)).toBe("Plan\n bold link code ~/a and gone /tmp/a.ts");
891 expect(shown(alert)).toBe(" indented body");
892 for (const markdown of [inline, alert]) {
893 expect(withoutRestoredWhitespace(userMessage(markdown)), markdown).toEqual(
894 withoutRestoredWhitespace(commonMarkUserMessage(markdown)),
895 );
896 }
897 expect(linkTargets(userMessage(inline))).toEqual(linkTargets(commonMarkUserMessage(inline)));
898 expect(linkTargets(userMessage(inline)).map(([label]) => label)).toEqual(["link", "/tmp/a.ts"]);
899
900 // A line ending written as a character reference is not a source line: it never takes a typed
901 // line's indentation, and no typed line's indentation moves onto it.
902 const decoded = shown("a b\n c").split("\n");
903 expect(decoded.slice(0, 2)).toEqual(["a", "b"]);
904 expect(["c", " c"]).toContain(decoded[2]);
905
906 // Code, and agent replies, keep CommonMark's reading.
907 for (const markdown of [
908 "```\n code\n more\n```",
909 "Plan\n\n code\n deeper",
910 "- item\n\n code",
911 ]) {
912 expect(userMessage(markdown), markdown).toEqual(commonMarkUserMessage(markdown));
913 }
914 for (const plugins of [CHAT_MARKDOWN_REMARK_PLUGINS, CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS]) {
915 expect(shownText(hastRenderer(plugins)(outline)).replaceAll("\n", " ")).toBe(
916 "Plan Step one Step two Detail a Detail b",
917 );
918 }
919});
920
921it("adds only the typed indentation, and renders what follows it as without it", () => {
922 const starts = [
923 "b",
924 "*b*",
925 "`b`",
926 "~~b~~",
927 "[b](https://example.com)",
928 "",
929 "https://example.com/b",
930 "/tmp/b.ts",
931 "~/b",
932 "@b",
933 "$b",
934 "&b",
935 " b",
936 // Spaces and tabs written as character references, which a line start drops.
937 " b",
938 " b",
939 "	b",
940 "	b",
941 " 	b",
942 " * b",
943 " `b`",
944 " **b**",
945 // Content whose first character is a space.
946 "` b`",
947 "[ b](https://example.com)",
948 "** b**",
949 "*** b***",
950 "[ b]",
951 ];
952 const lines = [
953 (indent: string, start: string, join: string) => `a${join}${indent}${start}`,
954 (indent: string, start: string, join: string) => `> a${join}> ${indent}${start}`,
955 (indent: string, start: string, join: string) => `- a${join} ${indent}${start}`,
956 ];
957 for (const indent of ["", " ", " ", "\t", " \t"]) {
958 for (const start of starts) {
959 const joins = ["\n", "\r\n", " \n", "\\\n"];
960 const markdowns = [
961 ...joins.flatMap((join) => lines.map((line) => line(indent, start, join))),
962 // A paragraph's first line takes at most three spaces before it reads as code.
963 ...(indent.includes("\t") ? [] : [`${indent}${start}`, `> ${indent}${start}`]),
964 ];
965 for (const markdown of markdowns) {
966 const label = JSON.stringify(markdown);
967 expect(withoutRestoredWhitespace(userMessage(markdown)), label).toEqual(
968 withoutRestoredWhitespace(commonMarkUserMessage(markdown)),
969 );
970 const shown = shownText(userMessage(markdown)).split("\n");
971 const before = shownText(commonMarkUserMessage(markdown)).split("\n");
972 expect(shown.length, label).toBe(before.length);
973 shown.forEach((line, index) =>
974 expect([before[index], `${indent}${before[index]}`], label).toContain(line),
975 );
976 }
977 }
978 }
979});
980
981it("moves a <picture>'s color-scheme sources onto its <img>, which the renderer resolves", () => {
982 const processor = unified()
983 .use(remarkParse)
984 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
985 .use(remarkRehype, { allowDangerousHtml: true })
986 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
987 type Node = { type: string; tagName?: string; properties?: object; children?: Node[] };
988 const tags = (node: Node): string[] => [
989 ...(node.tagName ? [node.tagName] : []),
990 ...(node.children ?? []).flatMap(tags),
991 ];
992 const images = (node: Node): Node[] =>
993 node.tagName === "img" ? [node] : (node.children ?? []).flatMap(images);
994 const tree = processor.runSync(
995 processor.parse(
996 [
997 "<picture>",
998 ' <source media="(prefers-color-scheme: dark)" srcset="docs/dark.webp 1x, docs/dark@2x.webp 2x">',
999 ' <source media="(prefers-color-scheme: dark)" srcset="docs/dark-unused.webp">',
1000 ' <source media="(min-width: 600px)" srcset="docs/wide.webp">',
1001 ' <img src="docs/light.webp" alt="Studio">',
1002 "</picture>",
1003 "",
1004 '<picture><source media="(prefers-color-scheme: light)" srcset="javascript:alert(1)"><img src="docs/dark.webp"></picture>',
1005 "",
1006 String.raw`<picture><source media="(prefers-color-scheme: dark)" srcset="C:\shots\dark.png"><img src="C:\shots\light.png"></picture>`,
1007 "",
1008 '<picture><source media="(prefers-color-scheme: dark)" srcset="https://example.com/a\u00a0b.png 2x"><img src="https://example.com/light.png"></picture>',
1009 "",
1010 '<picture><source media="(prefers-color-scheme: light)" srcset=" \thttps://example.com/\u00a0light\u00a0v2.png,\thttps://example.com/2x.png 2x"><img src="https://example.com/dark.png"></picture>',
1011 "",
1012 '<picture><source media=" \t(prefers-color-scheme: dark) " srcset="/dark.png"><img src="/base.png"></picture>',
1013 ].join("\n"),
1014 ),
1015 ) as Node;
1016
1017 expect(tags(tree)).toEqual([
1018 "picture",
1019 "img",
1020 "p",
1021 "picture",
1022 "img",
1023 "p",
1024 "picture",
1025 "img",
1026 "p",
1027 "picture",
1028 "img",
1029 "p",
1030 "picture",
1031 "img",
1032 "p",
1033 "picture",
1034 "img",
1035 ]);
1036 expect(images(tree).map((image) => image.properties)).toEqual([
1037 { src: "docs/light.webp", alt: "Studio", dataDarkSrc: "docs/dark.webp", dataStandalone: true },
1038 { src: "docs/dark.webp", dataStandalone: true },
1039 {
1040 dataLocalSrc: String.raw`C:\shots\light.png`,
1041 dataDarkSrc: "file:///C:/shots/dark.png",
1042 dataStandalone: true,
1043 },
1044 {
1045 src: "https://example.com/light.png",
1046 dataDarkSrc: "https://example.com/a\u00a0b.png",
1047 dataStandalone: true,
1048 },
1049 {
1050 src: "https://example.com/dark.png",
1051 dataLightSrc: "https://example.com/\u00a0light\u00a0v2.png",
1052 dataStandalone: true,
1053 },
1054 { src: "/base.png", dataDarkSrc: "/dark.png", dataStandalone: true },
1055 ]);
1056});
1057
1058it("marks a <picture> image standalone exactly where a bare <img> would be", () => {
1059 const processor = unified()
1060 .use(remarkParse)
1061 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
1062 .use(remarkRehype, { allowDangerousHtml: true })
1063 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
1064 type Node = { tagName?: string; properties?: Record<string, unknown>; children?: Node[] };
1065 const images = (node: Node): Node[] =>
1066 node.tagName === "img" ? [node] : (node.children ?? []).flatMap(images);
1067 const standalone = (markdown: string) =>
1068 images(processor.runSync(processor.parse(markdown)) as Node).map(
1069 (image) => image.properties?.dataStandalone === true,
1070 );
1071 const image = '<img src="https://example.com/light.png" alt="Logo">';
1072 const picture = `<picture><source media="(prefers-color-scheme: dark)" srcset="https://example.com/dark.png">${image}</picture>`;
1073
1074 for (const wrap of [
1075 (img: string) => `<p align="center">${img}</p>`,
1076 (img: string) => `<div align="center"><a href="https://example.com">${img}</a></div>`,
1077 (img: string) => `Inline ${img} icon`,
1078 (img: string) => `<p>${img}${img}</p>`,
1079 ]) {
1080 expect(standalone(wrap(picture))).toEqual(standalone(wrap(image)));
1081 }
1082 // Raw-HTML blocks between other blocks, as an agent's README-style reply writes them.
1083 const multilinePicture = `<picture>\n${image}\n</picture>`;
1084 for (const [block, expected] of [
1085 [multilinePicture, [true]],
1086 [image, [true]],
1087 [`${multilinePicture} caption`, [false]],
1088 [`${multilinePicture}${multilinePicture}`, [false, false]],
1089 ] as const) {
1090 expect(standalone(`# Heading\n\n${block}\n\nParagraph`)).toEqual(expected);
1091 }
1092 expect(standalone(`<p align="center">${picture}</p>`)).toEqual([true]);
1093 expect(standalone(`Inline ${picture} icon`)).toEqual([false]);
1094});
1095
1096it.each([
1097 ["default", CHAT_MARKDOWN_REMARK_PLUGINS],
1098 ["with breaks", CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS],
1099] as const)(
1100 "links complete absolute paths in prose and skips shortened ones (%s)",
1101 (_, plugins) => {
1102 const path =
1103 "/tmp/claude-1000/-home-user--t3-worktrees-app-t3-abc123/session/scratchpad/notes.md";
1104 const processor = unified().use(remarkParse).use(plugins);
1105 const links = (markdown: string) => {
1106 const urls: string[] = [];
1107 const visit = (node: Root | RootContent) => {
1108 if (node.type === "link") urls.push(node.url);
1109 if ("children" in node) node.children.forEach(visit);
1110 };
1111 visit(processor.runSync(processor.parse(markdown), markdown) as Root);
1112 return urls;
1113 };
1114 expect(links(`Saved to ${path} and /tmp/other.txt.`)).toEqual([path, "/tmp/other.txt"]);
1115 expect(links("- /Users/me/app.ts:42")).toEqual(["/Users/me/app.ts:42"]);
1116 expect(links("- `/Users/me/app.ts:42`")).toEqual([]);
1117 expect(links(" /Users/me/code.ts:42")).toEqual([]);
1118 expect(links(`See (${path}:12).`)).toEqual([`${path}:12`]);
1119 expect(links("See /tmp/report(1).txt. and /tmp/app/[id]/page.tsx.")).toEqual([
1120 "/tmp/report(1).txt",
1121 "/tmp/app/[id]/page.tsx",
1122 ]);
1123 expect(links("(see /tmp/claude-1000/...). and /tmp/claude-1000/….")).toEqual([]);
1124 expect(links("Served at /index.html; GET /api/users.json; see /tmp/x.md:3.")).toEqual([
1125 "/tmp/x.md:3",
1126 ]);
1127 expect(
1128 links("See /Users/me/app/foo.ts#L10-L20. and /Users/me/app/Makefile#L10 or /tmp/a.ts#L4C2"),
1129 ).toEqual(["/Users/me/app/foo.ts#L10-L20", "/Users/me/app/Makefile#L10", "/tmp/a.ts#L4C2"]);
1130 expect(
1131 links("/Users/me/a.ts#intro /Users/me/#L10 /tmp/a#b.ts#L1 /tmp/a?b.ts#L1 /tmp/a.ts#L0"),
1132 ).toEqual([]);
1133 expect(links("已保存到 /tmp/report.md。然后打开 /Users/me/app.ts:42,再刷新")).toEqual([
1134 "/tmp/report.md",
1135 "/Users/me/app.ts:42",
1136 ]);
1137 expect(
1138 links(
1139 '<a title="</a>" href="https://example.com">/tmp/notes.md</a> and **<a href="x">/tmp/a.md</a>**',
1140 ),
1141 ).toEqual([]);
1142 expect(links("Use <a> for links.\n\nSee /Users/me/app.ts:42")).toEqual(["/Users/me/app.ts:42"]);
1143 expect(
1144 links(
1145 'Use <a> for /Users/me/a.ts and <a href="https://example.com">/Users/me/b.ts</a> then /Users/me/c.ts',
1146 ),
1147 ).toEqual(["/Users/me/a.ts", "/Users/me/c.ts"]);
1148 expect(
1149 links("<a>/Users/me/closed.ts</a> <a/>/Users/me/also-closed.ts</a> /Users/me/after.ts"),
1150 ).toEqual(["/Users/me/after.ts"]);
1151 expect(links("Use <textarea><a></textarea> and /Users/me/app.ts:42")).toEqual([
1152 "/Users/me/app.ts:42",
1153 ]);
1154 expect(links('[<a href="x">label](https://example.com) /Users/me/app.ts:42')).toEqual([
1155 "https://example.com",
1156 "/Users/me/app.ts:42",
1157 ]);
1158 expect(
1159 links("Config lives in /Users/me/Library/Application Support/T3 Code/settings.json now."),
1160 ).toEqual([]);
1161 expect(links(`/chat/settings and https://example.com${path}`)).toEqual([
1162 `https://example.com${path}`,
1163 ]);
1164 expect(links(`[notes](${path}) and \`${path}\``)).toEqual([path]);
1165 expect(links(`\`\`\`\n${path}\n\`\`\``)).toEqual([]);
1166 },
1167);