Open History to see the last commit
1import { DiffsHighlighter, getSharedHighlighter, SupportedLanguages } from "@pierre/diffs";
2import { CheckIcon, CopyIcon } from "lucide-react";
3import type { ServerProviderSkill } from "@t3tools/contracts";
4import React, {
5 Children,
6 Suspense,
7 type MouseEvent as ReactMouseEvent,
8 isValidElement,
9 use,
10 useCallback,
11 memo,
12 useEffect,
13 useMemo,
14 useRef,
15 useState,
16 type ReactNode,
17} from "react";
18import type { Components } from "react-markdown";
19import ReactMarkdown from "react-markdown";
20import { defaultUrlTransform } from "react-markdown";
21import remarkGfm from "remark-gfm";
22import { VscodeEntryIcon } from "./chat/VscodeEntryIcon";
23import { renderSkillInlineMarkdownChildren } from "./chat/SkillInlineText";
24import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
25import { stackedThreadToast, toastManager } from "./ui/toast";
26import { openInPreferredEditor } from "../editorPreferences";
27import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
28import { fnv1a32 } from "../lib/diffRendering";
29import { LRUCache } from "../lib/lruCache";
30import { useTheme } from "../hooks/useTheme";
31import {
32 normalizeMarkdownLinkDestination,
33 resolveMarkdownFileLinkMeta,
34 rewriteMarkdownFileUriHref,
35} from "../markdown-links";
36import { readLocalApi } from "../localApi";
37import { cn } from "../lib/utils";
38
39class CodeHighlightErrorBoundary extends React.Component<
40 { fallback: ReactNode; children: ReactNode },
41 { hasError: boolean }
42> {
43 constructor(props: { fallback: ReactNode; children: ReactNode }) {
44 super(props);
45 this.state = { hasError: false };
46 }
47
48 static getDerivedStateFromError() {
49 return { hasError: true };
50 }
51
52 override render() {
53 if (this.state.hasError) {
54 return this.props.fallback;
55 }
56 return this.props.children;
57 }
58}
59
60interface ChatMarkdownProps {
61 text: string;
62 cwd: string | undefined;
63 isStreaming?: boolean;
64 skills?: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">>;
65}
66
67const EMPTY_MARKDOWN_SKILLS: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">> = [];
68
69const CODE_FENCE_LANGUAGE_REGEX = /(?:^|\s)language-([^\s]+)/;
70const MAX_HIGHLIGHT_CACHE_ENTRIES = 500;
71const MAX_HIGHLIGHT_CACHE_MEMORY_BYTES = 50 * 1024 * 1024;
72const highlightedCodeCache = new LRUCache<string>(
73 MAX_HIGHLIGHT_CACHE_ENTRIES,
74 MAX_HIGHLIGHT_CACHE_MEMORY_BYTES,
75);
76const highlighterPromiseCache = new Map<string, Promise<DiffsHighlighter>>();
77
78function extractFenceLanguage(className: string | undefined): string {
79 const match = className?.match(CODE_FENCE_LANGUAGE_REGEX);
80 const raw = match?.[1] ?? "text";
81 // Shiki doesn't bundle a gitignore grammar; ini is a close match (#685)
82 return raw === "gitignore" ? "ini" : raw;
83}
84
85function nodeToPlainText(node: ReactNode): string {
86 if (typeof node === "string" || typeof node === "number") {
87 return String(node);
88 }
89 if (Array.isArray(node)) {
90 return node.map((child) => nodeToPlainText(child)).join("");
91 }
92 if (isValidElement<{ children?: ReactNode }>(node)) {
93 return nodeToPlainText(node.props.children);
94 }
95 return "";
96}
97
98function extractCodeBlock(
99 children: ReactNode,
100): { className: string | undefined; code: string } | null {
101 const childNodes = Children.toArray(children);
102 if (childNodes.length !== 1) {
103 return null;
104 }
105
106 const onlyChild = childNodes[0];
107 if (
108 !isValidElement<{ className?: string; children?: ReactNode }>(onlyChild) ||
109 onlyChild.type !== "code"
110 ) {
111 return null;
112 }
113
114 return {
115 className: onlyChild.props.className,
116 code: nodeToPlainText(onlyChild.props.children),
117 };
118}
119
120function createHighlightCacheKey(code: string, language: string, themeName: DiffThemeName): string {
121 return `${fnv1a32(code).toString(36)}:${code.length}:${language}:${themeName}`;
122}
123
124function estimateHighlightedSize(html: string, code: string): number {
125 return Math.max(html.length * 2, code.length * 3);
126}
127
128function getHighlighterPromise(language: string): Promise<DiffsHighlighter> {
129 const cached = highlighterPromiseCache.get(language);
130 if (cached) return cached;
131
132 const promise = getSharedHighlighter({
133 themes: [resolveDiffThemeName("dark"), resolveDiffThemeName("light")],
134 langs: [language as SupportedLanguages],
135 preferredHighlighter: "shiki-js",
136 }).catch((err) => {
137 highlighterPromiseCache.delete(language);
138 if (language === "text") {
139 // "text" itself failed — Shiki cannot initialize at all, surface the error
140 throw err;
141 }
142 // Language not supported by Shiki — fall back to "text"
143 return getHighlighterPromise("text");
144 });
145 highlighterPromiseCache.set(language, promise);
146 return promise;
147}
148
149function MarkdownCodeBlock({ code, children }: { code: string; children: ReactNode }) {
150 const [copied, setCopied] = useState(false);
151 const copiedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
152 const handleCopy = useCallback(() => {
153 if (typeof navigator === "undefined" || navigator.clipboard == null) {
154 return;
155 }
156 void navigator.clipboard
157 .writeText(code)
158 .then(() => {
159 if (copiedTimerRef.current != null) {
160 clearTimeout(copiedTimerRef.current);
161 }
162 setCopied(true);
163 copiedTimerRef.current = setTimeout(() => {
164 setCopied(false);
165 copiedTimerRef.current = null;
166 }, 1200);
167 })
168 .catch(() => undefined);
169 }, [code]);
170
171 useEffect(
172 () => () => {
173 if (copiedTimerRef.current != null) {
174 clearTimeout(copiedTimerRef.current);
175 copiedTimerRef.current = null;
176 }
177 },
178 [],
179 );
180
181 return (
182 <div className="chat-markdown-codeblock leading-snug">
183 <button
184 type="button"
185 className="chat-markdown-copy-button"
186 onClick={handleCopy}
187 title={copied ? "Copied" : "Copy code"}
188 aria-label={copied ? "Copied" : "Copy code"}
189 >
190 {copied ? <CheckIcon className="size-3" /> : <CopyIcon className="size-3" />}
191 </button>
192 {children}
193 </div>
194 );
195}
196
197interface SuspenseShikiCodeBlockProps {
198 className: string | undefined;
199 code: string;
200 themeName: DiffThemeName;
201 isStreaming: boolean;
202}
203
204function SuspenseShikiCodeBlock({
205 className,
206 code,
207 themeName,
208 isStreaming,
209}: SuspenseShikiCodeBlockProps) {
210 const language = extractFenceLanguage(className);
211 const cacheKey = createHighlightCacheKey(code, language, themeName);
212 const cachedHighlightedHtml = !isStreaming ? highlightedCodeCache.get(cacheKey) : null;
213
214 if (cachedHighlightedHtml != null) {
215 return (
216 <div
217 className="chat-markdown-shiki"
218 dangerouslySetInnerHTML={{ __html: cachedHighlightedHtml }}
219 />
220 );
221 }
222
223 return (
224 <UncachedShikiCodeBlock
225 code={code}
226 language={language}
227 themeName={themeName}
228 cacheKey={cacheKey}
229 isStreaming={isStreaming}
230 />
231 );
232}
233
234interface UncachedShikiCodeBlockProps {
235 code: string;
236 language: string;
237 themeName: DiffThemeName;
238 cacheKey: string;
239 isStreaming: boolean;
240}
241
242function UncachedShikiCodeBlock({
243 code,
244 language,
245 themeName,
246 cacheKey,
247 isStreaming,
248}: UncachedShikiCodeBlockProps) {
249 const highlighter = use(getHighlighterPromise(language));
250 const highlightedHtml = useMemo(() => {
251 try {
252 return highlighter.codeToHtml(code, { lang: language, theme: themeName });
253 } catch (error) {
254 // Log highlighting failures for debugging while falling back to plain text
255 console.warn(
256 `Code highlighting failed for language "${language}", falling back to plain text.`,
257 error instanceof Error ? error.message : error,
258 );
259 // If highlighting fails for this language, render as plain text
260 return highlighter.codeToHtml(code, { lang: "text", theme: themeName });
261 }
262 }, [code, highlighter, language, themeName]);
263
264 useEffect(() => {
265 if (!isStreaming) {
266 highlightedCodeCache.set(
267 cacheKey,
268 highlightedHtml,
269 estimateHighlightedSize(highlightedHtml, code),
270 );
271 }
272 }, [cacheKey, code, highlightedHtml, isStreaming]);
273
274 return (
275 <div className="chat-markdown-shiki" dangerouslySetInnerHTML={{ __html: highlightedHtml }} />
276 );
277}
278
279interface MarkdownFileLinkProps {
280 href: string;
281 targetPath: string;
282 displayPath: string;
283 filePath: string;
284 label: string;
285 theme: "light" | "dark";
286 className?: string | undefined;
287}
288
289const MARKDOWN_LINK_HREF_PATTERN = /\[[^\]]*]\(([^)\s]+)(?:\s+["'][^"']*["'])?\)/g;
290const MARKDOWN_FILE_LINK_CLASS_NAME =
291 "chat-markdown-file-link relative top-[2px] max-w-full no-underline";
292const MARKDOWN_FILE_LINK_ICON_CLASS_NAME = "chat-markdown-file-link-icon size-3.5 shrink-0";
293const MARKDOWN_FILE_LINK_LABEL_CLASS_NAME = "chat-markdown-file-link-label truncate";
294
295function pathParentSegments(path: string): string[] {
296 const normalized = path.replaceAll("\\", "/");
297 const segments = normalized.split("/").filter((segment) => segment.length > 0);
298 return segments.slice(0, -1);
299}
300
301function buildFileLinkParentSuffixByPath(filePaths: ReadonlyArray<string>): Map<string, string> {
302 const groups = new Map<string, Set<string>>();
303 for (const filePath of filePaths) {
304 const pathSegments = filePath
305 .replaceAll("\\", "/")
306 .split("/")
307 .filter((segment) => segment.length > 0);
308 const basename = pathSegments[pathSegments.length - 1];
309 if (!basename) continue;
310 const group = groups.get(basename) ?? new Set<string>();
311 group.add(filePath);
312 groups.set(basename, group);
313 }
314
315 const suffixByPath = new Map<string, string>();
316 for (const group of groups.values()) {
317 const uniquePaths = [...group];
318 if (uniquePaths.length < 2) continue;
319
320 const parentSegmentsByPath = new Map(
321 uniquePaths.map((filePath) => [filePath, pathParentSegments(filePath)]),
322 );
323 const minUniqueDepthByPath = new Map<string, number>();
324
325 for (const filePath of uniquePaths) {
326 const segments = parentSegmentsByPath.get(filePath) ?? [];
327 let resolvedDepth = segments.length;
328 for (let depth = 1; depth <= segments.length; depth += 1) {
329 const candidate = segments.slice(-depth).join("/");
330 const collision = uniquePaths.some((otherPath) => {
331 if (otherPath === filePath) return false;
332 const otherSegments = parentSegmentsByPath.get(otherPath) ?? [];
333 return otherSegments.slice(-depth).join("/") === candidate;
334 });
335 if (!collision) {
336 resolvedDepth = depth;
337 break;
338 }
339 }
340 minUniqueDepthByPath.set(filePath, resolvedDepth);
341 }
342
343 for (const filePath of uniquePaths) {
344 const segments = parentSegmentsByPath.get(filePath) ?? [];
345 if (segments.length === 0) continue;
346 const minUniqueDepth = minUniqueDepthByPath.get(filePath) ?? 1;
347 const suffixDepth = Math.min(segments.length, Math.max(minUniqueDepth, 2));
348 suffixByPath.set(filePath, segments.slice(-suffixDepth).join("/"));
349 }
350 }
351
352 return suffixByPath;
353}
354
355function extractMarkdownLinkHrefs(text: string): string[] {
356 const hrefs: string[] = [];
357 for (const match of text.matchAll(MARKDOWN_LINK_HREF_PATTERN)) {
358 const href = match[1]?.trim();
359 if (!href) continue;
360 hrefs.push(href);
361 }
362 return hrefs;
363}
364
365function normalizeMarkdownLinkHrefKey(href: string): string {
366 const normalizedHref = normalizeMarkdownLinkDestination(href);
367 return rewriteMarkdownFileUriHref(normalizedHref) ?? normalizedHref;
368}
369
370const MarkdownFileLink = memo(function MarkdownFileLink({
371 href,
372 targetPath,
373 displayPath,
374 filePath,
375 label,
376 theme,
377 className,
378}: MarkdownFileLinkProps) {
379 const handleOpen = useCallback(() => {
380 const api = readLocalApi();
381 if (!api) {
382 toastManager.add({
383 type: "error",
384 title: "Open in editor is unavailable",
385 });
386 return;
387 }
388
389 void openInPreferredEditor(api, targetPath).catch((error) => {
390 toastManager.add(
391 stackedThreadToast({
392 type: "error",
393 title: "Unable to open file",
394 description: error instanceof Error ? error.message : "An error occurred.",
395 }),
396 );
397 });
398 }, [targetPath]);
399
400 const handleCopy = useCallback((value: string, title: string) => {
401 if (typeof window === "undefined" || !navigator.clipboard?.writeText) {
402 toastManager.add(
403 stackedThreadToast({
404 type: "error",
405 title: `Failed to copy ${title.toLowerCase()}`,
406 description: "Clipboard API unavailable.",
407 }),
408 );
409 return;
410 }
411
412 void navigator.clipboard.writeText(value).then(
413 () => {
414 toastManager.add({
415 type: "success",
416 title: `${title} copied`,
417 description: value,
418 });
419 },
420 (error) => {
421 toastManager.add(
422 stackedThreadToast({
423 type: "error",
424 title: `Failed to copy ${title.toLowerCase()}`,
425 description: error instanceof Error ? error.message : "An error occurred.",
426 }),
427 );
428 },
429 );
430 }, []);
431
432 const handleContextMenu = useCallback(
433 async (event: ReactMouseEvent<HTMLAnchorElement>) => {
434 event.preventDefault();
435 event.stopPropagation();
436
437 const api = readLocalApi();
438 if (!api) return;
439
440 const clicked = await api.contextMenu.show(
441 [
442 { id: "open", label: "Open in editor" },
443 { id: "copy-relative", label: "Copy relative path" },
444 { id: "copy-full", label: "Copy full path" },
445 ] as const,
446 { x: event.clientX, y: event.clientY },
447 );
448
449 if (clicked === "open") {
450 handleOpen();
451 return;
452 }
453 if (clicked === "copy-relative") {
454 handleCopy(displayPath, "Relative path");
455 return;
456 }
457 if (clicked === "copy-full") {
458 handleCopy(targetPath, "Full path");
459 }
460 },
461 [displayPath, handleCopy, handleOpen, targetPath],
462 );
463
464 return (
465 <Tooltip>
466 <TooltipTrigger
467 render={
468 <a
469 href={href}
470 className={cn(MARKDOWN_FILE_LINK_CLASS_NAME, className)}
471 onClick={(event) => {
472 event.preventDefault();
473 event.stopPropagation();
474 handleOpen();
475 }}
476 onContextMenu={handleContextMenu}
477 >
478 <VscodeEntryIcon
479 pathValue={filePath}
480 kind="file"
481 theme={theme}
482 className={cn(MARKDOWN_FILE_LINK_ICON_CLASS_NAME, "text-current")}
483 />
484 <span className={MARKDOWN_FILE_LINK_LABEL_CLASS_NAME}>{label}</span>
485 </a>
486 }
487 />
488 <TooltipPopup
489 side="top"
490 className="max-w-[min(40rem,calc(100vw-2rem))] font-mono text-[11px] leading-tight"
491 >
492 <div className="markdown-file-link-tooltip-scroll overflow-x-auto whitespace-nowrap">
493 {displayPath}
494 </div>
495 </TooltipPopup>
496 </Tooltip>
497 );
498}, areMarkdownFileLinkPropsEqual);
499
500function areMarkdownFileLinkPropsEqual(
501 previous: Readonly<MarkdownFileLinkProps>,
502 next: Readonly<MarkdownFileLinkProps>,
503): boolean {
504 return (
505 previous.href === next.href &&
506 previous.targetPath === next.targetPath &&
507 previous.displayPath === next.displayPath &&
508 previous.filePath === next.filePath &&
509 previous.label === next.label &&
510 previous.theme === next.theme &&
511 previous.className === next.className
512 );
513}
514
515function ChatMarkdown({
516 text,
517 cwd,
518 isStreaming = false,
519 skills = EMPTY_MARKDOWN_SKILLS,
520}: ChatMarkdownProps) {
521 const { resolvedTheme } = useTheme();
522 const diffThemeName = resolveDiffThemeName(resolvedTheme);
523 const markdownFileLinkMetaByHref = useMemo(() => {
524 const metaByHref = new Map<
525 string,
526 NonNullable<ReturnType<typeof resolveMarkdownFileLinkMeta>>
527 >();
528 for (const href of extractMarkdownLinkHrefs(text)) {
529 const normalizedHref = normalizeMarkdownLinkHrefKey(href);
530 if (metaByHref.has(normalizedHref)) continue;
531 const meta = resolveMarkdownFileLinkMeta(normalizedHref, cwd);
532 if (meta) {
533 metaByHref.set(normalizedHref, meta);
534 }
535 }
536 return metaByHref;
537 }, [cwd, text]);
538 const fileLinkParentSuffixByPath = useMemo(() => {
539 const filePaths = [...markdownFileLinkMetaByHref.values()].map((meta) => meta.filePath);
540 return buildFileLinkParentSuffixByPath(filePaths);
541 }, [markdownFileLinkMetaByHref]);
542 const markdownUrlTransform = useCallback((href: string) => {
543 return rewriteMarkdownFileUriHref(href) ?? defaultUrlTransform(href);
544 }, []);
545 const markdownComponents = useMemo<Components>(
546 () => ({
547 p({ node: _node, children, ...props }) {
548 return <p {...props}>{renderSkillInlineMarkdownChildren(children, skills)}</p>;
549 },
550 li({ node: _node, children, ...props }) {
551 return <li {...props}>{renderSkillInlineMarkdownChildren(children, skills)}</li>;
552 },
553 a({ node: _node, href, ...props }) {
554 const normalizedHref = href ? normalizeMarkdownLinkHrefKey(href) : "";
555 const fileLinkMeta = normalizedHref ? markdownFileLinkMetaByHref.get(normalizedHref) : null;
556 if (!fileLinkMeta) {
557 return <a {...props} href={href} target="_blank" rel="noopener noreferrer" />;
558 }
559
560 const parentSuffix = fileLinkParentSuffixByPath.get(fileLinkMeta.filePath);
561 const labelParts = [fileLinkMeta.basename];
562 if (typeof parentSuffix === "string" && parentSuffix.length > 0) {
563 labelParts.push(parentSuffix);
564 }
565 if (fileLinkMeta.line) {
566 labelParts.push(
567 `L${fileLinkMeta.line}${fileLinkMeta.column ? `:C${fileLinkMeta.column}` : ""}`,
568 );
569 }
570
571 return (
572 <MarkdownFileLink
573 href={fileLinkMeta.targetPath}
574 targetPath={fileLinkMeta.targetPath}
575 displayPath={fileLinkMeta.displayPath}
576 filePath={fileLinkMeta.filePath}
577 label={labelParts.join(" · ")}
578 theme={resolvedTheme}
579 className={props.className}
580 />
581 );
582 },
583 pre({ node: _node, children, ...props }) {
584 const codeBlock = extractCodeBlock(children);
585 if (!codeBlock) {
586 return <pre {...props}>{children}</pre>;
587 }
588
589 return (
590 <MarkdownCodeBlock code={codeBlock.code}>
591 <CodeHighlightErrorBoundary fallback={<pre {...props}>{children}</pre>}>
592 <Suspense fallback={<pre {...props}>{children}</pre>}>
593 <SuspenseShikiCodeBlock
594 className={codeBlock.className}
595 code={codeBlock.code}
596 themeName={diffThemeName}
597 isStreaming={isStreaming}
598 />
599 </Suspense>
600 </CodeHighlightErrorBoundary>
601 </MarkdownCodeBlock>
602 );
603 },
604 }),
605 [
606 diffThemeName,
607 fileLinkParentSuffixByPath,
608 isStreaming,
609 markdownFileLinkMetaByHref,
610 resolvedTheme,
611 skills,
612 ],
613 );
614
615 return (
616 <div className="chat-markdown w-full min-w-0 text-sm leading-relaxed text-foreground/80">
617 <ReactMarkdown
618 remarkPlugins={[remarkGfm]}
619 components={markdownComponents}
620 urlTransform={markdownUrlTransform}
621 >
622 {text}
623 </ReactMarkdown>
624 </div>
625 );
626}
627
628export default memo(ChatMarkdown);