@devries-cameron20 / t3code-1 / commits / 48b486bd73
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(web): render completed Mermaid blocks while streaming (#18308)

Co-authored-by: Julius Marminge <julius0216@outlook.com>

Nikita Maximilian Grimm committed Oct 20, 2026 at 01:19 UTC 48b486bd73855c109735e84337735658700b0599
4 files changed +126 -13
apps/web/src/components/ChatMarkdown.browser.test.tsx
+109 -4
@@ -49,17 +49,27 @@ vi.mock(import("../remoteOpen"), async (original) => ({
49 ...(await original()),
50 useRemoteOpenResolution: () => ({ state: { mode: "local-exec" }, isResolved: true }) as never,
51 }));
52 -// A rendered diagram is an SVG; real Mermaid layout is not what these tests exercise.
53 -vi.mock(import("./chat/MermaidDiagram"), async (original) => ({
54 - ...(await original()),
55 - MermaidDiagram: () => <svg aria-label="Diagram" />,
52 +const { renderDiagram } = vi.hoisted(() => ({
53 + renderDiagram: vi.fn<(source: string) => Promise<string> | undefined>(),
54 }));
55 +// Control rendering latency without running Mermaid layout.
56 +vi.mock(import("./chat/MermaidDiagram"), async (original) => {
57 + const { use } = await import("react");
58 + return {
59 + ...(await original()),
60 + MermaidDiagram: ({ source }: { source: string }) => {
61 + const pending = renderDiagram(source);
62 + return <svg role="img" aria-label={pending ? use(pending) : "Diagram"} />;
63 + },
64 + };
65 +});
66
67 import ChatMarkdown from "./ChatMarkdown";
68
69 const roots: Root[] = [];
70
71 beforeEach(() => {
72 + renderDiagram.mockReset();
73 workspaceSearch.mockReset().mockResolvedValue(AsyncResult.success({ entries: [] }));
74 filesystemMetadata.mockReset().mockResolvedValue(AsyncResult.success({ entries: [null] }));
75 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
@@ -152,6 +162,99 @@ describe("ChatMarkdown bare anchor placeholders", () => {
162 });
163 });
164
165 +describe("ChatMarkdown Mermaid streaming", () => {
166 + it("reveals a completed fence while streaming and preserves it through later prose and stream end", async () => {
167 + let finishRender!: (label: string) => void;
168 + renderDiagram.mockReturnValue(
169 + new Promise<string>((resolve) => {
170 + finishRender = resolve;
171 + }),
172 + );
173 + const source = "flowchart LR\nA --> B";
174 + const open = `\`\`\`mermaid\n${source}`;
175 + const closed = `${open}\n\`\`\`\n\n`;
176 + const message = (text: string, isStreaming = true) => (
177 + <ChatMarkdown cwd={undefined} text={text} isStreaming={isStreaming} />
178 + );
179 + const { container, rerender } = await render(message(open));
180 + expect(container.querySelector("pre")?.textContent).toContain(source);
181 + expect(renderDiagram).not.toHaveBeenCalled();
182 +
183 + await rerender(message(closed));
184 + expect(renderDiagram).toHaveBeenCalledWith(expect.stringContaining(source));
185 + expect(container.querySelector('svg[role="img"]')).toBeNull();
186 + expect(container.querySelector(".chat-markdown-shiki")).toBeNull();
187 + const placeholder = container.querySelector("pre");
188 + expect(placeholder?.getAttribute("aria-hidden")).toBe("true");
189 + expect(placeholder?.textContent).toContain(source);
190 +
191 + await act(async () => finishRender("Completed diagram"));
192 + const diagram = container.querySelector('svg[role="img"]');
193 + expect(diagram?.getAttribute("aria-label")).toBe("Completed diagram");
194 + for (const streaming of [true, false]) {
195 + await rerender(message(`${closed}The remaining explanation.`, streaming));
196 + expect(container.querySelector('svg[role="img"]')).toBe(diagram);
197 + expect(container.textContent).toContain("The remaining explanation.");
198 + }
199 +
200 + await act(async () => buttonsLabelled(container, "Show code")[0]!.click());
201 + expect(container.querySelector('svg[role="img"]')).toBeNull();
202 + expect(container.querySelector("pre")?.textContent).toContain(source);
203 + await act(async () => buttonsLabelled(container, "Show diagram")[0]!.click());
204 + expect(container.querySelector('svg[role="img"]')?.getAttribute("aria-label")).toBe(
205 + "Completed diagram",
206 + );
207 + });
208 +
209 + it.each([
210 + ["short tilde marker", "~~~~mermaid\nflowchart LR\nA --> B\n~~~", "\n~~~~"],
211 + [
212 + "overindented blockquote marker",
213 + "> ```mermaid\n> flowchart LR\n> A --> B\n> ```",
214 + "\n> ```",
215 + ],
216 + [
217 + "overindented list marker",
218 + "- Diagram\n\n ```mermaid\n flowchart LR\n A --> B\n ```",
219 + "\n ```",
220 + ],
221 + ])("keeps a %s in source until a real closer arrives", async (_, open, closing) => {
222 + const message = (text: string) => <ChatMarkdown cwd={undefined} text={text} isStreaming />;
223 + const { container, rerender } = await render(message(open));
224 + expect(renderDiagram).not.toHaveBeenCalled();
225 + expect(container.querySelector("pre")?.textContent).toContain("A --> B");
226 +
227 + await rerender(message(`${open}${closing}`));
228 + expect(container.querySelector('svg[role="img"]')?.getAttribute("aria-label")).toBe("Diagram");
229 + });
230 +
231 + it("does not mistake a CRLF stream cut after CR for a closed fence", async () => {
232 + const open = "```mermaid\r\nflowchart LR\r\nA --> B\r\n\t```";
233 + const message = (text: string) => <ChatMarkdown cwd={undefined} text={text} isStreaming />;
234 + const { container, rerender } = await render(message(open));
235 + expect(renderDiagram).not.toHaveBeenCalled();
236 + await rerender(message(`${open}\r`));
237 + expect(renderDiagram).not.toHaveBeenCalled();
238 + expect(container.querySelector("pre")?.textContent).toContain("A --> B");
239 +
240 + await rerender(message(`${open}\r\n\`\`\``));
241 + expect(container.querySelector('svg[role="img"]')?.getAttribute("aria-label")).toBe("Diagram");
242 + });
243 +
244 + it("falls back to source when a completed diagram fails during streaming", async () => {
245 + await getSyntaxHighlighterPromise("mermaid");
246 + renderDiagram.mockImplementation(() => {
247 + throw new Error("Invalid Mermaid diagram");
248 + });
249 + vi.spyOn(console, "error").mockImplementation(() => {});
250 + const container = await renderText("```mermaid\ninvalid diagram\n```", { isStreaming: true });
251 + expect(renderDiagram).toHaveBeenCalledWith(expect.stringContaining("invalid diagram"));
252 + expect(container.querySelector('svg[role="img"]')).toBeNull();
253 + expect(container.querySelector("pre")?.textContent).toContain("invalid diagram");
254 + expect(container.querySelector("pre")?.getAttribute("aria-hidden")).not.toBe("true");
255 + });
256 +});
257 +
258 describe("ChatMarkdown context references", () => {
259 it("renders text and image references through the chip renderer, with readable fallback", async () => {
260 const text =
@@ -235,6 +338,8 @@ describe("ChatMarkdown streaming", () => {
338 "~~~bash\necho tilde\n~~~",
339 "> ```bash\n> echo quote\n> ```",
340 "````bash\necho four\n````",
341 + "- Command\n\n ```bash\n echo list\n ```",
342 + "```bash\r\necho crlf\r\n```\r",
343 ]) {
344 await rerender(message(text));
345 expect(runButtons()).toHaveLength(1);
apps/web/src/components/ChatMarkdown.tsx
+14 -7
@@ -471,7 +471,11 @@ function extractPreCodeMeta(node: unknown): string | undefined {
471 return typeof meta === "string" && meta.trim().length > 0 ? meta.trim() : undefined;
472 }
473
474 -function isClosedCodeFence(node: ReactMarkdownExtraProps["node"], text: string): boolean {
474 +function isClosedCodeFence(
475 + node: ReactMarkdownExtraProps["node"],
476 + text: string,
477 + code: string,
478 +): boolean {
479 const start = node?.position?.start.offset;
480 const end = node?.position?.end.offset;
481 if (start === undefined || end === undefined) return false;
@@ -484,7 +488,10 @@ function isClosedCodeFence(node: ReactMarkdownExtraProps["node"], text: string):
488 opening !== undefined &&
489 closing !== undefined &&
490 opening[0] === closing[0] &&
487 - closing.length >= opening.length
491 + closing.length >= opening.length &&
492 + // Only a real closer is omitted from parsed code. A CRLF stream cut after
493 + // CR must not count as an extra source line.
494 + source.replace(/\r$/, "").split(/\r\n|\r|\n/).length > code.split(/\r\n|\r|\n/).length
495 );
496 }
497
@@ -1080,9 +1087,9 @@ function MarkdownMermaidCodeBlock({
1087 <RenderErrorBoundary resetKeys={[code, theme]} fallback={children}>
1088 <Suspense
1089 fallback={
1083 - <div className="flex min-h-36 items-center justify-center text-xs text-muted-foreground">
1084 - Rendering diagram
1085 - </div>
1090 + <pre className="invisible" aria-hidden>
1091 + {code}
1092 + </pre>
1093 }
1094 >
1095 <MermaidDiagram source={code} theme={theme} onExpand={onExpand} />
@@ -3366,7 +3373,7 @@ const CHAT_MARKDOWN_COMPONENTS = {
3373 code={codeBlock.code}
3374 fenceTitle={fenceTitle}
3375 theme={resolvedTheme}
3369 - isStreaming={isStreaming}
3376 + isStreaming={isStreaming && !isClosedCodeFence(node, text, codeBlock.code)}
3377 onExpand={(src) => expandMedia({ images: [{ src, name: "Mermaid diagram" }], index: 0 })}
3378 >
3379 {highlightedCode}
@@ -3380,7 +3387,7 @@ const CHAT_MARKDOWN_COMPONENTS = {
3387 fenceTitle={fenceTitle}
3388 theme={resolvedTheme}
3389 onRunShellCommand={
3383 - onRunShellCommand && !isStreaming && isClosedCodeFence(node, text)
3390 + onRunShellCommand && !isStreaming && isClosedCodeFence(node, text, codeBlock.code)
3391 ? onRunShellCommand
3392 : undefined
3393 }
apps/web/src/components/chat/MermaidDiagram.tsx
+1 -1
@@ -270,7 +270,7 @@ export function MermaidDiagram({
270 }
271
272 return (
273 - <div className="overflow-x-auto">
273 + <div className="chat-markdown-mermaid overflow-x-auto">
274 <button
275 type="button"
276 aria-label="Expand diagram"
apps/web/src/index.css
+2 -1
@@ -2045,7 +2045,8 @@ code {
2045 shot, no layout change. */
2046 @media (prefers-reduced-motion: no-preference) {
2047 .chat-markdown[data-streaming] > *,
2048 - .chat-markdown[data-streaming] .chat-markdown-shiki {
2048 + .chat-markdown[data-streaming] .chat-markdown-shiki,
2049 + .chat-markdown[data-streaming] .chat-markdown-mermaid {
2050 transition: opacity 600ms ease-out;
2051
2052 @starting-style {