Open History to see the last commit
1import type { Paragraph, PhrasingContent, Root, RootContent } from "mdast";
2import { remarkKeepWindowsPaths } from "./markdownWindowsPaths.ts";
3import { type PluggableList, type Processor, type Transformer, unified } from "unified";
4import remarkParse from "remark-parse";
5import remarkRehype from "remark-rehype";
6import { find, html } from "property-information";
7import rehypeRaw from "rehype-raw";
8import rehypeSanitize, { defaultSchema } from "rehype-sanitize";
9import remarkBreaks from "remark-breaks";
10import remarkGfm from "remark-gfm";
11import { remarkGithubAlerts } from "./markdownGithubAlerts.ts";
12import { remarkNormalizeListItemIndentation } from "./markdownListIndentation.ts";
13import {
14 CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES,
15 remarkCodexDirectives,
16} from "./codexMarkdownDirectives.ts";
17import { isWindowsDrivePathHref, normalizeMarkdownLinkDestination } from "./markdownLinks.ts";
18import { THREAD_LINK_PROTOCOL } from "./threadLinks.ts";
19
20type MarkdownImageHastNode = {
21 type?: string;
22 value?: string;
23 tagName?: string;
24 properties?: Record<string, unknown>;
25 children?: MarkdownImageHastNode[];
26};
27
28function meaningfulHastChildren(node: MarkdownImageHastNode): MarkdownImageHastNode[] {
29 return (node.children ?? []).filter(
30 (child) => !(child.type === "text" && (child as { value?: string }).value?.trim() === ""),
31 );
32}
33
34const STANDALONE_IMAGE_BLOCKS = new Set([
35 "p",
36 "div",
37 "li",
38 "td",
39 "th",
40 "figure",
41 "center",
42 "blockquote",
43]);
44
45function soleImageDescendant(node: MarkdownImageHastNode): MarkdownImageHastNode | undefined {
46 const children = meaningfulHastChildren(node);
47 if (children.length !== 1) return undefined;
48 const only = children[0];
49 if (only?.type !== "element") return undefined;
50 if (only.tagName === "img") return only;
51 return only.tagName === "a" || only.tagName === "strong" || only.tagName === "em"
52 ? soleImageDescendant(only)
53 : undefined;
54}
55
56function markStandaloneImages(node: MarkdownImageHastNode) {
57 if (node.type === "root" || (node.tagName && STANDALONE_IMAGE_BLOCKS.has(node.tagName))) {
58 const image = soleImageDescendant(node);
59 if (image) image.properties = { ...image.properties, dataStandalone: true };
60 }
61 node.children?.forEach((child) => {
62 if (child.type === "element") markStandaloneImages(child);
63 });
64}
65
66function rehypePreserveBareAnchorPlaceholders() {
67 return (tree: MarkdownImageHastNode) => {
68 const anchors: Array<MarkdownImageHastNode | null> = [];
69 let rawTextTag: string | undefined;
70 const visit = (node: MarkdownImageHastNode) => {
71 if (node.type === "raw" && typeof node.value === "string") {
72 // Scan whole tags, attributes, and comments so embedded closing-anchor text cannot match a placeholder.
73 const tags = /<!--[\s\S]*?(?:-->|$)|<\/?[A-Za-z](?:[^"'<>]|"[^"]*"|'[^']*')*>/g;
74 let offset = 0;
75 while (rawTextTag !== "plaintext") {
76 // Raw text ends at its closing tag even inside comment-looking text.
77 const matcher = rawTextTag ? new RegExp(`</${rawTextTag}\\s*>`, "gi") : tags;
78 matcher.lastIndex = offset;
79 const match = matcher.exec(node.value);
80 if (!match) break;
81 const [tag] = match;
82 offset = matcher.lastIndex;
83 if (rawTextTag) {
84 rawTextTag = undefined;
85 continue;
86 }
87 if (tag.startsWith("<!--")) continue;
88 const closing = /^<\/([a-z]+)\s*>$/i.exec(tag)?.[1]?.toLowerCase();
89 const opening = /^<([a-z]+)(?:\s|\/?>)/i.exec(tag)?.[1]?.toLowerCase();
90 if (
91 opening &&
92 /^(?:script|style|textarea|title|xmp|iframe|noembed|noframes|plaintext)$/.test(opening)
93 ) {
94 rawTextTag = opening;
95 } else if (opening === "a") {
96 anchors.push(node.value === tag && /^<a\s*\/?>$/i.test(tag) ? node : null);
97 } else if (closing === "a") {
98 anchors.pop();
99 }
100 }
101 }
102 node.children?.forEach(visit);
103 };
104
105 visit(tree);
106 for (const anchor of anchors) {
107 if (anchor) anchor.type = "text";
108 }
109 };
110}
111
112const COLOR_SCHEME_MEDIA = /^\(\s*prefers-color-scheme\s*:\s*(dark|light)\s*\)$/i;
113
114/**
115 * The renderer resolves an `<img>`'s `src` (workspace files, host media) but never a `<source>`'s
116 * `srcset`, which would load unresolved whenever its media matched. A color-scheme source moves
117 * onto the `<img>` for the renderer to pick by theme; every source is then dropped.
118 */
119function moveColorSchemeSourcesToImage(picture: MarkdownImageHastNode) {
120 if (!picture.children) return;
121 const image = picture.children.find((child) => child.tagName === "img");
122 for (const source of picture.children) {
123 if (source.tagName !== "source" || !image) continue;
124 const media = source.properties?.media;
125 const scheme = typeof media === "string" ? COLOR_SCHEME_MEDIA.exec(media)?.[1] : undefined;
126 const srcSet = source.properties?.srcSet;
127 const candidate = Array.isArray(srcSet) ? srcSet[0] : srcSet;
128 // A candidate's URL runs to the first space (a descriptor such as `2x` may follow).
129 const url =
130 typeof candidate === "string" ? candidate.trim().split(/\s/, 1)[0]?.replace(/,+$/, "") : "";
131 const key = scheme?.toLowerCase() === "dark" ? "dataDarkSrc" : "dataLightSrc";
132 // As in a browser, the first source that matches a scheme is the one shown.
133 if (scheme && url && image.properties?.[key] === undefined) {
134 // The sanitizer reads a drive letter as a protocol; as a file URL it resolves to the same path.
135 const value = isWindowsDrivePathHref(url) ? `file:///${url.replaceAll("\\", "/")}` : url;
136 image.properties = { ...image.properties, [key]: value };
137 }
138 }
139 picture.children = picture.children.filter((child) => child.tagName !== "source");
140}
141
142function rehypePreserveImageSourceMeta() {
143 return (tree: MarkdownImageHastNode) => {
144 const visit = (node: MarkdownImageHastNode) => {
145 const src = node.properties?.src;
146 const title = node.properties?.title;
147 if (node.type === "element" && node.tagName === "picture") {
148 moveColorSchemeSourcesToImage(node);
149 }
150 if (node.type === "element" && node.tagName === "img") {
151 node.properties = {
152 ...node.properties,
153 ...(typeof src === "string" && isWindowsDrivePathHref(src) ? { dataLocalSrc: src } : {}),
154 ...(typeof title === "string" ? { dataMarkdownTitle: title } : {}),
155 };
156 }
157 node.children?.forEach(visit);
158 };
159
160 visit(tree);
161 markStandaloneImages(tree);
162 };
163}
164
165const IMAGE_SRC_PROTOCOLS = [...(defaultSchema.protocols?.src ?? []), "file", "t3-context"];
166
167const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
168 ...defaultSchema,
169 attributes: {
170 ...defaultSchema.attributes,
171 "*": (defaultSchema.attributes?.["*"] ?? []).filter((attribute) => attribute !== "title"),
172 // Fence languages plus the two math classes the web chat's math plugin emits.
173 code: [
174 ["className", /^language-./, "math-inline", "math-display"],
175 "dataCodeMeta",
176 "dataInlineCode",
177 ],
178 blockquote: [...(defaultSchema.attributes?.blockquote ?? []), "dataAlert"],
179 div: [...(defaultSchema.attributes?.div ?? []), ...CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES],
180 a: [...(defaultSchema.attributes?.a ?? []), "dataPullRequestAutolink"],
181 img: [
182 ...(defaultSchema.attributes?.img ?? []),
183 "dataDarkSrc",
184 "dataLightSrc",
185 "dataLocalSrc",
186 "dataMarkdownTitle",
187 "dataStandalone",
188 ],
189 },
190 protocols: {
191 ...defaultSchema.protocols,
192 href: [
193 ...(defaultSchema.protocols?.href ?? []),
194 "file",
195 "t3-citation",
196 "t3-context",
197 THREAD_LINK_PROTOCOL,
198 ],
199 src: IMAGE_SRC_PROTOCOLS,
200 dataDarkSrc: IMAGE_SRC_PROTOCOLS,
201 dataLightSrc: IMAGE_SRC_PROTOCOLS,
202 },
203} satisfies Parameters<typeof rehypeSanitize>[0];
204
205export const CHAT_MARKDOWN_REMARK_PLUGINS: PluggableList = [
206 remarkGfm,
207 remarkKeepAutolinkSuffixes,
208 remarkKeepWindowsPaths,
209 remarkGithubAlerts,
210 remarkNormalizeListItemIndentation,
211 remarkCodexDirectives,
212 remarkBreakAroundImageLines,
213 remarkPreserveCodeMeta,
214 remarkNormalizeLinksAndTagInlineCode,
215];
216
217export const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS: PluggableList = [
218 remarkGfm,
219 remarkKeepAutolinkSuffixes,
220 remarkKeepWindowsPaths,
221 remarkGithubAlerts,
222 remarkNormalizeListItemIndentation,
223 remarkCodexDirectives,
224 remarkBreakAroundImageLines,
225 remarkBreaks,
226 remarkPreserveCodeMeta,
227 remarkNormalizeLinksAndTagInlineCode,
228];
229
230// Start tags an HTML parser closes an open `<p>` for.
231const CLOSES_PARAGRAPH = new Set(
232 "address article aside blockquote center details dialog dir div dl fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 header hgroup hr li listing main menu nav ol p plaintext pre search section summary table ul xmp dd dt".split(
233 " ",
234 ),
235);
236const HEADING = /^h[1-6]$/;
237
238interface HtmlScope {
239 readonly anchor: boolean;
240 readonly paragraph: boolean;
241 readonly heading: boolean;
242}
243
244/**
245 * Whether the tree needs the HTML parser: raw HTML, or nesting it repairs (a footnote call in a
246 * link label nests `<a>`). Otherwise it only rewrites properties as hast-util-to-parse5 does and
247 * drops `data`, both repeated here, and moves blank text that renders the same.
248 */
249function needsHtmlParser(node: MarkdownImageHastNode, scope: HtmlScope): boolean {
250 if (node.type === "raw") return true;
251 let inner = scope;
252 if (node.type === "element" && node.tagName) {
253 const { tagName } = node;
254 const heading = HEADING.test(tagName);
255 if (
256 (tagName === "a" && scope.anchor) ||
257 (scope.paragraph && CLOSES_PARAGRAPH.has(tagName)) ||
258 (heading && scope.heading)
259 ) {
260 return true;
261 }
262 inner = {
263 anchor: scope.anchor || tagName === "a",
264 paragraph: scope.paragraph || tagName === "p",
265 heading: scope.heading || heading,
266 };
267 const properties = node.properties ?? {};
268 for (const key of Object.keys(properties)) {
269 const value = properties[key];
270 const info = find(html, key);
271 if (
272 value === false ||
273 value === null ||
274 value === undefined ||
275 Number.isNaN(value) ||
276 (!value && info.boolean)
277 ) {
278 delete properties[key];
279 } else if (value === true && !info.boolean && !info.overloadedBoolean) {
280 properties[key] = "";
281 }
282 }
283 delete (node as { data?: unknown }).data;
284 }
285 return (node.children ?? []).some((child) => needsHtmlParser(child, inner));
286}
287
288const TOP_SCOPE: HtmlScope = { anchor: false, paragraph: false, heading: false };
289
290/** rehype-raw reparses the whole tree through an HTML parser, which most trees can skip. */
291function rehypeRawWhenPresent(this: Processor) {
292 const transform = rehypeRaw.call(this) as unknown as (
293 tree: MarkdownImageHastNode,
294 file: unknown,
295 ) => unknown;
296 return (tree: MarkdownImageHastNode, file: unknown) =>
297 needsHtmlParser(tree, TOP_SCOPE) ? transform(tree, file) : undefined;
298}
299
300export const CHAT_MARKDOWN_REHYPE_PLUGINS: PluggableList = [
301 rehypePreserveBareAnchorPlaceholders,
302 rehypeRawWhenPresent,
303 rehypePreserveImageSourceMeta,
304 [rehypeSanitize, CHAT_MARKDOWN_SANITIZE_SCHEMA],
305];
306
307const isImageNode = (node: PhrasingContent | undefined): boolean =>
308 node?.type === "image" ||
309 node?.type === "imageReference" ||
310 ((node?.type === "link" || node?.type === "linkReference") &&
311 node.children.length === 1 &&
312 isImageNode(node.children[0]));
313const endsLine = (node: PhrasingContent | undefined) =>
314 node === undefined ||
315 node.type === "break" ||
316 (node.type === "text" && /\n[ \t]*$/.test(node.value));
317const startsLine = (node: PhrasingContent | undefined) =>
318 node === undefined ||
319 node.type === "break" ||
320 (node.type === "text" && /^[ \t]*\n/.test(node.value));
321
322function breakLinesAroundImages(paragraph: Paragraph) {
323 const children = paragraph.children;
324 if (!children.some(isImageNode)) return;
325 const ownsLine = (index: number) =>
326 isImageNode(children[index]) &&
327 endsLine(children[index - 1]) &&
328 startsLine(children[index + 1]);
329 paragraph.children = children.flatMap((child, index): PhrasingContent[] => {
330 if (child.type !== "text") return [child];
331 const afterImage = ownsLine(index - 1);
332 const beforeImage = ownsLine(index + 1);
333 if (!afterImage && !beforeImage) return [child];
334 const parts: PhrasingContent[] = [];
335 let value = child.value;
336 if (afterImage) {
337 value = value.replace(/^[ \t]*\n/, "");
338 parts.push({ type: "break" });
339 }
340 const breakAfter = beforeImage && /\n[ \t]*$/.test(value);
341 if (breakAfter) value = value.replace(/[ \t]*\n[ \t]*$/, "");
342 if (value) parts.push({ type: "text", value });
343 if (breakAfter) parts.push({ type: "break" });
344 return parts;
345 });
346}
347
348/**
349 * Agents label screenshots with a line like `**Palette**` right above the image. CommonMark
350 * joins those lines into one paragraph, which puts the image inline beside its label. An
351 * image alone on its source line keeps that line; prose and inline badges still wrap.
352 */
353function remarkBreakAroundImageLines() {
354 return (tree: Root) => {
355 const visit = (node: Root | RootContent) => {
356 if (node.type === "paragraph") breakLinesAroundImages(node);
357 else if ("children" in node) node.children.forEach(visit);
358 };
359 visit(tree);
360 };
361}
362
363type MarkdownAstNode = {
364 type?: string;
365 meta?: unknown;
366 url?: string;
367 data?: {
368 hProperties?: Record<string, unknown>;
369 };
370 children?: MarkdownAstNode[];
371};
372
373function remarkKeepAutolinkSuffixes(): Transformer<Root> {
374 return (tree, file) => {
375 const source = String(file);
376 const visit = (node: Root | RootContent) => {
377 if (!("children" in node) || node.type === "link" || node.type === "linkReference") return;
378 for (let index = 0; index < node.children.length; index++) {
379 const child = node.children[index];
380 const next = node.children[index + 1];
381 if (child?.type === "link" && /^https?:\/\//i.test(child.url) && next?.type === "text") {
382 const suffix = /^[_~]+/.exec(next.value)?.[0];
383 if (!suffix) continue;
384 const label = child.children.length === 1 ? child.children[0] : undefined;
385 if (label?.type !== "text") continue;
386 if (label.value !== child.url && `http://${label.value}` !== child.url) continue;
387 const start = child.position?.start.offset;
388 const end = child.position?.end.offset;
389 const bare =
390 !child.position ||
391 (start !== undefined &&
392 end !== undefined &&
393 source.slice(start, end) === label.value &&
394 source.slice(end, end + suffix.length) === suffix);
395 if (bare) {
396 child.url += suffix;
397 label.value += suffix;
398 next.value = next.value.slice(suffix.length);
399 if (child.position && end !== undefined) {
400 const boundary = {
401 ...child.position.end,
402 column: child.position.end.column + suffix.length,
403 offset: end + suffix.length,
404 };
405 child.position.end = boundary;
406 if (label.position) label.position.end = boundary;
407 if (next.position) next.position.start = boundary;
408 }
409 if (!next.value) node.children.splice(index + 1, 1);
410 }
411 }
412 if (child) visit(child);
413 }
414 };
415 visit(tree);
416 };
417}
418
419function remarkPreserveCodeMeta() {
420 return (tree: MarkdownAstNode) => {
421 const visit = (node: MarkdownAstNode) => {
422 if (node.type === "code" && typeof node.meta === "string" && node.meta.trim().length > 0) {
423 node.data = {
424 ...node.data,
425 hProperties: {
426 ...node.data?.hProperties,
427 dataCodeMeta: node.meta.trim(),
428 },
429 };
430 }
431 node.children?.forEach(visit);
432 };
433
434 visit(tree);
435 };
436}
437
438function remarkNormalizeLinksAndTagInlineCode() {
439 return (tree: MarkdownAstNode) => {
440 const visit = (node: MarkdownAstNode, insideLink: boolean) => {
441 if (
442 (node.type === "link" || node.type === "definition") &&
443 typeof node.url === "string" &&
444 /^[A-Za-z]:[\\/]/.test(node.url)
445 ) {
446 node.url = `file:///${node.url.replaceAll("\\", "/")}`;
447 }
448 if (node.type === "inlineCode" && !insideLink) {
449 node.data = {
450 ...node.data,
451 hProperties: {
452 ...node.data?.hProperties,
453 dataInlineCode: "",
454 },
455 };
456 }
457 const childInsideLink = insideLink || node.type === "link" || node.type === "linkReference";
458 node.children?.forEach((child) => visit(child, childInsideLink));
459 };
460
461 visit(tree, false);
462 };
463}
464
465export function shouldPreserveAssistantLineBreaks(text: string): boolean {
466 return /^★ Insight(?:\s|─)/mu.test(text);
467}
468
469const imageSourceProcessor = unified()
470 .use(remarkParse)
471 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
472 .use(remarkRehype, { allowDangerousHtml: true })
473 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
474
475interface ImageSourceNode {
476 readonly type: string;
477 readonly tagName?: string;
478 readonly properties?: {
479 readonly src?: unknown;
480 readonly dataLocalSrc?: unknown;
481 readonly dataDarkSrc?: unknown;
482 readonly dataLightSrc?: unknown;
483 };
484 readonly children?: ReadonlyArray<ImageSourceNode>;
485}
486
487/**
488 * The sources of the images chat markdown shows, read as ChatMarkdown's `img` renderer reads
489 * them. Code, comments, and plain links show no image, so they add none.
490 */
491export function chatMarkdownImageSources(markdown: string): Array<string> {
492 const sources: Array<string> = [];
493 const visit = (node: ImageSourceNode) => {
494 if (node.type === "element" && node.tagName === "img") {
495 const { src, dataLocalSrc, dataDarkSrc, dataLightSrc } = node.properties ?? {};
496 // The sanitizer drops a Windows drive path from `src`; the renderer reads it from here.
497 if (typeof dataLocalSrc === "string") {
498 sources.push(normalizeMarkdownLinkDestination(dataLocalSrc).replaceAll("\\", "/"));
499 } else if (typeof src === "string") {
500 sources.push(normalizeMarkdownLinkDestination(src));
501 }
502 // A `<picture>` shows one of these instead, by the viewer's theme.
503 for (const variant of [dataDarkSrc, dataLightSrc]) {
504 if (typeof variant === "string") sources.push(normalizeMarkdownLinkDestination(variant));
505 }
506 }
507 node.children?.forEach(visit);
508 };
509 visit(imageSourceProcessor.runSync(imageSourceProcessor.parse(markdown)) as ImageSourceNode);
510 return sources;
511}