Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

markdownPipeline.test.ts

1,168 lines47.8 KB

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&#95;", `${link("https://x.com/a&#95")};`],
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` | ![d](./d.png) |\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) and mailto link and image URLs by lowercasing approved schemes 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) [mail](MAILTO:Hello@Example.com) [js](JAVASCRIPT:alert(1))",
568 "",
569 "![shot](HTTPS://Example.com/Shot.png)",
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 { href: "mailto:Hello@Example.com" },
579 {},
580 { src: "https://Example.com/Shot.png", alt: "shot", dataStandalone: true },
581 {
582 src: "http://Example.com/Light.png",
583 dataDarkSrc: "https://Example.com/Dark.png",
584 dataStandalone: true,
585 },
586 ]);
587});
588​
589it("keeps uppercase FILE link and image URLs by lowercasing the scheme before sanitizing", () => {
590 const processor = unified()
591 .use(remarkParse)
592 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
593 .use(remarkRehype, { allowDangerousHtml: true })
594 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
595 type Node = { tagName?: string; properties?: object; children?: Node[] };
596 const elements = (node: Node): Node[] => [
597 ...(node.tagName === "a" || node.tagName === "img" ? [node] : []),
598 ...(node.children ?? []).flatMap(elements),
599 ];
600 const markdown = [
601 '[upper](FILE:///tmp/A.md) <a href="FiLe:///C:/Demo%20A.md">raw</a>',
602 "",
603 "![shot](FILE:///tmp/Shot.png)",
604 "",
605 '<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>',
606 ].join("\n");
607 const tree = processor.runSync(processor.parse(markdown)) as Node;
608 expect(elements(tree).map((node) => node.properties)).toEqual([
609 { href: "file:///tmp/A.md" },
610 { href: "file:///C:/Demo%20A.md" },
611 { src: "file:///tmp/Shot.png", alt: "shot", dataStandalone: true },
612 {
613 src: "file://host/tmp/Fallback.png",
614 dataDarkSrc: "file:///tmp/Dark.png",
615 dataLightSrc: "file:///tmp/Light.png",
616 dataStandalone: true,
617 },
618 ]);
619 expect(chatMarkdownImageSources(markdown)).toHaveLength(4);
620});
621​
622it("keeps raw and percent-encoded Windows drive file links through the shared Markdown sanitizer", () => {
623 const processor = unified()
624 .use(remarkParse)
625 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
626 .use(remarkRehype, { allowDangerousHtml: true })
627 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
628 type Node = { tagName?: string; properties?: { href?: string }; children?: Node[] };
629 const hrefs = (node: Node): Array<string | undefined> => [
630 ...(node.tagName === "a" ? [node.properties?.href] : []),
631 ...(node.children ?? []).flatMap(hrefs),
632 ];
633 const tree = processor.runSync(
634 processor.parse(
635 [
636 "[report.md](<C:%5CUsers%5Ctest%5Creport.md#L7>)",
637 "[lower](c:%5cUsers/test%5creport.md)",
638 "[raw](C:\\Users\\test\\report.md)",
639 "[ref][win]",
640 "",
641 "[win]: <D:%5Cwork%5Creport.md#L12>",
642 ].join("\n"),
643 ),
644 ) as Node;
645 expect(hrefs(tree)).toEqual([
646 "file:///C:/Users/test/report.md#L7",
647 "file:///c:/Users/test/report.md",
648 "file:///C:/Users/test/report.md",
649 "file:///D:/work/report.md#L12",
650 ]);
651});
652​
653it("keeps backslashes that CommonMark would read as escapes in prose Windows paths", () => {
654 const processor = unified()
655 .use(remarkParse)
656 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
657 .use(remarkRehype, { allowDangerousHtml: true })
658 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
659 type Node = { type: string; value?: string; tagName?: string; children?: Node[] };
660 const text = (node: Node): string =>
661 node.type === "text"
662 ? (node.value ?? "")
663 : node.tagName === "code"
664 ? `<code>${(node.children ?? []).map(text).join("")}</code>`
665 : (node.children ?? []).map(text).join("");
666 const render = (markdown: string) => text(processor.runSync(processor.parse(markdown)) as Node);
667​
668 expect(
669 render(String.raw`Saved to C:\Users\me\.t3\_build and (C:\.scratch) and C:/work\.config.`),
670 ).toBe(String.raw`Saved to C:\Users\me\.t3\_build and (C:\.scratch) and C:/work\.config.`);
671 expect(render(String.raw`Escaped C:\\Users\\me`)).toBe(String.raw`Escaped C:\\Users\\me`);
672 expect(render(String.raw`See C:\x and \*this\* and Note:\*that\*.`)).toBe(
673 String.raw`See C:\x and *this* and Note:*that*.`,
674 );
675 expect(render(String.raw`${"`"}C:\me\.t3${"`"} and C:\me\.t3`)).toBe(
676 String.raw`<code>C:\me\.t3</code> and C:\me\.t3`,
677 );
678});
679​
680it("keeps an image on its own line under a label but leaves inline images inline", () => {
681 const processor = unified()
682 .use(remarkParse)
683 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
684 .use(remarkRehype, { allowDangerousHtml: true })
685 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
686 type Node = { type: string; value?: string; tagName?: string; children?: Node[] };
687 const shape = (node: Node): string =>
688 node.type === "text"
689 ? (node.value ?? "")
690 : node.tagName === "br" || node.tagName === "img"
691 ? `<${node.tagName}>`
692 : (node.children ?? []).map(shape).join("");
693 const render = (markdown: string) => shape(processor.runSync(processor.parse(markdown)) as Node);
694​
695 expect(
696 render("**Palette**\n![Palette](/tmp/palette.png)\n**Hero** (dark)\n![Hero](/tmp/hero.png)"),
697 ).toBe("Palette<br>\n<img><br>\nHero (dark)<br>\n<img>");
698 expect(render("Built [![CI](/ci.svg)](/ci)\nand wrapped")).toBe("Built <img>\nand wrapped");
699 expect(render("**Dialog** (native) ![a](/a.png) ![b](/b.png)")).toBe(
700 "Dialog (native)<br>\n<img> <img>",
701 );
702 expect(render("Hard-wrapped\nprose")).toBe("Hard-wrapped\nprose");
703});
704​
705it("keeps the number written on each ordered list item only when enabled", () => {
706 type Node = { tagName?: string; properties?: { value?: unknown }; children?: Node[] };
707 const values = (node: Node): unknown[] => [
708 ...(node.tagName === "li" ? [node.properties?.value] : []),
709 ...(node.children ?? []).flatMap(values),
710 ];
711 const renderer = (plugins: PluggableList) => {
712 const processor = unified()
713 .use(remarkParse)
714 .use(plugins)
715 .use(remarkRehype, { allowDangerousHtml: true });
716 return (markdown: string) =>
717 values(processor.runSync(processor.parse(markdown), markdown) as Node);
718 };
719 const render = renderer([
720 ...CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS,
721 remarkEnableOrderedListNumbers,
722 ]);
723​
724 expect(render("3. first\n5. second\n6. third")).toEqual([undefined, "5", undefined]);
725 expect(render("1. one\n1. one again")).toEqual([undefined, "1"]);
726 expect(render("> 1. quoted\n> 4. skipped")).toEqual([undefined, "4"]);
727 expect(render("1. outer\n 1. nested\n 7. jump\n9. back")).toEqual([
728 undefined,
729 undefined,
730 "7",
731 "9",
732 ]);
733 expect(render("1. one\n2. two\n- bullet")).toEqual([undefined, undefined, undefined]);
734 expect(render("- first block\n\n 3. first\n 5. second")).toEqual([
735 undefined,
736 undefined,
737 "5",
738 ]);
739 expect(
740 renderer(CHAT_MARKDOWN_REMARK_PLUGINS)(
741 "3. first\n5. second\n\n- first block\n\n 3. first\n 5. second",
742 ),
743 ).toEqual([undefined, undefined, undefined, undefined, undefined]);
744});
745​
746type ShownNode = {
747 type: string;
748 tagName?: string;
749 value?: string;
750 properties?: Record<string, unknown>;
751 children?: ShownNode[];
752};
753const SHOWN_BLOCKS = new Set([
754 "p",
755 "li",
756 "blockquote",
757 "ul",
758 "ol",
759 "pre",
760 "h1",
761 "h2",
762 "table",
763 "tr",
764]);
765​
766/** The text a browser shows, by line: whitespace collapses except in `pre` and kept whitespace. */
767function shownText(tree: ShownNode): string {
768 let out = "";
769 const visit = (node: ShownNode, keep: boolean) => {
770 if (node.type === "text") {
771 const value = node.value ?? "";
772 // Only spaces, tabs and line endings collapse; a no-break space shows.
773 out += keep
774 ? value.replace(/ /g, "\u0001").replace(/\t/g, "\u0002")
775 : value.replace(/[ \t\r\n]/g, " ");
776 }
777 // An image shows as something, which its alt text stands in for.
778 if (node.properties?.alt !== undefined) out += String(node.properties.alt);
779 if (node.tagName === "br" || SHOWN_BLOCKS.has(node.tagName ?? "")) out += "\n";
780 const inner =
781 keep || node.tagName === "pre" || node.properties?.dataLeadingWhitespace !== undefined;
782 node.children?.forEach((child) => visit(child, inner));
783 if (SHOWN_BLOCKS.has(node.tagName ?? "")) out += "\n";
784 };
785 visit(tree, false);
786 return out
787 .split("\n")
788 .map((line) => line.replace(/ +/g, " ").replace(/^ | $/g, ""))
789 .filter(Boolean)
790 .join("\n")
791 .replace(/\u0001/g, " ")
792 .replace(/\u0002/g, "\t");
794​
795const hastRenderer = (plugins: PluggableList) => {
796 const processor = unified()
797 .use(remarkParse)
798 .use(plugins)
799 .use(remarkRehype, { allowDangerousHtml: true });
800 return (markdown: string) => processor.runSync(processor.parse(markdown), markdown) as ShownNode;
801};
802const userMessage = hastRenderer([
803 ...CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS,
804 ...CHAT_USER_MARKDOWN_REMARK_PLUGINS,
805]);
806// The user pipeline as it was before leading whitespace was kept.
807const commonMarkUserMessage = hastRenderer([
808 ...CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS,
809 [remarkGfm, { singleTilde: false }],
810]);
811/** The tree with the restored indentation taken out, with the empty texts and positions it leaves. */
812const withoutRestoredWhitespace = ({
813 position: _position,
814 ...node
815}: ShownNode & { position?: unknown }): ShownNode => ({
816 ...node,
817 ...(node.children && {
818 children: node.children
819 .filter(
820 (child) =>
821 child.properties?.dataLeadingWhitespace === undefined &&
822 !(child.type === "text" && child.value === ""),
823 )
824 .map(withoutRestoredWhitespace),
825 }),
826});
827/** Each link's text and where it goes. */
828const linkTargets = (node: ShownNode): [string, unknown][] =>
829 node.properties?.href === undefined
830 ? (node.children ?? []).flatMap(linkTargets)
831 : [[shownText(node), node.properties.href]];
832​
833it("shows the spaces and tabs typed at the start of each line of a user message", () => {
834 const shown = (markdown: string) => shownText(userMessage(markdown));
835 const outline = "Plan\n Step one\n Step two\n Detail a\n Detail b";
836 expect(shown(outline)).toBe(outline);
837 expect(shown(outline.replaceAll("\n", "\r\n"))).toBe(outline);
838 expect(shown(" First line\nnext\n\n New paragraph")).toBe(
839 " First line\nnext\n New paragraph",
840 );
841 expect(shown("Plan\n\tTabbed\n \t Mixed")).toBe("Plan\n\tTabbed\n \t Mixed");
842 expect(shown("Plan \n After a hard break\\\n and an escaped one")).toBe(
843 "Plan\n After a hard break\n and an escaped one",
844 );
845 // In a container, only whitespace past its own structure counts.
846 expect(shown("- item\n continued")).toBe("item\ncontinued");
847 expect(shown("- item\n more")).toBe("item\n more");
848 expect(shown("- item\ncontinued")).toBe("item\ncontinued");
849 expect(shown("- item\n continued")).toBe("item\ncontinued");
850 expect(shown("1. one\n two")).toBe("one\n two");
851 expect(shown("- item\n\tsplit tab")).toBe("item\n split tab");
852 expect(shown("- item\n\n second paragraph")).toBe("item\n second paragraph");
853 // An item's content starts after its marker and the marker's spacing. A task's checkbox is
854 // content, so it does not move where continuation lines start, however the task begins.
855 expect(shown("- [ ] task\n under the task")).toBe("task\n under the task");
856 for (const task of ["task", "**task**", "[task](https://example.com)", "`task`"]) {
857 expect(shown(`- [ ] ${task}\n detail`), task).toBe("task\n detail");
858 }
859 expect(shown("- x\n y")).toBe("x\n y");
860 expect(shown("- x\n y")).toBe("x\n y");
861 expect(shown("-\tx\n\t y")).toBe("x\n y");
862 expect(shown("10. x\n y")).toBe("x\n y");
863 expect(shown("> a\n> b")).toBe("a\n b");
864 expect(shown("> first")).toBe(" first");
865 expect(shown("> a\n lazy")).toBe("a\nlazy");
866 expect(shown("> - item\n> more")).toBe("item\n more");
867 expect(shown("- > a\n > b")).toBe("a\n b");
868 expect(shown("- a\n - b\n c")).toBe("a\nb\n c");
869 // List recovery reparses over-indented content; its first line sets the indentation.
870 expect(shown("- first block\n continued\n deeper")).toBe(
871 "first block\ncontinued\n deeper",
872 );
873​
874 // A space or tab written as a character reference after the indentation is dropped, as it is
875 // without the indentation; only the typed indentation is added.
876 for (const reference of ["&#32;", "&#x20;", "&#9;", "&Tab;"]) {
877 expect(shown(`a\n ${reference}b`), reference).toBe("a\n b");
878 expect(shown(`a \n\t${reference}b`), reference).toBe("a\n\tb");
879 expect(shown(`a\\\r\n ${reference}${reference}b`), reference).toBe("a\n b");
880 }
881 // Converting to HTML also drops the spaces that start code or a link's text after a line break.
882 expect(shown("a\n ` npm i`")).toBe("a\n npm i");
883 expect(shown("a\n [ docs](https://example.com)")).toBe("a\n docs");
884 // A line whose text starts with whitespace the browser hides keeps no indentation, as without it.
885 expect(shown(" &#32;b")).toBe("b");
886 expect(shown("a\n ***&#32;b***")).toBe("a\nb");
887​
888 // Only the indentation is added: formatting, code, links and alerts render as without it.
889 const inline = "Plan\n **bold** [link](https://example.com) `code` ~/a and ~~gone~~ /tmp/a.ts";
890 const alert = "> [!NOTE]\n> indented body";
891 expect(shown(inline)).toBe("Plan\n bold link code ~/a and gone /tmp/a.ts");
892 expect(shown(alert)).toBe(" indented body");
893 for (const markdown of [inline, alert]) {
894 expect(withoutRestoredWhitespace(userMessage(markdown)), markdown).toEqual(
895 withoutRestoredWhitespace(commonMarkUserMessage(markdown)),
896 );
897 }
898 expect(linkTargets(userMessage(inline))).toEqual(linkTargets(commonMarkUserMessage(inline)));
899 expect(linkTargets(userMessage(inline)).map(([label]) => label)).toEqual(["link", "/tmp/a.ts"]);
900​
901 // A line ending written as a character reference is not a source line: it never takes a typed
902 // line's indentation, and no typed line's indentation moves onto it.
903 const decoded = shown("a &#10; b\n c").split("\n");
904 expect(decoded.slice(0, 2)).toEqual(["a", "b"]);
905 expect(["c", " c"]).toContain(decoded[2]);
906​
907 // Code, and agent replies, keep CommonMark's reading.
908 for (const markdown of [
909 "```\n code\n more\n```",
910 "Plan\n\n code\n deeper",
911 "- item\n\n code",
912 ]) {
913 expect(userMessage(markdown), markdown).toEqual(commonMarkUserMessage(markdown));
914 }
915 for (const plugins of [CHAT_MARKDOWN_REMARK_PLUGINS, CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS]) {
916 expect(shownText(hastRenderer(plugins)(outline)).replaceAll("\n", " ")).toBe(
917 "Plan Step one Step two Detail a Detail b",
918 );
919 }
920});
921​
922it("adds only the typed indentation, and renders what follows it as without it", () => {
923 const starts = [
924 "b",
925 "*b*",
926 "`b`",
927 "~~b~~",
928 "[b](https://example.com)",
929 "![b](https://example.com/b.png)",
930 "https://example.com/b",
931 "/tmp/b.ts",
932 "~/b",
933 "@b",
934 "$b",
935 "&amp;b",
936 "&nbsp;b",
937 // Spaces and tabs written as character references, which a line start drops.
938 "&#32;b",
939 "&#x20;b",
940 "&#9;b",
941 "&Tab;b",
942 "&#32;&#9;b",
943 "&#32;* b",
944 "&#32;`b`",
945 "&#32;**b**",
946 // Content whose first character is a space.
947 "` b`",
948 "[ b](https://example.com)",
949 "**&#32;b**",
950 "***&#32;b***",
951 "[ b]",
952 ];
953 const lines = [
954 (indent: string, start: string, join: string) => `a${join}${indent}${start}`,
955 (indent: string, start: string, join: string) => `> a${join}> ${indent}${start}`,
956 (indent: string, start: string, join: string) => `- a${join} ${indent}${start}`,
957 ];
958 for (const indent of ["", " ", " ", "\t", " \t"]) {
959 for (const start of starts) {
960 const joins = ["\n", "\r\n", " \n", "\\\n"];
961 const markdowns = [
962 ...joins.flatMap((join) => lines.map((line) => line(indent, start, join))),
963 // A paragraph's first line takes at most three spaces before it reads as code.
964 ...(indent.includes("\t") ? [] : [`${indent}${start}`, `> ${indent}${start}`]),
965 ];
966 for (const markdown of markdowns) {
967 const label = JSON.stringify(markdown);
968 expect(withoutRestoredWhitespace(userMessage(markdown)), label).toEqual(
969 withoutRestoredWhitespace(commonMarkUserMessage(markdown)),
970 );
971 const shown = shownText(userMessage(markdown)).split("\n");
972 const before = shownText(commonMarkUserMessage(markdown)).split("\n");
973 expect(shown.length, label).toBe(before.length);
974 shown.forEach((line, index) =>
975 expect([before[index], `${indent}${before[index]}`], label).toContain(line),
976 );
977 }
978 }
979 }
980});
981​
982it("moves a <picture>'s color-scheme sources onto its <img>, which the renderer resolves", () => {
983 const processor = unified()
984 .use(remarkParse)
985 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
986 .use(remarkRehype, { allowDangerousHtml: true })
987 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
988 type Node = { type: string; tagName?: string; properties?: object; children?: Node[] };
989 const tags = (node: Node): string[] => [
990 ...(node.tagName ? [node.tagName] : []),
991 ...(node.children ?? []).flatMap(tags),
992 ];
993 const images = (node: Node): Node[] =>
994 node.tagName === "img" ? [node] : (node.children ?? []).flatMap(images);
995 const tree = processor.runSync(
996 processor.parse(
997 [
998 "<picture>",
999 ' <source media="(prefers-color-scheme: dark)" srcset="docs/dark.webp 1x, docs/dark@2x.webp 2x">',
1000 ' <source media="(prefers-color-scheme: dark)" srcset="docs/dark-unused.webp">',
1001 ' <source media="(min-width: 600px)" srcset="docs/wide.webp">',
1002 ' <img src="docs/light.webp" alt="Studio">',
1003 "</picture>",
1004 "",
1005 '<picture><source media="(prefers-color-scheme: light)" srcset="javascript:alert(1)"><img src="docs/dark.webp"></picture>',
1006 "",
1007 String.raw`<picture><source media="(prefers-color-scheme: dark)" srcset="C:\shots\dark.png"><img src="C:\shots\light.png"></picture>`,
1008 "",
1009 '<picture><source media="(prefers-color-scheme: dark)" srcset="https://example.com/a\u00a0b.png 2x"><img src="https://example.com/light.png"></picture>',
1010 "",
1011 '<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>',
1012 "",
1013 '<picture><source media=" \t(prefers-color-scheme: dark) " srcset="/dark.png"><img src="/base.png"></picture>',
1014 ].join("\n"),
1015 ),
1016 ) as Node;
1017​
1018 expect(tags(tree)).toEqual([
1019 "picture",
1020 "img",
1021 "p",
1022 "picture",
1023 "img",
1024 "p",
1025 "picture",
1026 "img",
1027 "p",
1028 "picture",
1029 "img",
1030 "p",
1031 "picture",
1032 "img",
1033 "p",
1034 "picture",
1035 "img",
1036 ]);
1037 expect(images(tree).map((image) => image.properties)).toEqual([
1038 { src: "docs/light.webp", alt: "Studio", dataDarkSrc: "docs/dark.webp", dataStandalone: true },
1039 { src: "docs/dark.webp", dataStandalone: true },
1041 dataLocalSrc: String.raw`C:\shots\light.png`,
1042 dataDarkSrc: "file:///C:/shots/dark.png",
1043 dataStandalone: true,
1044 },
1046 src: "https://example.com/light.png",
1047 dataDarkSrc: "https://example.com/a\u00a0b.png",
1048 dataStandalone: true,
1049 },
1051 src: "https://example.com/dark.png",
1052 dataLightSrc: "https://example.com/\u00a0light\u00a0v2.png",
1053 dataStandalone: true,
1054 },
1055 { src: "/base.png", dataDarkSrc: "/dark.png", dataStandalone: true },
1056 ]);
1057});
1058​
1059it("marks a <picture> image standalone exactly where a bare <img> would be", () => {
1060 const processor = unified()
1061 .use(remarkParse)
1062 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
1063 .use(remarkRehype, { allowDangerousHtml: true })
1064 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
1065 type Node = { tagName?: string; properties?: Record<string, unknown>; children?: Node[] };
1066 const images = (node: Node): Node[] =>
1067 node.tagName === "img" ? [node] : (node.children ?? []).flatMap(images);
1068 const standalone = (markdown: string) =>
1069 images(processor.runSync(processor.parse(markdown)) as Node).map(
1070 (image) => image.properties?.dataStandalone === true,
1071 );
1072 const image = '<img src="https://example.com/light.png" alt="Logo">';
1073 const picture = `<picture><source media="(prefers-color-scheme: dark)" srcset="https://example.com/dark.png">${image}</picture>`;
1074​
1075 for (const wrap of [
1076 (img: string) => `<p align="center">${img}</p>`,
1077 (img: string) => `<div align="center"><a href="https://example.com">${img}</a></div>`,
1078 (img: string) => `Inline ${img} icon`,
1079 (img: string) => `<p>${img}${img}</p>`,
1080 ]) {
1081 expect(standalone(wrap(picture))).toEqual(standalone(wrap(image)));
1083 // Raw-HTML blocks between other blocks, as an agent's README-style reply writes them.
1084 const multilinePicture = `<picture>\n${image}\n</picture>`;
1085 for (const [block, expected] of [
1086 [multilinePicture, [true]],
1087 [image, [true]],
1088 [`${multilinePicture} caption`, [false]],
1089 [`${multilinePicture}${multilinePicture}`, [false, false]],
1090 ] as const) {
1091 expect(standalone(`# Heading\n\n${block}\n\nParagraph`)).toEqual(expected);
1093 expect(standalone(`<p align="center">${picture}</p>`)).toEqual([true]);
1094 expect(standalone(`Inline ${picture} icon`)).toEqual([false]);
1095});
1096​
1097it.each([
1098 ["default", CHAT_MARKDOWN_REMARK_PLUGINS],
1099 ["with breaks", CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS],
1100] as const)(
1101 "links complete absolute paths in prose and skips shortened ones (%s)",
1102 (_, plugins) => {
1103 const path =
1104 "/tmp/claude-1000/-home-user--t3-worktrees-app-t3-abc123/session/scratchpad/notes.md";
1105 const processor = unified().use(remarkParse).use(plugins);
1106 const links = (markdown: string) => {
1107 const urls: string[] = [];
1108 const visit = (node: Root | RootContent) => {
1109 if (node.type === "link") urls.push(node.url);
1110 if ("children" in node) node.children.forEach(visit);
1111 };
1112 visit(processor.runSync(processor.parse(markdown), markdown) as Root);
1113 return urls;
1114 };
1115 expect(links(`Saved to ${path} and /tmp/other.txt.`)).toEqual([path, "/tmp/other.txt"]);
1116 expect(links("- /Users/me/app.ts:42")).toEqual(["/Users/me/app.ts:42"]);
1117 expect(links("- `/Users/me/app.ts:42`")).toEqual([]);
1118 expect(links(" /Users/me/code.ts:42")).toEqual([]);
1119 expect(links(`See (${path}:12).`)).toEqual([`${path}:12`]);
1120 expect(links("See /tmp/report(1).txt. and /tmp/app/[id]/page.tsx.")).toEqual([
1121 "/tmp/report(1).txt",
1122 "/tmp/app/[id]/page.tsx",
1123 ]);
1124 expect(links("(see /tmp/claude-1000/...). and /tmp/claude-1000/….")).toEqual([]);
1125 expect(links("Served at /index.html; GET /api/users.json; see /tmp/x.md:3.")).toEqual([
1126 "/tmp/x.md:3",
1127 ]);
1128 expect(
1129 links("See /Users/me/app/foo.ts#L10-L20. and /Users/me/app/Makefile#L10 or /tmp/a.ts#L4C2"),
1130 ).toEqual(["/Users/me/app/foo.ts#L10-L20", "/Users/me/app/Makefile#L10", "/tmp/a.ts#L4C2"]);
1131 expect(
1132 links("/Users/me/a.ts#intro /Users/me/#L10 /tmp/a#b.ts#L1 /tmp/a?b.ts#L1 /tmp/a.ts#L0"),
1133 ).toEqual([]);
1134 expect(links("已保存到 /tmp/report.md。然后打开 /Users/me/app.ts:42,再刷新")).toEqual([
1135 "/tmp/report.md",
1136 "/Users/me/app.ts:42",
1137 ]);
1138 expect(
1139 links(
1140 '<a title="</a>" href="https://example.com">/tmp/notes.md</a> and **<a href="x">/tmp/a.md</a>**',
1141 ),
1142 ).toEqual([]);
1143 expect(links("Use <a> for links.\n\nSee /Users/me/app.ts:42")).toEqual(["/Users/me/app.ts:42"]);
1144 expect(
1145 links(
1146 'Use <a> for /Users/me/a.ts and <a href="https://example.com">/Users/me/b.ts</a> then /Users/me/c.ts',
1147 ),
1148 ).toEqual(["/Users/me/a.ts", "/Users/me/c.ts"]);
1149 expect(
1150 links("<a>/Users/me/closed.ts</a> <a/>/Users/me/also-closed.ts</a> /Users/me/after.ts"),
1151 ).toEqual(["/Users/me/after.ts"]);
1152 expect(links("Use <textarea><a></textarea> and /Users/me/app.ts:42")).toEqual([
1153 "/Users/me/app.ts:42",
1154 ]);
1155 expect(links('[<a href="x">label](https://example.com) /Users/me/app.ts:42')).toEqual([
1156 "https://example.com",
1157 "/Users/me/app.ts:42",
1158 ]);
1159 expect(
1160 links("Config lives in /Users/me/Library/Application Support/T3 Code/settings.json now."),
1161 ).toEqual([]);
1162 expect(links(`/chat/settings and https://example.com${path}`)).toEqual([
1163 `https://example.com${path}`,
1164 ]);
1165 expect(links(`[notes](${path}) and \`${path}\``)).toEqual([path]);
1166 expect(links(`\`\`\`\n${path}\n\`\`\``)).toEqual([]);
1167 },