From 58461a5b6815031c55a34901d7617a15a5e81773 Mon Sep 17 00:00:00 2001 From: wizardchen Date: Fri, 19 Jun 2026 23:05:20 +0800 Subject: [PATCH] feat(frontend): enhance chat markdown rendering and streaming behavior - Introduce functions to stabilize rendering of dangling inline markers during streaming, preventing flickering and layout shifts. - Implement tagging for standalone strong paragraphs to ensure consistent styling as subtitles. - Update CSS for chat components to improve animation smoothness and visual feedback during typing. - Add tests for new markdown rendering features, including handling of incomplete emphasis and citation tags. --- .../src/components/css/chat-markdown.less | 7 +- .../components/css/chat-timeline-loading.less | 8 +- frontend/src/utils/_repro_gap.mjs | 30 +++ .../src/utils/chatMarkdownRenderer.test.ts | 193 ++++++++++++++++++ frontend/src/utils/chatMarkdownRenderer.ts | 185 ++++++++++++++++- frontend/src/utils/citationMarkdown.ts | 8 +- .../chat/components/AgentStreamDisplay.vue | 17 +- frontend/src/views/chat/components/botmsg.vue | 8 +- frontend/src/views/dev/MarkdownTestPage.vue | 42 +++- 9 files changed, 477 insertions(+), 21 deletions(-) create mode 100644 frontend/src/utils/_repro_gap.mjs diff --git a/frontend/src/components/css/chat-markdown.less b/frontend/src/components/css/chat-markdown.less index 49b889b8..25d0fe19 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 , + // 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.less index e4f7dbcd..dcd6f624 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.mjs new file mode 100644 index 00000000..c5ccdd01 --- /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)', + '```', + '', + '', + '### 重要性', + '', + '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.ts index 114c7a26..6e6af566 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 only assert.match(renderChatMarkdown(source, { ...options, streaming: false }), /
/) }) +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 }), + /

平台访问地址: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 }), + /

\*\*平台访问地址/, + ) +}) + +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(语言)**是一种'), 'XBRL(语言)是一种') + assert.equal(repairFlankingEmphasis('**a)**b'), 'a)b') + assert.equal(repairFlankingEmphasis('~~删除)~~文字'), '删除)文字') + assert.equal(repairFlankingEmphasis('*斜体)*文字'), '斜体)文字') + + // 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 }), + /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

, and the next bullet's `*`/`**` (before its text) must + // not flash an empty nested
  • under A. + for (const partial of ['1. **AAAAA**\n - ', '1. **AAAAA**\n - *', '1. **AAAAA**\n - **']) { + const html = renderChatMarkdown(partial, options) + assert.doesNotMatch(html, /

    /) + assert.match(html, /
      \s*
    1. 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, /
    2. \*+<\/li>/) + assert.match(html, /
    3. 速游<\/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('

      小节标题:

      '), + '

      小节标题:

      ', + ) + + // 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 [ + '

      正文 加粗部分 与 **

      ', + '

      正文 A 与 B 收尾

      ', + '

      加粗 后续文字

      ', + ]) { + assert.equal(markStandaloneStrongParagraphs(html), html) + } + + // A bold list item (loose list wraps content in

      ) is list text, not a + // subtitle: it must keep the list's own margins, not gain a 1.25em top margin. + assert.equal( + markStandaloneStrongParagraphs('

      1. AAA

      '), + '
      1. AAA

      ', + ) +}) + +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, /

      总体来看/) + assert.match(html, /

      总结与建议<\/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 c assert.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 = '' + 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 = '' + const html = renderChatMarkdown( + ['```', 'APR = principal', '```', tag, '', '### 重要性'].join('\n'), + { + renderer, + escapeMarkdown: (text) => text, + sanitizeHtml: (html) => html, + }, + ) + + assert.doesNotMatch(html, /### 重要性/) + assert.match(html, /

      重要性<\/h3>/) + assert.equal((html.match(/
      /g) || []).length, 1)
      +})
      +
       test('renderChatMarkdown keeps fenced code blocks closed when citations follow', () => {
         const renderer = createChatMarkdownRenderer({
           imageRenderer: ({ href, text }) => `${text}`,
      diff --git a/frontend/src/utils/chatMarkdownRenderer.ts b/frontend/src/utils/chatMarkdownRenderer.ts
      index 0a208b26..76939987 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 = /(?$1')
      +    .replace(FLANKING_STRIKE, '$1')
      +    .replace(FLANKING_ITALIC, '$1')
      +}
      +
      +/**
      + * 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 `

      `, 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 = + /

      \s*((?:(?!<\/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('')) return html + return html.replace( + STANDALONE_STRONG_PARAGRAPH_RE, + (match: string, inner: string, offset: number, full: string) => { + // A `

      ` 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 (/

    4. \s*$/.test(full.slice(0, offset))) return match + return `

      ${inner}

      ` + }, + ) +} + 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: RenderChatMark configureMarkedForChatMarkdown() const streamingSafeText = options.streaming - ? stripTrailingStreamingHorizontalRule(rawText) + ? stripTrailingStreamingListMarker(stripTrailingStreamingHorizontalRule(rawText)) : rawText const citationSafeText = stripIncompleteCitationTag(streamingSafeText) const { text: tagSafe, tags } = preserveCitationTags(citationSafeText) @@ -141,13 +307,21 @@ export function renderChatMarkdown(rawMarkdown: unknown, options: RenderChatMark const 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 //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) : sanitized diff --git a/frontend/src/utils/citationMarkdown.ts b/frontend/src/utils/citationMarkdown.ts index 9703ea12..32710dcf 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( /(?]*?\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.vue index b50e6b67..987350df 100644 --- a/frontend/src/views/chat/components/AgentStreamDisplay.vue +++ b/frontend/src/views/chat/components/AgentStreamDisplay.vue @@ -43,9 +43,9 @@ aria-hidden="true" /> {{ event.title }} {{ $t('agent.think') - }} - {{ getThinkingSummary(event) }} + {{ getThinkingSummary(event) + }}
      @@ -243,7 +243,7 @@ {{ getThinkingSummary(event) }}
      @@ -260,7 +260,8 @@
      -
      +
      +
      { 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.vue index 3f713251..54d448f0 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.vue index a95d155d..1f3c6ed6 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) +\`\`\` + + +### 重要性 + + +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); } }