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, 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
112function rehypePreserveImageSourceMeta() {
113 return (tree: MarkdownImageHastNode) => {
114 const visit = (node: MarkdownImageHastNode) => {
115 const src = node.properties?.src;
116 const title = node.properties?.title;
117 if (node.type === "element" && node.tagName === "img") {
118 node.properties = {
119 ...node.properties,
120 ...(typeof src === "string" && isWindowsDrivePathHref(src) ? { dataLocalSrc: src } : {}),
121 ...(typeof title === "string" ? { dataMarkdownTitle: title } : {}),
122 };
123 }
124 node.children?.forEach(visit);
125 };
126
127 visit(tree);
128 markStandaloneImages(tree);
129 };
130}
131
132const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
133 ...defaultSchema,
134 attributes: {
135 ...defaultSchema.attributes,
136 "*": (defaultSchema.attributes?.["*"] ?? []).filter((attribute) => attribute !== "title"),
137 // Fence languages plus the two math classes the web chat's math plugin emits.
138 code: [
139 ["className", /^language-./, "math-inline", "math-display"],
140 "dataCodeMeta",
141 "dataInlineCode",
142 ],
143 blockquote: [...(defaultSchema.attributes?.blockquote ?? []), "dataAlert"],
144 div: [...(defaultSchema.attributes?.div ?? []), ...CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES],
145 a: [...(defaultSchema.attributes?.a ?? []), "dataPullRequestAutolink"],
146 img: [
147 ...(defaultSchema.attributes?.img ?? []),
148 "dataLocalSrc",
149 "dataMarkdownTitle",
150 "dataStandalone",
151 ],
152 },
153 protocols: {
154 ...defaultSchema.protocols,
155 href: [
156 ...(defaultSchema.protocols?.href ?? []),
157 "file",
158 "t3-citation",
159 "t3-context",
160 THREAD_LINK_PROTOCOL,
161 ],
162 src: [...(defaultSchema.protocols?.src ?? []), "file", "t3-context"],
163 },
164} satisfies Parameters<typeof rehypeSanitize>[0];
165
166export const CHAT_MARKDOWN_REMARK_PLUGINS: PluggableList = [
167 remarkGfm,
168 remarkKeepWindowsPaths,
169 remarkGithubAlerts,
170 remarkNormalizeListItemIndentation,
171 remarkCodexDirectives,
172 remarkBreakAroundImageLines,
173 remarkPreserveCodeMeta,
174 remarkNormalizeLinksAndTagInlineCode,
175];
176
177export const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS: PluggableList = [
178 remarkGfm,
179 remarkKeepWindowsPaths,
180 remarkGithubAlerts,
181 remarkNormalizeListItemIndentation,
182 remarkCodexDirectives,
183 remarkBreakAroundImageLines,
184 remarkBreaks,
185 remarkPreserveCodeMeta,
186 remarkNormalizeLinksAndTagInlineCode,
187];
188
189// Start tags an HTML parser closes an open `<p>` for.
190const CLOSES_PARAGRAPH = new Set(
191 "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(
192 " ",
193 ),
194);
195const HEADING = /^h[1-6]$/;
196
197interface HtmlScope {
198 readonly anchor: boolean;
199 readonly paragraph: boolean;
200 readonly heading: boolean;
201}
202
203/**
204 * Whether the tree needs the HTML parser: raw HTML, or nesting it repairs (a footnote call in a
205 * link label nests `<a>`). Otherwise it only rewrites properties as hast-util-to-parse5 does and
206 * drops `data`, both repeated here, and moves blank text that renders the same.
207 */
208function needsHtmlParser(node: MarkdownImageHastNode, scope: HtmlScope): boolean {
209 if (node.type === "raw") return true;
210 let inner = scope;
211 if (node.type === "element" && node.tagName) {
212 const { tagName } = node;
213 const heading = HEADING.test(tagName);
214 if (
215 (tagName === "a" && scope.anchor) ||
216 (scope.paragraph && CLOSES_PARAGRAPH.has(tagName)) ||
217 (heading && scope.heading)
218 ) {
219 return true;
220 }
221 inner = {
222 anchor: scope.anchor || tagName === "a",
223 paragraph: scope.paragraph || tagName === "p",
224 heading: scope.heading || heading,
225 };
226 const properties = node.properties ?? {};
227 for (const key of Object.keys(properties)) {
228 const value = properties[key];
229 const info = find(html, key);
230 if (
231 value === false ||
232 value === null ||
233 value === undefined ||
234 Number.isNaN(value) ||
235 (!value && info.boolean)
236 ) {
237 delete properties[key];
238 } else if (value === true && !info.boolean && !info.overloadedBoolean) {
239 properties[key] = "";
240 }
241 }
242 delete (node as { data?: unknown }).data;
243 }
244 return (node.children ?? []).some((child) => needsHtmlParser(child, inner));
245}
246
247const TOP_SCOPE: HtmlScope = { anchor: false, paragraph: false, heading: false };
248
249/** rehype-raw reparses the whole tree through an HTML parser, which most trees can skip. */
250function rehypeRawWhenPresent(this: Processor) {
251 const transform = rehypeRaw.call(this) as unknown as (
252 tree: MarkdownImageHastNode,
253 file: unknown,
254 ) => unknown;
255 return (tree: MarkdownImageHastNode, file: unknown) =>
256 needsHtmlParser(tree, TOP_SCOPE) ? transform(tree, file) : undefined;
257}
258
259export const CHAT_MARKDOWN_REHYPE_PLUGINS: PluggableList = [
260 rehypePreserveBareAnchorPlaceholders,
261 rehypeRawWhenPresent,
262 rehypePreserveImageSourceMeta,
263 [rehypeSanitize, CHAT_MARKDOWN_SANITIZE_SCHEMA],
264];
265
266const isImageNode = (node: PhrasingContent | undefined): boolean =>
267 node?.type === "image" ||
268 node?.type === "imageReference" ||
269 ((node?.type === "link" || node?.type === "linkReference") &&
270 node.children.length === 1 &&
271 isImageNode(node.children[0]));
272const endsLine = (node: PhrasingContent | undefined) =>
273 node === undefined ||
274 node.type === "break" ||
275 (node.type === "text" && /\n[ \t]*$/.test(node.value));
276const startsLine = (node: PhrasingContent | undefined) =>
277 node === undefined ||
278 node.type === "break" ||
279 (node.type === "text" && /^[ \t]*\n/.test(node.value));
280
281function breakLinesAroundImages(paragraph: Paragraph) {
282 const children = paragraph.children;
283 if (!children.some(isImageNode)) return;
284 const ownsLine = (index: number) =>
285 isImageNode(children[index]) &&
286 endsLine(children[index - 1]) &&
287 startsLine(children[index + 1]);
288 paragraph.children = children.flatMap((child, index): PhrasingContent[] => {
289 if (child.type !== "text") return [child];
290 const afterImage = ownsLine(index - 1);
291 const beforeImage = ownsLine(index + 1);
292 if (!afterImage && !beforeImage) return [child];
293 const parts: PhrasingContent[] = [];
294 let value = child.value;
295 if (afterImage) {
296 value = value.replace(/^[ \t]*\n/, "");
297 parts.push({ type: "break" });
298 }
299 const breakAfter = beforeImage && /\n[ \t]*$/.test(value);
300 if (breakAfter) value = value.replace(/[ \t]*\n[ \t]*$/, "");
301 if (value) parts.push({ type: "text", value });
302 if (breakAfter) parts.push({ type: "break" });
303 return parts;
304 });
305}
306
307/**
308 * Agents label screenshots with a line like `**Palette**` right above the image. CommonMark
309 * joins those lines into one paragraph, which puts the image inline beside its label. An
310 * image alone on its source line keeps that line; prose and inline badges still wrap.
311 */
312function remarkBreakAroundImageLines() {
313 return (tree: Root) => {
314 const visit = (node: Root | RootContent) => {
315 if (node.type === "paragraph") breakLinesAroundImages(node);
316 else if ("children" in node) node.children.forEach(visit);
317 };
318 visit(tree);
319 };
320}
321
322type MarkdownAstNode = {
323 type?: string;
324 meta?: unknown;
325 url?: string;
326 data?: {
327 hProperties?: Record<string, unknown>;
328 };
329 children?: MarkdownAstNode[];
330};
331
332function remarkPreserveCodeMeta() {
333 return (tree: MarkdownAstNode) => {
334 const visit = (node: MarkdownAstNode) => {
335 if (node.type === "code" && typeof node.meta === "string" && node.meta.trim().length > 0) {
336 node.data = {
337 ...node.data,
338 hProperties: {
339 ...node.data?.hProperties,
340 dataCodeMeta: node.meta.trim(),
341 },
342 };
343 }
344 node.children?.forEach(visit);
345 };
346
347 visit(tree);
348 };
349}
350
351function remarkNormalizeLinksAndTagInlineCode() {
352 return (tree: MarkdownAstNode) => {
353 const visit = (node: MarkdownAstNode, insideLink: boolean) => {
354 if (
355 (node.type === "link" || node.type === "definition") &&
356 typeof node.url === "string" &&
357 /^[A-Za-z]:[\\/]/.test(node.url)
358 ) {
359 node.url = `file:///${node.url.replaceAll("\\", "/")}`;
360 }
361 if (node.type === "inlineCode" && !insideLink) {
362 node.data = {
363 ...node.data,
364 hProperties: {
365 ...node.data?.hProperties,
366 dataInlineCode: "",
367 },
368 };
369 }
370 const childInsideLink = insideLink || node.type === "link" || node.type === "linkReference";
371 node.children?.forEach((child) => visit(child, childInsideLink));
372 };
373
374 visit(tree, false);
375 };
376}
377
378export function shouldPreserveAssistantLineBreaks(text: string): boolean {
379 return /^★ Insight(?:\s|─)/mu.test(text);
380}
381
382const imageSourceProcessor = unified()
383 .use(remarkParse)
384 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
385 .use(remarkRehype, { allowDangerousHtml: true })
386 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
387
388interface ImageSourceNode {
389 readonly type: string;
390 readonly tagName?: string;
391 readonly properties?: { readonly src?: unknown; readonly dataLocalSrc?: unknown };
392 readonly children?: ReadonlyArray<ImageSourceNode>;
393}
394
395/**
396 * The sources of the images chat markdown shows, read as ChatMarkdown's `img` renderer reads
397 * them. Code, comments, and plain links show no image, so they add none.
398 */
399export function chatMarkdownImageSources(markdown: string): Array<string> {
400 const sources: Array<string> = [];
401 const visit = (node: ImageSourceNode) => {
402 if (node.type === "element" && node.tagName === "img") {
403 const { src, dataLocalSrc } = node.properties ?? {};
404 // The sanitizer drops a Windows drive path from `src`; the renderer reads it from here.
405 if (typeof dataLocalSrc === "string") {
406 sources.push(normalizeMarkdownLinkDestination(dataLocalSrc).replaceAll("\\", "/"));
407 } else if (typeof src === "string") {
408 sources.push(normalizeMarkdownLinkDestination(src));
409 }
410 }
411 node.children?.forEach(visit);
412 };
413 visit(imageSourceProcessor.runSync(imageSourceProcessor.parse(markdown)) as ImageSourceNode);
414 return sources;
415}