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(chat): fold completed agent turn process (#16431)

Arvin Xue0cf68b6c635
diff --git a/locales/en-US/labs.json b/locales/en-US/labs.json
index 7d1e79ceb10..853f8e309e4 100644
--- a/locales/en-US/labs.json
+++ b/locales/en-US/labs.json
@@ -7,7 +7,7 @@
"features.assistantMessageGroup.title": "Agent Message Grouping",
"features.fleet.desc": "Show the Fleet entry in the title bar — a side-by-side dashboard of all running tasks across your agents.",
"features.fleet.title": "Fleet View",
- "features.foldFinishedTurn.desc": "Collapse the process (reasoning and tool calls) of finished, non-latest agent turns under a \"Processed\" header. The final answer stays visible; click to expand the process.",
+ "features.foldFinishedTurn.desc": "Collapse the process (reasoning and tool calls) of finished agent turns under a \"Processed\" header once the final answer is visible. Click to expand the process.",
"features.foldFinishedTurn.title": "Fold Finished Turns",
"features.groupChat.desc": "Enable multi-agent group chat coordination.",
"features.groupChat.title": "Group Chat (Multi-Agent)",
diff --git a/locales/zh-CN/labs.json b/locales/zh-CN/labs.json
index 95f950a769c..b41e328e397 100644
--- a/locales/zh-CN/labs.json
+++ b/locales/zh-CN/labs.json
@@ -7,7 +7,7 @@
"features.assistantMessageGroup.title": "代理消息分组",
"features.fleet.desc": "在标题栏显示 Fleet 入口——把当前账号下所有运行中的任务并排展示的看板。",
"features.fleet.title": "Fleet 并排视图",
- "features.foldFinishedTurn.desc": "将已完成、非最新回合的过程(推理与工具调用)折叠进「已处理」标题,最终回答始终显示;点击可展开过程。",
+ "features.foldFinishedTurn.desc": "当最终回答可见后,将已完成回合的过程(推理与工具调用)折叠进「已处理」标题;点击可展开过程。",
"features.foldFinishedTurn.title": "折叠已完成回合",
"features.groupChat.desc": "启用多代理协同群聊功能。",
"features.groupChat.title": "群聊(多代理)",
diff --git a/packages/locales/src/default/labs.ts b/packages/locales/src/default/labs.ts
index a458680f1e9..c03ce807f7e 100644
--- a/packages/locales/src/default/labs.ts
+++ b/packages/locales/src/default/labs.ts
@@ -12,7 +12,7 @@ export default {
'Show the Fleet entry in the title bar — a side-by-side dashboard of all running tasks across your agents.',
'features.fleet.title': 'Fleet View',
'features.foldFinishedTurn.desc':
- 'Collapse the process (reasoning and tool calls) of finished, non-latest agent turns under a "Processed" header. The final answer stays visible; click to expand the process.',
+ 'Collapse the process (reasoning and tool calls) of finished agent turns under a "Processed" header once the final answer is visible. Click to expand the process.',
'features.foldFinishedTurn.title': 'Fold Finished Turns',
'features.imessage.desc':
'Connect agents to iMessage through the local LobeHub Desktop BlueBubbles bridge.',
diff --git a/packages/types/src/user/preference.ts b/packages/types/src/user/preference.ts
index 0b6cca8c185..271a33e4b4f 100644
--- a/packages/types/src/user/preference.ts
+++ b/packages/types/src/user/preference.ts
@@ -51,7 +51,7 @@ export const UserLabSchema = z.object({
*/
enableFleet: z.boolean().optional(),
/**
- * fold a finished, non-latest agent turn's process under a "已处理" header
+ * fold a finished agent turn's process under a "已处理" header when its final answer is visible
*/
enableFoldFinishedTurn: z.boolean().optional(),
/**
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/Group.test.tsx b/src/features/Conversation/Messages/AssistantGroup/components/Group.test.tsx
index 2f6b4d1fd1d..d00e48ab970 100644
--- a/src/features/Conversation/Messages/AssistantGroup/components/Group.test.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/components/Group.test.tsx
@@ -5,6 +5,7 @@ import { cleanup, render, screen } from '@testing-library/react';
import type { ReactNode } from 'react';
import { afterEach, describe, expect, it, vi } from 'vitest';
+import { LOADING_FLAT } from '@/const/message';
import type { AssistantContentBlock } from '@/types/index';
import Group from './Group';
@@ -22,6 +23,16 @@ vi.mock('antd-style', () => ({
}),
}));
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (state: unknown) => unknown) => selector({}),
+}));
+
+vi.mock('@/store/chat/slices/operation/selectors', () => ({
+ operationSelectors: {
+ getOperationsByMessage: () => () => [],
+ },
+}));
+
// Mock the council list so importing Group doesn't pull in the AgentCouncil
// render chain (→ shared-tool-ui inspectors → antd-style `keyframes`), which is
// out of scope for this unit test.
@@ -86,6 +97,21 @@ vi.mock('./WorkflowCollapse', () => ({
),
}));
+vi.mock('./ProcessFold', () => ({
+ default: ({
+ children,
+ stepCount,
+ }: {
+ children?: ReactNode;
+ durationText?: string;
+ stepCount: number;
+ }) => (
+ <div data-step-count={stepCount} data-testid="process-fold">
+ {children}
+ </div>
+ ),
+}));
+
vi.mock('./GroupItem', () => ({
default: ({
content,
@@ -323,6 +349,32 @@ describe('Group', () => {
]);
});
+ it('does not fold the latest process behind a non-renderable final answer placeholder', () => {
+ render(
+ <Group
+ enableProcessFold
+ isLatestItem
+ id="assistant-1"
+ messageIndex={0}
+ blocks={[
+ blk({
+ content: 'I will run the checks.',
+ id: 'block-1',
+ tools: [
+ { apiName: 'bash', id: 'tool-1', result: { content: 'ok' } } as any,
+ { apiName: 'bash', id: 'tool-2', result: { content: 'ok' } } as any,
+ ],
+ }),
+ blk({ content: LOADING_FLAT, id: 'block-2' }),
+ ]}
+ />,
+ );
+
+ expect(screen.queryByTestId('process-fold')).not.toBeInTheDocument();
+ expect(screen.getByTestId('workflow-segment')).toBeInTheDocument();
+ expect(screen.queryByTestId('answer-segment')).not.toBeInTheDocument();
+ });
+
it('keeps assistant runtime errors outside the workflow collapse', () => {
const { container } = render(
<Group
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/Group.tsx b/src/features/Conversation/Messages/AssistantGroup/components/Group.tsx
index 81e3d9f1757..80eed52dfbf 100644
--- a/src/features/Conversation/Messages/AssistantGroup/components/Group.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/components/Group.tsx
@@ -5,6 +5,9 @@ import { memo, useMemo } from 'react';
import { LOADING_FLAT } from '@/const/message';
import ContentLoading from '@/features/Conversation/Messages/components/ContentLoading';
+import { useChatStore } from '@/store/chat';
+import { operationSelectors } from '@/store/chat/slices/operation/selectors';
+import type { OperationStatus } from '@/store/chat/slices/operation/types';
import type { AssistantContentBlock } from '@/types/index';
import { messageStateSelectors, useConversationStore } from '../../../store';
@@ -20,7 +23,13 @@ import {
import { CollapsedMessage } from './CollapsedMessage';
import GroupItem from './GroupItem';
import ProcessFold from './ProcessFold';
-import { type GroupRenderSegment, shouldFoldProcess, splitFinalAnswer } from './segments';
+import type { GroupRenderSegment } from './segments';
+import {
+ countFoldedProcessSteps,
+ hasRenderableFinalAnswer,
+ shouldFoldProcess,
+ splitFinalAnswer,
+} from './segments';
import type { RenderableAssistantContentBlock } from './types';
import WorkflowCollapse, { type WorkflowExpandLevelDefault } from './WorkflowCollapse';
@@ -83,6 +92,7 @@ interface PartitionedBlocks {
const ANSWER_DOM_ID_SUFFIX = '__answer';
const WORKFLOW_DOM_ID_SUFFIX = '__workflow';
+const ACTIVE_OPERATION_STATUSES = new Set<OperationStatus>(['pending', 'paused', 'running']);
const isEmptyBlock = (block: RenderableAssistantContentBlock) =>
(!block.content || block.content === LOADING_FLAT) &&
@@ -398,6 +408,11 @@ const Group = memo<GroupChildrenProps>(
messageStateSelectors.isMessageCollapsed(id)(s),
messageStateSelectors.isAssistantGroupItemGenerating(id)(s),
]);
+ const hasActiveOperation = useChatStore((s) =>
+ operationSelectors
+ .getOperationsByMessage(id)(s)
+ .some((op) => ACTIVE_OPERATION_STATUSES.has(op.status)),
+ );
const turnDurationMs = useConversationStore((s) => getTurnDurationMs(s.dbMessages, blocks));
const contextValue = useMemo(() => ({ assistantGroupId: id }), [id]);
const lastBlockId = blocks.at(-1)?.id;
@@ -499,15 +514,19 @@ const Group = memo<GroupChildrenProps>(
);
};
- // Codex-style turn folding: once a turn is finished and no longer the latest
- // one, fold its whole process (reasoning + tools + intermediate prose) under
- // a single "已处理 {duration}" header, leaving the final answer always
- // visible. The latest / still-generating turn renders in full.
+ // Codex-style turn folding: once the turn's op has ended, fold its whole
+ // process (reasoning + tools + intermediate prose) under a single "已处理
+ // {duration}" header, leaving the final answer always visible. The latest
+ // turn folds only after a final answer exists; still-generating turns render
+ // in full.
const { processSegments, finalSegments } = splitFinalAnswer(segments);
+ const processStepCount = countFoldedProcessSteps(processSegments);
const foldProcess = shouldFoldProcess({
enabled: enableProcessFold,
+ hasFinalAnswer: hasRenderableFinalAnswer(finalSegments),
isGenerating,
isLatestItem,
+ operationEnded: !hasActiveOperation,
processSegments,
});
@@ -519,7 +538,7 @@ const Group = memo<GroupChildrenProps>(
<Flexbox className={styles.container} gap={8}>
{foldProcess ? (
<>
- <ProcessFold durationText={durationText} stepCount={blocks.length}>
+ <ProcessFold durationText={durationText} stepCount={processStepCount}>
<Flexbox gap={8}>
{processSegments.map((segment) =>
renderSegment(segment, segments.indexOf(segment)),
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/segments.test.ts b/src/features/Conversation/Messages/AssistantGroup/components/segments.test.ts
index 95d3e92b156..60bdac0dfee 100644
--- a/src/features/Conversation/Messages/AssistantGroup/components/segments.test.ts
+++ b/src/features/Conversation/Messages/AssistantGroup/components/segments.test.ts
@@ -1,9 +1,24 @@
import { describe, expect, it } from 'vitest';
-import { shouldFoldProcess, splitFinalAnswer } from './segments';
+import { LOADING_FLAT } from '@/const/message';
-const a = (id: string) => ({ block: { id } as any, kind: 'answer' as const });
-const w = (id: string) => ({ blocks: [{ id } as any], kind: 'workflow' as const });
+import {
+ countFoldedProcessSteps,
+ hasRenderableFinalAnswer,
+ shouldFoldProcess,
+ splitFinalAnswer,
+} from './segments';
+
+const a = (id: string, content = 'answer') => ({
+ block: { content, id } as any,
+ kind: 'answer' as const,
+});
+const tools = (count: number) =>
+ Array.from({ length: count }, (_, index) => ({ id: `tool-${index}` }) as any);
+const w = (id: string, toolCount = 0) => ({
+ blocks: [{ id, tools: toolCount > 0 ? tools(toolCount) : undefined } as any],
+ kind: 'workflow' as const,
+});
describe('splitFinalAnswer', () => {
it('treats the trailing run of answer segments as the final answer', () => {
@@ -52,42 +67,129 @@ describe('splitFinalAnswer', () => {
});
});
+describe('countFoldedProcessSteps', () => {
+ it('counts folded assistant blocks and tool calls', () => {
+ const segments = [w('b1', 2), a('b2'), w('b3', 1)];
+
+ expect(countFoldedProcessSteps(segments)).toBe(6);
+ });
+
+ 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),
+ ];
+
+ expect(countFoldedProcessSteps(segments)).toBe(5);
+ });
+});
+
+describe('hasRenderableFinalAnswer', () => {
+ it('ignores empty settled answer placeholders', () => {
+ expect(hasRenderableFinalAnswer([a('empty', '')])).toBe(false);
+ expect(hasRenderableFinalAnswer([a('loading', LOADING_FLAT)])).toBe(false);
+ });
+
+ it('detects an answer segment that will render visible content', () => {
+ expect(hasRenderableFinalAnswer([w('t1'), a('final', 'Done.')])).toBe(true);
+ expect(
+ hasRenderableFinalAnswer([
+ {
+ block: { content: '', error: { message: 'failed' }, id: 'error-answer' } as any,
+ kind: 'answer',
+ },
+ ]),
+ ).toBe(true);
+ });
+});
+
describe('shouldFoldProcess', () => {
const proc = [w('t1')];
it('folds a finished, non-latest turn that has a workflow when enabled', () => {
- expect(shouldFoldProcess({ enabled: true, isGenerating: false, processSegments: proc })).toBe(
- true,
- );
+ expect(
+ shouldFoldProcess({
+ enabled: true,
+ isGenerating: false,
+ operationEnded: true,
+ processSegments: proc,
+ }),
+ ).toBe(true);
});
it('never folds when the lab flag is disabled', () => {
- expect(shouldFoldProcess({ enabled: false, isGenerating: false, processSegments: proc })).toBe(
- false,
- );
- expect(shouldFoldProcess({ isGenerating: false, processSegments: proc })).toBe(false);
+ expect(
+ shouldFoldProcess({
+ enabled: false,
+ isGenerating: false,
+ operationEnded: true,
+ processSegments: proc,
+ }),
+ ).toBe(false);
+ expect(
+ shouldFoldProcess({ isGenerating: false, operationEnded: true, processSegments: proc }),
+ ).toBe(false);
});
- it('never folds the latest turn', () => {
+ it('never folds before the operation has ended', () => {
expect(
shouldFoldProcess({
enabled: true,
+ hasFinalAnswer: true,
isGenerating: false,
isLatestItem: true,
+ operationEnded: false,
+ processSegments: proc,
+ }),
+ ).toBe(false);
+ });
+
+ it('folds a finished latest turn once a final answer is visible', () => {
+ expect(
+ shouldFoldProcess({
+ enabled: true,
+ hasFinalAnswer: true,
+ isGenerating: false,
+ isLatestItem: true,
+ operationEnded: true,
+ processSegments: proc,
+ }),
+ ).toBe(true);
+ });
+
+ it('keeps a latest tool-only turn expanded when no final answer is visible', () => {
+ expect(
+ shouldFoldProcess({
+ enabled: true,
+ hasFinalAnswer: false,
+ isGenerating: false,
+ isLatestItem: true,
+ operationEnded: true,
processSegments: proc,
}),
).toBe(false);
});
it('never folds while generating', () => {
- expect(shouldFoldProcess({ enabled: true, isGenerating: true, processSegments: proc })).toBe(
- false,
- );
+ expect(
+ shouldFoldProcess({
+ enabled: true,
+ isGenerating: true,
+ operationEnded: true,
+ processSegments: proc,
+ }),
+ ).toBe(false);
});
it('does not fold when the process has no workflow (e.g. pure prose)', () => {
expect(
- shouldFoldProcess({ enabled: true, isGenerating: false, processSegments: [a('p1')] }),
+ shouldFoldProcess({
+ enabled: true,
+ isGenerating: false,
+ operationEnded: true,
+ processSegments: [a('p1')],
+ }),
).toBe(false);
});
});
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/segments.ts b/src/features/Conversation/Messages/AssistantGroup/components/segments.ts
index f8bb6c3efd9..5e3f42931c4 100644
--- a/src/features/Conversation/Messages/AssistantGroup/components/segments.ts
+++ b/src/features/Conversation/Messages/AssistantGroup/components/segments.ts
@@ -1,3 +1,5 @@
+import { LOADING_FLAT } from '@/const/message';
+
import type { RenderableAssistantContentBlock } from './types';
export interface AnswerSegment {
@@ -50,24 +52,64 @@ export const splitFinalAnswer = (
};
};
+export const countFoldedProcessSteps = (segments: GroupRenderSegment[]): number => {
+ const assistantBlockIds = new Set<string>();
+ let toolCount = 0;
+
+ for (const segment of segments) {
+ if (segment.kind === 'answer') {
+ assistantBlockIds.add(segment.block.id);
+ continue;
+ }
+
+ for (const block of segment.blocks) {
+ assistantBlockIds.add(block.id);
+ toolCount += block.tools?.length ?? 0;
+ }
+ }
+
+ return assistantBlockIds.size + toolCount;
+};
+
+export const hasRenderableFinalAnswer = (segments: GroupRenderSegment[]): boolean =>
+ segments.some((segment) => {
+ if (segment.kind !== 'answer') return false;
+
+ const block = segment.block;
+ const content = (block.contentOverride ?? block.content)?.trim();
+
+ return (
+ (!!content && content !== LOADING_FLAT) ||
+ !!block.council?.length ||
+ !!block.error ||
+ !!block.reasoning?.content?.trim()
+ );
+ });
+
/**
* Whether a turn folds its process under the "已处理" header. Gated by the
- * `enabled` lab flag, then: only a finished (not generating), non-latest turn
- * that actually has a workflow to fold. The latest / still-generating turn
- * always renders in full.
+ * `enabled` lab flag, then: only after the associated operation has ended and
+ * the message is not generating. The latest turn is eligible only once its final
+ * answer is visible, so a tool-only latest turn does not collapse into a lone
+ * header.
*/
export const shouldFoldProcess = ({
enabled,
+ hasFinalAnswer,
isGenerating,
isLatestItem,
+ operationEnded,
processSegments,
}: {
enabled?: boolean;
+ hasFinalAnswer?: boolean;
isGenerating: boolean;
isLatestItem?: boolean;
+ operationEnded: boolean;
processSegments: GroupRenderSegment[];
}): boolean =>
!!enabled &&
- !isLatestItem &&
+ operationEnded &&
+ (!isLatestItem || !!hasFinalAnswer) &&
!isGenerating &&
processSegments.some((segment) => segment.kind === 'workflow');