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.
This commit is contained in:
wizardchen
2026-06-19 23:05:20 +08:00
committed by lyingbug
parent ae9038732a
commit 58461a5b68
9 changed files with 477 additions and 21 deletions
@@ -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 }), /<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 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 = '<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}">`,