diff --git a/frontend/src/directives/stableHtml.ts b/frontend/src/directives/stableHtml.ts
index 303ee746..723854bf 100644
--- a/frontend/src/directives/stableHtml.ts
+++ b/frontend/src/directives/stableHtml.ts
@@ -53,6 +53,27 @@ function morphImage(current: HTMLImageElement, next: HTMLImageElement): void {
syncAttributes(current, next);
}
+function isMermaidCanvas(el: Element): boolean {
+ return el.classList.contains('chat-mermaid-block__canvas')
+ || (el.tagName === 'PRE' && el.classList.contains('mermaid'));
+}
+
+function mermaidCanvasHasSvg(el: Element): boolean {
+ return !!el.querySelector('svg');
+}
+
+function morphMermaidCanvas(current: Element, next: Element): void {
+ // Incoming HTML from marked still has mermaid source. Keep a diagram that
+ // was already painted so typewriter / stream ticks cannot flash it back
+ // into a fenced code block.
+ if (mermaidCanvasHasSvg(current) && !mermaidCanvasHasSvg(next)) {
+ syncAttributes(current, next, new Set(['data-mermaid']));
+ return;
+ }
+ syncAttributes(current, next);
+ morphChildren(current, next);
+}
+
function morphNode(current: Node, next: Node): void {
if (current.nodeType === Node.TEXT_NODE || current.nodeType === Node.COMMENT_NODE) {
if (current.nodeValue !== next.nodeValue) current.nodeValue = next.nodeValue;
@@ -65,6 +86,10 @@ function morphNode(current: Node, next: Node): void {
morphImage(currentElement, nextElement);
return;
}
+ if (isMermaidCanvas(currentElement) && isMermaidCanvas(nextElement)) {
+ morphMermaidCanvas(currentElement, nextElement);
+ return;
+ }
syncAttributes(currentElement, nextElement);
morphChildren(currentElement, nextElement);
diff --git a/frontend/src/utils/chatMarkdownRenderer.ts b/frontend/src/utils/chatMarkdownRenderer.ts
index 7ce09d6b..c99b4f76 100644
--- a/frontend/src/utils/chatMarkdownRenderer.ts
+++ b/frontend/src/utils/chatMarkdownRenderer.ts
@@ -2,6 +2,7 @@ import { marked, type Renderer } from 'marked'
import markedKatex from 'marked-katex-extension'
import type { Tokens } from 'marked'
+import type { CachedMermaidSvgHtml } from './mermaidStreaming.ts'
import { normalizeSandboxArtifactRefs } from './sandboxArtifactRefs.ts'
import {
collapseStandaloneCitationParagraphs,
@@ -40,9 +41,9 @@ export type RenderChatMarkdownOptions = {
streaming?: boolean
collapseStandaloneCitations?: boolean
knowledgeReferences?: CitationKnowledgeRef[] | null
- cachedMermaidSvgHtml?: string | null
- injectCachedMermaidSvg?: (html: string, cachedSvgHtml?: string | null) => string
- prepareMarkdown?: (markdown: string, cachedSvgHtml?: string | null) => string
+ cachedMermaidSvgHtml?: CachedMermaidSvgHtml
+ injectCachedMermaidSvg?: (html: string, cachedSvgHtml?: CachedMermaidSvgHtml) => string
+ prepareMarkdown?: (markdown: string, cachedSvgHtml?: CachedMermaidSvgHtml) => string
}
export function configureMarkedForChatMarkdown(): void {
diff --git a/frontend/src/utils/chatMessageShared.ts b/frontend/src/utils/chatMessageShared.ts
index c09e82cd..3fea4099 100644
--- a/frontend/src/utils/chatMessageShared.ts
+++ b/frontend/src/utils/chatMessageShared.ts
@@ -1,9 +1,23 @@
import i18n from '@/i18n';
import { buildMermaidBlockHtml, buildMermaidLoadingHtml } from '@/utils/markdownEnhancements';
+import {
+ injectCachedMermaidSvg as injectCachedMermaidSvgHtml,
+ maskMermaidBlocksForStreaming as maskMermaidBlocks,
+ prepareStreamingMermaidMarkdown as prepareStreamingMermaid,
+ replaceIncompleteMermaidWithPlaceholder as replaceIncompleteMermaid,
+ type CachedMermaidSvgHtml,
+} from './mermaidStreaming';
+
+export type { CachedMermaidSvgHtml };
+export {
+ extractFirstMermaidCode,
+ extractMermaidCodes,
+ hasCompleteMermaidBlock,
+ normalizeCachedMermaidSvgs,
+} from './mermaidStreaming';
const STREAMING_IMAGE_PLACEHOLDER = '';
const STREAMING_MERMAID_PLACEHOLDER = buildMermaidLoadingHtml();
-const MERMAID_FENCE_START = '```mermaid';
export const replaceIncompleteImageWithPlaceholder = (content: string): string => {
if (!content) return '';
@@ -28,61 +42,28 @@ export const replaceIncompleteImageWithPlaceholder = (content: string): string =
/** Hide an unclosed trailing ```mermaid fence while streaming to avoid layout jitter. */
export const replaceIncompleteMermaidWithPlaceholder = (content: string): string => {
- if (!content) return '';
-
- const start = content.lastIndexOf(MERMAID_FENCE_START);
- if (start < 0) return content;
-
- const tail = content.slice(start + MERMAID_FENCE_START.length);
- if (tail.includes('```')) return content;
-
- return content.slice(0, start) + STREAMING_MERMAID_PLACEHOLDER;
+ return replaceIncompleteMermaid(content, STREAMING_MERMAID_PLACEHOLDER);
};
-const MERMAID_BLOCK_RE = /```mermaid[\s\S]*?```/;
-
-/** Keep mermaid as a stable placeholder for the whole stream; render once at the end. */
+/** Keep every mermaid fence as a stable placeholder; render SVG via cache injection. */
export const maskMermaidBlocksForStreaming = (content: string): string => {
- if (!content) return '';
- const masked = content.replace(MERMAID_BLOCK_RE, STREAMING_MERMAID_PLACEHOLDER);
- return replaceIncompleteMermaidWithPlaceholder(masked);
-};
-
-export const hasCompleteMermaidBlock = (content: string): boolean => {
- return MERMAID_BLOCK_RE.test(content);
+ return maskMermaidBlocks(content, STREAMING_MERMAID_PLACEHOLDER);
};
/** While streaming: loading placeholder for mermaid; swap to cached SVG after sanitize. */
export const prepareStreamingMermaidMarkdown = (
content: string,
- _cachedSvgHtml?: string | null,
+ _cachedSvgHtml?: CachedMermaidSvgHtml,
): string => {
- if (!content) return '';
-
- if (hasCompleteMermaidBlock(content)) {
- return maskMermaidBlocksForStreaming(content);
- }
-
- return replaceIncompleteMermaidWithPlaceholder(content);
+ return prepareStreamingMermaid(content, STREAMING_MERMAID_PLACEHOLDER);
};
-export const extractFirstMermaidCode = (content: string): string | null => {
- const match = content.match(/```mermaid([\s\S]*?)```/);
- return match?.[1]?.trim() || null;
-};
-
-const STREAMING_MERMAID_LOADING_RE = /
]*>[\s\S]*?
]*>[\s\S]*?<\/div>[\s\S]*?<\/div>/g;
-
-/** Inject trusted Mermaid SVG after DOMPurify, replacing the streaming loading shell. */
+/** Inject trusted Mermaid SVG after DOMPurify, 1:1 with complete mermaid fences. */
export const injectCachedMermaidSvg = (
html: string,
- cachedSvgHtml: string | null | undefined,
+ cachedSvgHtml: CachedMermaidSvgHtml,
): string => {
- if (!html || !cachedSvgHtml) return html;
- return html.replace(
- STREAMING_MERMAID_LOADING_RE,
- buildMermaidBlockHtml(cachedSvgHtml, 'data-mermaid="cached"'),
- );
+ return injectCachedMermaidSvgHtml(html, cachedSvgHtml, buildMermaidBlockHtml);
};
export const formatManualTitle = (question?: string): string => {
diff --git a/frontend/src/utils/mermaidShared.ts b/frontend/src/utils/mermaidShared.ts
index 3a26908e..5eaaf216 100644
--- a/frontend/src/utils/mermaidShared.ts
+++ b/frontend/src/utils/mermaidShared.ts
@@ -211,14 +211,17 @@ export const createMermaidCodeRenderer = (idPrefix: string) => {
}
}
-export const renderMermaidToSvg = async (code: string, id: string): Promise
=> {
+export const renderMermaidToSvg = async (code: string, id?: string): Promise => {
if (!code.trim()) return null
try {
const mermaid = await getMermaid()
ensureMermaidInitialized()
await initPromise
await mermaid.parse(code)
- const { svg } = await mermaid.render(id, code)
+ // Mermaid reuses the render id as the SVG root id. Always mint a fresh
+ // one so a later render cannot collide with an SVG already in the DOM.
+ const renderId = `${id || 'mermaid'}-${++mermaidCount}`
+ const { svg } = await mermaid.render(renderId, code)
return svg
} catch (e) {
console.error('Mermaid rendering error:', e)
@@ -226,6 +229,25 @@ export const renderMermaidToSvg = async (code: string, id: string): Promise {
+ const next = cache.slice()
+ while (next.length < codes.length) {
+ const i = next.length
+ const svg = await renderMermaidToSvg(codes[i], `${idPrefix}-${i}`)
+ next.push(svg || '')
+ }
+ return next
+}
+
export const renderMermaidInContainer = async (
rootElement: HTMLElement | null | undefined,
) => {
@@ -240,9 +262,14 @@ export const renderMermaidInContainer = async (
)
for (const el of mermaidElements) {
try {
- const code = el.innerText
+ if (el.querySelector('svg')) {
+ el.setAttribute('data-mermaid', 'true')
+ continue
+ }
+ const code = mermaidSourceFromElement(el)
+ if (!code) continue
await mermaid.parse(code)
- const renderId = el.id ? `${el.id}-svg` : `mermaid-render-${++mermaidCount}`
+ const renderId = `mermaid-render-${++mermaidCount}`
const { svg } = await mermaid.render(renderId, code)
el.classList.add('mermaid')
el.innerHTML = svg
diff --git a/frontend/src/utils/mermaidStreaming.test.ts b/frontend/src/utils/mermaidStreaming.test.ts
new file mode 100644
index 00000000..3e2382c9
--- /dev/null
+++ b/frontend/src/utils/mermaidStreaming.test.ts
@@ -0,0 +1,117 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+
+import {
+ extractMermaidCodes,
+ injectCachedMermaidSvg,
+ maskMermaidBlocksForStreaming,
+ prepareStreamingMermaidMarkdown,
+} from './mermaidStreaming.ts'
+
+const LOADING = ``
+
+function buildBlock(innerHtml: string, preAttrs = ''): string {
+ const attrs = preAttrs ? ` ${preAttrs}` : ''
+ return ``
+}
+
+const TWO_DIAGRAMS = `Intro
+
+\`\`\`mermaid
+graph TD
+ A --> B
+\`\`\`
+
+Middle
+
+\`\`\`mermaid
+sequenceDiagram
+ A->>B: hi
+\`\`\`
+
+Done.
+`
+
+test('extractMermaidCodes returns every complete mermaid fence in order', () => {
+ assert.deepEqual(extractMermaidCodes(TWO_DIAGRAMS), [
+ 'graph TD\n A --> B',
+ 'sequenceDiagram\n A->>B: hi',
+ ])
+})
+
+test('maskMermaidBlocksForStreaming hides every complete mermaid fence', () => {
+ const masked = maskMermaidBlocksForStreaming(TWO_DIAGRAMS, LOADING)
+ assert.equal(masked.includes('```mermaid'), false)
+ assert.equal([...masked.matchAll(/chat-mermaid-block--loading/g)].length, 2)
+ assert.match(masked, /Intro/)
+ assert.match(masked, /Middle/)
+ assert.match(masked, /Done\./)
+})
+
+test('injectCachedMermaidSvg maps cached SVGs onto loading placeholders 1:1', () => {
+ const html = `
+ Intro
+ ${LOADING}
+ Middle
+ ${LOADING}
+ Done.
+ `
+ const injected = injectCachedMermaidSvg(
+ html,
+ ['', ''],
+ buildBlock,
+ )
+ assert.match(injected, /data-mermaid="cached"[^>]*>\s*