Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
fix(frontend): keep streamed Mermaid diagrams from reverting to code (#2885)
wizardchen92da9c55c3e0
diff --git a/frontend/src/directives/stableHtml.ts b/frontend/src/directives/stableHtml.tsindex 303ee7467..723854bf1 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.tsindex 7ce09d6bf..c99b4f763 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?: booleancollapseStandaloneCitations?: booleanknowledgeReferences?: 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.tsindex c09e82cd0..3fea40992 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 = '<span class="streaming-image-loading"><span class="streaming-image-loading__skeleton"></span></span>';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 = /<div class="chat-mermaid-block[^"]*"[^>]*>[\s\S]*?<div class="streaming-mermaid-loading"[^>]*>[\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.tsindex 3a26908e0..5eaaf2167 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<string | null> => {+export const renderMermaidToSvg = async (code: string, id?: string): Promise<string | null> => {if (!code.trim()) return nulltry {const mermaid = await getMermaid()ensureMermaidInitialized()await initPromiseawait 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<stri}}+function mermaidSourceFromElement(el: HTMLElement): string {+ const codeEl = el.querySelector('code')+ return (codeEl?.textContent ?? el.textContent ?? '').trim()+}++export async function appendMermaidSvgCache(+ codes: string[],+ cache: readonly string[],+ idPrefix: string,+): Promise<string[]> {+ 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) continueawait 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 = svgdiff --git a/frontend/src/utils/mermaidStreaming.test.ts b/frontend/src/utils/mermaidStreaming.test.tsnew file mode 100644index 000000000..3e2382c92--- /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 = `<div class="chat-mermaid-block chat-mermaid-block--loading">+ <div class="chat-mermaid-block__header"><span class="chat-mermaid-block__badge">图表</span></div>+ <div class="streaming-mermaid-loading" aria-hidden="true"><span class="streaming-mermaid-loading__skeleton"></span></div>+</div>`++function buildBlock(innerHtml: string, preAttrs = ''): string {+ const attrs = preAttrs ? ` ${preAttrs}` : ''+ return `<div class="chat-mermaid-block">+ <pre class="chat-mermaid-block__canvas mermaid"${attrs}>${innerHtml}</pre>+ </div>`+}++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 = `+ <p>Intro</p>+ ${LOADING}+ <p>Middle</p>+ ${LOADING}+ <p>Done.</p>+ `+ const injected = injectCachedMermaidSvg(+ html,+ ['<svg id="first"></svg>', '<svg id="second"></svg>'],+ buildBlock,+ )+ assert.match(injected, /data-mermaid="cached"[^>]*>\s*<svg id="first">/)+ assert.match(injected, /data-mermaid="cached"[^>]*>\s*<svg id="second">/)+ assert.equal(injected.includes('streaming-mermaid-loading'), false)+ assert.match(injected, /Intro/)+ assert.match(injected, /Middle/)+ assert.match(injected, /Done\./)+})++test('injectCachedMermaidSvg does not swallow a cached diagram when a later skeleton exists', () => {+ const html = `+ <div class="chat-mermaid-block">+ <div class="chat-mermaid-block__header"><span class="chat-mermaid-block__badge">图表</span></div>+ <pre class="chat-mermaid-block__canvas mermaid" data-mermaid="cached"><svg id="kept"></svg></pre>+ </div>+ <p>between</p>+ ${LOADING}+ `+ const injected = injectCachedMermaidSvg(+ html,+ ['<svg id="first"></svg>', '<svg id="second"></svg>'],+ buildBlock,+ )+ assert.match(injected, /<svg id="kept">/)+ assert.match(injected, /between/)+ assert.match(injected, /<svg id="first">/)+ assert.equal(injected.includes('streaming-mermaid-loading'), false)+})++test('injectCachedMermaidSvg fills unrendered mermaid canvases after the stream completes', () => {+ const html = `+ <pre class="chat-mermaid-block__canvas mermaid" id="m-1" data-mermaid="false"><code>graph TD</code></pre>+ <pre class="chat-mermaid-block__canvas mermaid" id="m-2" data-mermaid="false"><code>sequenceDiagram</code></pre>+ `+ const injected = injectCachedMermaidSvg(+ html,+ ['<svg id="first"></svg>', '<svg id="second"></svg>'],+ buildBlock,+ )+ assert.match(injected, /id="m-1" data-mermaid="cached"><svg id="first">/)+ assert.match(injected, /id="m-2" data-mermaid="cached"><svg id="second">/)+ assert.equal(injected.includes('graph TD'), false)+})++test('prepareStreamingMermaidMarkdown masks a trailing incomplete mermaid fence', () => {+ const prepared = prepareStreamingMermaidMarkdown('Hello\n```mermaid\ngraph TD\n A', LOADING)+ assert.equal(prepared.includes('```mermaid'), false)+ assert.match(prepared, /chat-mermaid-block--loading/)+ assert.match(prepared, /Hello/)+})diff --git a/frontend/src/utils/mermaidStreaming.ts b/frontend/src/utils/mermaidStreaming.tsnew file mode 100644index 000000000..7440fbd32--- /dev/null+++ b/frontend/src/utils/mermaidStreaming.ts@@ -0,0 +1,106 @@+export type CachedMermaidSvgHtml = string | readonly (string | null | undefined)[] | null | undefined;++const MERMAID_FENCE_START = '```mermaid';+const COMPLETE_MERMAID_FENCE_RE = /```mermaid[\s\S]*?```/;++export const replaceIncompleteMermaidWithPlaceholder = (+ content: string,+ placeholder: 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) + placeholder;+};++/** Keep every mermaid fence as a stable placeholder; render SVG via cache injection. */+export const maskMermaidBlocksForStreaming = (content: string, placeholder: string): string => {+ if (!content) return '';+ const masked = content.replace(/```mermaid[\s\S]*?```/g, placeholder);+ return replaceIncompleteMermaidWithPlaceholder(masked, placeholder);+};++export const hasCompleteMermaidBlock = (content: string): boolean => {+ return COMPLETE_MERMAID_FENCE_RE.test(content);+};++export const prepareStreamingMermaidMarkdown = (+ content: string,+ placeholder: string,+): string => {+ if (!content) return '';++ if (hasCompleteMermaidBlock(content)) {+ return maskMermaidBlocksForStreaming(content, placeholder);+ }++ return replaceIncompleteMermaidWithPlaceholder(content, placeholder);+};++export const extractMermaidCodes = (content: string): string[] => {+ if (!content) return [];+ const codes: string[] = [];+ const re = /```mermaid([\s\S]*?)```/g;+ let match: RegExpExecArray | null;+ while ((match = re.exec(content)) !== null) {+ const code = match[1].trim();+ if (code) codes.push(code);+ }+ return codes;+};++export const extractFirstMermaidCode = (content: string): string | null => {+ return extractMermaidCodes(content)[0] || null;+};++export function normalizeCachedMermaidSvgs(cached: CachedMermaidSvgHtml): string[] {+ if (!cached) return [];+ if (typeof cached === 'string') return cached ? [cached] : [];+ return cached.map((svg) => svg || '');+}++// Require the loading modifier so a rendered/cached mermaid block cannot be+// paired with a later skeleton (the previous `chat-mermaid-block[^"]*` pattern+// swallowed the first diagram and everything after it).+const STREAMING_MERMAID_LOADING_RE =+ /<div class="chat-mermaid-block chat-mermaid-block--loading"[^>]*>[\s\S]*?<div class="streaming-mermaid-loading"[^>]*>[\s\S]*?<\/div>\s*<\/div>/g;++const MERMAID_UNRENDERED_CANVAS_RE =+ /<pre class="chat-mermaid-block__canvas mermaid"[^>]*data-mermaid="false"[^>]*>[\s\S]*?<\/pre>/g;++function replaceUnrenderedCanvas(+ match: string,+ svg: string,+): string {+ const openEnd = match.indexOf('>');+ if (openEnd < 0) return match;+ const openTag = match.slice(0, openEnd + 1).replace(/data-mermaid="false"/, 'data-mermaid="cached"');+ return `${openTag}${svg}</pre>`;+}++/** Inject trusted Mermaid SVG after DOMPurify, 1:1 with complete mermaid fences. */+export const injectCachedMermaidSvg = (+ html: string,+ cachedSvgHtml: CachedMermaidSvgHtml,+ buildBlock: (innerHtml: string, preAttrs?: string) => string,+): string => {+ if (!html) return html;+ const svgs = normalizeCachedMermaidSvgs(cachedSvgHtml);+ if (!svgs.some(Boolean)) return html;++ const index = { i: 0 };+ const withLoading = html.replace(STREAMING_MERMAID_LOADING_RE, (match) => {+ const svg = svgs[index.i++];+ return svg ? buildBlock(svg, 'data-mermaid="cached"') : match;+ });+ if (index.i >= svgs.length) return withLoading;+ return withLoading.replace(MERMAID_UNRENDERED_CANVAS_RE, (match) => {+ const svg = svgs[index.i++];+ return svg ? replaceUnrenderedCanvas(match, svg) : match;+ });+};diff --git a/frontend/src/views/chat/components/AgentStreamDisplay.vue b/frontend/src/views/chat/components/AgentStreamDisplay.vueindex 79f7f7266..96e87839f 100644--- a/frontend/src/views/chat/components/AgentStreamDisplay.vue+++ b/frontend/src/views/chat/components/AgentStreamDisplay.vue@@ -579,8 +579,9 @@ import {formatManualTitle,replaceIncompleteMermaidWithPlaceholder,prepareStreamingMermaidMarkdown,- extractFirstMermaidCode,+ extractMermaidCodes,injectCachedMermaidSvg,+ type CachedMermaidSvgHtml,} from '@/utils/chatMessageShared';import { copyWithToast } from '@/utils/clipboard';import {@@ -589,10 +590,10 @@ import {wrapChatMarkdownTables,} from '@/utils/chatMarkdownRenderer';import {+ appendMermaidSvgCache,createMermaidCodeRenderer,ensureMermaidInitialized,enhanceMarkdownContainer,- renderMermaidToSvg,} from '@/utils/mermaidShared';import { attachMarkdownEnhancementListeners, refreshMarkdownEnhancements } from '@/utils/markdownEnhancements';import { useTypewriter } from '@/composables/useTypewriter';@@ -1496,9 +1497,8 @@ const isConversationDone = computed(() => {return !!doneAnswer;});-const streamingMermaidSvgCache = ref<string | null>(null);+const streamingMermaidSvgCache = ref<string[]>([]);let streamingMermaidRenderTask: Promise<void> | null = null;-let streamingMermaidRenderId = 0;const activeAnswerMarkdown = computed(() => {const stream = eventStream.value;@@ -1526,25 +1526,31 @@ const { displayed: typedAnswer } = useTypewriter();const cacheStreamingMermaidSvg = async () => {- if (streamingMermaidSvgCache.value) return;- const code = extractFirstMermaidCode(activeAnswerMarkdown.value);- if (!code) return;+ const codes = extractMermaidCodes(activeAnswerMarkdown.value);+ if (codes.length <= streamingMermaidSvgCache.value.length) return;if (!streamingMermaidRenderTask) {streamingMermaidRenderTask = (async () => {- const svg = await renderMermaidToSvg(code, `mermaid-agent-stream-${++streamingMermaidRenderId}`);- if (svg) streamingMermaidSvgCache.value = svg;+ streamingMermaidSvgCache.value = await appendMermaidSvgCache(+ extractMermaidCodes(activeAnswerMarkdown.value),+ streamingMermaidSvgCache.value,+ 'mermaid-agent-stream',+ );})().finally(() => {streamingMermaidRenderTask = null;});}await streamingMermaidRenderTask;++ if (extractMermaidCodes(activeAnswerMarkdown.value).length > streamingMermaidSvgCache.value.length) {+ await cacheStreamingMermaidSvg();+ }};watch(isConversationDone, (done) => {if (!done) {- streamingMermaidSvgCache.value = null;+ streamingMermaidSvgCache.value = [];streamingMermaidRenderTask = null;}});@@ -1554,7 +1560,6 @@ watch(streamingMermaidSvgCache, () => {});watch(activeAnswerMarkdown, () => {- if (isConversationDone.value || streamingMermaidSvgCache.value) return;void cacheStreamingMermaidSvg();});@@ -1579,6 +1584,7 @@ watch(answerFullyRendered, (ready) => {clearProtectedFileFailureCache();nextTick(async () => {await hydrateProtectedFileImages(rootElement.value, protectedFileAccess.value);+ await enhanceMarkdownContainer(rootElement.value);});}, { immediate: true });@@ -2452,9 +2458,18 @@ agentRenderer.image = function agentImageRenderer(token) {return defaultImageRenderer.call(this, token);};-const prepareAgentMarkdown = (markdown: string, cachedSvgHtml?: string | null): string => {- const mermaidSafe = !isConversationDone.value- ? prepareStreamingMermaidMarkdown(markdown, cachedSvgHtml ?? streamingMermaidSvgCache.value)+const hasCachedMermaidSvg = (cached: CachedMermaidSvgHtml): boolean => {+ if (!cached) return false;+ if (typeof cached === 'string') return cached.length > 0;+ return cached.some((svg) => Boolean(svg));+};++const prepareAgentMarkdown = (markdown: string, cachedSvgHtml?: CachedMermaidSvgHtml): string => {+ const cache = cachedSvgHtml ?? streamingMermaidSvgCache.value;+ // Keep masking after the turn ends when SVG is already cached so v-html /+ // v-stable-html cannot replace a painted diagram with mermaid source.+ const mermaidSafe = !isConversationDone.value || hasCachedMermaidSvg(cache)+ ? prepareStreamingMermaidMarkdown(markdown, cache): replaceIncompleteMermaidWithPlaceholder(markdown);return mermaidSafe.replace(/<(?:kb|web)\b[^>]*$/i, '');};diff --git a/frontend/src/views/dev/MarkdownTestPage.vue b/frontend/src/views/dev/MarkdownTestPage.vueindex ddeb5b4b2..66d8b680b 100644--- a/frontend/src/views/dev/MarkdownTestPage.vue+++ b/frontend/src/views/dev/MarkdownTestPage.vue@@ -130,15 +130,15 @@ import {renderChatMarkdown,} from '@/utils/chatMarkdownRenderer';import {+ appendMermaidSvgCache,ensureMermaidInitialized,enhanceMarkdownContainer,- renderMermaidToSvg,createMermaidCodeRenderer,} from '@/utils/mermaidShared';import {replaceIncompleteMermaidWithPlaceholder,prepareStreamingMermaidMarkdown,- extractFirstMermaidCode,+ extractMermaidCodes,injectCachedMermaidSvg,} from '@/utils/chatMessageShared';@@ -416,9 +416,8 @@ const streamBuffer = ref('');const isStreaming = ref(false);const streamSpeed = ref(30);const customInput = ref('');-const streamMermaidSvgHtml = ref('');+const streamMermaidSvgHtml = ref<string[]>([]);let streamTimer: ReturnType<typeof setInterval> | null = null;-let streamMermaidRenderId = 0;let streamMermaidRenderTask: Promise<void> | null = null;// Pre-render static fixtures once so streaming ticks do not reset other sections.@@ -436,21 +435,26 @@ const streamHtml = computed(() => renderStreamMarkdown(streamBuffer.value));const customHtml = computed(() => render(customInput.value));const cacheStreamMermaidSvg = async () => {- if (streamMermaidSvgHtml.value) return;-- const code = extractFirstMermaidCode(streamBuffer.value);- if (!code) return;+ const codes = extractMermaidCodes(streamBuffer.value);+ if (codes.length <= streamMermaidSvgHtml.value.length) return;if (!streamMermaidRenderTask) {streamMermaidRenderTask = (async () => {- const svg = await renderMermaidToSvg(code, `mermaid-stream-${++streamMermaidRenderId}`);- if (svg) streamMermaidSvgHtml.value = svg;+ streamMermaidSvgHtml.value = await appendMermaidSvgCache(+ extractMermaidCodes(streamBuffer.value),+ streamMermaidSvgHtml.value,+ 'mermaid-stream',+ );})().finally(() => {streamMermaidRenderTask = null;});}await streamMermaidRenderTask;++ if (extractMermaidCodes(streamBuffer.value).length > streamMermaidSvgHtml.value.length) {+ await cacheStreamMermaidSvg();+ }};const startStream = () => {@@ -471,7 +475,7 @@ const startStream = () => {const resetStream = () => {if (streamTimer) clearInterval(streamTimer);streamBuffer.value = '';- streamMermaidSvgHtml.value = '';+ streamMermaidSvgHtml.value = [];streamMermaidRenderTask = null;isStreaming.value = false;};