Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(markdown): only parse leading <think> tags as Thinking blocks (#19766)

Arvin Xuc7f219a0bd11
diff --git a/src/features/Conversation/Markdown/plugins/Thinking/index.ts b/src/features/Conversation/Markdown/plugins/Thinking/index.ts
index 730765bd12e..0933bed007d 100644
--- a/src/features/Conversation/Markdown/plugins/Thinking/index.ts
+++ b/src/features/Conversation/Markdown/plugins/Thinking/index.ts
@@ -6,7 +6,7 @@ import Component from './Render';
const ThinkingElement: MarkdownElement = {
Component,
- remarkPlugin: createRemarkCustomTagPlugin(THINKING_TAG),
+ remarkPlugin: createRemarkCustomTagPlugin(THINKING_TAG, { leadingOnly: true }),
scope: 'assistant',
tag: THINKING_TAG,
};
diff --git a/src/features/Conversation/Markdown/plugins/remarkPlugins/createRemarkCustomTagPlugin.leadingOnly.test.ts b/src/features/Conversation/Markdown/plugins/remarkPlugins/createRemarkCustomTagPlugin.leadingOnly.test.ts
new file mode 100644
index 00000000000..0157cfa7123
--- /dev/null
+++ b/src/features/Conversation/Markdown/plugins/remarkPlugins/createRemarkCustomTagPlugin.leadingOnly.test.ts
@@ -0,0 +1,67 @@
+import remarkParse from 'remark-parse';
+import { unified } from 'unified';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { createRemarkCustomTagPlugin } from './createRemarkCustomTagPlugin';
+
+const processor = () =>
+ unified()
+ .use(remarkParse)
+ .use(createRemarkCustomTagPlugin('myTag', { leadingOnly: true }));
+
+const parse = (markdown: string) => processor().parse(markdown);
+
+describe('createRemarkCustomTagPlugin (leadingOnly)', () => {
+ let tree: any;
+
+ describe('tag at the very start of the document', () => {
+ beforeEach(() => {
+ // Blank lines matter: an HTML block swallows content until a blank line, so
+ // the real pipeline relies on `normalizeThinkTags` inserting `\n\n` to split
+ // the open tag / content / close tag into separate nodes.
+ tree = processor().runSync(parse('<myTag>\n\ninner content\n\n</myTag>'));
+ });
+
+ it('should collapse into a custom block node', () => {
+ expect(tree.children).toHaveLength(1);
+ expect(tree.children[0].type).toBe('myTagBlock');
+ expect(tree.children[0].data.hName).toBe('myTag');
+ expect(tree.children[0].data.hChildren[0].value).toContain('inner content');
+ });
+ });
+
+ describe('tag after other content', () => {
+ beforeEach(() => {
+ tree = processor().runSync(parse('Intro paragraph.\n\n<myTag>\ninner\n</myTag>'));
+ });
+
+ it('should keep the tag as raw html nodes', () => {
+ const types = tree.children.map((n: any) => n.type);
+ expect(types).toContain('html');
+ expect(types).not.toContain('myTagBlock');
+ });
+ });
+
+ describe('inline tag inside a paragraph', () => {
+ beforeEach(() => {
+ tree = processor().runSync(parse('Text with <myTag> inline tag stays raw.'));
+ });
+
+ it('should not produce a custom block', () => {
+ expect(tree.children).toHaveLength(1);
+ expect(tree.children[0].type).toBe('paragraph');
+ const hasHtmlChild = tree.children[0].children.some((c: any) => c.type === 'html');
+ expect(hasHtmlChild).toBe(true);
+ expect(tree.children.some((n: any) => n.type === 'myTagBlock')).toBe(false);
+ });
+ });
+
+ describe('no tag at all', () => {
+ it('should leave the document untouched', () => {
+ const input = '# Heading\n\nJust text.';
+ tree = processor().runSync(parse(input));
+
+ expect(tree.children[0].type).toBe('heading');
+ });
+ });
+});
diff --git a/src/features/Conversation/Markdown/plugins/remarkPlugins/createRemarkCustomTagPlugin.ts b/src/features/Conversation/Markdown/plugins/remarkPlugins/createRemarkCustomTagPlugin.ts
index ba5bb3f6470..a08d53e8469 100644
--- a/src/features/Conversation/Markdown/plugins/remarkPlugins/createRemarkCustomTagPlugin.ts
+++ b/src/features/Conversation/Markdown/plugins/remarkPlugins/createRemarkCustomTagPlugin.ts
@@ -2,10 +2,34 @@ import { SKIP, visit } from 'unist-util-visit';
import { treeNodeToString } from './getNodeContent';
-export const createRemarkCustomTagPlugin = (tag: string) => () => {
- return (tree: any) => {
- visit(tree, 'html', (node, index, parent) => {
- if (node.value === `<${tag}>`) {
+export interface RemarkCustomTagOptions {
+ /**
+ * Only parse the tag when it is the very first node of the document. Tags
+ * appearing mid-document — including inline ones inside a paragraph — stay
+ * as raw HTML / plain text instead of becoming a custom block.
+ */
+ leadingOnly?: boolean;
+}
+
+export const createRemarkCustomTagPlugin =
+ (tag: string, options: RemarkCustomTagOptions = {}) =>
+ () => {
+ const leadingOnly = options.leadingOnly === true;
+
+ return (tree: any) => {
+ visit(tree, 'html', (node, index, parent) => {
+ if (leadingOnly) {
+ // Leading-only mode (e.g. the `think` tag): the tag is a leading block,
+ // not an inline construct. Only an exact standalone open tag sitting at
+ // the very head of the document is eligible — anything else (inline tag
+ // inside a paragraph, or a block tag after other content) must stay raw
+ // HTML so quoting `<think>` mid-message never renders a Thinking block.
+ if (parent?.type !== 'root' || index !== 0) return;
+ if (node.value !== `<${tag}>`) return;
+ } else if (node.value !== `<${tag}>`) {
+ return;
+ }
+
const startIndex = index as number;
let endIndex = startIndex + 1;
let hasCloseTag = false;
@@ -50,7 +74,6 @@ export const createRemarkCustomTagPlugin = (tag: string) => () => {
// Skip already-processed nodes
return [SKIP, startIndex + 1];
- }
- });
+ });
+ };
};
-};
diff --git a/src/features/Conversation/components/ShareMessageModal/ShareText/template.test.ts b/src/features/Conversation/components/ShareMessageModal/ShareText/template.test.ts
index a8dc5c4cbeb..b214ad7c672 100644
--- a/src/features/Conversation/components/ShareMessageModal/ShareText/template.test.ts
+++ b/src/features/Conversation/components/ShareMessageModal/ShareText/template.test.ts
@@ -76,7 +76,25 @@ describe('generateMarkdown', () => {
expect(result).toContain('**Bold** *Italic* `Code`');
});
- it('should normalize think tags before exporting markdown', () => {
+ it('should normalize a leading think tag before exporting markdown', () => {
+ const messagesWithThinkTags = [
+ {
+ id: '1',
+ content: '<think>Reasoning</think>Outro',
+ role: 'assistant',
+ createdAt: Date.now(),
+ },
+ ] as UIChatMessage[];
+
+ const result = generateMarkdown({
+ ...defaultParams,
+ messages: messagesWithThinkTags,
+ });
+
+ expect(result).toContain('<think>\n\nReasoning\n\n</think>\n\nOutro');
+ });
+
+ it('should keep a mid-message think tag untouched when exporting markdown', () => {
const messagesWithThinkTags = [
{
id: '1',
@@ -91,6 +109,6 @@ describe('generateMarkdown', () => {
messages: messagesWithThinkTags,
});
- expect(result).toContain('Intro\n\n<think>\n\nReasoning\n\n</think>\n\nOutro');
+ expect(result).toContain('Intro<think>Reasoning</think>Outro');
});
});
diff --git a/src/features/Conversation/utils/markdown.test.ts b/src/features/Conversation/utils/markdown.test.ts
index 4d5a2d5fafe..af3fc22866c 100644
--- a/src/features/Conversation/utils/markdown.test.ts
+++ b/src/features/Conversation/utils/markdown.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
-import { processWithArtifact } from './markdown';
+import { normalizeThinkTags, processWithArtifact } from './markdown';
describe('processWithArtifact', () => {
it('should removeLineBreaks with closed tag', () => {
@@ -612,3 +612,44 @@ This HTML document includes the temperature converter with the requested feature
});
});
});
+
+describe('normalizeThinkTags', () => {
+ it('should only parse a <think> tag at the start of the message', () => {
+ const input = `<think>用户想要一个训练方案。</think>以下是方案:`;
+ const output = normalizeThinkTags(input);
+
+ expect(output).toEqual('<think>\n\n用户想要一个训练方案。\n\n</think>\n\n以下是方案:');
+ });
+
+ it('should not touch a <think> tag in the middle of the message', () => {
+ const input = '基座默认先吐一段 `<think>` 标签,要额外 pin 参数才行。';
+ const output = normalizeThinkTags(input);
+
+ expect(output).toEqual(input);
+ });
+
+ it('should not touch a <think> tag appearing after body text', () => {
+ const input = `先说结论:可行。
+
+<think>推理过程</think>
+
+然后是正文。`;
+ const output = normalizeThinkTags(input);
+
+ expect(output).toEqual(input);
+ });
+
+ it('should normalize when the message starts with a leading-newline <think> tag', () => {
+ const input = '\n<think>思考</think>正文';
+ const output = normalizeThinkTags(input);
+
+ expect(output).toEqual('\n<think>\n\n思考\n\n</think>\n\n正文');
+ });
+
+ it('should only add the opening gap for an unclosed leading <think> tag', () => {
+ const input = '<think>还在思考';
+ const output = normalizeThinkTags(input);
+
+ expect(output).toEqual('<think>\n\n还在思考');
+ });
+});
diff --git a/src/features/Conversation/utils/markdown.ts b/src/features/Conversation/utils/markdown.ts
index bd08c68613b..f86d9641686 100644
--- a/src/features/Conversation/utils/markdown.ts
+++ b/src/features/Conversation/utils/markdown.ts
@@ -80,16 +80,22 @@ export const processWithArtifact = (input: string = '') => {
return output;
};
-// Preprocessing function: ensure two newlines before and after think tags
+// Preprocessing function: ensure two newlines before and after think tags.
+// Thinking is a leading block, not an inline construct: normalization only
+// applies when the message itself starts with a <think> tag. A <think> tag
+// appearing mid-message (e.g. the model quoting it inside backticks) must stay
+// untouched — inserting newlines around it would split the paragraph and render
+// a stray "Thinking" collapsible in the middle of the reply.
export const normalizeThinkTags = (input: string) => {
+ if (!input.trimStart().startsWith('<think>')) return input;
+
return (
input
- // Ensure two newlines before and after <think> tags
- .replaceAll(/([^\n])\s*<think>/g, '$1\n\n<think>')
- .replaceAll(/<think>\s*([^\n])/g, '<think>\n\n$1')
- // Ensure two newlines before and after </think> tags
- .replaceAll(/([^\n])\s*<\/think>/g, '$1\n\n</think>')
- .replaceAll(/<\/think>\s*([^\n])/g, '</think>\n\n$1')
+ // Ensure two newlines after the leading <think> tag
+ .replace(/^(\s*<think>)\s*([^\n])/, '$1\n\n$2')
+ // Ensure two newlines before and after the first </think> tag
+ .replace(/([^\n])\s*(<\/think>)/, '$1\n\n$2')
+ .replace(/(<\/think>)\s*([^\n])/, '$1\n\n$2')
// Remove excess newlines that may have been introduced
.replaceAll(/\n{3,}/g, '\n\n')
);
diff --git a/src/features/ShareModal/ShareText/template.test.ts b/src/features/ShareModal/ShareText/template.test.ts
index d7573ca7d90..7e041f23ace 100644
--- a/src/features/ShareModal/ShareText/template.test.ts
+++ b/src/features/ShareModal/ShareText/template.test.ts
@@ -176,7 +176,25 @@ describe('generateMarkdown', () => {
expect(result).toContain('**Bold** *Italic* `Code`');
});
- it('should normalize think tags before exporting markdown', () => {
+ it('should normalize a leading think tag before exporting markdown', () => {
+ const messagesWithThinkTags = [
+ {
+ id: '1',
+ content: '<think>Reasoning</think>Outro',
+ role: 'assistant',
+ createdAt: Date.now(),
+ },
+ ] as UIChatMessage[];
+
+ const result = generateMarkdown({
+ ...defaultParams,
+ messages: messagesWithThinkTags,
+ });
+
+ expect(result).toContain('<think>\n\nReasoning\n\n</think>\n\nOutro');
+ });
+
+ it('should keep a mid-message think tag untouched when exporting markdown', () => {
const messagesWithThinkTags = [
{
id: '1',
@@ -191,6 +209,6 @@ describe('generateMarkdown', () => {
messages: messagesWithThinkTags,
});
- expect(result).toContain('Intro\n\n<think>\n\nReasoning\n\n</think>\n\nOutro');
+ expect(result).toContain('Intro<think>Reasoning</think>Outro');
});
});