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.

♻️ refactor(conversation-flow): centralize assistant group answer semantics (#17621)

AmAzing-6293cf3ef716
diff --git a/packages/conversation-flow/src/__tests__/assistantGroupContent.test.ts b/packages/conversation-flow/src/__tests__/assistantGroupContent.test.ts
index 65feaa2f171..58b12af9978 100644
--- a/packages/conversation-flow/src/__tests__/assistantGroupContent.test.ts
+++ b/packages/conversation-flow/src/__tests__/assistantGroupContent.test.ts
@@ -1,35 +1,56 @@
import type { AssistantContentBlock, UIChatMessage } from '@lobechat/types';
import { describe, expect, it } from 'vitest';
+import type {
+ AssistantGroupAnswerSegment,
+ AssistantGroupWorkflowSegment,
+} from '../assistantGroupContent';
import {
isAssistantGroupStatusText,
+ partitionAssistantGroupBlocks,
resolveAssistantGroupFinalContent,
+ splitAssistantGroupFinalAnswer,
} from '../assistantGroupContent';
-const block = (
- id: string,
- content: string,
- options: Pick<AssistantContentBlock, 'tools'> = {},
-): AssistantContentBlock => ({ content, id, ...options });
+type BlockOptions = Partial<Omit<AssistantContentBlock, 'content' | 'id'>>;
+
+const tool = (id: string) =>
+ ({ apiName: 'testTool', id }) as NonNullable<AssistantContentBlock['tools']>[number];
+
+const block = (id: string, content: string, options: BlockOptions = {}): AssistantContentBlock => ({
+ content,
+ id,
+ ...options,
+});
+
+const answerSegment = (id: string, content = 'answer'): AssistantGroupAnswerSegment => ({
+ block: block(id, content),
+ kind: 'answer',
+});
+
+const workflowSegment = (id: string): AssistantGroupWorkflowSegment => ({
+ blocks: [block(id, '', { tools: [tool(`${id}-tool`)] })],
+ kind: 'workflow',
+});
const group = (
children: AssistantContentBlock[],
taskCompletions?: AssistantContentBlock[],
-): UIChatMessage =>
- ({
- children,
- content: '',
- createdAt: 0,
- id: 'assistant-group',
- role: 'assistantGroup',
- taskCompletions,
- updatedAt: 0,
- }) as UIChatMessage;
+): UIChatMessage => ({
+ children,
+ content: '',
+ createdAt: 0,
+ id: 'assistant-group',
+ role: 'assistantGroup',
+ taskCompletions,
+ updatedAt: 0,
+});
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('Upgraded to Node.js 24.')).toBe(true);
expect(isAssistantGroupStatusText('First sentence. Second sentence.')).toBe(false);
expect(isAssistantGroupStatusText('Summary\n\nMore detail')).toBe(false);
@@ -37,30 +58,195 @@ describe('isAssistantGroupStatusText', () => {
expect(isAssistantGroupStatusText('- Result')).toBe(false);
expect(isAssistantGroupStatusText('x'.repeat(101))).toBe(false);
});
+
+ it.each(['第一句话。第二句话。', '第一句话!第二句话!', '第一句话?第二句话?'])(
+ 'recognizes CJK sentence boundaries in %s',
+ (content) => {
+ expect(isAssistantGroupStatusText(content)).toBe(false);
+ },
+ );
+});
+
+describe('partitionAssistantGroupBlocks', () => {
+ it('keeps a single-tool mixed block in workflow and the earlier answer final', () => {
+ const answer = block('answer', 'This is the visible final answer.');
+ const mixedTool = block(
+ 'mixed-tool',
+ 'This long tool narration has multiple sentences. It remains workflow content.',
+ { tools: [tool('only-tool')] },
+ );
+ const { segments } = partitionAssistantGroupBlocks([answer, mixedTool], {
+ isGenerating: false,
+ });
+
+ expect(segments.map(({ kind }) => kind)).toEqual(['answer', 'workflow']);
+ expect(segments[1]).toMatchObject({
+ blocks: [{ content: mixedTool.content, id: mixedTool.id }],
+ kind: 'workflow',
+ });
+ expect(splitAssistantGroupFinalAnswer(segments).finalSegments).toEqual([
+ { block: answer, kind: 'answer' },
+ ]);
+ });
+
+ it('projects answer-like mixed content out of a multi-tool workflow', () => {
+ const detailedAnswer =
+ 'The migration is complete. All affected paths now share the same invariant.';
+ const { segments } = partitionAssistantGroupBlocks(
+ [
+ block('status', 'I will inspect the code.', { tools: [tool('read-call')] }),
+ block('answer-with-tool', detailedAnswer, { tools: [tool('update-call')] }),
+ ],
+ { isGenerating: false },
+ );
+
+ expect(segments.map(({ kind }) => kind)).toEqual(['workflow', 'answer', 'workflow']);
+ expect(segments[1]).toMatchObject({
+ block: {
+ content: detailedAnswer,
+ id: 'answer-with-tool',
+ projection: 'answer',
+ tools: undefined,
+ },
+ kind: 'answer',
+ });
+ expect(segments[2]).toMatchObject({
+ blocks: [
+ {
+ content: '',
+ id: 'answer-with-tool',
+ projection: 'workflow',
+ tools: [expect.objectContaining({ id: 'update-call' })],
+ },
+ ],
+ kind: 'workflow',
+ });
+ });
+
+ it('promotes a substantive post-tool answer as soon as the tool phase settles', () => {
+ const { postToolTailPromoted, segments } = partitionAssistantGroupBlocks(
+ [
+ block('tool-step', 'Searching.', { tools: [tool('search-call')] }),
+ block('answer', 'The search is complete. Here are the results.'),
+ ],
+ { isGenerating: true, toolsPhaseComplete: true },
+ );
+
+ expect(postToolTailPromoted).toBe(true);
+ expect(segments.map(({ kind }) => kind)).toEqual(['workflow', 'answer']);
+ });
+
+ it('keeps a short post-tool status in workflow while generating', () => {
+ const { postToolTailPromoted, segments } = partitionAssistantGroupBlocks(
+ [
+ block('tool-step', 'Searching.', { tools: [tool('search-call')] }),
+ block('status', 'Now I will summarize the results.'),
+ ],
+ { isGenerating: true, toolsPhaseComplete: true },
+ );
+
+ expect(postToolTailPromoted).toBe(false);
+ expect(segments.map(({ kind }) => kind)).toEqual(['workflow']);
+ });
+});
+
+describe('splitAssistantGroupFinalAnswer', () => {
+ it('keeps only the last answer run outside the process', () => {
+ const segments = [
+ workflowSegment('tool-1'),
+ answerSegment('intro'),
+ workflowSegment('tool-2'),
+ answerSegment('final-1'),
+ answerSegment('final-2'),
+ ];
+ const { processSegments, finalSegments } = splitAssistantGroupFinalAnswer(segments);
+
+ expect(processSegments).toEqual([
+ workflowSegment('tool-1'),
+ answerSegment('intro'),
+ workflowSegment('tool-2'),
+ ]);
+ expect(finalSegments).toEqual([answerSegment('final-1'), answerSegment('final-2')]);
+ });
+
+ it('keeps the final answer visible before a trailing bookkeeping workflow', () => {
+ const summary = answerSegment('summary');
+ const trailingWorkflow = workflowSegment('mark-done');
+ const { processSegments, finalSegments } = splitAssistantGroupFinalAnswer([
+ workflowSegment('tool-1'),
+ summary,
+ trailingWorkflow,
+ ]);
+
+ expect(processSegments).toEqual([workflowSegment('tool-1'), trailingWorkflow]);
+ expect(finalSegments).toEqual([summary]);
+ });
+
+ it('returns no final answer for a workflow-only group', () => {
+ const segments = [workflowSegment('tool-1'), workflowSegment('tool-2')];
+
+ expect(splitAssistantGroupFinalAnswer(segments)).toEqual({
+ finalSegments: [],
+ processSegments: segments,
+ });
+ });
+
+ it('treats a pure-answer turn as entirely final', () => {
+ const segments = [answerSegment('only')];
+
+ expect(splitAssistantGroupFinalAnswer(segments)).toEqual({
+ finalSegments: segments,
+ processSegments: [],
+ });
+ });
});
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],
+ block('status', 'Now I will update the issue.', { tools: [tool('tool-call')] }),
+ ]);
+
+ expect(resolveAssistantGroupFinalContent(message)).toBe('This is the actual answer.');
+ });
+
+ it('uses shared single-tool semantics instead of treating mixed tool prose as final', () => {
+ const message = group([
+ block('answer', 'This is the answer outside the workflow.'),
+ block(
+ 'mixed-tool',
+ 'This long tool narration has multiple sentences. It remains workflow content.',
+ { tools: [tool('only-tool')] },
+ ),
+ ]);
+
+ expect(resolveAssistantGroupFinalContent(message)).toBe(
+ 'This is the answer outside the workflow.',
+ );
+ });
+
+ it('uses an earlier answer when the final answer run contains only an error', () => {
+ const message = group([
+ block('answer', 'This is the actual answer.'),
+ block('status', 'Now I will update the issue.', { tools: [tool('tool-call')] }),
+ block('error', '', {
+ error: {
+ message: 'The follow-up failed.',
+ type: 'ProviderBizError',
+ },
}),
]);
expect(resolveAssistantGroupFinalContent(message)).toBe('This is the actual answer.');
});
- it('keeps answer-like prose from a mixed tool block', () => {
+ it('keeps answer-like prose projected from a multi-tool mixed 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],
- }),
+ block('status', 'I will inspect the code.', { tools: [tool('read-call')] }),
+ block('answer-with-tool', detailedAnswer, { tools: [tool('update-call')] }),
]);
expect(resolveAssistantGroupFinalContent(message)).toBe(detailedAnswer);
@@ -77,12 +263,8 @@ describe('resolveAssistantGroupFinalContent', () => {
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],
- }),
+ block('status-1', 'Checking the repository.', { tools: [tool('search-call')] }),
+ block('status-2', 'Updating the repository.', { tools: [tool('edit-call')] }),
]);
expect(resolveAssistantGroupFinalContent(message)).toBe('Updating the repository.');
diff --git a/packages/conversation-flow/src/assistantGroupContent.ts b/packages/conversation-flow/src/assistantGroupContent.ts
index 9117caf64f6..9662fda95e9 100644
--- a/packages/conversation-flow/src/assistantGroupContent.ts
+++ b/packages/conversation-flow/src/assistantGroupContent.ts
@@ -1,18 +1,110 @@
import { LOADING_FLAT } from '@lobechat/const';
-import type { UIChatMessage } from '@lobechat/types';
+import type { AssistantContentBlock, UIChatMessage } from '@lobechat/types';
const ASSISTANT_GROUP_STATUS_TEXT_MAX_LENGTH = 100;
const MARKDOWN_HEADING_MAX_LEVEL = 6;
+export type AssistantGroupBlockProjection = 'answer' | 'workflow';
+
+/**
+ * A semantic view of an assistant block. `projection` is present only when one
+ * persisted block must be rendered twice: its answer content outside the fold
+ * and its workflow content inside it.
+ */
+export interface AssistantGroupSemanticBlock extends AssistantContentBlock {
+ projection?: AssistantGroupBlockProjection;
+}
+
+export interface AssistantGroupAnswerSegment<
+ Block extends AssistantContentBlock = AssistantGroupSemanticBlock,
+> {
+ block: Block;
+ kind: 'answer';
+}
+
+export interface AssistantGroupWorkflowSegment<
+ Block extends AssistantContentBlock = AssistantGroupSemanticBlock,
+> {
+ blocks: Block[];
+ kind: 'workflow';
+}
+
+export type AssistantGroupSegment<
+ Block extends AssistantContentBlock = AssistantGroupSemanticBlock,
+> = AssistantGroupAnswerSegment<Block> | AssistantGroupWorkflowSegment<Block>;
+
+export interface PartitionAssistantGroupOptions {
+ isGenerating: boolean;
+ /**
+ * Whether all non-intervention tools have settled. Only used while generating
+ * to promote a streamed post-tool answer before the operation itself ends.
+ */
+ toolsPhaseComplete?: boolean;
+}
+
+export interface PartitionedAssistantGroup {
+ /** Whether a generating post-tool answer was promoted outside the workflow. */
+ postToolTailPromoted: boolean;
+ segments: AssistantGroupSegment[];
+}
+
+export interface SplitAssistantGroupSegments<
+ Block extends AssistantContentBlock = AssistantGroupSemanticBlock,
+> {
+ finalSegments: AssistantGroupSegment<Block>[];
+ processSegments: AssistantGroupSegment<Block>[];
+}
+
const normalizeAuthoredContent = (content?: string | null) => {
if (!content?.trim() || content === LOADING_FLAT) return;
return content;
};
+const hasTools = (block: AssistantContentBlock): boolean => !!block.tools?.length;
+
+const hasSubstantiveContent = (block: AssistantContentBlock): boolean =>
+ !!normalizeAuthoredContent(block.content);
+
+const hasReasoningContent = (block: AssistantContentBlock): boolean =>
+ !!block.reasoning?.content?.trim();
+
+const isTrailingReasoningCandidate = (block: AssistantContentBlock): boolean =>
+ hasReasoningContent(block) && !hasTools(block) && !block.error;
+
+const createProjectedBlock = (
+ block: AssistantContentBlock,
+ projection: AssistantGroupBlockProjection,
+ overrides: Partial<AssistantContentBlock>,
+): AssistantGroupSemanticBlock => ({
+ ...block,
+ ...overrides,
+ projection,
+});
+
+const appendAnswerBlock = (
+ segments: AssistantGroupSegment[],
+ block: AssistantGroupSemanticBlock,
+) => {
+ segments.push({ block, kind: 'answer' });
+};
+
+const appendWorkflowBlock = (
+ segments: AssistantGroupSegment[],
+ block: AssistantGroupSemanticBlock,
+) => {
+ const lastSegment = segments.at(-1);
+
+ if (lastSegment?.kind === 'workflow') {
+ lastSegment.blocks.push(block);
+ return;
+ }
+
+ segments.push({ blocks: [block], kind: 'workflow' });
+};
+
/**
* 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.
+ * This classification is shared by semantic segmentation and every consumer of its output.
*/
export const isAssistantGroupStatusText = (content?: string | null): boolean => {
const raw = content?.trim() ?? '';
@@ -28,31 +120,267 @@ export const isAssistantGroupStatusText = (content?: string | null): boolean =>
return sentenceCount <= 1;
};
+const shouldPromoteMixedBlockContent = (block: AssistantContentBlock): boolean =>
+ hasTools(block) && hasSubstantiveContent(block) && !isAssistantGroupStatusText(block.content);
+
+const appendWorkflowRangeBlock = (
+ segments: AssistantGroupSegment[],
+ block: AssistantContentBlock,
+ collapsesIntoWorkflow: boolean,
+) => {
+ if (block.error) {
+ if (hasTools(block)) {
+ appendWorkflowBlock(
+ segments,
+ createProjectedBlock(block, 'workflow', {
+ content: '',
+ error: undefined,
+ imageList: undefined,
+ reasoning: undefined,
+ }),
+ );
+ appendAnswerBlock(
+ segments,
+ createProjectedBlock(block, 'answer', {
+ reasoning: undefined,
+ tools: undefined,
+ }),
+ );
+ return;
+ }
+
+ appendAnswerBlock(segments, block);
+ return;
+ }
+
+ if (collapsesIntoWorkflow && shouldPromoteMixedBlockContent(block)) {
+ appendAnswerBlock(
+ segments,
+ createProjectedBlock(block, 'answer', {
+ error: undefined,
+ tools: undefined,
+ }),
+ );
+ appendWorkflowBlock(
+ segments,
+ createProjectedBlock(block, 'workflow', {
+ content: '',
+ imageList: undefined,
+ reasoning: undefined,
+ }),
+ );
+ return;
+ }
+
+ appendWorkflowBlock(segments, block);
+};
+
+const appendPostToolBlocks = (
+ segments: AssistantGroupSegment[],
+ postBlocks: AssistantContentBlock[],
+) => {
+ let index = 0;
+ while (index < postBlocks.length) {
+ const block = postBlocks[index]!;
+ if (!isTrailingReasoningCandidate(block)) break;
+
+ appendWorkflowBlock(
+ segments,
+ createProjectedBlock(block, 'workflow', {
+ content: '',
+ }),
+ );
+
+ if (hasSubstantiveContent(block) || (block.imageList?.length ?? 0) > 0) {
+ appendAnswerBlock(
+ segments,
+ createProjectedBlock(block, 'answer', {
+ reasoning: undefined,
+ }),
+ );
+ }
+
+ index += 1;
+ }
+
+ for (const block of postBlocks.slice(index)) {
+ appendAnswerBlock(segments, block);
+ }
+};
+
+const getGeneratingAnswerSplitIndex = (
+ blocks: AssistantContentBlock[],
+ lastToolIndex: number,
+ toolsPhaseComplete: boolean,
+): number | null => {
+ if (!toolsPhaseComplete || lastToolIndex < 0 || lastToolIndex >= blocks.length - 1) return null;
+
+ for (let index = lastToolIndex + 1; index < blocks.length; index += 1) {
+ const block = blocks[index]!;
+ if (hasTools(block)) return null;
+ if (!isAssistantGroupStatusText(block.content)) return index;
+ }
+
+ return null;
+};
+
/**
- * 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.
+ * Partition assistant blocks into stable semantic segments. The result owns the
+ * answer/workflow decision; renderers only decorate the projected blocks with
+ * presentation metadata such as DOM ids.
*/
-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);
+export const partitionAssistantGroupBlocks = (
+ blocks: AssistantContentBlock[],
+ options: PartitionAssistantGroupOptions,
+): PartitionedAssistantGroup => {
+ const segments: AssistantGroupSegment[] = [];
+
+ let lastToolIndex = -1;
+ for (let index = blocks.length - 1; index >= 0; index -= 1) {
+ if (hasTools(blocks[index]!)) {
+ lastToolIndex = index;
+ break;
+ }
+ }
+
+ if (lastToolIndex === -1) {
+ for (const block of blocks) {
+ appendAnswerBlock(segments, block);
+ }
+
+ return { postToolTailPromoted: false, segments };
+ }
+
+ let firstToolIndex = 0;
+ for (let index = 0; index < blocks.length; index += 1) {
+ if (hasTools(blocks[index]!)) {
+ firstToolIndex = index;
+ break;
+ }
+ }
+
+ const totalToolCount = blocks.reduce((sum, block) => sum + (block.tools?.length ?? 0), 0);
+
+ for (const block of blocks.slice(0, firstToolIndex)) {
+ appendAnswerBlock(segments, block);
+ }
+
+ if (options.isGenerating) {
+ const answerSplitIndex = getGeneratingAnswerSplitIndex(
+ blocks,
+ lastToolIndex,
+ !!options.toolsPhaseComplete,
+ );
+ const workflowEndIndex = answerSplitIndex ?? blocks.length;
+
+ for (const block of blocks.slice(firstToolIndex, workflowEndIndex)) {
+ appendWorkflowRangeBlock(segments, block, totalToolCount > 1);
+ }
+
+ for (const block of blocks.slice(workflowEndIndex)) {
+ appendAnswerBlock(segments, block);
+ }
+
+ return {
+ postToolTailPromoted: answerSplitIndex !== null,
+ segments,
+ };
+ }
+
+ for (const block of blocks.slice(firstToolIndex, lastToolIndex + 1)) {
+ appendWorkflowRangeBlock(segments, block, totalToolCount > 1);
+ }
+
+ appendPostToolBlocks(segments, blocks.slice(lastToolIndex + 1));
+
+ return { postToolTailPromoted: false, segments };
+};
+
+/**
+ * Split semantic segments into process and final-answer runs. Trailing workflow
+ * segments remain process even when they follow the final answer.
+ */
+export const splitAssistantGroupFinalAnswer = <Block extends AssistantContentBlock>(
+ segments: AssistantGroupSegment<Block>[],
+): SplitAssistantGroupSegments<Block> => {
+ let lastAnswerIndex = -1;
+ for (let index = segments.length - 1; index >= 0; index -= 1) {
+ if (segments[index]!.kind === 'answer') {
+ lastAnswerIndex = index;
+ break;
+ }
+ }
+
+ if (lastAnswerIndex === -1) {
+ return { finalSegments: [], processSegments: segments };
+ }
+
+ let runStart = lastAnswerIndex;
+ while (runStart > 0 && segments[runStart - 1]!.kind === 'answer') {
+ runStart -= 1;
+ }
+
+ return {
+ finalSegments: segments.slice(runStart, lastAnswerIndex + 1),
+ processSegments: [...segments.slice(0, runStart), ...segments.slice(lastAnswerIndex + 1)],
+ };
+};
+
+interface AssistantGroupAuthoredContent {
+ answer?: string;
+ finalAnswer?: string;
+}
+
+const resolveLatestAnswerContent = (segments: AssistantGroupSegment[]): string | undefined => {
+ for (let index = segments.length - 1; index >= 0; index -= 1) {
+ const segment = segments[index];
+ if (segment?.kind !== 'answer') continue;
+
+ const content = normalizeAuthoredContent(segment.block.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;
+const resolveSegmentedAuthoredContent = (
+ blocks?: AssistantContentBlock[],
+): AssistantGroupAuthoredContent => {
+ if (!blocks?.length) return {};
- latestAuthoredContent ??= content;
- const isTrailingToolStatus =
- !!block?.tools?.length && isAssistantGroupStatusText(block.content);
- if (!isTrailingToolStatus) return content;
+ const { segments } = partitionAssistantGroupBlocks(blocks, { isGenerating: false });
+ const { finalSegments } = splitAssistantGroupFinalAnswer(segments);
+
+ return {
+ answer: resolveLatestAnswerContent(segments),
+ finalAnswer: resolveLatestAnswerContent(finalSegments),
+ };
+};
+
+const resolveLatestAuthoredContent = (blocks?: AssistantContentBlock[]): string | undefined => {
+ for (let index = (blocks?.length ?? 0) - 1; index >= 0; index -= 1) {
+ const content = normalizeAuthoredContent(blocks?.[index]?.content);
+ if (content) return content;
}
+};
+
+/**
+ * Resolve the authored text that best represents a parsed assistant group.
+ *
+ * Both the main chain and post-task summaries use the same settled semantic
+ * segmentation as the renderer. A textless final run (for example, an error-only
+ * block) falls back through earlier answer segments before raw block content so
+ * workflow narration cannot replace an authored answer in the preview.
+ */
+export const resolveAssistantGroupFinalContent = (message?: UIChatMessage): string | undefined => {
+ const taskContent = resolveSegmentedAuthoredContent(message?.taskCompletions);
+ const childContent = resolveSegmentedAuthoredContent(message?.children);
- return normalizeAuthoredContent(message?.content) ?? latestAuthoredContent;
+ return (
+ taskContent.finalAnswer ??
+ childContent.finalAnswer ??
+ normalizeAuthoredContent(message?.content) ??
+ taskContent.answer ??
+ childContent.answer ??
+ resolveLatestAuthoredContent(message?.taskCompletions) ??
+ resolveLatestAuthoredContent(message?.children)
+ );
};
diff --git a/packages/conversation-flow/src/index.ts b/packages/conversation-flow/src/index.ts
index 848f4860110..d7ae4e298b1 100644
--- a/packages/conversation-flow/src/index.ts
+++ b/packages/conversation-flow/src/index.ts
@@ -2,9 +2,21 @@
export { parse } from './parse';
// Assistant group authored-content semantics
+export type {
+ AssistantGroupAnswerSegment,
+ AssistantGroupBlockProjection,
+ AssistantGroupSegment,
+ AssistantGroupSemanticBlock,
+ AssistantGroupWorkflowSegment,
+ PartitionAssistantGroupOptions,
+ PartitionedAssistantGroup,
+ SplitAssistantGroupSegments,
+} from './assistantGroupContent';
export {
isAssistantGroupStatusText,
+ partitionAssistantGroupBlocks,
resolveAssistantGroupFinalContent,
+ splitAssistantGroupFinalAnswer,
} from './assistantGroupContent';
// Topic Doctor - detect and repair message trees the reader cannot fully render
diff --git a/packages/database/src/models/__tests__/topicComment.test.ts b/packages/database/src/models/__tests__/topicComment.test.ts
index b39cfb828e7..38c19a48ef7 100644
--- a/packages/database/src/models/__tests__/topicComment.test.ts
+++ b/packages/database/src/models/__tests__/topicComment.test.ts
@@ -392,6 +392,136 @@ describe('TopicCommentModel', () => {
expect(result.comment.anchorPreview?.excerpt).toBe('This is the actual answer.');
});
+ it('should use shared final-answer semantics for a single mixed tool block', async () => {
+ const userMessageId = 'tc-single-mixed-user';
+ const rootAssistantId = 'tc-single-mixed-root';
+ const mixedAssistantId = 'tc-single-mixed-step';
+ const toolMessageId = 'tc-single-mixed-tool';
+ const toolCallId = 'tc-single-mixed-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 answer outside the workflow.',
+ id: rootAssistantId,
+ parentId: userMessageId,
+ role: 'assistant',
+ topicId: workspaceTopicId,
+ userId: authorId,
+ workspaceId: workspaceAId,
+ },
+ {
+ content: 'This long tool narration has multiple sentences. It remains workflow content.',
+ id: mixedAssistantId,
+ parentId: rootAssistantId,
+ role: 'assistant',
+ tools: [{ id: toolCallId }],
+ topicId: workspaceTopicId,
+ userId: authorId,
+ workspaceId: workspaceAId,
+ },
+ {
+ content: 'issue updated',
+ id: toolMessageId,
+ parentId: mixedAssistantId,
+ 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-single-mixed-preview',
+ content: 'comment on the answer outside the workflow',
+ messageId: rootAssistantId,
+ topicId: workspaceTopicId,
+ });
+
+ expect(result.comment.anchorPreview?.excerpt).toBe(
+ 'This is the answer outside the workflow.',
+ );
+ });
+
+ it('should hydrate assistant errors before resolving a mixed tool-block preview', async () => {
+ const userMessageId = 'tc-mixed-error-user';
+ const rootAssistantId = 'tc-mixed-error-root';
+ const erroredAssistantId = 'tc-mixed-error-step';
+ const toolMessageId = 'tc-mixed-error-tool';
+ const toolCallId = 'tc-mixed-error-call';
+ const erroredAnswer =
+ 'The operation failed after producing this answer. The details remain visible.';
+ 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 earlier answer.',
+ id: rootAssistantId,
+ parentId: userMessageId,
+ role: 'assistant',
+ topicId: workspaceTopicId,
+ userId: authorId,
+ workspaceId: workspaceAId,
+ },
+ {
+ content: erroredAnswer,
+ error: {
+ message: 'The follow-up failed.',
+ type: 'ProviderBizError',
+ },
+ id: erroredAssistantId,
+ parentId: rootAssistantId,
+ role: 'assistant',
+ tools: [{ id: toolCallId }],
+ topicId: workspaceTopicId,
+ userId: authorId,
+ workspaceId: workspaceAId,
+ },
+ {
+ content: 'partial tool result',
+ id: toolMessageId,
+ parentId: erroredAssistantId,
+ 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-mixed-error-preview',
+ content: 'comment on the errored answer outside the workflow',
+ messageId: rootAssistantId,
+ topicId: workspaceTopicId,
+ });
+
+ expect(result.comment.anchorPreview?.excerpt).toBe(erroredAnswer);
+ });
+
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';
diff --git a/packages/database/src/models/topicComment.ts b/packages/database/src/models/topicComment.ts
index 305efdd0e43..293709878c0 100644
--- a/packages/database/src/models/topicComment.ts
+++ b/packages/database/src/models/topicComment.ts
@@ -307,6 +307,7 @@ export class TopicCommentModel {
agentId: messages.agentId,
content: messages.content,
createdAt: messages.createdAt,
+ error: messages.error,
groupId: messages.groupId,
id: messages.id,
metadata: messages.metadata,
diff --git a/packages/database/src/schemas/topicComment.ts b/packages/database/src/schemas/topicComment.ts
index f6ccbb9fee4..1f1b5dc18fd 100644
--- a/packages/database/src/schemas/topicComment.ts
+++ b/packages/database/src/schemas/topicComment.ts
@@ -16,11 +16,11 @@ import { workspaces } from './workspace';
* 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.
+ * block selected by conversation-flow's shared semantic segmentation. 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 authored-text excerpt of the anchored display message */
diff --git a/packages/types/src/topicComment.ts b/packages/types/src/topicComment.ts
index faaf6bc4769..a31e755bafb 100644
--- a/packages/types/src/topicComment.ts
+++ b/packages/types/src/topicComment.ts
@@ -5,8 +5,8 @@ export type 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.
+ * Server-derived excerpt of the final authored text block selected by the
+ * shared assistant-group semantics, truncated to at most 200 UTF-16 code units.
*/
excerpt: string;
role?: string;
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/Group.tsx b/src/features/Conversation/Messages/AssistantGroup/components/Group.tsx
index 43672ba6dc8..290f354a0b3 100644
--- a/src/features/Conversation/Messages/AssistantGroup/components/Group.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/components/Group.tsx
@@ -1,3 +1,11 @@
+import type {
+ AssistantGroupSegment,
+ AssistantGroupSemanticBlock,
+} from '@lobechat/conversation-flow';
+import {
+ partitionAssistantGroupBlocks,
+ splitAssistantGroupFinalAnswer,
+} from '@lobechat/conversation-flow';
import { Flexbox } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
import isEqual from 'fast-deep-equal';
@@ -13,22 +21,12 @@ import type { AssistantContentBlock } from '@/types/index';
import { messageStateSelectors, useConversationStore } from '../../../store';
import CouncilList from '../../AgentCouncil/components/CouncilList';
import { MessageAggregationContext } from '../../Contexts/MessageAggregationContext';
-import {
- areWorkflowToolsComplete,
- formatReasoningDuration,
- getPostToolAnswerSplitIndex,
- isFoldableStatusLine,
-} from '../toolDisplayNames';
+import { areWorkflowToolsComplete, formatReasoningDuration } from '../toolDisplayNames';
import { CollapsedMessage } from './CollapsedMessage';
import GroupItem from './GroupItem';
import ProcessFold from './ProcessFold';
import type { GroupRenderSegment } from './segments';
-import {
- countFoldedProcessSteps,
- hasRenderableFinalAnswer,
- shouldFoldProcess,
- splitFinalAnswer,
-} from './segments';
+import { countFoldedProcessSteps, hasRenderableFinalAnswer, shouldFoldProcess } from './segments';
import type { RenderableAssistantContentBlock } from './types';
import WorkflowCollapse, { type WorkflowExpandLevelDefault } from './WorkflowCollapse';
@@ -118,12 +116,6 @@ const getLastBlockCreatedAt = (
return latest;
};
-interface PartitionedBlocks {
- /** True while generating if long post-tool answer was moved outside the fold (tool phase UI may show “done”). */
- postToolTailPromoted: boolean;
- segments: GroupRenderSegment[];
-}
-
const ANSWER_DOM_ID_SUFFIX = '__answer';
const WORKFLOW_DOM_ID_SUFFIX = '__workflow';
const ACTIVE_OPERATION_STATUSES = new Set<OperationStatus>(['pending', 'paused', 'running']);
@@ -135,255 +127,26 @@ const isEmptyBlock = (block: RenderableAssistantContentBlock) =>
!block.error &&
!block.reasoning;
-/**
- * Check if a block contains any tool calls.
- */
-const hasTools = (block: AssistantContentBlock): boolean => {
- return !!block.tools && block.tools.length > 0;
-};
-
-const hasSubstantiveContent = (block: AssistantContentBlock): boolean => {
- const content = block.content?.trim();
- return !!content && content !== LOADING_FLAT;
-};
-
-const hasReasoningContent = (block: AssistantContentBlock): boolean => {
- return !!block.reasoning?.content?.trim();
-};
-
-const isTrailingReasoningCandidate = (block: AssistantContentBlock): boolean => {
- return hasReasoningContent(block) && !hasTools(block) && !block.error;
-};
+const toRenderableBlock = (block: AssistantGroupSemanticBlock): RenderableAssistantContentBlock => {
+ if (!block.projection) return block;
-const createAnswerRenderBlock = (
- block: AssistantContentBlock,
- overrides: Partial<RenderableAssistantContentBlock> = {},
-): RenderableAssistantContentBlock => {
- const content = 'content' in overrides ? overrides.content : block.content;
- const tools = 'tools' in overrides ? overrides.tools : block.tools;
+ const suffix = block.projection === 'answer' ? ANSWER_DOM_ID_SUFFIX : WORKFLOW_DOM_ID_SUFFIX;
return {
...block,
- contentOverride: content,
- domId: `${block.id}${ANSWER_DOM_ID_SUFFIX}`,
- hasToolsOverride: !!tools?.length,
- renderKey: `${block.id}${ANSWER_DOM_ID_SUFFIX}`,
- ...overrides,
+ contentOverride: block.content,
+ domId: `${block.id}${suffix}`,
+ hasToolsOverride: !!block.tools?.length,
+ renderKey: `${block.id}${suffix}`,
};
};
-const createWorkflowRenderBlock = (
- block: AssistantContentBlock,
- overrides: Partial<RenderableAssistantContentBlock> = {},
-): RenderableAssistantContentBlock => {
- const content = 'content' in overrides ? overrides.content : block.content;
- const tools = 'tools' in overrides ? overrides.tools : block.tools;
-
- return {
- ...block,
- contentOverride: content,
- domId: `${block.id}${WORKFLOW_DOM_ID_SUFFIX}`,
- hasToolsOverride: !!tools?.length,
- renderKey: `${block.id}${WORKFLOW_DOM_ID_SUFFIX}`,
- ...overrides,
- };
-};
-
-const appendAnswerBlock = (
- segments: GroupRenderSegment[],
- block: RenderableAssistantContentBlock,
-) => {
- segments.push({ block, kind: 'answer' });
-};
-
-const appendWorkflowBlock = (
- segments: GroupRenderSegment[],
- block: RenderableAssistantContentBlock,
-) => {
- const lastSegment = segments.at(-1);
-
- if (lastSegment?.kind === 'workflow') {
- lastSegment.blocks.push(block);
- return;
- }
-
- segments.push({ blocks: [block], kind: 'workflow' });
-};
-
-const shouldPromoteMixedBlockContent = (block: AssistantContentBlock): boolean => {
- if (!hasTools(block) || !hasSubstantiveContent(block)) return false;
-
- // Only a single short status line stays folded with its tools; everything else is prose.
- return !isFoldableStatusLine(block);
-};
-
-const appendWorkflowRangeBlock = (
- segments: GroupRenderSegment[],
- block: AssistantContentBlock,
- collapsesIntoWorkflow = false,
-) => {
- if (block.error) {
- if (hasTools(block)) {
- appendWorkflowBlock(
- segments,
- createWorkflowRenderBlock(block, {
- content: '',
- error: undefined,
- imageList: undefined,
- reasoning: undefined,
- }),
- );
- appendAnswerBlock(
- segments,
- createAnswerRenderBlock(block, {
- reasoning: undefined,
- tools: undefined,
- }),
- );
- return;
- }
-
- appendAnswerBlock(segments, block);
- return;
- }
-
- // Mixed blocks keep their natural order: assistant prose precedes tool_use.
- // Short step/status prose belongs with the workflow so adjacent tools can
- // still fold together; answer-like prose is lifted above the fold so it does
- // not disappear inside a collapsed WorkflowCollapse.
- if (collapsesIntoWorkflow && shouldPromoteMixedBlockContent(block)) {
- appendAnswerBlock(
- segments,
- createAnswerRenderBlock(block, {
- error: undefined,
- tools: undefined,
- }),
- );
- appendWorkflowBlock(
- segments,
- createWorkflowRenderBlock(block, {
- content: '',
- imageList: undefined,
- reasoning: undefined,
- }),
- );
- return;
- }
-
- appendWorkflowBlock(segments, block);
-};
-
-const appendPostToolBlocks = (
- segments: GroupRenderSegment[],
- postBlocks: AssistantContentBlock[],
-) => {
- let index = 0;
- while (index < postBlocks.length) {
- const block = postBlocks[index]!;
- if (!isTrailingReasoningCandidate(block)) break;
-
- appendWorkflowBlock(
- segments,
- createWorkflowRenderBlock(block, {
- content: '',
- }),
- );
-
- if (hasSubstantiveContent(block) || (block.imageList?.length ?? 0) > 0) {
- appendAnswerBlock(
- segments,
- createAnswerRenderBlock(block, {
- reasoning: undefined,
- }),
- );
- }
-
- index += 1;
- }
-
- for (const block of postBlocks.slice(index)) {
- appendAnswerBlock(segments, block);
- }
-};
-
-/**
- * Partition blocks into ordered render segments. Workflow segments stay collapsible; answer
- * segments render inline so long prose can remain visible even when tools are present nearby.
- */
-const partitionBlocks = (
- blocks: AssistantContentBlock[],
- isGenerating: boolean,
-): PartitionedBlocks => {
- const segments: GroupRenderSegment[] = [];
-
- let lastToolIndex = -1;
- for (let i = blocks.length - 1; i >= 0; i--) {
- if (hasTools(blocks[i])) {
- lastToolIndex = i;
- break;
- }
- }
-
- if (lastToolIndex === -1) {
- for (const block of blocks) {
- appendAnswerBlock(segments, block);
- }
-
- return { postToolTailPromoted: false, segments };
- }
-
- let firstToolIndex = 0;
- for (let i = 0; i < blocks.length; i++) {
- if (hasTools(blocks[i])) {
- firstToolIndex = i;
- break;
- }
- }
-
- const totalToolCount = blocks.reduce((sum, block) => sum + (block.tools?.length ?? 0), 0);
-
- for (const block of blocks.slice(0, firstToolIndex)) {
- appendAnswerBlock(segments, block);
- }
-
- if (isGenerating) {
- const toolsFlat = blocks.flatMap((b) => b.tools ?? []);
- const toolsPhaseComplete = areWorkflowToolsComplete(toolsFlat);
- let workingEndExclusive = blocks.length;
- let postToolTailPromoted = false;
- if (toolsPhaseComplete) {
- const split = getPostToolAnswerSplitIndex(blocks, lastToolIndex, toolsPhaseComplete, true);
- if (split != null) {
- workingEndExclusive = split;
- postToolTailPromoted = true;
- }
- }
-
- for (const block of blocks.slice(firstToolIndex, workingEndExclusive)) {
- appendWorkflowRangeBlock(segments, block, totalToolCount > 1);
- }
-
- for (const block of blocks.slice(workingEndExclusive)) {
- appendAnswerBlock(segments, block);
- }
-
- return {
- postToolTailPromoted,
- segments,
- };
- }
-
- for (const block of blocks.slice(firstToolIndex, lastToolIndex + 1)) {
- appendWorkflowRangeBlock(segments, block, totalToolCount > 1);
- }
-
- appendPostToolBlocks(segments, blocks.slice(lastToolIndex + 1));
-
- return {
- postToolTailPromoted: false,
- segments,
- };
-};
+const toRenderSegments = (segments: AssistantGroupSegment[]): GroupRenderSegment[] =>
+ segments.map((segment) =>
+ segment.kind === 'answer'
+ ? { block: toRenderableBlock(segment.block), kind: 'answer' }
+ : { blocks: segment.blocks.map(toRenderableBlock), kind: 'workflow' },
+ );
const withMarkdownStreamingState = (
block: RenderableAssistantContentBlock,
@@ -456,10 +219,19 @@ const Group = memo<GroupChildrenProps>(
getLastBlockCreatedAt(s.dbMessages, lastBlock),
);
- const { segments, postToolTailPromoted } = useMemo(
- () => partitionBlocks(blocks, isGenerating),
- [blocks, isGenerating],
- );
+ const { segments, postToolTailPromoted } = useMemo(() => {
+ const partitioned = partitionAssistantGroupBlocks(blocks, {
+ isGenerating,
+ toolsPhaseComplete: isGenerating
+ ? areWorkflowToolsComplete(blocks.flatMap((block) => block.tools ?? []))
+ : undefined,
+ });
+
+ return {
+ postToolTailPromoted: partitioned.postToolTailPromoted,
+ segments: toRenderSegments(partitioned.segments),
+ };
+ }, [blocks, isGenerating]);
const workflowChromeComplete = !isGenerating || postToolTailPromoted;
@@ -573,7 +345,7 @@ const Group = memo<GroupChildrenProps>(
// is eligible only once its final answer exists (so a tool-only latest turn
// does not collapse into a lone header); still-generating turns render in
// full.
- const { processSegments, finalSegments } = splitFinalAnswer(segments);
+ const { processSegments, finalSegments } = splitAssistantGroupFinalAnswer(segments);
const processStepCount = countFoldedProcessSteps(processSegments);
const foldProcess = shouldFoldProcess({
enabled: enableProcessFold,
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/segments.test.ts b/src/features/Conversation/Messages/AssistantGroup/components/segments.test.ts
index 60bdac0dfee..f270498387e 100644
--- a/src/features/Conversation/Messages/AssistantGroup/components/segments.test.ts
+++ b/src/features/Conversation/Messages/AssistantGroup/components/segments.test.ts
@@ -2,12 +2,7 @@ import { describe, expect, it } from 'vitest';
import { LOADING_FLAT } from '@/const/message';
-import {
- countFoldedProcessSteps,
- hasRenderableFinalAnswer,
- shouldFoldProcess,
- splitFinalAnswer,
-} from './segments';
+import { countFoldedProcessSteps, hasRenderableFinalAnswer, shouldFoldProcess } from './segments';
const a = (id: string, content = 'answer') => ({
block: { content, id } as any,
@@ -20,53 +15,6 @@ const w = (id: string, toolCount = 0) => ({
kind: 'workflow' as const,
});
-describe('splitFinalAnswer', () => {
- it('treats the trailing run of answer segments as the final answer', () => {
- const segments = [w('t1'), a('intro'), w('t2'), a('final')];
- const { processSegments, finalSegments } = splitFinalAnswer(segments);
- // intro prose + both tool segments fold into the process
- expect(processSegments).toEqual([w('t1'), a('intro'), w('t2')]);
- expect(finalSegments).toEqual([a('final')]);
- });
-
- it('keeps multiple trailing answer segments together as the final answer', () => {
- const segments = [w('t1'), a('a1'), a('a2')];
- const { processSegments, finalSegments } = splitFinalAnswer(segments);
- expect(processSegments).toEqual([w('t1')]);
- expect(finalSegments).toEqual([a('a1'), a('a2')]);
- });
-
- it('keeps the final answer visible when a trailing bookkeeping tool follows it', () => {
- // The agent writes its summary, then ends the turn on a "mark task done" tool
- // call. The answer must stay out of the fold; only the trailing tool folds.
- const segments = [w('t1'), a('intro'), w('t2'), a('summary'), w('mark-done')];
- const { processSegments, finalSegments } = splitFinalAnswer(segments);
- expect(processSegments).toEqual([w('t1'), a('intro'), w('t2'), w('mark-done')]);
- expect(finalSegments).toEqual([a('summary')]);
- });
-
- it('surfaces the lone answer even when the turn ends on a workflow segment', () => {
- const segments = [a('intro'), w('t1')];
- const { processSegments, finalSegments } = splitFinalAnswer(segments);
- expect(processSegments).toEqual([w('t1')]);
- expect(finalSegments).toEqual([a('intro')]);
- });
-
- it('folds everything when the turn has no answer segment at all', () => {
- const segments = [w('t1'), w('t2')];
- const { processSegments, finalSegments } = splitFinalAnswer(segments);
- expect(processSegments).toEqual([w('t1'), w('t2')]);
- expect(finalSegments).toEqual([]);
- });
-
- it('treats a pure-answer turn as all final, nothing to fold', () => {
- const segments = [a('only')];
- const { processSegments, finalSegments } = splitFinalAnswer(segments);
- expect(processSegments).toEqual([]);
- expect(finalSegments).toEqual([a('only')]);
- });
-});
-
describe('countFoldedProcessSteps', () => {
it('counts folded assistant blocks and tool calls', () => {
const segments = [w('b1', 2), a('b2'), w('b3', 1)];
@@ -75,11 +23,7 @@ describe('countFoldedProcessSteps', () => {
});
it('does not double-count a mixed block split into answer and workflow segments', () => {
- const segments = [
- a('mixed-block'),
- w('mixed-block', 2),
- w('next-block', 1),
- ];
+ const segments = [a('mixed-block'), w('mixed-block', 2), w('next-block', 1)];
expect(countFoldedProcessSteps(segments)).toBe(5);
});
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/segments.ts b/src/features/Conversation/Messages/AssistantGroup/components/segments.ts
index 5e3f42931c4..d9b325f72bb 100644
--- a/src/features/Conversation/Messages/AssistantGroup/components/segments.ts
+++ b/src/features/Conversation/Messages/AssistantGroup/components/segments.ts
@@ -1,56 +1,10 @@
+import type { AssistantGroupSegment } from '@lobechat/conversation-flow';
+
import { LOADING_FLAT } from '@/const/message';
import type { RenderableAssistantContentBlock } from './types';
-export interface AnswerSegment {
- block: RenderableAssistantContentBlock;
- kind: 'answer';
-}
-
-export interface WorkflowSegment {
- blocks: RenderableAssistantContentBlock[];
- kind: 'workflow';
-}
-
-export type GroupRenderSegment = AnswerSegment | WorkflowSegment;
-
-/**
- * Split a turn's render segments into its process and its final answer.
- *
- * The final answer is the *last run* of `answer` segments — even when one or
- * more bookkeeping tool calls (e.g. "mark task done", "update issue") trail it.
- * Those trailing workflow segments fold into the process alongside the leading
- * reasoning/tools so the answer text stays visible, rather than disappearing
- * inside the fold whenever a turn happens to end on a tool call. Everything that
- * is not the final answer — leading tools/reasoning/intermediate prose and any
- * trailing bookkeeping tools — folds under the Codex-style "已处理 {duration}"
- * header. A turn with no answer segment at all has no final answer to surface.
- */
-export const splitFinalAnswer = (
- segments: GroupRenderSegment[],
-): { finalSegments: GroupRenderSegment[]; processSegments: GroupRenderSegment[] } => {
- let lastAnswerIndex = -1;
- for (let i = segments.length - 1; i >= 0; i--) {
- if (segments[i].kind === 'answer') {
- lastAnswerIndex = i;
- break;
- }
- }
-
- if (lastAnswerIndex === -1) {
- return { finalSegments: [], processSegments: segments };
- }
-
- let runStart = lastAnswerIndex;
- while (runStart > 0 && segments[runStart - 1].kind === 'answer') {
- runStart -= 1;
- }
-
- return {
- finalSegments: segments.slice(runStart, lastAnswerIndex + 1),
- processSegments: [...segments.slice(0, runStart), ...segments.slice(lastAnswerIndex + 1)],
- };
-};
+export type GroupRenderSegment = AssistantGroupSegment<RenderableAssistantContentBlock>;
export const countFoldedProcessSteps = (segments: GroupRenderSegment[]): number => {
const assistantBlockIds = new Set<string>();
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/types.ts b/src/features/Conversation/Messages/AssistantGroup/components/types.ts
index cda5348d53b..93ef10c3e88 100644
--- a/src/features/Conversation/Messages/AssistantGroup/components/types.ts
+++ b/src/features/Conversation/Messages/AssistantGroup/components/types.ts
@@ -1,6 +1,6 @@
-import type { AssistantContentBlock } from '@/types/index';
+import type { AssistantGroupSemanticBlock } from '@lobechat/conversation-flow';
-export interface RenderableAssistantContentBlock extends AssistantContentBlock {
+export interface RenderableAssistantContentBlock extends AssistantGroupSemanticBlock {
contentOverride?: string;
disableMarkdownStreaming?: boolean;
domId?: string;
diff --git a/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.test.ts b/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.test.ts
index 1549c142eba..5c1ee206c80 100644
--- a/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.test.ts
+++ b/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.test.ts
@@ -1,13 +1,11 @@
import { describe, expect, it } from 'vitest';
-import { type AssistantContentBlock } from '@/types/index';
+import type { AssistantContentBlock } from '@/types/index';
import {
- getPostToolAnswerSplitIndex,
getToolDisplayName,
getWorkflowStreamingHeadlineState,
getWorkflowSummaryText,
- isFoldableStatusLine,
shapeProseForWorkflowHeadline,
} from './toolDisplayNames';
@@ -119,59 +117,6 @@ describe('shapeProseForWorkflowHeadline', () => {
});
});
-describe('isFoldableStatusLine', () => {
- it('keeps a single short status line folded', () => {
- expect(isFoldableStatusLine(blk({ id: '0', content: '先重建 worktree:' }))).toBe(true);
- expect(isFoldableStatusLine(blk({ id: '1', content: '现在我来搜索资料。' }))).toBe(true);
- });
-
- it('keeps a single sentence with a dotted token folded', () => {
- // "src/a.ts" and "Node.js" must not be counted as extra sentence boundaries.
- expect(isFoldableStatusLine(blk({ id: '0', content: '已更新 src/a.ts 完成。' }))).toBe(true);
- expect(isFoldableStatusLine(blk({ id: '1', content: '升级到 Node.js 24。' }))).toBe(true);
- });
-
- it('treats multi-sentence, multi-line, markdown or long lines as prose', () => {
- expect(isFoldableStatusLine(blk({ id: '0', content: '第一句话。第二句话。' }))).toBe(false);
- expect(isFoldableStatusLine(blk({ id: '1', content: '先总结。\n\n## 下一步' }))).toBe(false);
- expect(isFoldableStatusLine(blk({ id: '2', content: '- 对比方案 A' }))).toBe(false);
- expect(isFoldableStatusLine(blk({ id: '3', content: 'x'.repeat(120) }))).toBe(false);
- });
-
- it('treats empty / loading content as foldable (nothing to lift out)', () => {
- expect(isFoldableStatusLine(blk({ id: '0', content: '' }))).toBe(true);
- });
-});
-
-describe('post-tool answer split', () => {
- it('returns split index for real prose block after last tool', () => {
- const long =
- 'Direct summary - Node.js 24 (released May 6, 2025) is a major platform update that upgrades V8 to a newer track, ships notable HTTP and fetch-related changes, and introduces practical migration items for native addons and tooling.\n\n## Checklist\n\n- Rebuild native modules';
- const blocks = [
- blk({ id: '0', content: 'intro', tools: [{ apiName: 'search', id: 't1' } as any] }),
- blk({ id: '1', content: long }),
- ];
- const ix = getPostToolAnswerSplitIndex(blocks, 0, true, true);
- expect(ix).toBe(1);
- });
-
- it('splits on a multi-sentence prose block after tools', () => {
- const blocks = [
- blk({ id: '0', content: 'x', tools: [{ apiName: 'search', id: 't1' } as any] }),
- blk({ id: '1', content: '先跑测试。全部通过了。' }),
- ];
- expect(getPostToolAnswerSplitIndex(blocks, 0, true, true)).toBe(1);
- });
-
- it('does not split a short single-line step after tools', () => {
- const blocks = [
- blk({ id: '0', content: 'x', tools: [{ apiName: 'search', id: 't1' } as any] }),
- blk({ id: '1', content: '现在我来搜索资料。' }),
- ];
- expect(getPostToolAnswerSplitIndex(blocks, 0, true, true)).toBeNull();
- });
-});
-
describe('reasoning headline extraction', () => {
it('uses the last markdown heading for a trailing thinking-only block', () => {
const state = getWorkflowStreamingHeadlineState([
diff --git a/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.ts b/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.ts
index a27158827be..ce0d351c189 100644
--- a/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.ts
+++ b/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.ts
@@ -2,12 +2,11 @@ import {
formatBrowserMcpShortLabel,
formatLinearMcpShortLabel,
} from '@lobechat/builtin-tool-claude-code/client/labels';
-import { isAssistantGroupStatusText } from '@lobechat/conversation-flow';
-import { type ChatToolPayloadWithResult } from '@lobechat/types';
+import type { ChatToolPayloadWithResult } from '@lobechat/types';
import { t } from 'i18next';
import { LOADING_FLAT } from '@/const/message';
-import { type AssistantContentBlock } from '@/types/index';
+import type { AssistantContentBlock } from '@/types/index';
import {
DURATION_SECONDS_PER_MINUTE,
@@ -31,38 +30,6 @@ export const areWorkflowToolsComplete = (tools: ChatToolPayloadWithResult[]): bo
return collapsible.every((t) => t.result != null && t.result.content !== LOADING_FLAT);
};
-/**
- * A mixed / post-tool prose block that is just a single short status line
- * (e.g. "先重建 worktree:") stays folded together with its tools. Anything richer —
- * multiple lines, markdown structure, more than one sentence, or a long run-on line —
- * is treated as real prose and lifted out of the fold so it renders inline in reading order.
- */
-export const isFoldableStatusLine = (block: AssistantContentBlock): boolean => {
- return isAssistantGroupStatusText(block.content);
-};
-
-/**
- * While generating, first index at or after {@param lastToolIndex} whose prose-only block reads as
- * real prose rather than a one-line status. Tail from here stays out of the workflow fold. Returns
- * null if tooling reappears or nothing qualifies.
- */
-export const getPostToolAnswerSplitIndex = (
- blocks: AssistantContentBlock[],
- lastToolIndex: number,
- toolsPhaseComplete: boolean,
- isGenerating: boolean,
-): number | null => {
- if (!isGenerating || !toolsPhaseComplete || lastToolIndex < 0) return null;
- if (lastToolIndex >= blocks.length - 1) return null;
-
- for (let i = lastToolIndex + 1; i < blocks.length; i++) {
- const b = blocks[i]!;
- if (b.tools && b.tools.length > 0) return null;
- if (!isFoldableStatusLine(b)) return i;
- }
- return null;
-};
-
const toTitleCase = (apiName: string): string => {
return apiName
.replaceAll(/([A-Z])/g, ' $1')