Skip to content
TypeScript

perf(web): keep Markdown mounted during streaming (#9677)

Theo Browne887ece307131
diff --git a/apps/web/package.json b/apps/web/package.json
index 283024eca09..4c9396cc725 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -61,10 +61,12 @@
"@types/culori": "^4.0.1",
"@types/react": "~19.2.14",
"@types/react-dom": "~19.2.3",
+ "@types/react-test-renderer": "19.1.0",
"@vercel/config": "^0.3.0",
"@vitejs/plugin-react": "^6.0.0",
"babel-plugin-react-compiler": "1.0.0",
"compression": "^1.8.1",
+ "react-test-renderer": "19.2.6",
"tailwindcss": "^4.0.0",
"vite": "catalog:",
"vite-plus": "catalog:"
diff --git a/apps/web/src/components/ChatMarkdown.test.tsx b/apps/web/src/components/ChatMarkdown.test.tsx
index c3e536d70ae..18a6c5115ee 100644
--- a/apps/web/src/components/ChatMarkdown.test.tsx
+++ b/apps/web/src/components/ChatMarkdown.test.tsx
@@ -1,9 +1,38 @@
import { EnvironmentId } from "@t3tools/contracts";
+import { act, type ComponentProps, type ReactNode } from "react";
import { renderToStaticMarkup } from "react-dom/server";
+import { create, type ReactTestRenderer } from "react-test-renderer";
import { describe, expect, it, vi } from "vite-plus/test";
+import { getSyntaxHighlighterPromise } from "../lib/syntaxHighlighting";
+import { Button } from "./ui/button";
+import { setMarkdownTaskChecked } from "./files/filePreviewMode";
+
vi.mock("@effect/atom-react", () => ({ useAtomValue: () => null }));
vi.mock("../hooks/useTheme", () => ({ useTheme: () => ({ resolvedTheme: "dark" }) }));
+vi.mock("../hooks/useSettings", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("../hooks/useSettings")>();
+ const settings = actual.getClientSettings();
+ return {
+ ...actual,
+ useClientSettings: (select?: (value: typeof settings) => unknown) =>
+ select ? select(settings) : settings,
+ };
+});
+vi.mock("./ui/tooltip", async () => {
+ const { cloneElement, isValidElement } = await import("react");
+ return {
+ Tooltip: ({ children }: { children: ReactNode }) => <>{children}</>,
+ TooltipTrigger({
+ render,
+ children,
+ }: ComponentProps<typeof import("./ui/tooltip").TooltipTrigger>) {
+ if (!isValidElement(render)) return <>{children}</>;
+ return children === undefined ? render : cloneElement(render, undefined, children);
+ },
+ TooltipPopup: () => null,
+ };
+});
vi.mock("../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => vi.fn() }));
vi.mock("../state/use-atom-command", () => ({ useAtomCommand: () => vi.fn() }));
vi.mock("../state/session", async (importOriginal) => ({
@@ -35,6 +64,147 @@ import ChatMarkdown, {
shouldUseMarkdownFileBrowserPrimaryAction,
} from "./ChatMarkdown";
+function codeButton(renderer: ReactTestRenderer, label: string) {
+ const button = renderer.root
+ .findAllByType(Button)
+ .find((instance) => instance.props["aria-label"] === label);
+ if (!button) throw new Error(`Missing code button: ${label}`);
+ return button.props as ComponentProps<typeof Button>;
+}
+
+describe("ChatMarkdown streaming", () => {
+ it("preserves code controls and details without highlighting an unchanged fence again", async () => {
+ const highlighter = await getSyntaxHighlighterPromise("text");
+ const highlight = vi.spyOn(highlighter, "codeToHtml");
+ const writeText = vi.fn(async (_text: string) => {});
+ vi.stubGlobal("navigator", { clipboard: { writeText } });
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
+ let renderer: ReactTestRenderer | undefined;
+ const text = [
+ "```text",
+ "First code block",
+ "```",
+ "",
+ "<details><summary>More</summary>",
+ "",
+ "Details content",
+ "",
+ "</details>",
+ "",
+ "Streaming reply",
+ ].join("\n");
+
+ try {
+ await act(async () => {
+ renderer = create(<ChatMarkdown cwd="/tmp/project" text={text} isStreaming />);
+ });
+ const mounted = renderer!;
+ const codeBlock = mounted.root.findByProps({ "data-language": "text" });
+ const initialWrap = codeBlock.props["data-wrap"] === "true";
+ const wrap = codeButton(mounted, initialWrap ? "Disable line wrap" : "Wrap lines");
+ const copy = codeButton(mounted, "Copy code");
+ await act(async () => {
+ wrap.onClick?.({} as Parameters<NonNullable<typeof wrap.onClick>>[0]);
+ copy.onClick?.({} as Parameters<NonNullable<typeof copy.onClick>>[0]);
+ });
+
+ const detailsButton = mounted.root.find(
+ (instance) =>
+ instance.type === "button" && instance.props["data-markdown-details-summary"] === "",
+ );
+ await act(async () => {
+ detailsButton.props.onClick({ nativeEvent: new Event("click") });
+ });
+ const details = mounted.root.findByProps({ "data-markdown-details": "" });
+ expect(details.props["data-markdown-details-open"]).toBe("true");
+ expect(writeText).toHaveBeenCalledWith("First code block\n");
+ expect(highlight).toHaveBeenCalledTimes(1);
+
+ for (let index = 0; index < 10; index += 1) {
+ await act(async () => {
+ mounted.update(<ChatMarkdown cwd="/tmp/project" text={`${text} ${index}`} isStreaming />);
+ });
+ }
+
+ expect(highlight).toHaveBeenCalledTimes(1);
+ expect(mounted.root.findByProps({ "data-language": "text" })).toBe(codeBlock);
+ expect(codeBlock.props["data-wrap"]).toBe(String(!initialWrap));
+ expect(mounted.root.findByProps({ "data-markdown-details": "" })).toBe(details);
+ expect(details.props["data-markdown-details-open"]).toBe("true");
+ await act(async () => {
+ mounted.update(
+ <ChatMarkdown
+ cwd="/tmp/project"
+ text={text.replace("First code block", "Updated code block")}
+ isStreaming
+ />,
+ );
+ });
+ const copyUpdated = codeButton(mounted, "Copied");
+ await act(async () => {
+ copyUpdated.onClick?.({} as Parameters<NonNullable<typeof copyUpdated.onClick>>[0]);
+ });
+ expect(writeText).toHaveBeenLastCalledWith("Updated code block\n");
+ expect(highlight).toHaveBeenCalledTimes(2);
+ } finally {
+ await act(async () => renderer?.unmount());
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ }
+ });
+
+ it("edits the current task text and marker after reusing a renderer", async () => {
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ let renderer: ReactTestRenderer | undefined;
+ let editedText: string | undefined;
+ const message = (text: string) => (
+ <ChatMarkdown
+ cwd="/tmp/project"
+ text={text}
+ onTaskListChange={({ markerOffset, checked }) => {
+ editedText = setMarkdownTaskChecked(text, markerOffset, checked);
+ renderer!.update(message(editedText));
+ }}
+ />
+ );
+
+ try {
+ await act(async () => {
+ renderer = create(message("- [ ] First\n- [ ] Second"));
+ });
+ const mounted = renderer!;
+ const originalInput = mounted.root.findAllByType("input")[1]!;
+ await act(async () => {
+ mounted.update(message("- [ ] A longer first task\n- [ ] Second"));
+ });
+
+ const input = mounted.root.findAllByType("input")[1]!;
+ const listItem = mounted.root.findAllByType("li")[1]!;
+ const { onChange } = input.props as ComponentProps<"input">;
+ if (!onChange) throw new Error("Task checkbox has no edit handler");
+ await act(async () => {
+ onChange({
+ currentTarget: {
+ checked: true,
+ closest: () => ({
+ dataset: { taskMarkerOffset: String(listItem.props["data-task-marker-offset"]) },
+ }),
+ },
+ } as unknown as Parameters<typeof onChange>[0]);
+ });
+
+ expect(input).toBe(originalInput);
+ expect(editedText).toBe("- [ ] A longer first task\n- [x] Second");
+ expect(mounted.root.findAllByType("input")[1]!.props.checked).toBe(true);
+ } finally {
+ await act(async () => renderer?.unmount());
+ vi.unstubAllGlobals();
+ }
+ });
+});
+
describe("canUseMarkdownFileShellActions", () => {
const environmentId = EnvironmentId.make("environment-1");
diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx
index 75127ea124e..2226605827d 100644
--- a/apps/web/src/components/ChatMarkdown.tsx
+++ b/apps/web/src/components/ChatMarkdown.tsx
@@ -1952,7 +1952,7 @@ function areMarkdownFileLinkPropsEqual(
);
}
-function ChatMarkdown({
+function useChatMarkdownState({
text,
cwd,
threadRef,
@@ -1960,13 +1960,9 @@ function ChatMarkdown({
onTaskListChange,
isStreaming = false,
skills = EMPTY_MARKDOWN_SKILLS,
- className,
- lineBreaks = false,
- parseRawHtml = true,
onUseArtifactTemplate,
imageBaseDir,
onImageExpand,
- extraRemarkPlugins = EMPTY_REMARK_PLUGINS,
}: ChatMarkdownProps) {
const { resolvedTheme } = useTheme();
const [localMediaPreview, setLocalMediaPreview] = useState<ExpandedImagePreview | null>(null);
@@ -2270,11 +2266,8 @@ function ChatMarkdown({
},
[cwd, findWorkspaceBasenameMatch, revealFileInFileManager],
);
- /* eslint-disable react/no-unstable-nested-components -- ReactMarkdown requires component
- * renderers that close over this message's metadata. useMemo keeps them stable until that
- * metadata changes. */
- const markdownComponents = useMemo<Components>(() => {
- const fileLinkChip = (
+ const fileLinkChip = useCallback(
+ (
fileLinkMeta: MarkdownFileLinkMeta,
copyMarkdown: string,
className?: string,
@@ -2339,433 +2332,507 @@ function ChatMarkdown({
className={className}
/>
);
- };
+ },
+ [
+ canUseShellActions,
+ fileLinkParentSuffixByPath,
+ openFileInPanel,
+ openInPreferredEditor,
+ openMarkdownFileInPreview,
+ openMarkdownMedia,
+ preferredEditorMenuLabel,
+ resolvedTheme,
+ revealInFileManagerLabel,
+ revealMarkdownFileInFileManager,
+ threadRef,
+ ],
+ );
- return {
- div({ node, children, ...props }) {
- const artifactTemplate = artifactTemplateFromHastProperties(node?.properties);
- if (artifactTemplate) {
- return (
- <CodexArtifactTemplateCard template={artifactTemplate} onUse={onUseArtifactTemplate} />
- );
- }
- return <div {...props}>{children}</div>;
- },
- p({ node: _node, children, ...props }) {
- return <p {...props}>{renderSkillInlineMarkdownChildren(children, skills)}</p>;
- },
- blockquote({ node: _node, children, ...props }) {
- const alert =
- GITHUB_ALERT_PRESENTATIONS[
- String((props as Record<string, unknown>)["data-alert"] ?? "")
- ];
- if (!alert) {
- return <blockquote {...props}>{children}</blockquote>;
- }
- // Not a <blockquote>: the stylesheet mutes those, and an alert's body is ordinary
- // text under a colored title — which is how the host renders it.
- return (
- <div role="note" className={cn("my-1 border-l-2 pl-3", alert.borderClassName)}>
- <p className={cn("flex items-center gap-1.5 font-medium", alert.titleClassName)}>
- <alert.Icon aria-hidden className="size-3.5 shrink-0" />
- {alert.label}
- </p>
- {children}
- </div>
- );
- },
- ol({ node, start, style, ...props }) {
- const itemCount =
- node?.children?.filter((child) => child.type === "element" && child.tagName === "li")
- .length ?? 0;
- const gutterStyle = orderedListGutterStyle(itemCount, start);
- return (
- <ol {...props} start={start} style={gutterStyle ? { ...style, ...gutterStyle } : style} />
- );
- },
- li({ node, children, ...props }) {
- const listItemStart = node?.position?.start.offset;
- const markerOffset =
- typeof listItemStart === "number" ? findTaskListMarkerOffset(text, listItemStart) : null;
- return (
- <li {...props} data-task-marker-offset={markerOffset ?? undefined}>
- {renderSkillInlineMarkdownChildren(children, skills)}
- </li>
- );
- },
- input({ node: _node, type, checked, disabled: _disabled, ...props }) {
- if (type !== "checkbox" || !onTaskListChange) {
- return (
- <input
- {...props}
- type={type}
- checked={checked}
- disabled={_disabled}
- readOnly={type === "checkbox"}
- />
- );
- }
- return (
- <input
- {...props}
- type="checkbox"
- name="markdown-task"
- aria-label="Toggle task"
- checked={checked}
- onChange={(event) => {
- const markerOffset = Number(
- event.currentTarget.closest("li")?.dataset.taskMarkerOffset,
+ const componentState = useMemo(
+ () => ({
+ cwd,
+ diffThemeName,
+ expandMedia,
+ fileLinkChip,
+ imageBaseDir,
+ inlineCodeFileLinkMetaByText,
+ isStreaming,
+ linkTargetPreference,
+ markdownFileLinkMetaByHref,
+ onTaskListChange,
+ onUseArtifactTemplate,
+ openChangeRequestLink,
+ openExternalLinkInPreview,
+ openMarkdownMedia,
+ resolveThreadPullRequest,
+ resolvedTheme,
+ skills,
+ text,
+ threadRef,
+ updateThreadPullRequestLink,
+ }),
+ [
+ cwd,
+ diffThemeName,
+ expandMedia,
+ fileLinkChip,
+ imageBaseDir,
+ inlineCodeFileLinkMetaByText,
+ isStreaming,
+ linkTargetPreference,
+ markdownFileLinkMetaByHref,
+ onTaskListChange,
+ onUseArtifactTemplate,
+ openChangeRequestLink,
+ openExternalLinkInPreview,
+ openMarkdownMedia,
+ resolveThreadPullRequest,
+ resolvedTheme,
+ skills,
+ text,
+ threadRef,
+ updateThreadPullRequestLink,
+ ],
+ );
+ return {
+ componentState,
+ handleCopy,
+ markdownUrlTransform,
+ localMediaPreview,
+ setLocalMediaPreview,
+ };
+}
+
+const ChatMarkdownRendererContext = React.createContext<
+ ReturnType<typeof useChatMarkdownState>["componentState"]
+>(null!);
+
+// Keep component types stable when streaming changes the message state.
+const CHAT_MARKDOWN_COMPONENTS = {
+ div: function MarkdownDiv({ node, children, ...props }) {
+ const { onUseArtifactTemplate } = use(ChatMarkdownRendererContext);
+ const artifactTemplate = artifactTemplateFromHastProperties(node?.properties);
+ if (artifactTemplate) {
+ return (
+ <CodexArtifactTemplateCard template={artifactTemplate} onUse={onUseArtifactTemplate} />
+ );
+ }
+ return <div {...props}>{children}</div>;
+ },
+ p: function MarkdownParagraph({ node: _node, children, ...props }) {
+ const { skills } = use(ChatMarkdownRendererContext);
+ return <p {...props}>{renderSkillInlineMarkdownChildren(children, skills)}</p>;
+ },
+ blockquote: function MarkdownBlockquote({ node: _node, children, ...props }) {
+ const alert =
+ GITHUB_ALERT_PRESENTATIONS[String((props as Record<string, unknown>)["data-alert"] ?? "")];
+ if (!alert) {
+ return <blockquote {...props}>{children}</blockquote>;
+ }
+ // Not a <blockquote>: the stylesheet mutes those, and an alert's body is ordinary
+ // text under a colored title — which is how the host renders it.
+ return (
+ <div role="note" className={cn("my-1 border-l-2 pl-3", alert.borderClassName)}>
+ <p className={cn("flex items-center gap-1.5 font-medium", alert.titleClassName)}>
+ <alert.Icon aria-hidden className="size-3.5 shrink-0" />
+ {alert.label}
+ </p>
+ {children}
+ </div>
+ );
+ },
+ ol: function MarkdownOrderedList({ node, start, style, ...props }) {
+ const itemCount =
+ node?.children?.filter((child) => child.type === "element" && child.tagName === "li")
+ .length ?? 0;
+ const gutterStyle = orderedListGutterStyle(itemCount, start);
+ return (
+ <ol {...props} start={start} style={gutterStyle ? { ...style, ...gutterStyle } : style} />
+ );
+ },
+ li: function MarkdownListItem({ node, children, ...props }) {
+ const { text, skills } = use(ChatMarkdownRendererContext);
+ const listItemStart = node?.position?.start.offset;
+ const markerOffset =
+ typeof listItemStart === "number" ? findTaskListMarkerOffset(text, listItemStart) : null;
+ return (
+ <li {...props} data-task-marker-offset={markerOffset ?? undefined}>
+ {renderSkillInlineMarkdownChildren(children, skills)}
+ </li>
+ );
+ },
+ input: function MarkdownInput({ node: _node, type, checked, disabled: _disabled, ...props }) {
+ const { onTaskListChange } = use(ChatMarkdownRendererContext);
+ if (type !== "checkbox" || !onTaskListChange) {
+ return (
+ <input
+ {...props}
+ type={type}
+ checked={checked}
+ disabled={_disabled}
+ readOnly={type === "checkbox"}
+ />
+ );
+ }
+ return (
+ <input
+ {...props}
+ type="checkbox"
+ name="markdown-task"
+ aria-label="Toggle task"
+ checked={checked}
+ onChange={(event) => {
+ const markerOffset = Number(event.currentTarget.closest("li")?.dataset.taskMarkerOffset);
+ if (!Number.isSafeInteger(markerOffset)) return;
+ onTaskListChange({ markerOffset, checked: event.currentTarget.checked });
+ }}
+ />
+ );
+ },
+ a: function MarkdownAnchor({ node, href, children, title: _title, ...props }) {
+ const {
+ cwd,
+ imageBaseDir,
+ markdownFileLinkMetaByHref,
+ threadRef,
+ openMarkdownMedia,
+ openChangeRequestLink,
+ linkTargetPreference,
+ openExternalLinkInPreview,
+ resolveThreadPullRequest,
+ updateThreadPullRequestLink,
+ fileLinkChip,
+ } = use(ChatMarkdownRendererContext);
+ const citation = href ? parseAssistantCitationHref(href) : null;
+ if (citation) return <AssistantCitationChip citation={citation} />;
+ const normalizedHref = href ? normalizeMarkdownLinkHrefKey(href) : "";
+ const fileLinkMeta = normalizedHref
+ ? (markdownFileLinkMetaByHref.get(normalizedHref) ??
+ resolveMarkdownFileLinkMeta(normalizedHref, cwd, imageBaseDir ?? cwd))
+ : null;
+ if (!fileLinkMeta) {
+ const faviconHost = resolveExternalWebLinkHost(href);
+ const pullRequestAutolink = String(
+ (props as Record<string, unknown>)["data-pull-request-autolink"] ?? "",
+ );
+ const pullRequestCopy =
+ pullRequestAutolink === "commit"
+ ? /\/commit\/([0-9a-f]{40})$/iu.exec(href ?? "")?.[1]
+ : pullRequestAutolink === "reference"
+ ? plainHastText(node)
+ : undefined;
+ const isPullRequestAutolink = pullRequestCopy !== undefined;
+ const isSameDocumentLink = href?.startsWith("#") ?? false;
+ const onClick = props.onClick;
+ const canOpenInPreview = Boolean(threadRef) && isPreviewSupportedInRuntime();
+ const linkChildren = <MarkdownLinkContext value>{children}</MarkdownLinkContext>;
+ const link = (
+ <a
+ {...props}
+ className={cn(props.className, pullRequestAutolink === "commit" && "font-mono")}
+ data-markdown-copy={pullRequestCopy}
+ href={href}
+ target={isSameDocumentLink ? undefined : "_blank"}
+ rel={isSameDocumentLink ? undefined : "noopener noreferrer"}
+ onClick={(event) => {
+ onClick?.(event);
+ if (isSameDocumentLink && href) {
+ handleMarkdownFragmentClick(event, href);
+ return;
+ }
+ if (
+ href &&
+ faviconHost !== null &&
+ mediaKindFromPath(href) !== null &&
+ !event.defaultPrevented &&
+ !event.metaKey &&
+ !event.ctrlKey &&
+ !event.shiftKey &&
+ !event.altKey
+ ) {
+ event.preventDefault();
+ event.stopPropagation();
+ openMarkdownMedia(href);
+ return;
+ }
+ // A link to a change request in a workspace project opens beside the
+ // conversation instead of in a browser: it is the thing being talked about, and
+ // the panel it opens offers the browser as one of its actions.
+ if (!href || openChangeRequestLink(event, href)) return;
+ // Anything else follows the "Open links in" setting. The system browser
+ // keeps the `_blank` the shell already handles; the in-app browser needs
+ // the click intercepted here. A modifier click is the way out of the
+ // in-app default, so it is left to the shell too.
+ if (
+ event.defaultPrevented ||
+ resolveLinkTarget({
+ url: href,
+ event,
+ preference: linkTargetPreference,
+ canOpenInApp: canOpenInPreview,
+ }) !== "app"
+ ) {
+ return;
+ }
+ event.preventDefault();
+ event.stopPropagation();
+ // The click was taken from the shell, so an in-app open that fails
+ // hands the link to the system browser instead of dropping it.
+ void openExternalLinkInPreview(href).then((result) => {
+ if (result._tag === "Success" || isAtomCommandInterrupted(result)) return;
+ reportMarkdownActionFailure(
+ { operation: "open-link-in-preview", target: href },
+ result.cause,
);
- if (!Number.isSafeInteger(markerOffset)) return;
- onTaskListChange({ markerOffset, checked: event.currentTarget.checked });
- }}
- />
- );
- },
- a({ node, href, children, title: _title, ...props }) {
- const citation = href ? parseAssistantCitationHref(href) : null;
- if (citation) return <AssistantCitationChip citation={citation} />;
- const normalizedHref = href ? normalizeMarkdownLinkHrefKey(href) : "";
- const fileLinkMeta = normalizedHref
- ? (markdownFileLinkMetaByHref.get(normalizedHref) ??
- resolveMarkdownFileLinkMeta(normalizedHref, cwd, imageBaseDir ?? cwd))
- : null;
- if (!fileLinkMeta) {
- const faviconHost = resolveExternalWebLinkHost(href);
- const pullRequestAutolink = String(
- (props as Record<string, unknown>)["data-pull-request-autolink"] ?? "",
- );
- const pullRequestCopy =
- pullRequestAutolink === "commit"
- ? /\/commit\/([0-9a-f]{40})$/iu.exec(href ?? "")?.[1]
- : pullRequestAutolink === "reference"
- ? plainHastText(node)
- : undefined;
- const isPullRequestAutolink = pullRequestCopy !== undefined;
- const isSameDocumentLink = href?.startsWith("#") ?? false;
- const onClick = props.onClick;
- const canOpenInPreview = Boolean(threadRef) && isPreviewSupportedInRuntime();
- const linkChildren = <MarkdownLinkContext value>{children}</MarkdownLinkContext>;
- const link = (
- <a
- {...props}
- className={cn(props.className, pullRequestAutolink === "commit" && "font-mono")}
- data-markdown-copy={pullRequestCopy}
- href={href}
- target={isSameDocumentLink ? undefined : "_blank"}
- rel={isSameDocumentLink ? undefined : "noopener noreferrer"}
- onClick={(event) => {
- onClick?.(event);
- if (isSameDocumentLink && href) {
- handleMarkdownFragmentClick(event, href);
- return;
- }
- if (
- href &&
- faviconHost !== null &&
- mediaKindFromPath(href) !== null &&
- !event.defaultPrevented &&
- !event.metaKey &&
- !event.ctrlKey &&
- !event.shiftKey &&
- !event.altKey
- ) {
- event.preventDefault();
- event.stopPropagation();
- openMarkdownMedia(href);
- return;
+ void readLocalApi()?.shell.openExternal(href);
+ });
+ }}
+ onContextMenu={(event) => {
+ if (!href || !faviconHost) return;
+ event.preventDefault();
+ event.stopPropagation();
+ const api = readLocalApi();
+ if (!api) return;
+ const pullRequest = resolveThreadPullRequest(href);
+ const currentPullRequest =
+ threadRef === undefined ? null : readThreadShell(threadRef)?.linkedPullRequest;
+ const threadLinkAction =
+ currentPullRequest != null && matchesLinkedPullRequestUrl(currentPullRequest, href)
+ ? "unlink-from-thread"
+ : pullRequest === null
+ ? undefined
+ : "link-to-thread";
+ void showExternalLinkContextMenu({
+ href,
+ canOpenInPreview,
+ threadLinkAction,
+ position: { x: event.clientX, y: event.clientY },
+ showContextMenu: (items, position) => api.contextMenu.show(items, position),
+ openInPreview: async (target) => {
+ const result = await openExternalLinkInPreview(target);
+ if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
+ reportMarkdownActionFailure(
+ { operation: "open-link-in-preview", target },
+ result.cause,
+ );
}
- // A link to a change request in a workspace project opens beside the
- // conversation instead of in a browser: it is the thing being talked about, and
- // the panel it opens offers the browser as one of its actions.
- if (!href || openChangeRequestLink(event, href)) return;
- // Anything else follows the "Open links in" setting. The system browser
- // keeps the `_blank` the shell already handles; the in-app browser needs
- // the click intercepted here. A modifier click is the way out of the
- // in-app default, so it is left to the shell too.
+ },
+ openExternal: (target) => api.shell.openExternal(target),
+ copyLink: (target) => writeTextToClipboard(target, "link"),
+ updateThreadLink: updateThreadPullRequestLink,
+ reportFailure: (operation, cause) => {
+ reportMarkdownActionFailure({ operation, target: href }, cause);
if (
- event.defaultPrevented ||
- resolveLinkTarget({
- url: href,
- event,
- preference: linkTargetPreference,
- canOpenInApp: canOpenInPreview,
- }) !== "app"
+ operation === "link-pull-request-to-thread" ||
+ operation === "unlink-pull-request-from-thread"
) {
- return;
- }
- event.preventDefault();
- event.stopPropagation();
- // The click was taken from the shell, so an in-app open that fails
- // hands the link to the system browser instead of dropping it.
- void openExternalLinkInPreview(href).then((result) => {
- if (result._tag === "Success" || isAtomCommandInterrupted(result)) return;
- reportMarkdownActionFailure(
- { operation: "open-link-in-preview", target: href },
- result.cause,
+ toastManager.add(
+ stackedThreadToast({
+ type: "error",
+ title:
+ operation === "link-pull-request-to-thread"
+ ? "Unable to link pull request"
+ : "Unable to unlink pull request",
+ description: cause instanceof Error ? cause.message : "The request failed.",
+ }),
);
- void readLocalApi()?.shell.openExternal(href);
- });
- }}
- onContextMenu={(event) => {
- if (!href || !faviconHost) return;
- event.preventDefault();
- event.stopPropagation();
- const api = readLocalApi();
- if (!api) return;
- const pullRequest = resolveThreadPullRequest(href);
- const currentPullRequest =
- threadRef === undefined ? null : readThreadShell(threadRef)?.linkedPullRequest;
- const threadLinkAction =
- currentPullRequest != null &&
- matchesLinkedPullRequestUrl(currentPullRequest, href)
- ? "unlink-from-thread"
- : pullRequest === null
- ? undefined
- : "link-to-thread";
- void showExternalLinkContextMenu({
- href,
- canOpenInPreview,
- threadLinkAction,
- position: { x: event.clientX, y: event.clientY },
- showContextMenu: (items, position) => api.contextMenu.show(items, position),
- openInPreview: async (target) => {
- const result = await openExternalLinkInPreview(target);
- if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
- reportMarkdownActionFailure(
- { operation: "open-link-in-preview", target },
- result.cause,
- );
- }
- },
- openExternal: (target) => api.shell.openExternal(target),
- copyLink: (target) => writeTextToClipboard(target, "link"),
- updateThreadLink: updateThreadPullRequestLink,
- reportFailure: (operation, cause) => {
- reportMarkdownActionFailure({ operation, target: href }, cause);
- if (
- operation === "link-pull-request-to-thread" ||
- operation === "unlink-pull-request-from-thread"
- ) {
- toastManager.add(
- stackedThreadToast({
- type: "error",
- title:
- operation === "link-pull-request-to-thread"
- ? "Unable to link pull request"
- : "Unable to unlink pull request",
- description:
- cause instanceof Error ? cause.message : "The request failed.",
- }),
- );
- }
- },
- });
- }}
- >
- {faviconHost && hastHasText(node) && !isPullRequestAutolink ? (
- <MarkdownExternalLinkContent host={faviconHost} plainText={plainHastText(node)}>
- {linkChildren}
- </MarkdownExternalLinkContent>
- ) : (
- linkChildren
- )}
- </a>
- );
- if (!faviconHost || !href) {
- return link;
- }
- return (
- <Tooltip>
- <TooltipTrigger render={link} />
- <TooltipPopup
- side="top"
- className="max-w-[min(36rem,calc(100vw-2rem))] whitespace-normal leading-tight wrap-anywhere"
- >
- {href}
- </TooltipPopup>
- </Tooltip>
- );
- }
+ }
+ },
+ });
+ }}
+ >
+ {faviconHost && hastHasText(node) && !isPullRequestAutolink ? (
+ <MarkdownExternalLinkContent host={faviconHost} plainText={plainHastText(node)}>
+ {linkChildren}
+ </MarkdownExternalLinkContent>
+ ) : (
+ linkChildren
+ )}
+ </a>
+ );
+ if (!faviconHost || !href) {
+ return link;
+ }
+ return (
+ <Tooltip>
+ <TooltipTrigger render={link} />
+ <TooltipPopup
+ side="top"
+ className="max-w-[min(36rem,calc(100vw-2rem))] whitespace-normal leading-tight wrap-anywhere"
+ >
+ {href}
+ </TooltipPopup>
+ </Tooltip>
+ );
+ }
+ return fileLinkChip(
+ fileLinkMeta,
+ `[${fileLinkMeta.basename}](${normalizedHref})`,
+ props.className,
+ normalizedHref,
+ );
+ },
+ code: function MarkdownCode({ node, children, className, ...props }) {
+ const { cwd, imageBaseDir, inlineCodeFileLinkMetaByText, fileLinkChip } = use(
+ ChatMarkdownRendererContext,
+ );
+ if (node?.properties?.dataInlineCode != null) {
+ const codeText = nodeToPlainText(children);
+ const fileLinkMeta =
+ inlineCodeFileLinkMetaByText.get(codeText.trim()) ??
+ resolveInlineCodeFileLinkMeta(codeText, cwd, imageBaseDir ?? cwd);
+ if (fileLinkMeta) {
return fileLinkChip(
fileLinkMeta,
- `[${fileLinkMeta.basename}](${normalizedHref})`,
- props.className,
- normalizedHref,
+ `\`${codeText}\``,
+ undefined,
+ inlineCodeFilePathCandidate(codeText) ?? codeText.trim(),
);
- },
- code({ node, children, className, ...props }) {
- if (node?.properties?.dataInlineCode != null) {
- const codeText = nodeToPlainText(children);
- const fileLinkMeta =
- inlineCodeFileLinkMetaByText.get(codeText.trim()) ??
- resolveInlineCodeFileLinkMeta(codeText, cwd, imageBaseDir ?? cwd);
- if (fileLinkMeta) {
- return fileLinkChip(
- fileLinkMeta,
- `\`${codeText}\``,
- undefined,
- inlineCodeFilePathCandidate(codeText) ?? codeText.trim(),
- );
- }
- }
+ }
+ }
+ return (
+ <code {...props} className={className}>
+ {children}
+ </code>
+ );
+ },
+ img: function MarkdownImage({ node, title, src, alt, ...props }) {
+ const { expandMedia, cwd, imageBaseDir, threadRef } = use(ChatMarkdownRendererContext);
+ const imageExpand = use(MarkdownLinkContext) ? undefined : expandMedia;
+ const localSrc = node?.properties?.dataLocalSrc;
+ const markdownTitle = node?.properties?.dataMarkdownTitle;
+ const authoredSrc = typeof localSrc === "string" ? localSrc : src;
+ const authoredTitle = typeof markdownTitle === "string" ? markdownTitle : title;
+ const srcString =
+ typeof authoredSrc === "string" ? normalizeMarkdownLinkDestination(authoredSrc) : "";
+ const classifiedSrc =
+ typeof localSrc === "string" ? srcString.replaceAll("\\", "/") : srcString;
+ const altText = alt ?? "";
+ const copyMarkdown = markdownImageCopy(altText, srcString, authoredTitle);
+ const authoredSizeStyle = authoredImageSizeStyle(props.width, props.height);
+ const imageSource = classifyMarkdownImageSource(classifiedSrc, imageBaseDir ?? cwd);
+ const kind = mediaKindFromPath(classifiedSrc) ?? "image";
+ if (imageSource._tag === "Direct") {
+ const mediaSrc = resolveProtocolRelativeMediaUrl(imageSource.uri);
+ const originalUrl =
+ resolveExternalWebLinkHost(imageSource.uri) !== null ? imageSource.uri : undefined;
+ const reference = mediaUrlReference(imageSource.uri);
+ const actionsSource: MediaActionSource = {
+ kind,
+ name: altText || kind,
+ src: mediaSrc,
+ ...(reference ? { reference } : {}),
+ };
+ if (kind === "video") {
return (
- <code {...props} className={className}>
- {children}
- </code>
+ <ChatMarkdownVideo
+ src={mediaSrc}
+ alt={altText}
+ copyMarkdown={copyMarkdown}
+ originalUrl={originalUrl}
+ style={authoredSizeStyle}
+ actionsSource={actionsSource}
+ />
);
- },
- img: function MarkdownImage({ node, title, src, alt, ...props }) {
- const imageExpand = use(MarkdownLinkContext) ? undefined : expandMedia;
- const localSrc = node?.properties?.dataLocalSrc;
- const markdownTitle = node?.properties?.dataMarkdownTitle;
- const authoredSrc = typeof localSrc === "string" ? localSrc : src;
- const authoredTitle = typeof markdownTitle === "string" ? markdownTitle : title;
- const srcString =
- typeof authoredSrc === "string" ? normalizeMarkdownLinkDestination(authoredSrc) : "";
- const classifiedSrc =
- typeof localSrc === "string" ? srcString.replaceAll("\\", "/") : srcString;
- const altText = alt ?? "";
- const copyMarkdown = markdownImageCopy(altText, srcString, authoredTitle);
- const authoredSizeStyle = authoredImageSizeStyle(props.width, props.height);
- const imageSource = classifyMarkdownImageSource(classifiedSrc, imageBaseDir ?? cwd);
- const kind = mediaKindFromPath(classifiedSrc) ?? "image";
- if (imageSource._tag === "Direct") {
- const mediaSrc = resolveProtocolRelativeMediaUrl(imageSource.uri);
- const originalUrl =
- resolveExternalWebLinkHost(imageSource.uri) !== null ? imageSource.uri : undefined;
- const reference = mediaUrlReference(imageSource.uri);
- const actionsSource: MediaActionSource = {
- kind,
- name: altText || kind,
- src: mediaSrc,
- ...(reference ? { reference } : {}),
- };
- if (kind === "video") {
- return (
- <ChatMarkdownVideo
- src={mediaSrc}
- alt={altText}
- copyMarkdown={copyMarkdown}
- originalUrl={originalUrl}
- style={authoredSizeStyle}
- actionsSource={actionsSource}
- />
- );
- }
- return (
- <MediaActions source={actionsSource}>
- <img
- {...props}
- src={mediaSrc}
- alt={altText}
- loading="lazy"
- className={cn(
- props.className,
- CHAT_MARKDOWN_IMAGE_SIZE_CLASS_NAME,
- imageExpand && "cursor-zoom-in",
- )}
- style={authoredSizeStyle}
- {...expandableMarkdownImageProps(
- imageExpand,
- mediaSrc,
- altText,
- originalUrl,
- actionsSource,
- )}
- />
- </MediaActions>
- );
- }
- if (imageSource._tag === "WorkspaceFile" && threadRef) {
- return (
- <ChatMarkdownAssetImage
- environmentId={threadRef.environmentId}
- resource={{
- _tag: "media-file",
- threadId: threadRef.threadId,
- path: imageSource.path,
- }}
- alt={altText}
- kind={kind}
- copyMarkdown={copyMarkdown}
- srcFragment={markdownImageSourceFragment(classifiedSrc)}
- style={authoredSizeStyle}
- workspaceRoot={cwd}
- onImageExpand={imageExpand}
- />
- );
- }
- return <ChatMarkdownImageFallback alt={altText} copyMarkdown={copyMarkdown} kind={kind} />;
- },
- table({ node: _node, ...props }) {
- return <MarkdownTable {...props} />;
- },
- details({ node: _node, children, open: detailsOpen }) {
- return <MarkdownDetails open={detailsOpen}>{children}</MarkdownDetails>;
- },
- pre({ node, children, ...props }) {
- const codeBlock = extractCodeBlock(children);
- if (!codeBlock) {
- return <pre {...props}>{children}</pre>;
- }
+ }
+ return (
+ <MediaActions source={actionsSource}>
+ <img
+ {...props}
+ src={mediaSrc}
+ alt={altText}
+ loading="lazy"
+ className={cn(
+ props.className,
+ CHAT_MARKDOWN_IMAGE_SIZE_CLASS_NAME,
+ imageExpand && "cursor-zoom-in",
+ )}
+ style={authoredSizeStyle}
+ {...expandableMarkdownImageProps(
+ imageExpand,
+ mediaSrc,
+ altText,
+ originalUrl,
+ actionsSource,
+ )}
+ />
+ </MediaActions>
+ );
+ }
+ if (imageSource._tag === "WorkspaceFile" && threadRef) {
+ return (
+ <ChatMarkdownAssetImage
+ environmentId={threadRef.environmentId}
+ resource={{
+ _tag: "media-file",
+ threadId: threadRef.threadId,
+ path: imageSource.path,
+ }}
+ alt={altText}
+ kind={kind}
+ copyMarkdown={copyMarkdown}
+ srcFragment={markdownImageSourceFragment(classifiedSrc)}
+ style={authoredSizeStyle}
+ workspaceRoot={cwd}
+ onImageExpand={imageExpand}
+ />
+ );
+ }
+ return <ChatMarkdownImageFallback alt={altText} copyMarkdown={copyMarkdown} kind={kind} />;
+ },
+ table: function MarkdownTableRenderer({ node: _node, ...props }) {
+ return <MarkdownTable {...props} />;
+ },
+ details: function MarkdownDetailsRenderer({ node: _node, children, open: detailsOpen }) {
+ return <MarkdownDetails open={detailsOpen}>{children}</MarkdownDetails>;
+ },
+ pre: function MarkdownPre({ node, children, ...props }) {
+ const { resolvedTheme, diffThemeName, isStreaming } = use(ChatMarkdownRendererContext);
+ const codeBlock = extractCodeBlock(children);
+ if (!codeBlock) {
+ return <pre {...props}>{children}</pre>;
+ }
- const language = extractFenceLanguage(codeBlock.className);
- const fenceTitle = extractFenceTitle(extractPreCodeMeta(node));
- return (
- <MarkdownCodeBlock
- code={codeBlock.code}
- language={language}
- fenceTitle={fenceTitle}
- theme={resolvedTheme}
- >
- <RenderErrorBoundary fallback={<pre {...props}>{children}</pre>}>
- <Suspense fallback={<pre {...props}>{children}</pre>}>
- <SuspenseShikiCodeBlock
- className={codeBlock.className}
- code={codeBlock.code}
- themeName={diffThemeName}
- isStreaming={isStreaming}
- />
- </Suspense>
- </RenderErrorBoundary>
- </MarkdownCodeBlock>
- );
- },
- };
- }, [
- canUseShellActions,
- cwd,
- diffThemeName,
- fileLinkParentSuffixByPath,
- inlineCodeFileLinkMetaByText,
- imageBaseDir,
- isStreaming,
- linkTargetPreference,
- markdownFileLinkMetaByHref,
- onTaskListChange,
- onUseArtifactTemplate,
- onImageExpand,
- expandMedia,
- openMarkdownMedia,
- openFileInPanel,
- openInPreferredEditor,
- openChangeRequestLink,
- openExternalLinkInPreview,
- openMarkdownFileInPreview,
- preferredEditorMenuLabel,
- resolveThreadPullRequest,
- resolvedTheme,
- revealMarkdownFileInFileManager,
- revealInFileManagerLabel,
- skills,
- text,
- threadRef,
- updateThreadPullRequestLink,
- ]);
- /* eslint-enable react/no-unstable-nested-components */
+ const language = extractFenceLanguage(codeBlock.className);
+ const fenceTitle = extractFenceTitle(extractPreCodeMeta(node));
+ return (
+ <MarkdownCodeBlock
+ code={codeBlock.code}
+ language={language}
+ fenceTitle={fenceTitle}
+ theme={resolvedTheme}
+ >
+ <RenderErrorBoundary fallback={<pre {...props}>{children}</pre>}>
+ <Suspense fallback={<pre {...props}>{children}</pre>}>
+ <SuspenseShikiCodeBlock
+ className={codeBlock.className}
+ code={codeBlock.code}
+ themeName={diffThemeName}
+ isStreaming={isStreaming}
+ />
+ </Suspense>
+ </RenderErrorBoundary>
+ </MarkdownCodeBlock>
+ );
+ },
+} satisfies Components;
+function ChatMarkdown({
+ text,
+ className,
+ lineBreaks = false,
+ parseRawHtml = true,
+ extraRemarkPlugins = EMPTY_REMARK_PLUGINS,
+ ...props
+}: ChatMarkdownProps) {
+ const {
+ componentState,
+ handleCopy,
+ markdownUrlTransform,
+ localMediaPreview,
+ setLocalMediaPreview,
+ } = useChatMarkdownState({ text, ...props });
const remarkPlugins = useMemo(
() => [
...(lineBreaks ? CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS : CHAT_MARKDOWN_REMARK_PLUGINS),
@@ -2785,15 +2852,17 @@ function ChatMarkdown({
)}
onCopy={handleCopy}
>
- <ReactMarkdown
- remarkPlugins={remarkPlugins}
- rehypePlugins={parseRawHtml ? CHAT_MARKDOWN_REHYPE_PLUGINS : undefined}
- skipHtml={false}
- components={markdownComponents}
- urlTransform={markdownUrlTransform}
- >
- {text}
- </ReactMarkdown>
+ <ChatMarkdownRendererContext value={componentState}>
+ <ReactMarkdown
+ remarkPlugins={remarkPlugins}
+ rehypePlugins={parseRawHtml ? CHAT_MARKDOWN_REHYPE_PLUGINS : undefined}
+ skipHtml={false}
+ components={CHAT_MARKDOWN_COMPONENTS}
+ urlTransform={markdownUrlTransform}
+ >
+ {text}
+ </ReactMarkdown>
+ </ChatMarkdownRendererContext>
{localMediaPreview ? (
<ExpandedImageDialog
preview={localMediaPreview}
diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx
index e97f10c3943..f21d10b26be 100644
--- a/apps/web/src/components/chat/MessagesTimeline.tsx
+++ b/apps/web/src/components/chat/MessagesTimeline.tsx
@@ -639,10 +639,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
listRef,
timestampFormat,
routeThreadKey,
- // Must be referentially stable: ChatMarkdown keys its react-markdown
- // component map on threadRef, and a fresh object here remounts every
- // rendered markdown node whenever this memo recomputes (e.g. on each
- // activity delta while the thread is working).
+ // Keep Markdown callbacks memoized during unrelated activity updates.
threadRef: citationThreadRef,
markdownCwd,
resolvedTheme,
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index d69028c3609..8d5ee2875cc 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -690,6 +690,9 @@ importers:
'@types/react-dom':
specifier: ~19.2.3
version: 19.2.3(@types/[email protected])
+ '@types/react-test-renderer':
+ specifier: 19.1.0
+ version: 19.1.0
'@vercel/config':
specifier: ^0.3.0
version: 0.3.0
@@ -702,6 +705,9 @@ importers:
compression:
specifier: ^1.8.1
version: 1.8.1
+ react-test-renderer:
+ specifier: 19.2.6
+ version: 19.2.6([email protected])
tailwindcss:
specifier: 4.3.3
version: 4.3.3
@@ -9092,6 +9098,11 @@ packages:
'@types/react':
optional: true
+ resolution: {integrity: sha512-GbS6V23YduFTPiWJ5xICbKEjRcqx1Z90js/V5miqhz7qp/d6xSe9Dd6NjSQODFRdzdsqRMPW82E/sFpPRbY5Mw==}
+ peerDependencies:
+ react: ^19.2.6
+
resolution: {integrity: sha512-Ku/hhYbVjOQnXDZFv2+RibmLFGwFdeeKHFcOTlrt7xplBnya5OGn/hIRDsqDiSUcfORsDC7MPxwork8jBwsIWA==}
engines: {node: '>=0.10.0'}
@@ -19795,6 +19806,12 @@ snapshots:
optionalDependencies:
'@types/react': 19.2.16
+ dependencies:
+ react: 19.2.6
+ react-is: 19.2.7
+ scheduler: 0.27.0
+