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(topic-comment): preserve assistant reply anchor previews (#17619)

AmAzing-9f5bd7ab14e0
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 9098e79f48a..1f96657536b 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -1307,7 +1307,7 @@
"topic.saveCurrentMessages": "Save current conversation as topic",
"topic.viewAll": "View All Topics",
"topicComment.anchor": "Original message",
- "topicComment.anchorDeleted": "Original message deleted",
+ "topicComment.anchorDeletedTag": "Deleted",
"topicComment.anchorEmpty": "Empty message",
"topicComment.author.deactivated": "Deleted user",
"topicComment.author.former": "Former member",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 687d1b640de..a3c20782666 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -1307,7 +1307,7 @@
"topic.saveCurrentMessages": "保存为话题",
"topic.viewAll": "查看全部主题",
"topicComment.anchor": "原消息",
- "topicComment.anchorDeleted": "原消息已删除",
+ "topicComment.anchorDeletedTag": "已删除",
"topicComment.anchorEmpty": "空消息",
"topicComment.author.deactivated": "已注销用户",
"topicComment.author.former": "已离开成员",
diff --git a/packages/conversation-flow/package.json b/packages/conversation-flow/package.json
index 179a9daac63..0f9989f7afd 100644
--- a/packages/conversation-flow/package.json
+++ b/packages/conversation-flow/package.json
@@ -7,6 +7,9 @@
"test": "vitest",
"test:coverage": "vitest --coverage --silent='passed-only'"
},
+ "dependencies": {
+ "@lobechat/const": "workspace:*"
+ },
"devDependencies": {
"@lobechat/types": "workspace:*"
}
diff --git a/packages/conversation-flow/src/__tests__/assistantGroupContent.test.ts b/packages/conversation-flow/src/__tests__/assistantGroupContent.test.ts
new file mode 100644
index 00000000000..65feaa2f171
--- /dev/null
+++ b/packages/conversation-flow/src/__tests__/assistantGroupContent.test.ts
@@ -0,0 +1,90 @@
+import type { AssistantContentBlock, UIChatMessage } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import {
+ isAssistantGroupStatusText,
+ resolveAssistantGroupFinalContent,
+} from '../assistantGroupContent';
+
+const block = (
+ id: string,
+ content: string,
+ options: Pick<AssistantContentBlock, 'tools'> = {},
+): AssistantContentBlock => ({ content, id, ...options });
+
+const group = (
+ children: AssistantContentBlock[],
+ taskCompletions?: AssistantContentBlock[],
+): UIChatMessage =>
+ ({
+ children,
+ content: '',
+ createdAt: 0,
+ id: 'assistant-group',
+ role: 'assistantGroup',
+ taskCompletions,
+ updatedAt: 0,
+ }) as UIChatMessage;
+
+describe('isAssistantGroupStatusText', () => {
+ it('classifies only short, unstructured single-line prose as workflow status', () => {
+ expect(isAssistantGroupStatusText('Now I will update the issue.')).toBe(true);
+ expect(isAssistantGroupStatusText('Updated src/a.ts successfully.')).toBe(true);
+
+ expect(isAssistantGroupStatusText('First sentence. Second sentence.')).toBe(false);
+ expect(isAssistantGroupStatusText('Summary\n\nMore detail')).toBe(false);
+ expect(isAssistantGroupStatusText('## Result')).toBe(false);
+ expect(isAssistantGroupStatusText('- Result')).toBe(false);
+ expect(isAssistantGroupStatusText('x'.repeat(101))).toBe(false);
+ });
+});
+
+describe('resolveAssistantGroupFinalContent', () => {
+ it('skips a trailing tool status and keeps the answer rendered before it', () => {
+ const message = group([
+ block('answer', 'This is the actual answer.'),
+ block('status', 'Now I will update the issue.', {
+ tools: [{ apiName: 'updateIssue', id: 'tool-call' } as any],
+ }),
+ ]);
+
+ expect(resolveAssistantGroupFinalContent(message)).toBe('This is the actual answer.');
+ });
+
+ it('keeps answer-like prose from a mixed tool block', () => {
+ const detailedAnswer =
+ 'The migration is complete. All affected paths now share the same invariant.';
+ const message = group([
+ block('status', 'I will inspect the code.', {
+ tools: [{ apiName: 'readFile', id: 'read-call' } as any],
+ }),
+ block('answer-with-tool', detailedAnswer, {
+ tools: [{ apiName: 'updateIssue', id: 'update-call' } as any],
+ }),
+ ]);
+
+ expect(resolveAssistantGroupFinalContent(message)).toBe(detailedAnswer);
+ });
+
+ it('prefers the last post-task summary over the main assistant chain', () => {
+ const message = group(
+ [block('main-answer', 'Initial answer')],
+ [block('summary-1', 'First task summary'), block('summary-2', 'Final task summary')],
+ );
+
+ expect(resolveAssistantGroupFinalContent(message)).toBe('Final task summary');
+ });
+
+ it('falls back to the latest authored status for a status-only group', () => {
+ const message = group([
+ block('status-1', 'Checking the repository.', {
+ tools: [{ apiName: 'search', id: 'search-call' } as any],
+ }),
+ block('status-2', 'Updating the repository.', {
+ tools: [{ apiName: 'edit', id: 'edit-call' } as any],
+ }),
+ ]);
+
+ expect(resolveAssistantGroupFinalContent(message)).toBe('Updating the repository.');
+ });
+});
diff --git a/packages/conversation-flow/src/assistantGroupContent.ts b/packages/conversation-flow/src/assistantGroupContent.ts
new file mode 100644
index 00000000000..9117caf64f6
--- /dev/null
+++ b/packages/conversation-flow/src/assistantGroupContent.ts
@@ -0,0 +1,58 @@
+import { LOADING_FLAT } from '@lobechat/const';
+import type { UIChatMessage } from '@lobechat/types';
+
+const ASSISTANT_GROUP_STATUS_TEXT_MAX_LENGTH = 100;
+const MARKDOWN_HEADING_MAX_LEVEL = 6;
+
+const normalizeAuthoredContent = (content?: string | null) => {
+ if (!content?.trim() || content === LOADING_FLAT) return;
+ return content;
+};
+
+/**
+ * Whether assistant prose reads as a short workflow status rather than answer content.
+ * Keep this shared with the renderer so persisted previews do not surface text that the UI
+ * folds into the workflow process.
+ */
+export const isAssistantGroupStatusText = (content?: string | null): boolean => {
+ const raw = content?.trim() ?? '';
+ if (!raw || raw === LOADING_FLAT) return true;
+ if (raw.includes('\n')) return false;
+
+ if (new RegExp(`^#{1,${MARKDOWN_HEADING_MAX_LEVEL}}\\s`).test(raw) || /^[-*]\s+\S/.test(raw))
+ return false;
+
+ if (raw.length > ASSISTANT_GROUP_STATUS_TEXT_MAX_LENGTH) return false;
+
+ const sentenceCount = (raw.match(/[。!?]|[.!?](?=\s|$)/g) ?? []).length;
+ return sentenceCount <= 1;
+};
+
+/**
+ * Resolve the authored text that best represents a parsed assistant group.
+ *
+ * Post-task summaries render after the main chain and therefore win. In the main chain,
+ * trailing short status text attached to tool calls stays folded as workflow context when an
+ * earlier answer exists. If a group contains only such status text, keep the latest authored
+ * block as a useful fallback instead of returning an empty preview.
+ */
+export const resolveAssistantGroupFinalContent = (message?: UIChatMessage): string | undefined => {
+ for (let index = (message?.taskCompletions?.length ?? 0) - 1; index >= 0; index -= 1) {
+ const content = normalizeAuthoredContent(message?.taskCompletions?.[index]?.content);
+ if (content) return content;
+ }
+
+ let latestAuthoredContent: string | undefined;
+ for (let index = (message?.children?.length ?? 0) - 1; index >= 0; index -= 1) {
+ const block = message?.children?.[index];
+ const content = normalizeAuthoredContent(block?.content);
+ if (!content) continue;
+
+ latestAuthoredContent ??= content;
+ const isTrailingToolStatus =
+ !!block?.tools?.length && isAssistantGroupStatusText(block.content);
+ if (!isTrailingToolStatus) return content;
+ }
+
+ return normalizeAuthoredContent(message?.content) ?? latestAuthoredContent;
+};
diff --git a/packages/conversation-flow/src/index.ts b/packages/conversation-flow/src/index.ts
index c972cf6d0d0..848f4860110 100644
--- a/packages/conversation-flow/src/index.ts
+++ b/packages/conversation-flow/src/index.ts
@@ -1,6 +1,12 @@
// Main parse function
export { parse } from './parse';
+// Assistant group authored-content semantics
+export {
+ isAssistantGroupStatusText,
+ resolveAssistantGroupFinalContent,
+} from './assistantGroupContent';
+
// Topic Doctor - detect and repair message trees the reader cannot fully render
export type { RepairOp, TopicDiagnosis, TopicIssue, TopicIssueKind } from './doctor';
export { diagnoseTopic } from './doctor';
diff --git a/packages/database/src/models/__tests__/topicComment.test.ts b/packages/database/src/models/__tests__/topicComment.test.ts
index 7d08759ac1b..b39cfb828e7 100644
--- a/packages/database/src/models/__tests__/topicComment.test.ts
+++ b/packages/database/src/models/__tests__/topicComment.test.ts
@@ -4,6 +4,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../core/getTestDB';
import {
+ messagePlugins,
messages,
topicCommentMentions,
topicComments,
@@ -149,6 +150,360 @@ describe('TopicCommentModel', () => {
expect(result.topicParticipantUserIds).toEqual([]);
});
+ it('should snapshot the final authored text of a tool-anchored assistant group', async () => {
+ const userMessageId = 'tc-group-user';
+ const rootAssistantId = 'tc-group-root';
+ const toolMessageId = 'tc-group-tool';
+ const finalAssistantId = 'tc-group-final';
+ const toolCallId = 'tc-group-tool-call';
+ await serverDB.insert(messages).values([
+ {
+ content: 'research this',
+ id: userMessageId,
+ role: 'user',
+ topicId: workspaceTopicId,
+ userId: authorId,
+ workspaceId: workspaceAId,
+ },
+ {
+ content: '',
+ id: rootAssistantId,
+ parentId: userMessageId,
+ role: 'assistant',
+ tools: [{ id: toolCallId }],
+ topicId: workspaceTopicId,
+ userId: authorId,
+ workspaceId: workspaceAId,
+ },
+ {
+ content: 'tool result',
+ id: toolMessageId,
+ parentId: rootAssistantId,
+ role: 'tool',
+ topicId: workspaceTopicId,
+ userId: authorId,
+ workspaceId: workspaceAId,
+ },
+ {
+ content: 'the final agent answer',
+ id: finalAssistantId,
+ parentId: toolMessageId,
+ role: 'assistant',
+ topicId: workspaceTopicId,
+ userId: authorId,
+ workspaceId: workspaceAId,
+ },
+ ]);
+ await serverDB.insert(messagePlugins).values({
+ id: toolMessageId,
+ toolCallId,
+ userId: authorId,
+ workspaceId: workspaceAId,
+ });
+
+ const result = await authorModel.createWithMentions({
+ clientId: 'client-assistant-group-final',
+ content: 'comment on the complete agent reply',
+ messageId: rootAssistantId,
+ topicId: workspaceTopicId,
+ });
+
+ expect(result.comment).toMatchObject({
+ anchorPreview: { excerpt: 'the final agent answer', role: 'assistant' },
+ messageId: rootAssistantId,
+ });
+ });
+
+ it('should resolve the complete reply when the topic exceeds the message query page size', async () => {
+ const rootAssistantId = 'tc-long-topic-root';
+ await serverDB.insert(messages).values([
+ {
+ content: '',
+ createdAt: new Date('2020-01-01'),
+ id: rootAssistantId,
+ role: 'assistant',
+ tools: [{ id: 'tc-long-topic-tool-call' }],
+ topicId: workspaceTopicId,
+ userId: authorId,
+ workspaceId: workspaceAId,
+ },
+ {
+ content: 'the final answer outside the newest message page',
+ createdAt: new Date('2020-01-01T00:00:01Z'),
+ id: 'tc-long-topic-final',
+ parentId: rootAssistantId,
+ role: 'assistant',
+ topicId: workspaceTopicId,
+ userId: authorId,
+ workspaceId: workspaceAId,
+ },
+ ]);
+ await serverDB.insert(messages).values(
+ Array.from({ length: 1001 }, (_, index) => ({
+ content: `newer unrelated message ${index}`,
+ createdAt: new Date('2021-01-01'),
+ id: `tc-long-topic-noise-${index.toString().padStart(4, '0')}`,
+ role: 'user',
+ topicId: workspaceTopicId,
+ userId: authorId,
+ workspaceId: workspaceAId,
+ })),
+ );
+
+ const result = await authorModel.createWithMentions({
+ clientId: 'client-long-topic-preview',
+ content: 'comment on an older complete reply',
+ messageId: rootAssistantId,
+ topicId: workspaceTopicId,
+ });
+
+ expect(result.comment.anchorPreview?.excerpt).toBe(
+ 'the final answer outside the newest message page',
+ );
+ });
+
+ it('should include the user parent when grouping a toolless narration head', async () => {
+ const userMessageId = 'tc-narrated-group-user';
+ const rootAssistantId = 'tc-narrated-group-root';
+ const toolMessageId = 'tc-narrated-group-tool';
+ const toolCallId = 'tc-narrated-tool-call';
+ await serverDB.insert(messages).values([
+ {
+ content: 'investigate this',
+ id: userMessageId,
+ role: 'user',
+ topicId: workspaceTopicId,
+ userId: authorId,
+ workspaceId: workspaceAId,
+ },
+ {
+ content: 'I will check first',
+ id: rootAssistantId,
+ parentId: userMessageId,
+ role: 'assistant',
+ topicId: workspaceTopicId,
+ userId: authorId,
+ workspaceId: workspaceAId,
+ },
+ {
+ content: 'I found the right tool',
+ id: 'tc-narrated-group-tool-step',
+ parentId: rootAssistantId,
+ role: 'assistant',
+ tools: [{ id: toolCallId }],
+ topicId: workspaceTopicId,
+ userId: authorId,
+ workspaceId: workspaceAId,
+ },
+ {
+ content: 'tool result',
+ id: toolMessageId,
+ parentId: 'tc-narrated-group-tool-step',
+ role: 'tool',
+ topicId: workspaceTopicId,
+ userId: authorId,
+ workspaceId: workspaceAId,
+ },
+ {
+ content: 'the later complete answer',
+ id: 'tc-narrated-group-final',
+ parentId: toolMessageId,
+ role: 'assistant',
+ topicId: workspaceTopicId,
+ userId: authorId,
+ workspaceId: workspaceAId,
+ },
+ ]);
+ await serverDB.insert(messagePlugins).values({
+ id: toolMessageId,
+ toolCallId,
+ userId: authorId,
+ workspaceId: workspaceAId,
+ });
+
+ const result = await authorModel.createWithMentions({
+ clientId: 'client-narrated-group-final',
+ content: 'comment on the final answer',
+ messageId: rootAssistantId,
+ topicId: workspaceTopicId,
+ });
+
+ expect(result.comment.anchorPreview?.excerpt).toBe('the later complete answer');
+ });
+
+ it('should keep the rendered answer when a trailing tool status closes the group', async () => {
+ const userMessageId = 'tc-trailing-status-user';
+ const rootAssistantId = 'tc-trailing-status-root';
+ const statusAssistantId = 'tc-trailing-status-step';
+ const toolMessageId = 'tc-trailing-status-tool';
+ const toolCallId = 'tc-trailing-status-call';
+ await serverDB.insert(messages).values([
+ {
+ content: 'investigate and update this issue',
+ id: userMessageId,
+ role: 'user',
+ topicId: workspaceTopicId,
+ userId: authorId,
+ workspaceId: workspaceAId,
+ },
+ {
+ content: 'This is the actual answer.',
+ id: rootAssistantId,
+ parentId: userMessageId,
+ role: 'assistant',
+ topicId: workspaceTopicId,
+ userId: authorId,
+ workspaceId: workspaceAId,
+ },
+ {
+ content: 'Now I will update the issue.',
+ id: statusAssistantId,
+ parentId: rootAssistantId,
+ role: 'assistant',
+ tools: [{ id: toolCallId }],
+ topicId: workspaceTopicId,
+ userId: authorId,
+ workspaceId: workspaceAId,
+ },
+ {
+ content: 'issue updated',
+ id: toolMessageId,
+ parentId: statusAssistantId,
+ role: 'tool',
+ topicId: workspaceTopicId,
+ userId: authorId,
+ workspaceId: workspaceAId,
+ },
+ ]);
+ await serverDB.insert(messagePlugins).values({
+ id: toolMessageId,
+ toolCallId,
+ userId: authorId,
+ workspaceId: workspaceAId,
+ });
+
+ const result = await authorModel.createWithMentions({
+ clientId: 'client-trailing-status-preview',
+ content: 'comment on the answer, not the bookkeeping status',
+ messageId: rootAssistantId,
+ topicId: workspaceTopicId,
+ });
+
+ expect(result.comment.anchorPreview?.excerpt).toBe('This is the actual answer.');
+ });
+
+ it('should prefer a post-task summary rendered after the main assistant chain', async () => {
+ const rootAssistantId = 'tc-task-completion-root';
+ const toolMessageId = 'tc-task-completion-tool';
+ const toolCallId = 'tc-task-completion-tool-call';
+ await serverDB.insert(messages).values([
+ {
+ content: 'I started the background task',
+ id: rootAssistantId,
+ role: 'assistant',
+ tools: [{ id: toolCallId }],
+ topicId: workspaceTopicId,
+ userId: authorId,
+ workspaceId: workspaceAId,
+ },
+ {
+ content: 'background task result',
+ id: toolMessageId,
+ parentId: rootAssistantId,
+ role: 'tool',
+ topicId: workspaceTopicId,
+ userId: authorId,
+ workspaceId: workspaceAId,
+ },
+ {
+ content: 'the post-task summary shown last',
+ id: 'tc-task-completion-summary',
+ metadata: {
+ signal: {
+ sourceToolCallId: toolCallId,
+ sourceToolName: 'backgroundTask',
+ type: 'task-completion',
+ },
+ },
+ parentId: toolMessageId,
+ role: 'assistant',
+ topicId: workspaceTopicId,
+ userId: authorId,
+ workspaceId: workspaceAId,
+ },
+ ]);
+ await serverDB.insert(messagePlugins).values({
+ id: toolMessageId,
+ toolCallId,
+ userId: authorId,
+ workspaceId: workspaceAId,
+ });
+
+ const result = await authorModel.createWithMentions({
+ clientId: 'client-task-completion-preview',
+ content: 'comment on the completed task reply',
+ messageId: rootAssistantId,
+ topicId: workspaceTopicId,
+ });
+
+ expect(result.comment.anchorPreview?.excerpt).toBe('the post-task summary shown last');
+ });
+
+ it('should keep an empty preview for an assistant group with no authored text', async () => {
+ const rootAssistantId = 'tc-tool-only-group-root';
+ await serverDB.insert(messages).values({
+ content: '',
+ id: rootAssistantId,
+ role: 'assistant',
+ tools: [{ id: 'tc-tool-only-call' }],
+ topicId: workspaceTopicId,
+ userId: authorId,
+ workspaceId: workspaceAId,
+ });
+
+ const result = await authorModel.createWithMentions({
+ clientId: 'client-tool-only-group',
+ content: 'comment on a tool-only reply',
+ messageId: rootAssistantId,
+ topicId: workspaceTopicId,
+ });
+
+ expect(result.comment.anchorPreview).toEqual({ excerpt: '', role: 'assistant' });
+ });
+
+ it('should truncate a derived group preview without splitting a surrogate pair', async () => {
+ const rootAssistantId = 'tc-long-group-root';
+ await serverDB.insert(messages).values([
+ {
+ content: '',
+ id: rootAssistantId,
+ role: 'assistant',
+ tools: [{ id: 'tc-long-group-tool-call' }],
+ topicId: workspaceTopicId,
+ userId: authorId,
+ workspaceId: workspaceAId,
+ },
+ {
+ content: 'a'.repeat(199) + '😀 and more text',
+ id: 'tc-long-group-final',
+ parentId: rootAssistantId,
+ role: 'assistant',
+ topicId: workspaceTopicId,
+ userId: authorId,
+ workspaceId: workspaceAId,
+ },
+ ]);
+
+ const result = await authorModel.createWithMentions({
+ clientId: 'client-long-group-preview',
+ content: 'comment on a long grouped reply',
+ messageId: rootAssistantId,
+ topicId: workspaceTopicId,
+ });
+
+ expect(result.comment.anchorPreview?.excerpt).toBe('a'.repeat(199));
+ });
+
it('should not split a surrogate pair at the excerpt cut (jsonb rejects lone surrogates)', async () => {
// 199 ASCII chars put the 200th code unit in the middle of the emoji's
// surrogate pair — a bare slice(0, 200) would keep a lone high
diff --git a/packages/database/src/models/topicComment.ts b/packages/database/src/models/topicComment.ts
index a374d95f368..305efdd0e43 100644
--- a/packages/database/src/models/topicComment.ts
+++ b/packages/database/src/models/topicComment.ts
@@ -1,3 +1,6 @@
+import { LOADING_FLAT } from '@lobechat/const';
+import { parse, resolveAssistantGroupFinalContent } from '@lobechat/conversation-flow';
+import type { UIChatMessage } from '@lobechat/types';
import { truncateSurrogateSafe } from '@lobechat/utils';
import type { SQL } from 'drizzle-orm';
import {
@@ -21,7 +24,7 @@ import {
} from 'drizzle-orm';
import { alias } from 'drizzle-orm/pg-core';
-import { messages } from '../schemas/message';
+import { messagePlugins, messages } from '../schemas/message';
import { topics } from '../schemas/topic';
import type { TopicCommentAnchorPreview, TopicCommentItem } from '../schemas/topicComment';
import { topicCommentMentions, topicComments } from '../schemas/topicComment';
@@ -55,6 +58,11 @@ const topicCommentChildren = alias(topicComments, 'topic_comment_children');
*/
const ANCHOR_PREVIEW_MAX_LENGTH = 200;
+const normalizeAnchorPreviewContent = (content?: string | null) => {
+ if (!content?.trim() || content === LOADING_FLAT) return;
+ return content;
+};
+
/**
* Deletion-stable keyset cursor over the exact database `(createdAt, id)` key.
* The timestamp is selected as text so PostgreSQL microseconds survive the
@@ -238,6 +246,91 @@ export class TopicCommentModel {
return this.workspaceId;
};
+ private resolveAnchorPreviewExcerpt = async (
+ db: LobeChatDatabase,
+ anchor: {
+ content: string | null;
+ groupId: string | null;
+ id: string;
+ role: string;
+ threadId: string | null;
+ },
+ topicId: string,
+ workspaceId: string,
+ ) => {
+ let content = normalizeAnchorPreviewContent(anchor.content);
+ if (anchor.role === 'assistant') {
+ // Fetch only this reply's non-user descendant tree. A normal topic query
+ // pages at 1000 rows and can omit an older anchor or its final answer;
+ // stopping at user turns keeps the chain complete without loading the
+ // rest of a long conversation. Include the immediate user parent because
+ // conversation-flow uses it to recognize a toolless narration as the head
+ // of the following tool chain.
+ const result = await db.execute(sql`
+ WITH RECURSIVE anchor_reply(id) AS (
+ SELECT id
+ FROM messages
+ WHERE id = ${anchor.id}
+ AND topic_id = ${topicId}
+ AND workspace_id = ${workspaceId}
+ AND group_id IS NOT DISTINCT FROM ${anchor.groupId}
+ AND thread_id IS NOT DISTINCT FROM ${anchor.threadId}
+ UNION
+ SELECT child.id
+ FROM messages child
+ JOIN anchor_reply parent ON child.parent_id = parent.id
+ WHERE child.role <> 'user'
+ AND child.topic_id = ${topicId}
+ AND child.workspace_id = ${workspaceId}
+ AND child.group_id IS NOT DISTINCT FROM ${anchor.groupId}
+ AND child.thread_id IS NOT DISTINCT FROM ${anchor.threadId}
+ )
+ SELECT id FROM anchor_reply
+ UNION
+ SELECT parent.id
+ FROM messages anchor
+ JOIN messages parent ON parent.id = anchor.parent_id
+ WHERE anchor.id = ${anchor.id}
+ AND parent.role = 'user'
+ AND parent.topic_id = ${topicId}
+ AND parent.workspace_id = ${workspaceId}
+ AND parent.group_id IS NOT DISTINCT FROM ${anchor.groupId}
+ AND parent.thread_id IS NOT DISTINCT FROM ${anchor.threadId}
+ `);
+ const messageIds = (result.rows as { id: string }[]).map(({ id }) => id);
+ // Preview reconstruction only needs conversation-flow's structural fields.
+ // Avoid MessageModel.queryWithWhere here: it also hydrates files, parsed
+ // documents, RAG chunks, translations, TTS and other UI relations while
+ // this transaction holds the topic lock.
+ const messageList = await db
+ .select({
+ agentId: messages.agentId,
+ content: messages.content,
+ createdAt: messages.createdAt,
+ groupId: messages.groupId,
+ id: messages.id,
+ metadata: messages.metadata,
+ parentId: messages.parentId,
+ role: messages.role,
+ targetId: messages.targetId,
+ threadId: messages.threadId,
+ tool_call_id: messagePlugins.toolCallId,
+ tools: messages.tools,
+ updatedAt: messages.updatedAt,
+ })
+ .from(messages)
+ .leftJoin(messagePlugins, eq(messagePlugins.id, messages.id))
+ .where(and(inArray(messages.id, messageIds), isNull(messages.messageGroupId)))
+ .orderBy(asc(messages.createdAt), asc(messages.id));
+ const { flatList } = parse(messageList as UIChatMessage[]);
+ content =
+ resolveAssistantGroupFinalContent(flatList.find((message) => message.id === anchor.id)) ??
+ content;
+ }
+
+ return truncateSurrogateSafe(content ?? '', ANCHOR_PREVIEW_MAX_LENGTH);
+ };
+
/**
* Non-owners can read their own recoverable placeholder. Everyone can read
* a recoverable root while active replies need its thread structure. The
@@ -313,8 +406,10 @@ export class TopicCommentModel {
const [message] = await tx
.select({
content: messages.content,
+ groupId: messages.groupId,
id: messages.id,
role: messages.role,
+ threadId: messages.threadId,
topicId: messages.topicId,
userId: messages.userId,
})
@@ -326,7 +421,12 @@ export class TopicCommentModel {
throw new Error(TOPIC_COMMENT_MESSAGE_NOT_IN_TOPIC);
anchorPreview = {
- excerpt: truncateSurrogateSafe(message.content ?? '', ANCHOR_PREVIEW_MAX_LENGTH),
+ excerpt: await this.resolveAnchorPreviewExcerpt(
+ tx as LobeChatDatabase,
+ message,
+ params.topicId,
+ workspaceId,
+ ),
role: message.role,
};
messageOwnerUserId = message.userId;
diff --git a/packages/database/src/schemas/topicComment.ts b/packages/database/src/schemas/topicComment.ts
index 2c0f5294e2f..f6ccbb9fee4 100644
--- a/packages/database/src/schemas/topicComment.ts
+++ b/packages/database/src/schemas/topicComment.ts
@@ -14,9 +14,16 @@ import { workspaces } from './workspace';
* created. Messages are hard-deleted (no tombstones anywhere in the domain),
* so this snapshot is the only way to keep rendering the comment's context
* after its anchor message is gone.
+ *
+ * `excerpt` is up to the first 200 UTF-16 code units of the final authored text
+ * block in the anchored reply as conversation-flow renders it. For an assistant
+ * group this is normally the final answer or post-task summary, not the virtual
+ * root's empty content, a trailing workflow status, tool output, reasoning,
+ * errors, signal callbacks or council members. It is empty only when the reply
+ * has no authored text.
*/
export interface TopicCommentAnchorPreview {
- /** Truncated plain-text excerpt of the anchored message */
+ /** Truncated authored-text excerpt of the anchored display message */
excerpt: string;
/** Message role at snapshot time, e.g. 'user' | 'assistant' */
role?: string;
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 3b3d90177e4..900c637e777 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -1473,7 +1473,7 @@ export default {
'topic.saveCurrentMessages': 'Save current conversation as topic',
'topic.viewAll': 'View All Topics',
'topicComment.anchor': 'Original message',
- 'topicComment.anchorDeleted': 'Original message deleted',
+ 'topicComment.anchorDeletedTag': 'Deleted',
'topicComment.anchorEmpty': 'Empty message',
'topicComment.author.deactivated': 'Deleted user',
'topicComment.author.former': 'Former member',
diff --git a/packages/types/src/topicComment.ts b/packages/types/src/topicComment.ts
index 70106a09921..faaf6bc4769 100644
--- a/packages/types/src/topicComment.ts
+++ b/packages/types/src/topicComment.ts
@@ -4,6 +4,10 @@ export type TopicCommentJson =
boolean | number | string | null | TopicCommentJson[] | { [key: string]: TopicCommentJson };
export interface TopicCommentAnchorPreview {
+ /**
+ * Server-derived excerpt of the final authored text block in the anchored
+ * display message, truncated to at most 200 UTF-16 code units.
+ */
excerpt: string;
role?: string;
}
diff --git a/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.ts b/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.ts
index 7357421fd45..a27158827be 100644
--- a/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.ts
+++ b/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.ts
@@ -2,6 +2,7 @@ import {
formatBrowserMcpShortLabel,
formatLinearMcpShortLabel,
} from '@lobechat/builtin-tool-claude-code/client/labels';
+import { isAssistantGroupStatusText } from '@lobechat/conversation-flow';
import { type ChatToolPayloadWithResult } from '@lobechat/types';
import { t } from 'i18next';
@@ -37,26 +38,7 @@ export const areWorkflowToolsComplete = (tools: ChatToolPayloadWithResult[]): bo
* is treated as real prose and lifted out of the fold so it renders inline in reading order.
*/
export const isFoldableStatusLine = (block: AssistantContentBlock): boolean => {
- const raw = (block.content ?? '').trim();
- if (!raw || raw === LOADING_FLAT) return true;
-
- // A status line is a single line; any newline means paragraphed prose.
- if (raw.includes('\n')) return false;
-
- // Markdown heading or list marker → structured deliverable, not a status line.
- if (
- new RegExp(`^#{1,${WORKFLOW_MARKDOWN_HEADING_MAX_LEVEL}}\\s`).test(raw) ||
- /^[-*]\s+\S/.test(raw)
- )
- return false;
-
- // A long run-on line reads as prose even without a second sentence.
- if (raw.length > WORKFLOW_PROSE_HEADLINE_MAX_CHARS) return false;
-
- // Fold only a single sentence. Latin .!? count only at a real sentence boundary
- // (end or whitespace) so dotted tokens like "src/a.ts" or "Node.js" don't inflate it.
- const sentenceCount = (raw.match(/[。!?]|[.!?](?=\s|$)/g) ?? []).length;
- return sentenceCount <= 1;
+ return isAssistantGroupStatusText(block.content);
};
/**
diff --git a/src/features/Portal/TopicComments/AnchorPreview.tsx b/src/features/Portal/TopicComments/AnchorPreview.tsx
index 6716c2d1373..2d5f740a6b9 100644
--- a/src/features/Portal/TopicComments/AnchorPreview.tsx
+++ b/src/features/Portal/TopicComments/AnchorPreview.tsx
@@ -1,5 +1,5 @@
import type { TopicCommentItem } from '@lobechat/types';
-import { Flexbox, Icon, Text } from '@lobehub/ui';
+import { Flexbox, Icon, Tag, Text } from '@lobehub/ui';
import { MessageSquareText } from 'lucide-react';
import { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
@@ -9,6 +9,7 @@ import { displayMessageSelectors } from '@/store/chat/selectors';
import {
highlightMessageWhenScrollSettles,
+ isTopicCommentAnchorDeleted,
resolveTopicCommentMessageLocation,
} from './messageLocator';
import { styles } from './styles';
@@ -26,25 +27,26 @@ const AnchorPreview = memo<{ comment: TopicCommentItem }>(({ comment }) => {
return [location?.index ?? -1, location?.elementId, s.mainConversationScrollToIndex] as const;
});
- const hasMessage = messageIndex >= 0;
+ const canLocateMessage = messageIndex >= 0;
+ const isDeleted = isTopicCommentAnchorDeleted(comment.messageId);
const locateMessage = useCallback(() => {
- if (!messageElementId || !hasMessage || !scrollToIndex) return;
+ if (!messageElementId || !canLocateMessage || !scrollToIndex) return;
requestAnimationFrame(() => {
scrollToIndex(messageIndex, { align: 'center', smooth: true });
highlightMessageWhenScrollSettles(messageElementId);
});
- }, [hasMessage, messageElementId, messageIndex, scrollToIndex]);
+ }, [canLocateMessage, messageElementId, messageIndex, scrollToIndex]);
if (!comment.anchorPreview) return null;
return (
<Flexbox
- aria-disabled={hasMessage ? undefined : true}
+ aria-disabled={canLocateMessage ? undefined : true}
className={styles.anchor}
gap={4}
- role={hasMessage ? 'button' : undefined}
- tabIndex={hasMessage ? 0 : undefined}
+ role={canLocateMessage ? 'button' : undefined}
+ tabIndex={canLocateMessage ? 0 : undefined}
onClick={locateMessage}
onKeyDown={(event) => {
if (event.key !== 'Enter' && event.key !== ' ') return;
@@ -55,8 +57,9 @@ const AnchorPreview = memo<{ comment: TopicCommentItem }>(({ comment }) => {
<Flexbox horizontal align={'center'} gap={6}>
<Icon icon={MessageSquareText} size={14} />
<Text fontSize={12} weight={500}>
- {hasMessage ? t('topicComment.anchor') : t('topicComment.anchorDeleted')}
+ {t('topicComment.anchor')}
</Text>
+ {isDeleted && <Tag size={'small'}>{t('topicComment.anchorDeletedTag')}</Tag>}
</Flexbox>
<Text ellipsis={{ rows: 2 }} fontSize={12} type={'secondary'}>
{comment.anchorPreview.excerpt || t('topicComment.anchorEmpty')}
diff --git a/src/features/Portal/TopicComments/messageLocator.test.ts b/src/features/Portal/TopicComments/messageLocator.test.ts
index 74ce8591f3a..53e94da0c63 100644
--- a/src/features/Portal/TopicComments/messageLocator.test.ts
+++ b/src/features/Portal/TopicComments/messageLocator.test.ts
@@ -5,9 +5,17 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
highlightMessageWhenScrollSettles,
+ isTopicCommentAnchorDeleted,
resolveTopicCommentMessageLocation,
} from './messageLocator';
+describe('isTopicCommentAnchorDeleted', () => {
+ it('uses the persisted foreign-key state instead of current message locatability', () => {
+ expect(isTopicCommentAnchorDeleted('message-not-currently-loaded')).toBe(false);
+ expect(isTopicCommentAnchorDeleted(null)).toBe(true);
+ });
+});
+
describe('resolveTopicCommentMessageLocation', () => {
it('locates a main-conversation message at its rendered index', () => {
expect(
diff --git a/src/features/Portal/TopicComments/messageLocator.ts b/src/features/Portal/TopicComments/messageLocator.ts
index 9ce07e6b136..78396a8d9b6 100644
--- a/src/features/Portal/TopicComments/messageLocator.ts
+++ b/src/features/Portal/TopicComments/messageLocator.ts
@@ -11,6 +11,9 @@ const MESSAGE_HIGHLIGHT_POSITION_EPSILON = 0.5;
const MESSAGE_HIGHLIGHT_SETTLE_MS = 150;
let messageHighlightSequence = 0;
+/** The message FK is SET NULL on deletion; absence from the currently loaded list is not deletion. */
+export const isTopicCommentAnchorDeleted = (messageId: string | null) => messageId === null;
+
export const resolveTopicCommentMessageLocation = (
messages: LocatableMessage[],
messageId: string | null,