🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(task): render agent task comments as Markdown (#21689)
Lobehub Coder84dd012d806c
diff --git a/src/features/AgentTasks/AgentTaskDetail/CommentCard.tsx b/src/features/AgentTasks/AgentTaskDetail/CommentCard.tsxindex 54b8a6bee7d..2bf1384c943 100644--- a/src/features/AgentTasks/AgentTaskDetail/CommentCard.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/CommentCard.tsx@@ -24,6 +24,7 @@ import { isOptimisticActivityId } from '@/store/task/slices/detail/optimisticActimport { styles } from '../shared/style';import { commentMarkdownProps } from './commentMarkdown';+import { resolveMarkdownSnapshotContent } from './commentRenderSource';// Keep saved comments visually consistent with the editor: render FileNodes// as the Linear-style card on its own row instead of the default inline pill.@@ -62,6 +63,15 @@ const CommentCard = memo<CommentCardProps>(({ activity }) => {}),[activity.content, activity.editorData],);+ const snapshotMarkdown = useMemo(+ () =>+ resolveMarkdownSnapshotContent({+ content: activity.content,+ editorData: activity.editorData,+ }),+ [activity.content, activity.editorData],+ );+ const renderSnapshot = Boolean(activity.editorData) && snapshotMarkdown === undefined;useEffect(() => {if (activity.files && activity.files.length > 0) {@@ -183,7 +193,7 @@ const CommentCard = memo<CommentCardProps>(({ activity }) => {</Flexbox></>)}- {!isEditing && Boolean(activity.editorData) && (+ {!isEditing && renderSnapshot && (<LexicalRendererclassName={mentionPlainClassName}overrides={rendererOverrides}@@ -191,9 +201,9 @@ const CommentCard = memo<CommentCardProps>(({ activity }) => {variant={'chat'}/>)}- {!isEditing && !activity.editorData && (+ {!isEditing && !renderSnapshot && (<Markdown fontSize={14} variant={'chat'} {...commentMarkdownProps}>- {content}+ {snapshotMarkdown ?? content}</Markdown>)}diff --git a/src/features/AgentTasks/AgentTaskDetail/commentRenderSource.test.ts b/src/features/AgentTasks/AgentTaskDetail/commentRenderSource.test.tsnew file mode 100644index 00000000000..4978a24f899--- /dev/null+++ b/src/features/AgentTasks/AgentTaskDetail/commentRenderSource.test.ts@@ -0,0 +1,148 @@+import { describe, expect, it } from 'vitest';++import { resolveMarkdownSnapshotContent } from './commentRenderSource';++const text = (value: string, extra: Record<string, unknown> = {}) => ({+ detail: 0,+ format: 0,+ mode: 'normal',+ style: '',+ text: value,+ type: 'text',+ version: 1,+ ...extra,+});++const mention = (label: string, id: string) => ({+ label,+ metadata: { id, type: 'member' },+ type: 'mention',+ version: 1,+});++const paragraph = (...children: unknown[]) => ({ children, type: 'paragraph', version: 1 });++const snapshot = (...children: unknown[]) => ({ root: { children, type: 'root', version: 1 } });++describe('resolveMarkdownSnapshotContent', () => {+ // Shape of an agent comment that hand-built editorData only to carry mentions.+ const content = [+ '@Arvin @Lin 补测完成。',+ '',+ '**部署**',+ '- #21544(`b8485fce`)已上线。',+ '- 话题:tpc_x。',+ ].join('\n');+ const handBuilt = snapshot(+ paragraph(mention('Arvin', 'user_a'), text(' '), mention('Lin', 'user_b'), text(' 补测完成。')),+ paragraph(),+ paragraph(text('部署')),+ paragraph(text('- #21544(`b8485fce`)已上线。')),+ paragraph(text('- 话题:tpc_x。')),+ );++ it('renders the markdown body of a hand-built plain snapshot and restores its mentions', () => {+ expect(resolveMarkdownSnapshotContent({ content, editorData: handBuilt })).toBe(+ [+ '<mention name="Arvin" id="user_a" /> <mention name="Lin" id="user_b" /> 补测完成。',+ '',+ '**部署**',+ '- #21544(`b8485fce`)已上线。',+ '- 话题:tpc_x。',+ ].join('\n'),+ );+ });++ it('restores every mention of the same member in order', () => {+ expect(+ resolveMarkdownSnapshotContent({+ content: '@Lin 看下 `a`,@Lin 再确认',+ editorData: snapshot(+ paragraph(+ mention('Lin', 'user_b'),+ text(' 看下 `a`,'),+ mention('Lin', 'user_b'),+ text(' 再确认'),+ ),+ ),+ }),+ ).toBe(+ '<mention name="Lin" id="user_b" /> 看下 `a`,<mention name="Lin" id="user_b" /> 再确认',+ );+ });++ it('renders a body whose only formatting the snapshot dropped', () => {+ expect(+ resolveMarkdownSnapshotContent({+ content: '@Lin **部署** 完成,_详见_ 链接',+ editorData: snapshot(paragraph(mention('Lin', 'user_b'), text(' 部署 完成,详见 链接'))),+ }),+ ).toBe('<mention name="Lin" id="user_b" /> **部署** 完成,_详见_ 链接');+ });++ it('restores a mention at its own position, not at an earlier literal @Name', () => {+ expect(+ resolveMarkdownSnapshotContent({+ content: '`@Lin` is syntax; @Lin review **this**',+ editorData: snapshot(+ paragraph(text('`@Lin` is syntax; '), mention('Lin', 'user_b'), text(' review this')),+ ),+ }),+ ).toBe('`@Lin` is syntax; <mention name="Lin" id="user_b" /> review **this**');+ });++ it('keeps an editor snapshot whose body only escapes literal markers', () => {+ expect(+ resolveMarkdownSnapshotContent({+ content: 'snake\\_case and 2 \\* 3 \\* 4\n\nfine',+ editorData: snapshot(paragraph(text('snake_case and 2 * 3 * 4')), paragraph(text('fine'))),+ }),+ ).toBeUndefined();+ });++ it('keeps a body that already serializes its mention tags', () => {+ const tagged = content.replace('@Arvin', '<mention name="Arvin" id="user_a" />');++ expect(resolveMarkdownSnapshotContent({ content: tagged, editorData: handBuilt })).toBe(tagged);+ });++ it('keeps an editor snapshot without markdown source', () => {+ expect(+ resolveMarkdownSnapshotContent({+ content: '<mention name="Lin" id="user_b" /> looks good\n\nship it',+ editorData: snapshot(+ paragraph(mention('Lin', 'user_b'), text(' looks good')),+ paragraph(text('ship it')),+ ),+ }),+ ).toBeUndefined();+ });++ it('keeps plain text that only looks like a quote marker', () => {+ expect(+ resolveMarkdownSnapshotContent({+ content: '>_< 又挂了\n\n>= 3 次',+ editorData: snapshot(paragraph(text('>_< 又挂了')), paragraph(text('>= 3 次'))),+ }),+ ).toBeUndefined();+ });++ it('keeps snapshots with rich structure', () => {+ const list = { children: [{ children: [text('a')], type: 'listitem' }], type: 'list' };++ expect(+ resolveMarkdownSnapshotContent({ content: '- a', editorData: snapshot(list) }),+ ).toBeUndefined();+ expect(+ resolveMarkdownSnapshotContent({+ content: '**`x`**',+ editorData: snapshot(paragraph(text('`x`', { format: 1 }))),+ }),+ ).toBeUndefined();+ });++ it('keeps the snapshot when there is no markdown body or snapshot', () => {+ expect(resolveMarkdownSnapshotContent({ content: '', editorData: handBuilt })).toBeUndefined();+ expect(resolveMarkdownSnapshotContent({ content, editorData: null })).toBeUndefined();+ });+});diff --git a/src/features/AgentTasks/AgentTaskDetail/commentRenderSource.ts b/src/features/AgentTasks/AgentTaskDetail/commentRenderSource.tsnew file mode 100644index 00000000000..17436f3dcff--- /dev/null+++ b/src/features/AgentTasks/AgentTaskDetail/commentRenderSource.ts@@ -0,0 +1,157 @@+import { writeTopicCommentMentionMarkdown } from '@/features/Portal/TopicComments/editorUtils';++interface CommentSource {+ content?: string | null;+ editorData?: unknown;+}++interface SnapshotMention {+ label: string;+ metadata: Record<string, unknown>;+ /** How many `@label` spellings precede this mention in the snapshot text. */+ occurrence: number;+}++type LexicalNode = Record<string, unknown>;++const asNode = (value: unknown): LexicalNode | undefined =>+ value && typeof value === 'object' && !Array.isArray(value) ? (value as LexicalNode) : undefined;++const childrenOf = (node: LexicalNode): unknown[] =>+ Array.isArray(node.children) ? node.children : [];++// The editor turns these into lists, headings, quotes, code, emphasis and links+// as they are typed, so plain text only holds them when the snapshot was built+// by hand from markdown source (API / CLI / agent callers).+const MARKDOWN_BLOCK_SOURCE =+ /^\s{0,3}(?:[*+-]\s|\d+[.)]\s|#{1,6}\s|>(?:\s|$)|```|~~~)|^\s*\|.*\|\s*$/;+const MARKDOWN_INLINE_SOURCE =+ /`[^`\n]+`|\*\*[^*\n]+\*\*|__[^_\n]+__|~~[^~\n]+~~|(?:^|[^\w*])\*[^\s*][^*\n]*\*(?![\w*])|(?:^|\W)_[^\s_][^_\n]*_\b|\[[^\]\n]+\]\([^)\s]+\)/;++const isMarkdownSourceLine = (line: string) =>+ MARKDOWN_BLOCK_SOURCE.test(line) || MARKDOWN_INLINE_SOURCE.test(line);++const countOccurrences = (text: string, needle: string) => text.split(needle).length - 1;++// Escaped characters are literal text, never markdown syntax.+const stripEscapes = (markdown: string) => markdown.replaceAll(/\\[\s\S]/g, '');++const MENTION_TAG_NAME = /<mention\s(?:[^>]*\s)?name\s*=\s*(?:"([^"]*)"|'([^']*)')[^>]*\/>/gi;++/** The visible text of a markdown body, whitespace and escapes ignored. */+const toComparableText = (markdown: string) =>+ markdown+ .replaceAll(+ MENTION_TAG_NAME,+ (_, doubleQuoted, singleQuoted) => `@${doubleQuoted ?? singleQuoted}`,+ )+ .replaceAll(/\\([\s\S])/g, '$1')+ .replaceAll(/\s+/g, '');++/**+ * Whether the markdown body carries formatting the snapshot lost. Hand-built+ * snapshots may keep the source markers (`- `, backticks) or drop them (bold+ * reduced to plain text), so check both. An editor snapshot's body is its own+ * serialization: the same visible text, with any literal markers escaped.+ */+const hasMarkdownBeyondSnapshot = (content: string, lines: string[]) => {+ if (lines.some(isMarkdownSourceLine)) return true;+ if (toComparableText(content) === toComparableText(lines.join('\n'))) return false;++ return stripEscapes(content).split('\n').some(isMarkdownSourceLine);+};++/**+ * Read a snapshot made only of unformatted paragraphs. Returns its text lines+ * and mentions, or `undefined` once any node carries rich structure the+ * markdown body could not reproduce (lists, files, images, styled text…).+ */+const readPlainSnapshot = (+ editorData: unknown,+): { lines: string[]; mentions: SnapshotMention[] } | undefined => {+ const root = asNode(asNode(editorData)?.root);+ if (!root) return;++ const lines: string[] = [];+ const mentions: SnapshotMention[] = [];+ let previousText = '';++ for (const block of childrenOf(root)) {+ const paragraph = asNode(block);+ if (paragraph?.type !== 'paragraph') return;++ let line = '';+ for (const child of childrenOf(paragraph)) {+ const node = asNode(child);+ if (!node) return;++ if (node.type === 'text') {+ if (node.format || node.style || typeof node.text !== 'string') return;+ line += node.text;+ } else if (node.type === 'linebreak') {+ lines.push(line);+ previousText += `${line}\n`;+ line = '';+ } else if (node.type === 'mention') {+ const metadata = asNode(node.metadata);+ const label = typeof node.label === 'string' ? node.label : '';+ if (metadata && label) {+ const occurrence = countOccurrences(`${previousText}${line}`, `@${label}`);+ mentions.push({ label, metadata, occurrence });+ }+ line += `@${label}`;+ } else {+ return;+ }+ }+ lines.push(line);+ previousText += `${line}\n`;+ }++ return { lines, mentions };+};++/**+ * Callers without the rich editor sometimes send a hand-built Lexical snapshot+ * (one plain paragraph per markdown line, just to carry member mentions) next+ * to the real markdown `content`. Rendering that snapshot shows raw `- ` and+ * backticks, or loses formatting the builder stripped, so render the markdown+ * body instead.+ *+ * Returns the markdown to render, or `undefined` when the snapshot is the+ * faithful source and should be rendered as is. Snapshot mentions that the+ * body only spells as `@Name` are restored as mention tags.+ */+export const resolveMarkdownSnapshotContent = ({+ content,+ editorData,+}: CommentSource): string | undefined => {+ if (!content?.trim()) return;++ const snapshot = readPlainSnapshot(editorData);+ if (!snapshot || !hasMarkdownBeyondSnapshot(content, snapshot.lines)) return;++ // A body that already serializes its mentions is rendered as written.+ if (content.includes('<mention')) return content;++ // Restore each mention at the same `@label` occurrence the snapshot puts it,+ // so a literal `@Name` (for example in inline code) is left alone.+ const replacements = snapshot.mentions.flatMap((mention) => {+ const needle = `@${mention.label}`;+ let index = -1;+ for (let seen = 0; seen <= mention.occurrence; seen++) {+ index = content.indexOf(needle, index + 1);+ if (index < 0) return [];+ }+ return [+ { end: index + needle.length, start: index, tag: writeTopicCommentMentionMarkdown(mention) },+ ];+ });++ let markdown = content;+ for (const { end, start, tag } of replacements.sort((a, b) => b.start - a.start)) {+ markdown = markdown.slice(0, start) + tag + markdown.slice(end);+ }++ return markdown;+};