fix: LaTeX formulas flash and disappear during streaming response (#1056)

Replace token-by-token rendering (marked.lexer + v-for + marked.parser)
with single-pass marked.parse() in botmsg.vue and AgentStreamDisplay.vue.
This prevents Vue's v-for keyed diffing from destroying KaTeX DOM nodes
on each streaming update.

Also adds a dev-only markdown test page (/platform/dev/markdown) with
LaTeX, code, tables, Mermaid, and streaming simulation for visual
regression testing.
This commit is contained in:
wizardchen
2026-04-28 19:30:51 +08:00
committed by lyingbug
parent 1f03741462
commit 4b87239929
4 changed files with 509 additions and 60 deletions
@@ -42,7 +42,7 @@
</div>
<div v-if="event.content && isEventExpanded(event.event_id)" class="action-details">
<div class="thinking-detail-content markdown-content">
<div v-for="(token, idx) in getTokens(event.content)" :key="idx" v-html="getTokenHTML(token)"></div>
<div v-html="renderMarkdownContent(event.content)"></div>
</div>
</div>
</div>
@@ -64,7 +64,7 @@
</div>
<div v-if="event.tool_data?.thought && isEventExpanded(event.tool_call_id)" class="action-details">
<div class="thinking-detail-content markdown-content">
<div v-for="(token, idx) in getTokens(event.tool_data.thought)" :key="idx" v-html="getTokenHTML(token)"></div>
<div v-html="renderMarkdownContent(event.tool_data.thought)"></div>
</div>
</div>
</div>
@@ -173,7 +173,7 @@
</div>
<div v-if="event.content && isEventExpanded(event.event_id)" class="action-details">
<div class="thinking-detail-content markdown-content">
<div v-for="(token, idx) in getTokens(event.content)" :key="idx" v-html="getTokenHTML(token)"></div>
<div v-html="renderMarkdownContent(event.content)"></div>
</div>
</div>
</div>
@@ -195,7 +195,7 @@
</div>
<div v-if="event.tool_data?.thought && isEventExpanded(event.tool_call_id)" class="action-details">
<div class="thinking-detail-content markdown-content">
<div v-for="(token, idx) in getTokens(event.tool_data.thought)" :key="idx" v-html="getTokenHTML(token)"></div>
<div v-html="renderMarkdownContent(event.tool_data.thought)"></div>
</div>
</div>
</div>
@@ -207,7 +207,7 @@
v-if="event.content && event.content.trim()"
class="answer-content markdown-content"
>
<div v-for="(token, idx) in getTokens(event.content)" :key="idx" v-html="getTokenHTML(token)"></div>
<div v-html="renderMarkdownContent(event.content)"></div>
</div>
<div v-if="event.done" class="answer-toolbar">
<t-button size="small" variant="outline" shape="round" @click.stop="handleCopyAnswer(event)" :title="$t('agent.copy')">
@@ -1657,10 +1657,14 @@ const preprocessMarkdown = (contentStr: string): string => {
);
};
// Get tokens from markdown content (with sanitization for user-friendly display)
const getTokens = (content: any) => {
// 自定义渲染器 - 支持 Mermaid
const agentRenderer = new marked.Renderer();
agentRenderer.code = createMermaidCodeRenderer('mermaid-agent');
// 单次渲染 Markdown 内容(替代 token-by-token,修复 KaTeX 公式在 streaming 时闪烁消失的问题)
const renderMarkdownContent = (content: any): string => {
const contentStr = typeof content === 'string' ? content : String(content || '');
if (!contentStr.trim()) return [];
if (!contentStr.trim()) return '';
// Extract <kb.../> and <web.../> tags before sanitization to prevent
// sanitizeForDisplay from stripping chunk_id labels and UUIDs inside them.
@@ -1692,31 +1696,17 @@ const getTokens = (content: any) => {
// Restore preserved wiki links
sanitized = sanitized.replace(/\x00WIKI(\d+)\x00/g, (_, idx) => wikiPlaceholders[Number(idx)]);
// Restore preserved images
sanitized = sanitized.replace(/\x00IMG(\d+)\x00/g, (_, idx) => imagePlaceholders[Number(idx)]);
// Restore preserved tags
sanitized = sanitized.replace(/\x00TAG(\d+)\x00/g, (_, idx) => tagPlaceholders[Number(idx)]);
const processed = preprocessMarkdown(preprocessMathDelimiters(sanitized));
return marked.lexer(processed);
};
// 自定义渲染器 - 支持 Mermaid
const agentRenderer = new marked.Renderer();
agentRenderer.code = createMermaidCodeRenderer('mermaid-agent');
// Render HTML from a single token
const getTokenHTML = (token: any): string => {
try {
const html = marked.parser([token], { renderer: agentRenderer });
const protectedHTML = protectProviderImageSrcInHTML(html);
return DOMPurify.sanitize(protectedHTML, DOMPurifyConfig);
} catch (e) {
console.error('Token rendering error:', e);
return '';
}
const html = marked.parse(processed, { renderer: agentRenderer }) as string;
const protectedHTML = protectProviderImageSrcInHTML(html);
return DOMPurify.sanitize(protectedHTML, DOMPurifyConfig);
};
// Legacy Markdown rendering function (kept for summaries)
+6 -33
View File
@@ -27,8 +27,7 @@
<!-- 直接渲染完整内容,避免切分导致的问题,样式与 thinking 一致 -->
<!-- 只有当有实际内容时才显示包围框 -->
<div class="content-wrapper" v-if="hasActualContent">
<div class="ai-markdown-template markdown-content">
<div v-for="(token, index) in markdownTokens" :key="index" v-html="renderToken(token)"></div>
<div class="ai-markdown-template markdown-content" v-html="renderedHTML">
</div>
</div>
<!-- Streaming indicator (non-Agent mode) -->
@@ -164,20 +163,15 @@ const mentionedItems = computed(() => {
return props.session?.mentioned_items || [];
});
const markdownTokens = computed(() => {
// 单次渲染整个 Markdown 内容(替代 token-by-token,修复 KaTeX 公式在 streaming 时闪烁消失的问题)
const renderedHTML = computed(() => {
const text = props.content || props.session?.content || '';
if (!text || typeof text !== 'string') {
return [];
}
if (!text || typeof text !== 'string') return '';
const processed = replaceIncompleteImageWithPlaceholder(text);
const safeText = preprocessMathDelimiters(processed);
// 首先对 Markdown 内容进行安全处理
const safeMarkdown = safeMarkdownToHTML(safeText);
// 使用 marked.lexer 分词
return marked.lexer(safeMarkdown);
const html = marked.parse(safeMarkdown, { renderer: customRenderer, breaks: true });
return sanitizeHTML(html);
});
// 计算属性:判断是否有实际内容(非空且不只是空白)
@@ -186,27 +180,6 @@ const hasActualContent = computed(() => {
return text && text.trim().length > 0;
});
// 渲染单个 token 为 HTML
const renderToken = (token) => {
try {
// 创建临时的 marked 配置
const markedOptions = {
renderer: customRenderer,
breaks: true
};
// 解析单个 token
// marked.parser 接受 token 数组
let html = marked.parser([token], markedOptions);
// 使用 DOMPurify 进行最终的安全清理
return sanitizeHTML(html);
} catch (e) {
console.error('Token rendering error:', e);
return '';
}
};
// 获取实际内容
const getActualContent = () => {
return (props.content || props.session?.content || '').trim();