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
feat(frontend): enhance chat markdown rendering and streaming behavior
wizardchen58461a5b6815
diff --git a/frontend/src/components/css/chat-markdown.less b/frontend/src/components/css/chat-markdown.lessindex 49b889b8f..25d0fe193 100644--- a/frontend/src/components/css/chat-markdown.less+++ b/frontend/src/components/css/chat-markdown.less@@ -46,7 +46,12 @@}// Models often emit standalone **小节标题:** paragraphs instead of headings.- :deep(p:has(> strong:only-child)) {+ // Tagged at render time (markStandaloneStrongParagraphs) rather than via+ // `p:has(> strong:only-child)`: CSS `:only-child` ignores text nodes, so the+ // selector matched any paragraph whose only *element* child was a <strong>,+ // causing a visible top-margin jump mid-stream the instant one **bold** run+ // closed inside an otherwise text-heavy paragraph.+ :deep(p.md-strong-title) {margin-top: 1.25em;margin-bottom: 0.5em;line-height: 1.5;diff --git a/frontend/src/components/css/chat-timeline-loading.less b/frontend/src/components/css/chat-timeline-loading.lessindex e4f7dbcd3..dcd6f6246 100644--- a/frontend/src/components/css/chat-timeline-loading.less+++ b/frontend/src/components/css/chat-timeline-loading.less@@ -3,11 +3,11 @@0%,60%,100% {- transform: translateY(0);+ transform: translate3d(0, 0, 0);}30% {- transform: translateY(-8px);+ transform: translate3d(0, -5px, 0);}}@@ -52,6 +52,10 @@border-radius: 50%;background: var(--td-text-color-placeholder);animation: chatTimelineTypingBounce 1.4s ease-in-out infinite;+ // Composite each dot on its own layer so the bounce runs off the main+ // thread and does not smear/ghost while the answer relayouts every token.+ will-change: transform;+ backface-visibility: hidden;&:nth-child(1) {animation-delay: 0s;diff --git a/frontend/src/utils/_repro_gap.mjs b/frontend/src/utils/_repro_gap.mjsnew file mode 100644index 000000000..c5ccdd01c--- /dev/null+++ b/frontend/src/utils/_repro_gap.mjs@@ -0,0 +1,30 @@+import {+ createChatMarkdownRenderer,+ renderChatMarkdown,+} from './chatMarkdownRenderer.ts'+import { joinCitationTagsToPreviousLine } from './citationMarkdown.ts'++const renderer = createChatMarkdownRenderer()+const snippet = [+ '该数据集...例如:',+ '```',+ 'APR = ((Fees + Interest) / Principal) × (365 / Days in Loan Term)',+ '```',+ '<kb doc="2502.08127v1.pdf" chunk_id="1ecdce8a-f922-4d0c-b124-257ab4634da2" />',+ '',+ '### 重要性',+ '',+ '1. **AAAAA**',+].join('\n')++console.log('--- joinCitationTagsToPreviousLine output ---')+console.log(JSON.stringify(joinCitationTagsToPreviousLine(snippet)))++console.log('\n--- final render ---')+console.log(renderChatMarkdown(snippet, {+ renderer,+ escapeMarkdown: (t) => t,+ sanitizeHtml: (h) => h,+ streaming: false,+ knowledgeReferences: [{ doc: '2502.08127v1.pdf', chunk_id: '1ecdce8a-f922-4d0c-b124-257ab4634da2' }],+}))diff --git a/frontend/src/utils/chatMarkdownRenderer.test.ts b/frontend/src/utils/chatMarkdownRenderer.test.tsindex 114c7a263..6e6af566d 100644--- a/frontend/src/utils/chatMarkdownRenderer.test.ts+++ b/frontend/src/utils/chatMarkdownRenderer.test.ts@@ -2,11 +2,15 @@ import assert from 'node:assert/strict'import test from 'node:test'import {+ closeDanglingStreamingEmphasis,createChatMarkdownRenderer,+ markStandaloneStrongParagraphs,preprocessMathDelimiters,renderChatMarkdown,+ repairFlankingEmphasis,replaceIncompleteImageWithPlaceholder,stripTrailingStreamingHorizontalRule,+ stripTrailingStreamingListMarker,} from './chatMarkdownRenderer.ts'import {collapseStandaloneCitationParagraphs,@@ -64,6 +68,172 @@ test('stripTrailingStreamingHorizontalRule hides an ambiguous trailing rule onlyassert.match(renderChatMarkdown(source, { ...options, streaming: false }), /<hr>/)})+test('closeDanglingStreamingEmphasis closes unfinished inline markers without false positives', () => {+ assert.equal(closeDanglingStreamingEmphasis('**平台地址:example.com'), '**平台地址:example.com**')+ assert.equal(closeDanglingStreamingEmphasis('前文 *斜体'), '前文 *斜体*')+ assert.equal(closeDanglingStreamingEmphasis('前文 ~~删除'), '前文 ~~删除~~')+ assert.equal(closeDanglingStreamingEmphasis('***又粗又斜'), '***又粗又斜***')+ assert.equal(closeDanglingStreamingEmphasis('运行 `npm run'), '运行 `npm run`')++ // A trailing marker run with no content after it is ambiguous (e.g. the start+ // of the next `**` in a bold list) and is hidden until content arrives, rather+ // than rendered as a literal `*`/`**` that flickers a frame later.+ assert.equal(closeDanglingStreamingEmphasis('4. **朝阳实验**\n5. *'), '4. **朝阳实验**\n5. ')+ assert.equal(closeDanglingStreamingEmphasis('5. **'), '5. ')+ assert.equal(closeDanglingStreamingEmphasis('3. **泳燃游泳*'), '3. **泳燃游泳**')++ // No dangling markers / structural markers must be left untouched.+ assert.equal(closeDanglingStreamingEmphasis('正文 **加粗** 收尾'), '正文 **加粗** 收尾')+ assert.equal(closeDanglingStreamingEmphasis('* 列表项一'), '* 列表项一')+ assert.equal(closeDanglingStreamingEmphasis('普通文本没有标记'), '普通文本没有标记')+ // Markers inside an open fenced code block are literal, not emphasis.+ assert.equal(+ closeDanglingStreamingEmphasis('```js\nconst x = **y'),+ '```js\nconst x = **y',+ )+})++test('renderChatMarkdown renders an unfinished bold line as bold immediately while streaming', () => {+ const renderer = createChatMarkdownRenderer()+ const options = {+ renderer,+ escapeMarkdown: (text: string) => text,+ sanitizeHtml: (html: string) => html,+ }+ const partial = '**平台访问地址:chatbot.weixin.qq.com'+ // Streaming: optimistically bold so no raw `**` and no late layout jump.+ assert.match(+ renderChatMarkdown(partial, { ...options, streaming: true }),+ /<p class="md-strong-title"><strong>平台访问地址:chatbot\.weixin\.qq\.com<\/strong><\/p>/,+ )+ // Completed: a genuinely unterminated marker stays literal (we never invent+ // content for the final, authoritative render).+ assert.match(+ renderChatMarkdown(partial, { ...options, streaming: false }),+ /<p>\*\*平台访问地址/,+ )+})++test('repairFlankingEmphasis bolds punctuation-adjacent emphasis CommonMark would drop', () => {+ // Closing delimiter sits between punctuation and a letter -> CommonMark rejects+ // it; we convert exactly that blocked pattern to explicit HTML.+ assert.equal(repairFlankingEmphasis('**XBRL(语言)**是一种'), '<strong>XBRL(语言)</strong>是一种')+ assert.equal(repairFlankingEmphasis('**a)**b'), '<strong>a)</strong>b')+ assert.equal(repairFlankingEmphasis('~~删除)~~文字'), '<del>删除)</del>文字')+ assert.equal(repairFlankingEmphasis('*斜体)*文字'), '<em>斜体)</em>文字')++ // Cases marked already handles, literal markers, and code must be untouched.+ assert.equal(repairFlankingEmphasis('**中文**后面'), '**中文**后面')+ assert.equal(repairFlankingEmphasis('**中文)** 后面'), '**中文)** 后面')+ assert.equal(repairFlankingEmphasis('正文 **加粗** 收尾'), '正文 **加粗** 收尾')+ assert.equal(repairFlankingEmphasis('`**a)**b`'), '`**a)**b`')+ assert.equal(repairFlankingEmphasis('2 ** 3 ** 4'), '2 ** 3 ** 4')+ assert.equal(repairFlankingEmphasis('价格 3 * 5 * 7 元'), '价格 3 * 5 * 7 元')+})++test('renderChatMarkdown bolds punctuation-adjacent emphasis both mid-stream and when complete', () => {+ const renderer = createChatMarkdownRenderer()+ const options = {+ renderer,+ escapeMarkdown: (text: string) => text,+ sanitizeHtml: (html: string) => html,+ }+ const text = '**XBRL(语言)**是一种标准'+ for (const streaming of [true, false]) {+ assert.match(+ renderChatMarkdown(text, { ...options, streaming }),+ /<strong>XBRL(语言)<\/strong>是一种标准/,+ )+ }+})++test('stripTrailingStreamingListMarker hides a content-less trailing list/underline marker', () => {+ assert.equal(stripTrailingStreamingListMarker('1. **AAAAA**\n - '), '1. **AAAAA**\n')+ assert.equal(stripTrailingStreamingListMarker('文本\n1. '), '文本\n')+ assert.equal(stripTrailingStreamingListMarker('标题\n=='), '标题\n')+ // A lone trailing number is the start of an ordered marker (no `.` yet).+ assert.equal(stripTrailingStreamingListMarker('文本\n1'), '文本\n')+ // A marker with content after it is a real list item and must stay.+ assert.equal(stripTrailingStreamingListMarker('- 项目'), '- 项目')+ assert.equal(stripTrailingStreamingListMarker('1. 内容'), '1. 内容')+ // An in-sentence number must not be touched.+ assert.equal(stripTrailingStreamingListMarker('值是 1'), '值是 1')+})++test('renderChatMarkdown does not flash a setext heading when a nested bullet dash streams in', () => {+ const renderer = createChatMarkdownRenderer()+ const options = {+ renderer,+ escapeMarkdown: (text: string) => text,+ sanitizeHtml: (html: string) => html,+ streaming: true,+ }+ // A must stay a plain bold item through the whole lead-up to B: the bare dash+ // must not flash <h2>, and the next bullet's `*`/`**` (before its text) must+ // not flash an empty nested <li> under A.+ for (const partial of ['1. **AAAAA**\n - ', '1. **AAAAA**\n - *', '1. **AAAAA**\n - **']) {+ const html = renderChatMarkdown(partial, options)+ assert.doesNotMatch(html, /<h2/)+ assert.doesNotMatch(html, /<ul>/)+ assert.match(html, /<ol>\s*<li><strong>AAAAA<\/strong><\/li>\s*<\/ol>/)+ }+})++test('renderChatMarkdown streams a bold ordered list without literal-marker flicker', () => {+ const renderer = createChatMarkdownRenderer()+ const options = {+ renderer,+ escapeMarkdown: (text: string) => text,+ sanitizeHtml: (html: string) => html,+ streaming: true,+ }+ // Next item's marker has arrived but its content/closing ** has not.+ const html = renderChatMarkdown('1. **速游**\n2. *', options)+ assert.doesNotMatch(html, /<li>\*+<\/li>/)+ assert.match(html, /<li><strong>速游<\/strong><\/li>/)+})++test('markStandaloneStrongParagraphs tags only paragraphs that are entirely one bold run', () => {+ // A model emitting **小节标题** as a pseudo-heading: should be tagged.+ assert.equal(+ markStandaloneStrongParagraphs('<p><strong>小节标题:</strong></p>'),+ '<p class="md-strong-title"><strong>小节标题:</strong></p>',+ )++ // Mid-stream body paragraph with one completed bold run plus body text must+ // NOT be tagged (this is the streaming spacing-jump regression).+ for (const html of [+ '<p>正文 <strong>加粗部分</strong> 与 **</p>',+ '<p>正文 <strong>A</strong> 与 <strong>B</strong> 收尾</p>',+ '<p><strong>加粗</strong> 后续文字</p>',+ ]) {+ assert.equal(markStandaloneStrongParagraphs(html), html)+ }++ // A bold list item (loose list wraps content in <p>) is list text, not a+ // subtitle: it must keep the list's own margins, not gain a 1.25em top margin.+ assert.equal(+ markStandaloneStrongParagraphs('<ol><li><p><strong>AAA</strong></p></li></ol>'),+ '<ol><li><p><strong>AAA</strong></p></li></ol>',+ )+})++test('renderChatMarkdown does not give a text-heavy paragraph the strong-title margin mid-stream', () => {+ const renderer = createChatMarkdownRenderer()+ const options = {+ renderer,+ escapeMarkdown: (text: string) => text,+ sanitizeHtml: (html: string) => html,+ streaming: true,+ }+ const head = '#### **总结与建议**\n\n'+ // One bold run closed inside an otherwise text-heavy body paragraph.+ const midStream = head + '总体来看,体现在 **"补短板"(高端核心部件)** 与 **'+ const html = renderChatMarkdown(midStream, options)+ assert.doesNotMatch(html, /<p class="md-strong-title">总体来看/)+ assert.match(html, /<h4><strong>总结与建议<\/strong><\/h4>/)+})+test('renderChatMarkdown preserves citations, math, and sanitized output through one shared pipeline', () => {const renderer = createChatMarkdownRenderer({imageRenderer: ({ href, title, text }) =>@@ -241,6 +411,29 @@ test('joinCitationTagsToPreviousLine does not merge citations onto fenced code cassert.equal(joinCitationTagsToPreviousLine(input), '```bash\nunzip setup.zip\n```\n\n' + tag)})+test('joinCitationTagsToPreviousLine does not merge citations onto an unlabeled closing fence on a single newline', () => {+ const tag = '<kb doc="guide.pdf" chunk_id="1" />'+ const input = '```\nAPR = principal\n```\n' + tag+ assert.equal(joinCitationTagsToPreviousLine(input), '```\nAPR = principal\n```\n' + tag)+})++test('renderChatMarkdown keeps an unlabeled fenced code block closed when a citation immediately follows', () => {+ const renderer = createChatMarkdownRenderer()+ const tag = '<kb doc="guide.pdf" chunk_id="1" />'+ const html = renderChatMarkdown(+ ['```', 'APR = principal', '```', tag, '', '### 重要性'].join('\n'),+ {+ renderer,+ escapeMarkdown: (text) => text,+ sanitizeHtml: (html) => html,+ },+ )++ assert.doesNotMatch(html, /### 重要性/)+ assert.match(html, /<h3>重要性<\/h3>/)+ assert.equal((html.match(/<pre>/g) || []).length, 1)+})+test('renderChatMarkdown keeps fenced code blocks closed when citations follow', () => {const renderer = createChatMarkdownRenderer({imageRenderer: ({ href, text }) => `<img src="${href}" alt="${text}">`,diff --git a/frontend/src/utils/chatMarkdownRenderer.ts b/frontend/src/utils/chatMarkdownRenderer.tsindex 0a208b263..769399870 100644--- a/frontend/src/utils/chatMarkdownRenderer.ts+++ b/frontend/src/utils/chatMarkdownRenderer.ts@@ -94,6 +94,141 @@ export function stripTrailingStreamingHorizontalRule(content: string): string {)}+function maskMatches(text: string, regex: RegExp): string {+ return text.replace(regex, (match) => match.replace(/[^\n]/g, '\u0000'))+}++function isOdd(text: string, marker: RegExp): boolean {+ const matches = text.match(marker)+ return matches ? matches.length % 2 === 1 : false+}++/**+ * Stabilize dangling inline markers while content is streaming.+ *+ * Two distinct mid-stream artifacts are smoothed out:+ *+ * - A marker run with **nothing after it yet** (`… 实验**\n5. *`, or a bare+ * trailing `**`) is ambiguous — it might open bold, italic, or be the start+ * of the next `**`. Rendering it shows literal `*`/`~` that vanish a frame+ * later, so it is hidden until real content follows (like the citation/image+ * guards).+ * - A marker run **with content after it** but no closer (`**平台地址:…`) is a+ * genuinely opened emphasis; its closer is appended so marked renders it as+ * emphasis from the first frame instead of showing raw `**` and then snapping+ * to bold (and, for a standalone bold line, also gaining the subtitle+ * margin) — the jump reported on streamed bold lists/headings.+ *+ * Inline/fenced code and leading list bullets are masked so their literal+ * `*`/`` ` `` are never treated as emphasis, and an open fenced block is left+ * untouched.+ */+export function closeDanglingStreamingEmphasis(text: string): string {+ if (!text || !/[*~`]/.test(text)) return text++ // Mask code so markers inside it are never counted; \u0000 keeps offsets.+ let masked = maskMatches(text, /```[\s\S]*?```/g)+ if (isOdd(masked, /```/g)) {+ const open = masked.lastIndexOf('```')+ masked = masked.slice(0, open) + masked.slice(open).replace(/[^\n]/g, '\u0000')+ }+ masked = maskMatches(masked, /`[^`\n]*`/g)+ let appendInlineCode = false+ if (isOdd(masked, /`/g)) {+ appendInlineCode = true+ const open = masked.lastIndexOf('`')+ masked = masked.slice(0, open) + masked.slice(open).replace(/[^\n]/g, '\u0000')+ }++ // Drop a trailing emphasis-marker run with no content after it: ambiguous and+ // not yet renderable. Anchored to the current line so earlier text is intact.+ let working = text+ if (!appendInlineCode) {+ const trailing = masked.match(/[*~]+[ \t]*$/)+ if (trailing) {+ working = text.slice(0, text.length - trailing[0].length)+ masked = masked.slice(0, masked.length - trailing[0].length)+ }+ }++ // Leading list/bullet markers are structure, not emphasis.+ masked = masked.replace(/^(\s*)([*+-])(\s)/gm, (_m, p1, _p2, p3) => `${p1}\u0000${p3}`)++ const needStrike = isOdd(masked, /~~/g)+ const withoutBold = maskMatches(masked, /\*\*/g)+ const needBold = isOdd(masked, /\*\*/g)+ const needItalic = isOdd(withoutBold, /\*/g)++ let closers = ''+ if (appendInlineCode) closers += '`'+ if (needItalic) closers += '*'+ if (needBold) closers += '**'+ if (needStrike) closers += '~~'++ if (!closers) return working++ // A closing emphasis delimiter must not be preceded by whitespace (CommonMark+ // flanking rule), so insert the closers before any trailing whitespace. Bold+ // content with internal spaces (`**XBRL Reporting `) otherwise renders literal+ // (non-bold) on every frame that pauses on a space, flickering bold on/off.+ const trailingWs = working.match(/\s+$/)+ if (!trailingWs) return working + closers+ const cut = working.length - trailingWs[0].length+ return working.slice(0, cut) + closers + working.slice(cut)+}++const FLANKING_BOLD = /(?<!\*)\*\*(?=\S)([^*\n]*?\p{P})\*\*(?=[\p{L}\p{N}])/gu+const FLANKING_STRIKE = /(?<!~)~~(?=\S)([^~\n]*?\p{P})~~(?=[\p{L}\p{N}])/gu+const FLANKING_ITALIC = /(?<![*\p{L}\p{N}])\*(?=\S)([^*\n]*?\p{P})\*(?=[\p{L}\p{N}])/gu++function repairFlankingEmphasisSegment(segment: string): string {+ return segment+ .replace(FLANKING_BOLD, '<strong>$1</strong>')+ .replace(FLANKING_STRIKE, '<del>$1</del>')+ .replace(FLANKING_ITALIC, '<em>$1</em>')+}++/**+ * Render emphasis the model clearly intended but CommonMark refuses to parse.+ *+ * CommonMark's flanking rule rejects a closing `**`/`*`/`~~` that is preceded by+ * punctuation and immediately followed by a letter/number, so a very common+ * model pattern like `**XBRL(…语言)**是一种` (and even ASCII `**a)**b`) renders+ * as literal asterisks — both mid-stream and when complete. We convert just that+ * blocked pattern (closing delimiter after punctuation, before an alphanumeric)+ * into explicit HTML so it bolds reliably. Code spans/fences are skipped so+ * their literal markers are untouched.+ */+export function repairFlankingEmphasis(text: string): string {+ if (!text || !/[*~]/.test(text)) return text+ const parts = text.split(/(```[\s\S]*?```|`[^`\n]*`)/g)+ for (let i = 0; i < parts.length; i += 2) {+ parts[i] = repairFlankingEmphasisSegment(parts[i])+ }+ return parts.join('')+}++/**+ * Hide a trailing list/underline marker that has no content after it yet.+ *+ * While streaming, the moment a nested bullet's dash arrives before its text+ * (`1. **AAAAA**\n - `), marked reads the lone `-` as a setext underline and+ * renders the previous line as a giant `<h2>`, which collapses back to bold text+ * once the bullet content streams in — a large layout swing. An ordered marker+ * with no content (`text\n1. `) and bare setext underlines (`==`/`--`) cause the+ * same fl/flicker. Dropping the dangling marker line defers it by a token until+ * it is unambiguous; a real list/heading still renders once content follows.+ *+ * A trailing line that is only a number (`…\n1`) is the start of an ordered+ * marker before its `.`/`)` arrives; rendering it shows a bare unstyled "1" that+ * disappears a frame later, so it is hidden too. Because the line must be only+ * the number, in-sentence numbers (`值是 1`) are unaffected.+ */+export function stripTrailingStreamingListMarker(text: string): string {+ if (!text) return text+ return text.replace(/(^|\n)[ \t]*(?:[-*+]|[-=]{2,}|\d{1,9}[.)]?)[ \t]*$/, '$1')+}+export function createChatMarkdownRenderer(options: ChatMarkdownRendererOptions = {}): Renderer {const renderer = new marked.Renderer()@@ -126,6 +261,37 @@ export function wrapChatMarkdownTables(html: string): string {)}+const STANDALONE_STRONG_PARAGRAPH_RE =+ /<p>\s*<strong>((?:(?!<\/strong>)[\s\S])*?)<\/strong>\s*<\/p>/g++/**+ * Tag paragraphs whose entire content is a single bold run (e.g. a model that+ * emits `**小节标题:**` instead of a real heading) so they can be styled as a+ * subtitle deterministically.+ *+ * This replaces the CSS `p:has(> strong:only-child)` heuristic, which was+ * streaming-unstable: CSS `:only-child` ignores text nodes, so a normal+ * paragraph that momentarily contained exactly one completed `**bold**` run+ * (surrounded by plenty of body text) matched it and gained a large top margin,+ * then lost it once a second bold run finished — a visible spacing jump+ * mid-stream. Matching the whole paragraph content here only fires when the+ * bold run truly is the entire paragraph.+ */+export function markStandaloneStrongParagraphs(html: string): string {+ if (!html || !html.includes('<strong>')) return html+ return html.replace(+ STANDALONE_STRONG_PARAGRAPH_RE,+ (match: string, inner: string, offset: number, full: string) => {+ // A `<p>` that is a list item's content is list text, not a standalone+ // subtitle. Marking it adds a large margin that shifts sibling items when+ // a streamed list flips from tight to loose, so leave list paragraphs to+ // the list's own (zero) margins.+ if (/<li>\s*$/.test(full.slice(0, offset))) return match+ return `<p class="md-strong-title"><strong>${inner}</strong></p>`+ },+ )+}+export function renderChatMarkdown(rawMarkdown: unknown, options: RenderChatMarkdownOptions): string {const rawText = typeof rawMarkdown === 'string' ? rawMarkdown : String(rawMarkdown || '')if (!rawText.trim()) return ''@@ -133,7 +299,7 @@ export function renderChatMarkdown(rawMarkdown: unknown, options: RenderChatMarkconfigureMarkedForChatMarkdown()const streamingSafeText = options.streaming- ? stripTrailingStreamingHorizontalRule(rawText)+ ? stripTrailingStreamingListMarker(stripTrailingStreamingHorizontalRule(rawText)): rawTextconst citationSafeText = stripIncompleteCitationTag(streamingSafeText)const { text: tagSafe, tags } = preserveCitationTags(citationSafeText)@@ -141,13 +307,21 @@ export function renderChatMarkdown(rawMarkdown: unknown, options: RenderChatMarkconst mathSafe = preprocessMathDelimiters(imageSafe)const restoredTags = restoreCitationTags(mathSafe, tags)const inlineTags = joinCitationTagsToPreviousLine(restoredTags)- const preparedMarkdown = options.prepareMarkdown- ? options.prepareMarkdown(inlineTags, options.cachedMermaidSvgHtml)+ // Run the list-marker guard again after emphasis balancing: closing/hiding a+ // dangling `*`/`**` (the first chars of the next bullet's bold) can re-expose a+ // bare ` - `, which would otherwise flash an empty nested item under the+ // previous line right as the next item starts streaming.+ const balancedInline = options.streaming+ ? stripTrailingStreamingListMarker(closeDanglingStreamingEmphasis(inlineTags)): inlineTags+ const preparedMarkdown = options.prepareMarkdown+ ? options.prepareMarkdown(balancedInline, options.cachedMermaidSvgHtml)+ : balancedInline+ const flankingSafeMarkdown = repairFlankingEmphasis(preparedMarkdown)// Convert <kb>/<web>/wiki tags to HTML placeholders before escapeMarkdown so// agent sanitizers (e.g. UUID stripping) cannot damage chunk_id attributes.const { content: markdownWithPlaceholders, htmlSnippets } =- extractCitationHtmlPlaceholders(preparedMarkdown, options.knowledgeReferences)+ extractCitationHtmlPlaceholders(flankingSafeMarkdown, options.knowledgeReferences)const escapedMarkdown = options.escapeMarkdown(markdownWithPlaceholders)const html = marked.parse(markdownWithPlaceholders, {renderer: options.renderer,@@ -159,7 +333,8 @@ export function renderChatMarkdown(rawMarkdown: unknown, options: RenderChatMark? restoredHtml: collapseStandaloneCitationParagraphs(restoredHtml)const tableWrappedHtml = wrapChatMarkdownTables(citationHtml)- const sanitized = options.sanitizeHtml(tableWrappedHtml)+ const strongTitleHtml = markStandaloneStrongParagraphs(tableWrappedHtml)+ const sanitized = options.sanitizeHtml(strongTitleHtml)return options.injectCachedMermaidSvg? options.injectCachedMermaidSvg(sanitized, options.cachedMermaidSvgHtml): sanitizeddiff --git a/frontend/src/utils/citationMarkdown.ts b/frontend/src/utils/citationMarkdown.tsindex 9703ea126..32710dcfb 100644--- a/frontend/src/utils/citationMarkdown.ts+++ b/frontend/src/utils/citationMarkdown.ts@@ -261,8 +261,12 @@ export function joinCitationTagsToPreviousLine(content: string): string {// Single newline before citation when it follows text or another citation (not after a blank line)result = result.replace(/(?<!\n)(<(?:kb|web)\b[^>]*?\s*\/?>|[ \t]*\S[^\n]*?)\n([ \t]*<(?:kb|web)\b)/g,- (match, beforePart: string, kbStart: string) => {- if (isFencedCodeDelimiterLine(beforePart)) {+ (match, beforePart: string, kbStart: string, offset: number, full: string) => {+ // Resolve the full preceding line: lazy capture + lookbehind can grab only a+ // partial line (e.g. ``` captured as ``), which would skip the fence check.+ const lineStart = full.lastIndexOf('\n', offset - 1) + 1+ const fullPrevLine = full.slice(lineStart, offset + beforePart.length)+ if (isFencedCodeDelimiterLine(fullPrevLine)) {return match}return `${beforePart} ${kbStart.trimStart()}`diff --git a/frontend/src/views/chat/components/AgentStreamDisplay.vue b/frontend/src/views/chat/components/AgentStreamDisplay.vueindex b50e6b677..987350dfd 100644--- a/frontend/src/views/chat/components/AgentStreamDisplay.vue+++ b/frontend/src/views/chat/components/AgentStreamDisplay.vue@@ -43,9 +43,9 @@aria-hidden="true" /><span v-if="event.title" class="action-name action-preamble-title">{{ event.title }}</span><span v-else-if="isEventExpanded(event.event_id)" class="action-name">{{ $t('agent.think')- }}</span>- <span v-else-if="getThinkingSummary(event)" class="action-summary">{{ getThinkingSummary(event)}}</span>+ <span v-else-if="getThinkingSummary(event)" class="action-summary">{{ getThinkingSummary(event)+ }}</span></div></div><div v-if="event.content && isEventExpanded(event.event_id)" class="action-details">@@ -243,7 +243,7 @@<span class="action-title-icon icon-mask" :style="maskIconStyle(thinkingIcon)" aria-hidden="true" /><span class="action-name">{{ $t('agent.think') }}</span><span v-if="event.tool_data?.thought_number" class="action-badge">{{ event.tool_data.thought_number- }}/{{ event.tool_data.total_thoughts }}</span>+ }}/{{ event.tool_data.total_thoughts }}</span><span v-if="getThinkingSummary(event) && !isEventExpanded(event.tool_call_id)"class="action-summary">{{ getThinkingSummary(event) }}</span></div>@@ -260,7 +260,8 @@<div v-else-if="event.type === 'answer' && (event.done || (event.content && event.content.trim()))"class="answer-event"><div v-if="event.content && event.content.trim()" class="answer-content markdown-content">- <div v-stable-html="renderAnswerContent(event === activeAnswerEventRef ? typedAnswer : event.content)"></div>+ <div v-stable-html="renderAnswerContent(event === activeAnswerEventRef ? typedAnswer : event.content)">+ </div></div><div v-if="event.done && event.content && event.content.trim() && !embeddedMode" class="answer-toolbar"><t-button size="small" variant="outline" shape="round" @click.stop="handleCopyAnswer(event)"@@ -2621,11 +2622,11 @@ const handleAddToKnowledge = (answerEvent: any) => {0%,60%,100% {- transform: translateY(0);+ transform: translate3d(0, 0, 0);}30% {- transform: translateY(-8px);+ transform: translate3d(0, -5px, 0);}}@@ -2962,6 +2963,10 @@ const handleAddToKnowledge = (answerEvent: any) => {border-radius: 50%;background: var(--td-text-color-placeholder);animation: typingBounce 1.4s ease-in-out infinite;+ // Composite each dot so the bounce stays smooth and ghost-free while the+ // streaming answer relayouts every token.+ will-change: transform;+ backface-visibility: hidden;&:nth-child(1) {animation-delay: 0s;diff --git a/frontend/src/views/chat/components/botmsg.vue b/frontend/src/views/chat/components/botmsg.vueindex 3f7132512..54d448f00 100644--- a/frontend/src/views/chat/components/botmsg.vue+++ b/frontend/src/views/chat/components/botmsg.vue@@ -459,6 +459,10 @@ onBeforeUnmount(() => {border-radius: 50%;background: var(--td-brand-color);animation: typingBounce 1.4s ease-in-out infinite;+ // Composite the dots so the bounce stays smooth and ghost-free while the+ // answer relayouts each streamed token.+ will-change: transform;+ backface-visibility: hidden;&:nth-child(1) {animation-delay: 0s;@@ -479,11 +483,11 @@ onBeforeUnmount(() => {0%,60%,100% {- transform: translateY(0);+ transform: translate3d(0, 0, 0);}30% {- transform: translateY(-8px);+ transform: translate3d(0, -6px, 0);}}diff --git a/frontend/src/views/dev/MarkdownTestPage.vue b/frontend/src/views/dev/MarkdownTestPage.vueindex a95d155d3..1f3c6ed6b 100644--- a/frontend/src/views/dev/MarkdownTestPage.vue+++ b/frontend/src/views/dev/MarkdownTestPage.vue@@ -145,6 +145,9 @@ const renderStreamMarkdown = (raw: string): string => {renderer: mermaidRenderer,escapeMarkdown: (markdown) => markdown,sanitizeHtml: sanitizeMarkdownHTML,+ // Match production: the live chat marks unfinished answers as streaming so+ // mid-stream guards (dangling emphasis, trailing rules) are exercised here.+ streaming: isStreaming.value,cachedMermaidSvgHtml: streamMermaidSvgHtml.value,prepareMarkdown: prepareStreamingMermaidMarkdown,injectCachedMermaidSvg,@@ -260,7 +263,38 @@ graph TD`;// --- Streaming Simulation ----const fullStreamText = `The energy-mass equivalence is $E = mc^2$.+const fullStreamText = `+**XBRL(eXtensible Business Reporting Language,可扩展商业报告语言)**是一种基于XML的标准化标记语言,专门用于电子化商业和财务报告的编制、交换和分析++该数据集包含90个文本和方程对,挑战模型提取、解释和推理相互关联的财务术语和公式的能力,例如:+\`\`\`+APR = ((Fees + Interest) / Principal) × (365 / Days in Loan Term)+\`\`\`+<kb doc="2502.08127v1.pdf" chunk_id="1ecdce8a-f922-4d0c-b124-257ab4634da2" />++### 重要性+++1. **AAAAA**+ - **BBBBB**+ - **CCCCC**++1. **AAA**+2. **BBB**+3. **CCC**+4. **DDD**+5. **EEE**+6. **FFF**+7. **GGG**+8. **HHH**+9. **III**++**标题:JJJ**++**标题:KKK**+++The energy-mass equivalence is $E = mc^2$.In chemistry, the neutralization reaction:@@ -530,6 +564,8 @@ watch(customInput, () => {border-radius: 50%;background: var(--td-brand-color, #0052d9);animation: typingBounce 1.4s ease-in-out infinite;+ will-change: transform;+ backface-visibility: hidden;&:nth-child(1) {animation-delay: 0s;@@ -550,11 +586,11 @@ watch(customInput, () => {0%,60%,100% {- transform: translateY(0);+ transform: translate3d(0, 0, 0);}30% {- transform: translateY(-8px);+ transform: translate3d(0, -6px, 0);}}