🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(conversation): render queued steer messages as a continuation of the interrupted turn (#19195)
Innei37515dbd1dad
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex dc55a519f1e..d7664748a42 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -1584,6 +1584,7 @@"signalCallbacks.empty": "No callback messages","signalCallbacks.expand": "Show details","signalCallbacks.title": "{{tool}} · {{count}} callback updates",+ "steer.tag": "Steered","stt.action": "Voice Input","stt.loading": "Recognizing...","stt.prettifying": "Polishing...",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 8fa5cede77d..8f2c88c9fcb 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -1584,6 +1584,7 @@"signalCallbacks.empty": "没有回调消息","signalCallbacks.expand": "显示详情","signalCallbacks.title": "{{tool}} · {{count}} 条回调更新",+ "steer.tag": "追加指令","stt.action": "语音输入","stt.loading": "识别中…","stt.prettifying": "润色中…",diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 3802eec4ced..ba22b391ac5 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -1339,6 +1339,7 @@ export default {'sendPlaceholderWithAgentAssignment':'Ask, create, or start a task. @ to assign tasks to other agents.','sender.unknownMember': 'Member',+ 'steer.tag': 'Steered','sessionGroup.config': 'Category Management','sessionGroup.manageCategory': 'Manage Category','sessionGroup.confirmRemoveGroupAlert':diff --git a/packages/types/src/message/common/metadata.ts b/packages/types/src/message/common/metadata.tsindex 6551a364f1b..dbb435f0a97 100644--- a/packages/types/src/message/common/metadata.ts+++ b/packages/types/src/message/common/metadata.ts@@ -254,6 +254,7 @@ export const MessageMetadataSchema = ModelUsageSchema.merge(ModelPerformanceSchescope: z.string().optional(),// External-signal lineage for Monitor-style callback turns ().signal: MessageSignalSchema.optional(),+ steer: z.boolean().optional(),subAgentId: z.string().optional(),// role='taskCallback' card: which task delivered its handoff back to this// conversation, and the run outcome. The card header + jump link read this.@@ -488,6 +489,11 @@ export interface MessageMetadata {* `@lobechat/types` stays free of an adapter-package dependency.*/signal?: MessageSignal;+ /**+ * User message sent from the input queue while the previous turn was still+ * running. Renders as a continuation of that turn instead of a new one.+ */+ steer?: boolean;/*** Sub Agent ID - behavior depends on scope* - scope: 'sub_agent': conversation-flow will transform message.agentId to this value for displaydiff --git a/src/features/Conversation/ChatInput/QueueTray.tsx b/src/features/Conversation/ChatInput/QueueTray.tsxindex 009c0b37706..c4b97f64783 100644--- a/src/features/Conversation/ChatInput/QueueTray.tsx+++ b/src/features/Conversation/ChatInput/QueueTray.tsx@@ -224,6 +224,7 @@ const QueueTray = memo(() => {editorData: msg.editorData,files: filesArray,message: msg.content,+ metadata: { ...msg.metadata, steer: true },});}).catch((error) => console.error('[QueueTray] sendNow failed:', error));diff --git a/src/features/Conversation/ChatItem/ChatItem.tsx b/src/features/Conversation/ChatItem/ChatItem.tsxindex e507ab9eaaa..ebdd1826d30 100644--- a/src/features/Conversation/ChatItem/ChatItem.tsx+++ b/src/features/Conversation/ChatItem/ChatItem.tsx@@ -39,6 +39,7 @@ const ChatItem = memo<ChatItemProps>(onDoubleClick,aboveMessage,belowMessage,+ headerAddon,showAvatar = true,titleAddon,disabled = false,@@ -86,6 +87,7 @@ const ChatItem = memo<ChatItemProps>(>{showAvatar &&(customAvatarRender ? customAvatarRender(avatar, avatarContent) : avatarContent)}+ {headerAddon}<Title avatar={avatar} showTitle={showTitle} time={time} titleAddon={titleAddon} /></Flexbox><Flexboxdiff --git a/src/features/Conversation/ChatItem/type.ts b/src/features/Conversation/ChatItem/type.tsindex 7e058472b4c..98874015b22 100644--- a/src/features/Conversation/ChatItem/type.ts+++ b/src/features/Conversation/ChatItem/type.ts@@ -36,6 +36,8 @@ export interface ChatItemProps extends Omit<FlexboxProps, 'children' | 'onChange*/error?: AlertProps;fontSize?: number;+ /** Rendered in the header row next to the time, independent of `showTitle`. */+ headerAddon?: ReactNode;/*** @description Whether the chat item is in loading state*/diff --git a/src/features/Conversation/ChatList/components/VirtualizedList.tsx b/src/features/Conversation/ChatList/components/VirtualizedList.tsxindex d34db60d29f..e7cfb2d8480 100644--- a/src/features/Conversation/ChatList/components/VirtualizedList.tsx+++ b/src/features/Conversation/ChatList/components/VirtualizedList.tsx@@ -248,7 +248,7 @@ const VirtualizedList = memo<VirtualizedListProps>(for (let i = 0; i < dataSource.length; i++) {const id = dataSource[i];if (!id) continue;- if (messageStateSelectors.isMessageGenerating(id)(s)) indices.push(i);+ if (messageStateSelectors.isRowGenerating(id)(s)) indices.push(i);}return indices;}),@@ -256,7 +256,10 @@ const VirtualizedList = memo<VirtualizedListProps>(// Also keep items that host the active text selection — unmounting a node// containing a Selection endpoint would silently drop the user's highlight.- const selectionMessageIds = useSelectionMessageIds();+ const selectedNodeIds = useSelectionMessageIds();+ const selectionMessageIds = useConversationStore(+ useShallow((s) => new Set([...selectedNodeIds].map((id) => dataSelectors.hostRowOf(id)(s)))),+ );const keepMountedIndices = useMemo(() => {if (selectionMessageIds.size === 0) return streamingIndices;diff --git a/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.test.ts b/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.test.tsindex 1d3631e3f95..0a00a9ce806 100644--- a/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.test.ts+++ b/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.test.ts@@ -172,6 +172,49 @@ describe('useAgentSignalReceipts', () => {expect(result.current.receiptsByAnchor.get('user-1')).toBeUndefined();});+ it('re-anchors steered continuation receipts under the original visible host group', async () => {+ vi.mocked(agentSignalService.listReceipts).mockResolvedValueOnce({+ cursor: undefined,+ receipts: [+ { ...receipt, anchorMessageId: 'assistant-group-2', id: 'receipt-continuation-group' },+ { ...receipt, anchorMessageId: 'assistant-child-2', id: 'receipt-continuation-child' },+ {+ ...receipt,+ anchorMessageId: undefined,+ id: 'receipt-continuation-trigger',+ triggerMessageId: 'steer-1',+ },+ ],+ });++ const { result } = renderReceiptsHook({+ agentId: 'agent-1',+ displayMessages: [+ message({ id: 'user-1', role: 'user' }),+ message({ id: 'assistant-group-1', parentId: 'user-1', role: 'assistantGroup' }),+ message({ id: 'steer-1', metadata: { steer: true }, role: 'user' }),+ message({+ children: [{ content: 'Final assistant step', id: 'assistant-child-2' }],+ id: 'assistant-group-2',+ parentId: 'steer-1',+ role: 'assistantGroup',+ }),+ ],+ enabled: true,+ topicId: 'topic-1',+ });++ await waitFor(() => {+ expect(result.current.receiptsByAnchor.get('assistant-group-1')).toEqual([+ expect.objectContaining({ id: 'receipt-continuation-group' }),+ expect.objectContaining({ id: 'receipt-continuation-child' }),+ expect.objectContaining({ id: 'receipt-continuation-trigger' }),+ ]);+ });+ expect(result.current.receiptsByAnchor.get('assistant-group-2')).toBeUndefined();+ expect(result.current.receiptsByAnchor.get('steer-1')).toBeUndefined();+ });+it('groups trigger-only receipts under the trigger message when no assistant child exists', async () => {vi.mocked(agentSignalService.listReceipts).mockResolvedValueOnce({cursor: undefined,diff --git a/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.ts b/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.tsindex 59f0c2b5619..07b8c2aa5bd 100644--- a/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.ts+++ b/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.ts@@ -5,6 +5,8 @@ import useSWR from 'swr';import { agentSignalKeys } from '@/libs/swr/keys';import { agentSignalService } from '@/services/agentSignal';+import { collectSteerChains } from '../../store/slices/data/steerChains';+/** Poll cadence for the active conversation's Agent Signal receipt surface. */const AGENT_SIGNAL_RECEIPT_INITIAL_REFRESH_INTERVAL_MS = 3000;@@ -139,13 +141,19 @@ const resolveDisplayedAnchorMessageId = (anchorMessageId: string,displayMessages: UIChatMessage[],) => {- if (displayMessages.some((message) => message.id === anchorMessageId)) return anchorMessageId;+ const { hostOf } = collectSteerChains(displayMessages);- return displayMessages.find(+ if (displayMessages.some((message) => message.id === anchorMessageId)) {+ return hostOf.get(anchorMessageId) ?? anchorMessageId;+ }++ const assistantGroupId = displayMessages.find((message) =>message.role === 'assistantGroup' &&message.children?.some((block) => block.id === anchorMessageId),)?.id;++ return assistantGroupId ? (hostOf.get(assistantGroupId) ?? assistantGroupId) : undefined;};const resolveEffectiveAnchorMessageId = (@@ -161,7 +169,7 @@ const resolveEffectiveAnchorMessageId = (receipt.triggerMessageId,displayMessages,);- if (assistantReplyId) return assistantReplyId;+ if (assistantReplyId) return resolveDisplayedAnchorMessageId(assistantReplyId, displayMessages);// Display fallback belongs here, not in the persisted receipt. A trigger-only// receipt tells us why the signal fired; the UI can attach it to the assistantdiff --git a/src/features/Conversation/ChatList/index.tsx b/src/features/Conversation/ChatList/index.tsxindex 2362cc30954..3bc6136bdc1 100644--- a/src/features/Conversation/ChatList/index.tsx+++ b/src/features/Conversation/ChatList/index.tsx@@ -28,6 +28,7 @@ import VirtualizedList from './components/VirtualizedList';import { useAgentSignalReceipts } from './hooks/useAgentSignalReceipts';import { useMessageRefreshError } from './hooks/useMessageRefreshError';import { resolveMessageListFeedback } from './resolveMessageListFeedback';+import { buildChatRows } from './utils/chatRows';import type { MessageDeepLink } from './utils/messageDeepLink';import { resolveMessageDeepLink } from './utils/messageDeepLink';@@ -146,9 +147,20 @@ const ChatList = memo<ChatListProps>([allDisplayMessages, filterItem],);const displayMessageIds = useMemo(() => displayMessages.map((m) => m.id), [displayMessages]);+ // Steered follow-up turns fold into the turn they interrupted. Custom item+ // renderers address messages by id, so they keep the flat list.+ const rows = useMemo(+ () => (itemContent ? undefined : buildChatRows(displayMessages)),+ [displayMessages, itemContent],+ );+ const rowIds = useMemo(+ () => rows?.map((row) => row.id) ?? displayMessageIds,+ [displayMessageIds, rows],+ );+ const rowById = useMemo(() => new Map(rows?.map((row) => [row.id, row])), [rows]);const resolvedMessageDeepLink = useMemo(- () => resolveMessageDeepLink(displayMessages, messageDeepLink),- [displayMessages, messageDeepLink],+ () => resolveMessageDeepLink(displayMessages, rowIds, messageDeepLink),+ [displayMessages, messageDeepLink, rowIds],);const overlayHeight = useConversationStore(inputSelectors.chatInputOverlayHeight);const latestMessageId = displayMessageIds.at(-1);@@ -202,7 +214,8 @@ const ChatList = memo<ChatListProps>(const defaultItemContent = useCallback((index: number, id: string) => {- const isLatestItem = displayMessageIds.length === index + 1;+ const isLatestItem = rowIds.length === index + 1;+ const row = rowById.get(id);const anchoredReceipts = receiptsByAnchor.get(id) ?? [];const receiptRender =anchoredReceipts.length > 0 ? (@@ -211,6 +224,7 @@ const ChatList = memo<ChatListProps>(return (<MessageItem+ continuations={row?.continuations}defaultWorkflowExpandLevel={defaultWorkflowExpandLevel}footerRender={receiptRender}id={id}@@ -219,7 +233,7 @@ const ChatList = memo<ChatListProps>(/>);},- [displayMessageIds.length, defaultWorkflowExpandLevel, receiptsByAnchor],+ [rowIds.length, rowById, defaultWorkflowExpandLevel, receiptsByAnchor],);const messagesInit = useConversationStore(dataSelectors.messagesInit);@@ -276,7 +290,7 @@ const ChatList = memo<ChatListProps>() : (<MessageActionProvider withSingletonActionsBar={!disableActionsBar}><VirtualizedList- dataSource={displayMessageIds}+ dataSource={rowIds}footerSlot={footerSlot}headerSlot={headerSlot}itemContent={itemContent ?? defaultItemContent}diff --git a/src/features/Conversation/ChatList/utils/chatRows.test.ts b/src/features/Conversation/ChatList/utils/chatRows.test.tsnew file mode 100644index 00000000000..500dd28a0d5--- /dev/null+++ b/src/features/Conversation/ChatList/utils/chatRows.test.ts@@ -0,0 +1,76 @@+import type { UIChatMessage } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { buildChatRows } from './chatRows';++const msg = (+ id: string,+ role: UIChatMessage['role'],+ metadata?: UIChatMessage['metadata'],+): UIChatMessage => ({ content: '', createdAt: 0, id, metadata, role, updatedAt: 0 }) as any;++const steered = [+ msg('u1', 'user'),+ msg('g1', 'assistantGroup'),+ msg('s1', 'user', { steer: true }),+ msg('g2', 'assistantGroup'),+ msg('s2', 'user', { steer: true }),+ msg('a3', 'assistant'),+];++describe('buildChatRows', () => {+ it('keeps a plain conversation flat', () => {+ const rows = buildChatRows([+ msg('u1', 'user'),+ msg('g1', 'assistantGroup'),+ msg('u2', 'user'),+ msg('g2', 'assistantGroup'),+ ]);++ expect(rows).toEqual([{ id: 'u1' }, { id: 'g1' }, { id: 'u2' }, { id: 'g2' }]);+ });++ it('folds steer turns into the host row and never lifts the steer messages out', () => {+ expect(buildChatRows(steered)).toEqual([+ { id: 'u1' },+ {+ continuations: [+ { groupId: 'g2', steerUserId: 's1' },+ { groupId: 'a3', steerUserId: 's2' },+ ],+ id: 'g1',+ },+ ]);+ });++ it('is a pure function of the messages', () => {+ expect(buildChatRows(steered)).toEqual(buildChatRows([...steered]));+ });++ it('leaves a steer message flat when nothing follows it or no group precedes it', () => {+ expect(+ buildChatRows([+ msg('u1', 'user'),+ msg('g1', 'assistantGroup'),+ msg('s1', 'user', { steer: true }),+ ]),+ ).toEqual([{ id: 'u1' }, { id: 'g1' }, { id: 's1' }]);++ expect(+ buildChatRows([msg('s1', 'user', { steer: true }), msg('g1', 'assistantGroup')]),+ ).toEqual([{ id: 's1' }, { id: 'g1' }]);+ });++ it('breaks the chain at a regular user message', () => {+ const rows = buildChatRows([+ msg('u1', 'user'),+ msg('g1', 'assistantGroup'),+ msg('u2', 'user'),+ msg('g2', 'assistantGroup'),+ msg('s1', 'user', { steer: true }),+ msg('g3', 'assistantGroup'),+ ]);++ expect(rows.map((row) => row.id)).toEqual(['u1', 'g1', 'u2', 'g2']);+ });+});diff --git a/src/features/Conversation/ChatList/utils/chatRows.ts b/src/features/Conversation/ChatList/utils/chatRows.tsnew file mode 100644index 00000000000..f2954f3db20--- /dev/null+++ b/src/features/Conversation/ChatList/utils/chatRows.ts@@ -0,0 +1,22 @@+import type { UIChatMessage } from '@lobechat/types';++import type { SteerContinuation } from '../../store/slices/data/steerChains';+import { collectSteerChains } from '../../store/slices/data/steerChains';++export interface ChatRow {+ continuations?: SteerContinuation[];+ id: string;+}++export const buildChatRows = (messages: UIChatMessage[]): ChatRow[] => {+ const { byHost, hostOf } = collectSteerChains(messages);+ const rows: ChatRow[] = [];++ for (const message of messages) {+ if (hostOf.has(message.id)) continue;+ const chain = byHost.get(message.id);+ rows.push(chain ? { continuations: chain.continuations, id: message.id } : { id: message.id });+ }++ return rows;+};diff --git a/src/features/Conversation/ChatList/utils/messageDeepLink.test.ts b/src/features/Conversation/ChatList/utils/messageDeepLink.test.tsindex 2cf976f5fb6..fec56ebeb2d 100644--- a/src/features/Conversation/ChatList/utils/messageDeepLink.test.ts+++ b/src/features/Conversation/ChatList/utils/messageDeepLink.test.ts@@ -14,11 +14,14 @@ const message = (id: string, overrides: Partial<UIChatMessage> = {}): UIChatMessconst deepLink = (id: string) => ({ id, navigationKey: 'navigation-1' });+const resolve = (messages: UIChatMessage[], id: string, rowIds = messages.map((m) => m.id)) =>+ resolveMessageDeepLink(messages, rowIds, deepLink(id));+describe('resolveMessageDeepLink', () => {it('returns the top-level virtual row for a direct message', () => {const messages = [message('first'), message('target')];- expect(resolveMessageDeepLink(messages, deepLink('target'))).toMatchObject({+ expect(resolve(messages, 'target')).toMatchObject({displayMessageId: 'target',index: 1,});@@ -36,7 +39,7 @@ describe('resolveMessageDeepLink', () => {}),];- expect(resolveMessageDeepLink(messages, deepLink('assistant-2'))).toMatchObject({+ expect(resolve(messages, 'assistant-2')).toMatchObject({displayMessageId: 'assistant-group',index: 1,});@@ -55,12 +58,31 @@ describe('resolveMessageDeepLink', () => {}),];- expect(resolveMessageDeepLink(messages, deepLink('task-hit'))?.index).toBe(0);- expect(resolveMessageDeepLink(messages, deepLink('council-hit'))?.index).toBe(1);- expect(resolveMessageDeepLink(messages, deepLink('compressed-hit'))?.index).toBe(2);+ expect(resolve(messages, 'task-hit')?.index).toBe(0);+ expect(resolve(messages, 'council-hit')?.index).toBe(1);+ expect(resolve(messages, 'compressed-hit')?.index).toBe(2);});it('returns undefined when the message is not rendered by the list', () => {- expect(resolveMessageDeepLink([message('first')], deepLink('missing'))).toBeUndefined();+ expect(resolve([message('first')], 'missing')).toBeUndefined();+ });++ it('targets the host row for a message folded into a steered chain', () => {+ const messages = [+ message('user'),+ message('group-1', { children: [{ content: '', id: 'group-1' }], role: 'assistantGroup' }),+ message('steer-1', { metadata: { steer: true } }),+ message('group-2', { children: [{ content: '', id: 'child-2' }], role: 'assistantGroup' }),+ ];+ const rowIds = ['user', 'group-1'];++ expect(resolve(messages, 'child-2', rowIds)).toMatchObject({+ displayMessageId: 'group-1',+ index: 1,+ });+ expect(resolve(messages, 'steer-1', rowIds)).toMatchObject({+ displayMessageId: 'group-1',+ index: 1,+ });});});diff --git a/src/features/Conversation/ChatList/utils/messageDeepLink.ts b/src/features/Conversation/ChatList/utils/messageDeepLink.tsindex 18224c98fff..50921201c87 100644--- a/src/features/Conversation/ChatList/utils/messageDeepLink.ts+++ b/src/features/Conversation/ChatList/utils/messageDeepLink.ts@@ -1,5 +1,7 @@import type { AssistantContentBlock, ChatToolPayload, UIChatMessage } from '@lobechat/types';+import { collectSteerChains } from '../../store/slices/data/steerChains';+export interface MessageDeepLink {id: string;navigationKey: string;@@ -45,16 +47,19 @@ function messageContainsMessage(message: UIChatMessage, messageId: string): bool/** Resolves a raw database message id to the virtual list row that renders it. */export const resolveMessageDeepLink = (messages: UIChatMessage[],+ rowIds: string[],deepLink: MessageDeepLink | undefined,): ResolvedMessageDeepLink | undefined => {if (!deepLink) return;- const index = messages.findIndex((message) => messageContainsMessage(message, deepLink.id));+ const owner = messages.find((message) => messageContainsMessage(message, deepLink.id));+ if (!owner) return;++ const displayMessageId = rowIds.includes(owner.id)+ ? owner.id+ : (collectSteerChains(messages).hostOf.get(owner.id) ?? owner.id);+ const index = rowIds.indexOf(displayMessageId);if (index < 0) return;- return {- ...deepLink,- displayMessageId: messages[index].id,- index,- };+ return { ...deepLink, displayMessageId, index };};diff --git a/src/features/Conversation/MessageForward/ForwardModal.tsx b/src/features/Conversation/MessageForward/ForwardModal.tsxindex add3460c65d..7b55de3dcbb 100644--- a/src/features/Conversation/MessageForward/ForwardModal.tsx+++ b/src/features/Conversation/MessageForward/ForwardModal.tsx@@ -11,10 +11,17 @@ import { useTranslation } from 'react-i18next';import AgentAvatar from '@/features/HomeSidebar/Body/Agent/List/AgentItem/Avatar';import { useFetchAgentList } from '@/hooks/useFetchAgentList';+import { getForwardedMessageText } from '@/store/chat/slices/forward/helpers';import { useHomeStore } from '@/store/home';import { homeAgentListSelectors } from '@/store/home/selectors';-import { contextSelectors, type ConversationStore, Provider, useConversationStore } from '../store';+import {+ contextSelectors,+ type ConversationStore,+ messageStateSelectors,+ Provider,+ useConversationStore,+} from '../store';import SelectCircle from './SelectCircle';import { type ForwardTarget, useForwardMessages } from './useForwardMessages';@@ -98,13 +105,12 @@ const ForwardModalContent = memo(() => {// What's being forwarded — count + a few role-labelled snippets for the panel.const preview = useConversationStore((s) => {- const selected = new Set(s.selectedMessageIds);- const msgs = s.displayMessages.filter((m) => selected.has(m.id));+ const msgs = messageStateSelectors.forwardableSelectedMessages(s);return {count: msgs.length,lines: msgs.slice(0, 6).map((m) => ({role: m.role === 'user' ? t('messageForward.role.user') : t('messageForward.role.agent'),- text: (m.content ?? '').replaceAll(/\s+/g, ' ').slice(0, 60),+ text: getForwardedMessageText(m).replaceAll(/\s+/g, ' ').slice(0, 60),})),};}, isEqual);diff --git a/src/features/Conversation/MessageForward/SelectionFooterBar.tsx b/src/features/Conversation/MessageForward/SelectionFooterBar.tsxindex e373e4363e4..13067f3a674 100644--- a/src/features/Conversation/MessageForward/SelectionFooterBar.tsx+++ b/src/features/Conversation/MessageForward/SelectionFooterBar.tsx@@ -44,7 +44,9 @@ const SelectionFooterBar = memo(() => {const [forwardOpen, setForwardOpen] = useState(false);const storeApi = useConversationStoreApi();const selectedCount = useConversationStore(messageStateSelectors.selectedMessageCount);- const selectedMessageIds = useConversationStore((s) => s.selectedMessageIds);+ const selectedMessageIds = useConversationStore(+ messageStateSelectors.selectedDeletableMessageIds,+ );const exitSelectionMode = useConversationStore((s) => s.exitSelectionMode);const deleteMessages = useConversationStore((s) => s.deleteMessages);diff --git a/src/features/Conversation/MessageForward/useForwardMessages.ts b/src/features/Conversation/MessageForward/useForwardMessages.tsindex 4aa7b6898ad..e9fccc2eb87 100644--- a/src/features/Conversation/MessageForward/useForwardMessages.ts+++ b/src/features/Conversation/MessageForward/useForwardMessages.ts@@ -8,7 +8,7 @@ import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwarimport { useChatStore } from '@/store/chat';import type { ForwardTarget } from '@/store/chat/slices/forward/action';-import { useConversationStore } from '../store';+import { messageStateSelectors, useConversationStore } from '../store';export type { ForwardTarget } from '@/store/chat/slices/forward/action';@@ -27,10 +27,10 @@ export const useForwardMessages = () => {// The conversation store is context-scoped (no global getState), so read the// selected messages reactively. They're frozen while the picker is open.- const selectedMessages = useConversationStore((s) => {- const selected = new Set(s.selectedMessageIds);- return s.displayMessages.filter((m) => selected.has(m.id));- }, isEqual);+ const selectedMessages = useConversationStore(+ messageStateSelectors.forwardableSelectedMessages,+ isEqual,+ );return useCallback(async (targets: ForwardTarget[], note?: string) => {diff --git a/src/features/Conversation/Messages/AssistantGroup/components/Group.test.tsx b/src/features/Conversation/Messages/AssistantGroup/components/Group.test.tsxindex 45f35945f5c..71ef5a21503 100644--- a/src/features/Conversation/Messages/AssistantGroup/components/Group.test.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/components/Group.test.tsx@@ -42,6 +42,10 @@ vi.mock('../../../store', () => ({selector({ dbMessages: mockDbMessages }),}));+vi.mock('./SteerMessage', () => ({+ default: ({ id }: { id: string }) => <div data-id={id} data-testid="steer-message" />,+}));+vi.mock('./CollapsedMessage', () => ({CollapsedMessage: ({ content }: { content?: string }) => <div>{content}</div>,}));@@ -874,4 +878,111 @@ describe('Group', () => {'false',);});++ describe('steered continuations', () => {+ const chain1 = [+ blk({+ content: 'Looking into it.',+ id: 'a1',+ tools: [{ apiName: 'search', id: 't1' } as any],+ }),+ blk({ content: 'Turn one answer.', id: 'a2' }),+ ];+ const chain2 = [+ blk({ content: '', id: 'b1', tools: [{ apiName: 'readFile', id: 't2' } as any] }),+ blk({ content: 'Final answer.', id: 'b2' }),+ ];++ it('renders steer bubbles inline between chains while streaming', () => {+ mockIsGenerating = true;++ const { container } = render(+ <Group+ isLatestItem+ blocks={chain1}+ continuations={[{ blocks: chain2, id: 'group-2', steerUserId: 'steer-1' }]}+ id="group-1"+ messageIndex={0}+ />,+ );++ const sequence = Array.from(container.querySelectorAll('[data-testid]')).map((node) =>+ node.getAttribute('data-testid'),+ );+ expect(sequence).toEqual([+ 'answer-segment',+ 'answer-segment',+ 'steer-message',+ 'answer-segment',+ 'answer-segment',+ ]);+ expect(screen.getByTestId('steer-message').getAttribute('data-id')).toBe('steer-1');+ expect(screen.queryByTestId('process-fold')).not.toBeInTheDocument();+ });++ it('folds each turn separately and keeps the steer bubble between the folds', () => {+ mockOperations = [];++ const { container } = render(+ <Group+ enableProcessFold+ isLatestItem+ blocks={chain1}+ continuations={[{ blocks: chain2, id: 'group-2', steerUserId: 'steer-1' }]}+ id="group-1"+ messageIndex={0}+ />,+ );++ const folds = screen.getAllByTestId('process-fold');+ expect(folds.map((fold) => fold.getAttribute('data-step-count'))).toEqual(['2', '2']);++ const steer = screen.getByTestId('steer-message');+ expect(+ folds[0]!.compareDocumentPosition(steer) & Node.DOCUMENT_POSITION_FOLLOWING,+ ).toBeTruthy();+ expect(+ steer.compareDocumentPosition(folds[1]!) & Node.DOCUMENT_POSITION_FOLLOWING,+ ).toBeTruthy();+ expect(folds.some((fold) => fold.contains(steer))).toBe(false);++ const idsIn = (root: Element) =>+ Array.from(root.querySelectorAll('[data-testid="answer-segment"]')).map(+ (node) => JSON.parse(node.getAttribute('data-block') || '{}').id,+ );+ expect(idsIn(folds[0]!)).toEqual(['a1', 'a2']);+ expect(idsIn(folds[1]!)).toEqual(['b1']);++ const outside = Array.from(container.querySelectorAll('[data-testid="answer-segment"]'))+ .filter((node) => !folds.some((fold) => fold.contains(node)))+ .map((node) => JSON.parse(node.getAttribute('data-block') || '{}').id);+ expect(outside).toEqual(['b2']);+ });++ it('skips the fold for a continuation whose whole output is the final answer', () => {+ mockOperations = [];++ render(+ <Group+ enableProcessFold+ isLatestItem+ blocks={chain1}+ id="group-1"+ messageIndex={0}+ continuations={[+ {+ blocks: [blk({ content: 'Final answer.', id: 'b2' })],+ id: 'group-2',+ steerUserId: 'steer-1',+ },+ ]}+ />,+ );++ const folds = screen.getAllByTestId('process-fold');+ expect(folds).toHaveLength(1);+ expect(folds[0]!.getAttribute('data-step-count')).toBe('2');+ expect(screen.getByTestId('steer-message')).toBeInTheDocument();+ });+ });});diff --git a/src/features/Conversation/Messages/AssistantGroup/components/Group.tsx b/src/features/Conversation/Messages/AssistantGroup/components/Group.tsxindex f25de0aeaaf..c3f3b91afe6 100644--- a/src/features/Conversation/Messages/AssistantGroup/components/Group.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/components/Group.tsx@@ -1,17 +1,9 @@-import type {- AssistantGroupSegment,- AssistantGroupSemanticBlock,-} from '@lobechat/conversation-flow';-import {- partitionAssistantGroupBlocks,- splitAssistantGroupFinalAnswer,-} from '@lobechat/conversation-flow';+import { splitAssistantGroupFinalAnswer } from '@lobechat/conversation-flow';import { Flexbox } from '@lobehub/ui';import { createStaticStyles } from 'antd-style';import isEqual from 'fast-deep-equal';-import { memo, useMemo } from 'react';+import { Fragment, 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';@@ -19,17 +11,17 @@ import type { OperationStatus } from '@/store/chat/slices/operation/types';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 } from '../toolDisplayNames';-import { isImageBearingTool } from '../toolRenderRules';+import { formatReasoningDuration } from '../toolDisplayNames';import { CollapsedMessage } from './CollapsedMessage';-import GroupItem from './GroupItem';+import type { GroupChainInput, GroupChainView } from './groupChain';+import { buildChainView, getLastBlockCreatedAt, getTurnDurationMs } from './groupChain';import ProcessFold from './ProcessFold';+import { renderChainSegment } from './renderChainSegment';import type { GroupRenderSegment } from './segments';import { countAssistantLlmCalls, hasRenderableFinalAnswer, shouldFoldProcess } from './segments';-import type { RenderableAssistantContentBlock } from './types';-import WorkflowCollapse, { type WorkflowExpandLevelDefault } from './WorkflowCollapse';+import SteerMessage from './SteerMessage';+import type { WorkflowExpandLevelDefault } from './WorkflowCollapse';const styles = createStaticStyles(({ css }) => {return {@@ -41,10 +33,14 @@ const styles = createStaticStyles(({ css }) => {};});+const ACTIVE_OPERATION_STATUSES = new Set<OperationStatus>(['pending', 'paused', 'running']);+interface GroupChildrenProps {blocks: AssistantContentBlock[];content?: string;contentId?: string;+ /** Later turns steered onto this one; each renders as a continuation of the same chain. */+ continuations?: GroupChainInput[];defaultWorkflowExpandLevel?: WorkflowExpandLevelDefault;disableEditing?: boolean;/** Lab flag: fold finished non-latest turns' process under a "已处理" header. */@@ -55,147 +51,11 @@ interface GroupChildrenProps {messageIndex: number;}-/**- * Wall-clock span of a turn = last − first `createdAt` across the turn's own- * assistant-step messages (the group's child blocks resolved against the raw- * `dbMessages`). The group record's own `createdAt/updatedAt` only covers its- * final step, so it under-reports multi-step turns.- */-const getTurnDurationMs = (- dbMessages: { createdAt?: Date | number | string | null; id: string }[] | undefined,- blocks: AssistantContentBlock[],-): number => {- if (!Array.isArray(dbMessages) || blocks.length < 2) return 0;- const ids = new Set(blocks.map((block) => block.id));- let min = Infinity;- let max = -Infinity;- for (const message of dbMessages) {- if (!ids.has(message.id) || message.createdAt == null) continue;- const time =- message.createdAt instanceof Date- ? message.createdAt.getTime()- : new Date(message.createdAt).getTime();- if (Number.isNaN(time)) continue;- if (time < min) min = time;- if (time > max) max = time;- }- return max > min ? max - min : 0;-};--/**- * `createdAt` of the turn's last step, normalized to epoch ms. Used to anchor the- * tail running indicator's elapsed timer to "time since the last step" instead of- * the whole run — the operation's own startTime marks the run's beginning.- *- * When the last block ends on tool calls, its freshest message is the tool RESULT- * row (`result_msg_id`), created when the tool finished — not the assistant block- * that issued the call. Anchoring to the block id alone would fold the tool's- * runtime back into the elapsed time, defeating the point. So we take the latest- * `createdAt` across the block and its tool-result rows.- */-const getLastBlockCreatedAt = (- dbMessages: { createdAt?: Date | number | string | null; id: string }[] | undefined,- lastBlock: AssistantContentBlock | undefined,-): number | undefined => {- if (!Array.isArray(dbMessages) || !lastBlock) return undefined;-- const candidateIds = new Set<string>([lastBlock.id]);- for (const tool of lastBlock.tools ?? []) {- if (tool.result_msg_id) candidateIds.add(tool.result_msg_id);- }-- let latest: number | undefined;- for (const message of dbMessages) {- if (!candidateIds.has(message.id) || message.createdAt == null) continue;- const time =- message.createdAt instanceof Date- ? message.createdAt.getTime()- : new Date(message.createdAt).getTime();- if (Number.isNaN(time)) continue;- if (latest === undefined || time > latest) latest = time;- }- return latest;-};--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) &&- (!block.tools || block.tools.length === 0) &&- (!block.council || block.council.length === 0) &&- !block.error &&- !block.reasoning;--const toRenderableBlock = (block: AssistantGroupSemanticBlock): RenderableAssistantContentBlock => {- if (!block.projection) return block;-- const suffix = block.projection === 'answer' ? ANSWER_DOM_ID_SUFFIX : WORKFLOW_DOM_ID_SUFFIX;- const key = `${block.projectionKey ?? block.id}${suffix}`;-- return {- ...block,- contentOverride: block.content,- domId: key,- hasToolsOverride: !!block.tools?.length,- renderKey: key,- };-};--const toRenderSegments = (segments: AssistantGroupSegment[]): GroupRenderSegment[] =>- segments.map((segment) =>- segment.kind === 'answer'- ? { block: toRenderableBlock(segment.block), kind: 'answer' }- : { ...segment, blocks: segment.blocks.map(toRenderableBlock) },- );--const withMarkdownStreamingState = (- block: RenderableAssistantContentBlock,- lastBlockId: string | undefined,-): RenderableAssistantContentBlock => ({- ...block,- disableMarkdownStreaming: block.disableMarkdownStreaming || block.id !== lastBlockId,-});--const shouldInlineWorkflowSegment = (blocks: RenderableAssistantContentBlock[]): boolean => {- let toolCount = 0;-- for (const block of blocks) {- toolCount += block.tools?.length ?? 0;- if (toolCount > 1) return false;- }-- return toolCount === 1;-};--/**- * A workflow segment is only the "active" step while it is the last thing in the- * group. Once any later segment has real content below it (e.g. an errored- * tool block whose error text renders as a trailing answer segment), the tools- * are settled and the collapse should read as done rather than keep showing its- * streaming "working" header. Empty trailing blocks (an answer not streamed yet)- * don't count. `postToolTailPromoted` already covers the promoted-final-answer- * path at the group level; this catches the remaining segment-ordering cases.- */-const hasRenderedContentAfter = (segments: GroupRenderSegment[], index: number): boolean =>- segments- .slice(index + 1)- .some((seg) => (seg.kind === 'workflow' ? seg.blocks.length > 0 : !isEmptyBlock(seg.block)));--/**- * A pending intervention still needs the user's confirmation, so the collapse- * must keep its streaming "awaiting confirmation" chrome even when a later- * segment has already rendered below it. `areWorkflowToolsComplete` ignores- * pending tools, so the completion shortcut must not be applied here.- */-const hasPendingIntervention = (blocks: RenderableAssistantContentBlock[]): boolean =>- blocks.some((block) => block.tools?.some((tool) => tool.intervention?.status === 'pending'));-const Group = memo<GroupChildrenProps>(({blocks,contentId,+ continuations,defaultWorkflowExpandLevel,disableEditing,messageIndex,@@ -204,75 +64,62 @@ const Group = memo<GroupChildrenProps>(isLatestItem,enableProcessFold,}) => {- const [isCollapsed, isGenerating] = useConversationStore((s) => [- messageStateSelectors.isMessageCollapsed(id)(s),- messageStateSelectors.isAssistantGroupItemGenerating(id)(s),- ]);+ const chains = useMemo<GroupChainInput[]>(+ () => [{ blocks, contentId, id }, ...(continuations ?? [])],+ [blocks, contentId, continuations, id],+ );+ const [isCollapsed, generatingFlags] = useConversationStore(+ (s) => [+ messageStateSelectors.isMessageCollapsed(id)(s),+ chains.map((chain) => messageStateSelectors.isAssistantGroupItemGenerating(chain.id)(s)),+ ],+ isEqual,+ );// A running op whose visible output already ended (`visible_output_end` →// `metadata.visibleLoadingDone`) only has terminal bookkeeping left// (server-side persistence, agent_runtime_end, completeRun). Treating it as// still active would delay process folding by seconds after the answer// finished streaming. Safe to fold early: `stream_start` resets the flag,// so a follow-up step re-activates the operation.- const hasActiveOperation = useChatStore((s) =>- operationSelectors- .getOperationsByMessage(id)(s)- .some(- (op) =>- ACTIVE_OPERATION_STATUSES.has(op.status) &&- !(op.status === 'running' && op.metadata.visibleLoadingDone),+ const activeFlags = useChatStore(+ (s) =>+ chains.map((chain) =>+ operationSelectors+ .getOperationsByMessage(chain.id)(s)+ .some(+ (op) =>+ ACTIVE_OPERATION_STATUSES.has(op.status) &&+ !(op.status === 'running' && op.metadata.visibleLoadingDone),+ ),),+ isEqual,+ );+ const allBlocks = useMemo(() => chains.flatMap((chain) => chain.blocks), [chains]);+ const chainDurations = useConversationStore(+ (s) => chains.map((chain) => getTurnDurationMs(s.dbMessages, chain.blocks)),+ isEqual,);- const turnDurationMs = useConversationStore((s) => getTurnDurationMs(s.dbMessages, blocks));- const contextValue = useMemo(() => ({ assistantGroupId: id }), [id]);- const lastBlock = blocks.at(-1);- const lastBlockId = lastBlock?.id;+ const lastBlock = allBlocks.at(-1);const lastBlockCreatedAt = useConversationStore((s) =>getLastBlockCreatedAt(s.dbMessages, lastBlock),);+ const contextValues = useMemo(+ () => chains.map((chain) => ({ assistantGroupId: chain.id })),+ [chains],+ );- const { segments, postToolTailPromoted } = useMemo(() => {- const partitioned = partitionAssistantGroupBlocks(blocks, {- isBreakoutTool: isImageBearingTool,- isGenerating,- toolsPhaseComplete: isGenerating- ? areWorkflowToolsComplete(blocks.flatMap((block) => block.tools ?? []))- : undefined,- });-- return {- postToolTailPromoted: partitioned.postToolTailPromoted,- segments: toRenderSegments(partitioned.segments),- };- }, [blocks, isGenerating]);-- const workflowChromeComplete = !isGenerating || postToolTailPromoted;-- // When the turn ends on an inline single-tool segment whose tool already- // settled but the run is still generating (waiting on the next step), the- // inline path renders no working chrome — unlike WorkflowCollapse, which has- // its own streaming header. Without this the user sees a blank gap below the- // finished tool. Render the same "running" indicator used at turn start to- // fill it. Multi-tool segments keep their own chrome; a tool still executing- // is covered by its own loading placeholder (areWorkflowToolsComplete=false).- const lastSegment = segments.at(-1);- // …unless that inline segment already ends on a LOADING_FLAT placeholder:- // that block mounts MessageContent, which renders its OWN "…is running" line- // (ContentBlock gates on text/LOADING_FLAT/tools), so the tail would stack a- // second identical line on top. Narrowly LOADING_FLAT (and tool-less): a- // blank `content: ''` shell — what the gateway emits on stream_start — does- // NOT mount MessageContent, so the tail must stay to fill the gap until the- // first content chunk lands.- const lastInlineBlock =- lastSegment?.kind === 'workflow' ? lastSegment.blocks.at(-1) : undefined;- const lastInlineRendersOwnLoading =- lastInlineBlock?.content === LOADING_FLAT && !lastInlineBlock.tools?.length;- const showTailRunningIndicator =- isGenerating &&- lastSegment?.kind === 'workflow' &&- shouldInlineWorkflowSegment(lastSegment.blocks) &&- areWorkflowToolsComplete(lastSegment.blocks.flatMap((block) => block.tools ?? [])) &&- !lastInlineRendersOwnLoading;+ const views = useMemo(+ () =>+ chains.map((chain, index) =>+ buildChainView(chain, {+ hasActiveOperation: !!activeFlags[index],+ isGenerating: !!generatingFlags[index],+ }),+ ),+ [activeFlags, chains, generatingFlags],+ );+ const lastView = views.at(-1)!;+ const isGenerating = lastView.isGenerating;if (isCollapsed) {return (@@ -284,81 +131,26 @@ const Group = memo<GroupChildrenProps>();}- const renderSegment = (segment: GroupRenderSegment, index: number) => {- if (segment.kind === 'workflow') {- if (segment.blocks.length === 0) return null;-- if (segment.standalone || shouldInlineWorkflowSegment(segment.blocks)) {- return segment.blocks.map((block, blockIndex) => {- const item = withMarkdownStreamingState(block, lastBlockId);- if (!isGenerating && isEmptyBlock(item)) return null;-- return (- <GroupItem- {...item}- assistantId={id}- contentId={contentId}- disableEditing={disableEditing}- key={item.renderKey ?? `${id}.workflow-inline.${index}.${blockIndex}`}- messageIndex={messageIndex}- />- );- });- }-- return (- <WorkflowCollapse- assistantMessageId={id}- blocks={segment.blocks.map((block) => withMarkdownStreamingState(block, lastBlockId))}- defaultWorkflowExpandLevel={defaultWorkflowExpandLevel}- disableEditing={disableEditing}- key={segment.blocks[0]?.renderKey ?? `${id}.workflow.${index}`}- // While the turn's operation is still running, process folding may- // take over the moment it ends: the segment tree re-parents into- // ProcessFold, which remounts WorkflowCollapse already collapsed —- // one non-animated reflow. Letting the collapse also self-animate- // from semi → collapsed first would shrink the layout twice and make- // the conversation jitter. Once the op ends without a fold happening- // (tool-only turn, no final answer), suppression releases and- // WorkflowCollapse applies its completion level then.- suppressAutoCollapse={!!enableProcessFold && hasActiveOperation}- workflowChromeComplete={- workflowChromeComplete ||- (hasRenderedContentAfter(segments, index) && !hasPendingIntervention(segment.blocks))- }- />- );- }-- const item = segment.block;-- // AgentCouncil block: broadcast members rendered as parallel columns inside- // the supervisor's bubble.- if (item.council && item.council.length > 0) {- return (- <CouncilList- activeTab={0}- displayMode={'horizontal'}- key={item.renderKey ?? `${id}.${item.id}.${index}`}- members={item.council}- />- );- }-- if (!isGenerating && isEmptyBlock(item)) return null;-- return (- <GroupItem- {...withMarkdownStreamingState(item, lastBlockId)}- assistantId={id}- contentId={contentId}- disableEditing={disableEditing}- key={item.renderKey ?? `${id}.${item.id}.${index}`}- messageIndex={messageIndex}- />- );+ const renderOptions = {+ defaultWorkflowExpandLevel,+ disableEditing,+ enableProcessFold,+ messageIndex,};+ const renderChain = (+ view: GroupChainView,+ segments: GroupRenderSegment[],+ variant: 'process' | 'final',+ ) => (+ <MessageAggregationContext+ key={`${view.id}.${variant}`}+ value={contextValues[views.indexOf(view)]!}+ >+ {segments.map((segment) => renderChainSegment(view, segment, renderOptions))}+ </MessageAggregationContext>+ );+// 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 — for every@@ -366,45 +158,50 @@ const Group = memo<GroupChildrenProps>(// that is the turn's payload; only the process collapses. The latest turn// 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 } = splitAssistantGroupFinalAnswer(segments);- const llmCallCount = countAssistantLlmCalls(segments);+ // full. Steered continuations fold per turn: every earlier turn's output is+ // process, only the last turn's final answer stays visible, and each steer+ // bubble sits between the fold it interrupted and the fold it started.+ const { processSegments, finalSegments } = splitAssistantGroupFinalAnswer(lastView.segments);+ const processSegmentsOf = (view: GroupChainView) =>+ view === lastView ? processSegments : view.segments;const foldProcess = shouldFoldProcess({enabled: enableProcessFold,hasFinalAnswer: hasRenderableFinalAnswer(finalSegments),isGenerating,isLatestItem,- operationEnded: !hasActiveOperation,- processSegments,+ operationEnded: !views.some((view) => view.hasActiveOperation),+ processSegments: views.flatMap(processSegmentsOf),});- const durationText =- turnDurationMs >= 1000 ? formatReasoningDuration(turnDurationMs) : undefined;+ const renderFold = (view: GroupChainView, index: number) => {+ const segments = processSegmentsOf(view);+ if (segments.length === 0) return null;+ const durationMs = chainDurations[index] ?? 0;+ return (+ <ProcessFold+ durationText={durationMs >= 1000 ? formatReasoningDuration(durationMs) : undefined}+ key={view.id}+ stepCount={countAssistantLlmCalls(view.segments)}+ >+ <Flexbox gap={8}>{renderChain(view, segments, 'process')}</Flexbox>+ </ProcessFold>+ );+ };return (- <MessageAggregationContext value={contextValue}>- <Flexbox className={styles.container} gap={4}>- {foldProcess ? (- <>- <ProcessFold durationText={durationText} stepCount={llmCallCount}>- <Flexbox gap={8}>- {processSegments.map((segment) =>- renderSegment(segment, segments.indexOf(segment)),- )}- </Flexbox>- </ProcessFold>- {finalSegments.map((segment) => renderSegment(segment, segments.indexOf(segment)))}- </>- ) : (- <>- {segments.map((segment, index) => renderSegment(segment, index))}- {showTailRunningIndicator && (- <ContentLoading id={id} startTime={lastBlockCreatedAt} />- )}- </>- )}- </Flexbox>- </MessageAggregationContext>+ <Flexbox className={styles.container} gap={4}>+ {views.map((view, index) => (+ <Fragment key={view.id}>+ {view.steerUserId && <SteerMessage id={view.steerUserId} />}+ {foldProcess ? renderFold(view, index) : renderChain(view, view.segments, 'process')}+ </Fragment>+ ))}+ {foldProcess+ ? renderChain(lastView, finalSegments, 'final')+ : lastView.showTailRunningIndicator && (+ <ContentLoading id={lastView.id} startTime={lastBlockCreatedAt} />+ )}+ </Flexbox>);},isEqual,diff --git a/src/features/Conversation/Messages/AssistantGroup/components/SteerMessage.tsx b/src/features/Conversation/Messages/AssistantGroup/components/SteerMessage.tsxnew file mode 100644index 00000000000..0526dd34b30--- /dev/null+++ b/src/features/Conversation/Messages/AssistantGroup/components/SteerMessage.tsx@@ -0,0 +1,44 @@+import { Flexbox } from '@lobehub/ui';+import { Tag } from '@lobehub/ui/base-ui';+import { createStaticStyles } from 'antd-style';+import isEqual from 'fast-deep-equal';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { dataSelectors, useConversationStore } from '../../../store';+import UserMessageContent from '../../User/components/MessageContent';++const styles = createStaticStyles(({ css, cssVar }) => ({+ bubble: css`+ max-width: 100%;+ padding-block: 8px;+ padding-inline: 12px;+ border-radius: 12px;++ background: ${cssVar.colorFillTertiary};+ `,+}));++interface SteerMessageProps {+ id: string;+}++const SteerMessage = memo<SteerMessageProps>(({ id }) => {+ const { t } = useTranslation('chat');+ const item = useConversationStore(dataSelectors.getDisplayMessageById(id), isEqual);++ if (!item) return null;++ return (+ <Flexbox align={'flex-end'} data-message-id={id} data-steer-message={id}>+ <Flexbox align={'flex-start'} className={styles.bubble} gap={4}>+ <Tag>{t('steer.tag')}</Tag>+ <UserMessageContent {...item} />+ </Flexbox>+ </Flexbox>+ );+});++SteerMessage.displayName = 'SteerMessage';++export default SteerMessage;diff --git a/src/features/Conversation/Messages/AssistantGroup/components/groupChain.ts b/src/features/Conversation/Messages/AssistantGroup/components/groupChain.tsnew file mode 100644index 00000000000..5d3f0d43fae--- /dev/null+++ b/src/features/Conversation/Messages/AssistantGroup/components/groupChain.ts@@ -0,0 +1,219 @@+import type {+ AssistantGroupSegment,+ AssistantGroupSemanticBlock,+} from '@lobechat/conversation-flow';+import { partitionAssistantGroupBlocks } from '@lobechat/conversation-flow';++import { LOADING_FLAT } from '@/const/message';+import type { AssistantContentBlock } from '@/types/index';++import { areWorkflowToolsComplete } from '../toolDisplayNames';+import { isImageBearingTool } from '../toolRenderRules';+import type { GroupRenderSegment } from './segments';+import type { RenderableAssistantContentBlock } from './types';++const ANSWER_DOM_ID_SUFFIX = '__answer';+const WORKFLOW_DOM_ID_SUFFIX = '__workflow';++type DbMessageLike = { createdAt?: Date | number | string | null; id: string };++export interface GroupChainInput {+ blocks: AssistantContentBlock[];+ contentId?: string;+ id: string;+ steerUserId?: string;+}++export interface GroupChainView extends GroupChainInput {+ hasActiveOperation: boolean;+ isGenerating: boolean;+ lastBlockId?: string;+ postToolTailPromoted: boolean;+ segments: GroupRenderSegment[];+ showTailRunningIndicator: boolean;+ workflowChromeComplete: boolean;+}++const toEpochMs = (createdAt: DbMessageLike['createdAt']): number | undefined => {+ if (createdAt == null) return;+ const time = createdAt instanceof Date ? createdAt.getTime() : new Date(createdAt).getTime();+ return Number.isNaN(time) ? undefined : time;+};++/**+ * Wall-clock span of a turn = last − first `createdAt` across the turn's own+ * assistant-step messages (the group's child blocks resolved against the raw+ * `dbMessages`). The group record's own `createdAt/updatedAt` only covers its+ * final step, so it under-reports multi-step turns.+ */+export const getTurnDurationMs = (+ dbMessages: DbMessageLike[] | undefined,+ blocks: AssistantContentBlock[],+): number => {+ if (!Array.isArray(dbMessages) || blocks.length < 2) return 0;+ const ids = new Set(blocks.map((block) => block.id));+ let min = Infinity;+ let max = -Infinity;+ for (const message of dbMessages) {+ if (!ids.has(message.id)) continue;+ const time = toEpochMs(message.createdAt);+ if (time === undefined) continue;+ if (time < min) min = time;+ if (time > max) max = time;+ }+ return max > min ? max - min : 0;+};++/**+ * `createdAt` of the turn's last step, normalized to epoch ms. Used to anchor the+ * tail running indicator's elapsed timer to "time since the last step" instead of+ * the whole run — the operation's own startTime marks the run's beginning.+ *+ * When the last block ends on tool calls, its freshest message is the tool RESULT+ * row (`result_msg_id`), created when the tool finished — not the assistant block+ * that issued the call. Anchoring to the block id alone would fold the tool's+ * runtime back into the elapsed time, defeating the point. So we take the latest+ * `createdAt` across the block and its tool-result rows.+ */+export const getLastBlockCreatedAt = (+ dbMessages: DbMessageLike[] | undefined,+ lastBlock: AssistantContentBlock | undefined,+): number | undefined => {+ if (!Array.isArray(dbMessages) || !lastBlock) return undefined;++ const candidateIds = new Set<string>([lastBlock.id]);+ for (const tool of lastBlock.tools ?? []) {+ if (tool.result_msg_id) candidateIds.add(tool.result_msg_id);+ }++ let latest: number | undefined;+ for (const message of dbMessages) {+ if (!candidateIds.has(message.id)) continue;+ const time = toEpochMs(message.createdAt);+ if (time === undefined) continue;+ if (latest === undefined || time > latest) latest = time;+ }+ return latest;+};++export const isEmptyBlock = (block: RenderableAssistantContentBlock) =>+ (!block.content || block.content === LOADING_FLAT) &&+ (!block.tools || block.tools.length === 0) &&+ (!block.council || block.council.length === 0) &&+ !block.error &&+ !block.reasoning;++const toRenderableBlock = (block: AssistantGroupSemanticBlock): RenderableAssistantContentBlock => {+ if (!block.projection) return block;++ const suffix = block.projection === 'answer' ? ANSWER_DOM_ID_SUFFIX : WORKFLOW_DOM_ID_SUFFIX;+ const key = `${block.projectionKey ?? block.id}${suffix}`;++ return {+ ...block,+ contentOverride: block.content,+ domId: key,+ hasToolsOverride: !!block.tools?.length,+ renderKey: key,+ };+};++const toRenderSegments = (segments: AssistantGroupSegment[]): GroupRenderSegment[] =>+ segments.map((segment) =>+ segment.kind === 'answer'+ ? { block: toRenderableBlock(segment.block), kind: 'answer' }+ : { ...segment, blocks: segment.blocks.map(toRenderableBlock) },+ );++export const withMarkdownStreamingState = (+ block: RenderableAssistantContentBlock,+ lastBlockId: string | undefined,+): RenderableAssistantContentBlock => ({+ ...block,+ disableMarkdownStreaming: block.disableMarkdownStreaming || block.id !== lastBlockId,+});++export const shouldInlineWorkflowSegment = (blocks: RenderableAssistantContentBlock[]): boolean => {+ let toolCount = 0;++ for (const block of blocks) {+ toolCount += block.tools?.length ?? 0;+ if (toolCount > 1) return false;+ }++ return toolCount === 1;+};++/**+ * A workflow segment is only the "active" step while it is the last thing in the+ * group. Once any later segment has real content below it (e.g. an errored+ * tool block whose error text renders as a trailing answer segment), the tools+ * are settled and the collapse should read as done rather than keep showing its+ * streaming "working" header. Empty trailing blocks (an answer not streamed yet)+ * don't count. `postToolTailPromoted` already covers the promoted-final-answer+ * path at the group level; this catches the remaining segment-ordering cases.+ */+export const hasRenderedContentAfter = (segments: GroupRenderSegment[], index: number): boolean =>+ segments+ .slice(index + 1)+ .some((seg) => (seg.kind === 'workflow' ? seg.blocks.length > 0 : !isEmptyBlock(seg.block)));++/**+ * A pending intervention still needs the user's confirmation, so the collapse+ * must keep its streaming "awaiting confirmation" chrome even when a later+ * segment has already rendered below it. `areWorkflowToolsComplete` ignores+ * pending tools, so the completion shortcut must not be applied here.+ */+export const hasPendingIntervention = (blocks: RenderableAssistantContentBlock[]): boolean =>+ blocks.some((block) => block.tools?.some((tool) => tool.intervention?.status === 'pending'));++export const buildChainView = (+ chain: GroupChainInput,+ state: { hasActiveOperation: boolean; isGenerating: boolean },+): GroupChainView => {+ const { isGenerating } = state;+ const partitioned = partitionAssistantGroupBlocks(chain.blocks, {+ isBreakoutTool: isImageBearingTool,+ isGenerating,+ toolsPhaseComplete: isGenerating+ ? areWorkflowToolsComplete(chain.blocks.flatMap((block) => block.tools ?? []))+ : undefined,+ });+ const segments = toRenderSegments(partitioned.segments);++ // When the turn ends on an inline single-tool segment whose tool already+ // settled but the run is still generating (waiting on the next step), the+ // inline path renders no working chrome — unlike WorkflowCollapse, which has+ // its own streaming header. Without this the user sees a blank gap below the+ // finished tool. Render the same "running" indicator used at turn start to+ // fill it. Multi-tool segments keep their own chrome; a tool still executing+ // is covered by its own loading placeholder (areWorkflowToolsComplete=false).+ // …unless that inline segment already ends on a LOADING_FLAT placeholder:+ // that block mounts MessageContent, which renders its OWN "…is running" line+ // (ContentBlock gates on text/LOADING_FLAT/tools), so the tail would stack a+ // second identical line on top. Narrowly LOADING_FLAT (and tool-less): a+ // blank `content: ''` shell — what the gateway emits on stream_start — does+ // NOT mount MessageContent, so the tail must stay to fill the gap until the+ // first content chunk lands.+ const lastSegment = segments.at(-1);+ const lastInlineBlock = lastSegment?.kind === 'workflow' ? lastSegment.blocks.at(-1) : undefined;+ const lastInlineRendersOwnLoading =+ lastInlineBlock?.content === LOADING_FLAT && !lastInlineBlock.tools?.length;+ const showTailRunningIndicator =+ isGenerating &&+ lastSegment?.kind === 'workflow' &&+ shouldInlineWorkflowSegment(lastSegment.blocks) &&+ areWorkflowToolsComplete(lastSegment.blocks.flatMap((block) => block.tools ?? [])) &&+ !lastInlineRendersOwnLoading;++ return {+ ...chain,+ hasActiveOperation: state.hasActiveOperation,+ isGenerating,+ lastBlockId: chain.blocks.at(-1)?.id,+ postToolTailPromoted: partitioned.postToolTailPromoted,+ segments,+ showTailRunningIndicator,+ workflowChromeComplete: !isGenerating || partitioned.postToolTailPromoted,+ };+};diff --git a/src/features/Conversation/Messages/AssistantGroup/components/renderChainSegment.tsx b/src/features/Conversation/Messages/AssistantGroup/components/renderChainSegment.tsxnew file mode 100644index 00000000000..fda20b12e9b--- /dev/null+++ b/src/features/Conversation/Messages/AssistantGroup/components/renderChainSegment.tsx@@ -0,0 +1,104 @@+import type { ReactNode } from 'react';++import CouncilList from '../../AgentCouncil/components/CouncilList';+import type { GroupChainView } from './groupChain';+import {+ hasPendingIntervention,+ hasRenderedContentAfter,+ isEmptyBlock,+ shouldInlineWorkflowSegment,+ withMarkdownStreamingState,+} from './groupChain';+import GroupItem from './GroupItem';+import type { GroupRenderSegment } from './segments';+import WorkflowCollapse, { type WorkflowExpandLevelDefault } from './WorkflowCollapse';++export interface ChainSegmentRenderOptions {+ defaultWorkflowExpandLevel?: WorkflowExpandLevelDefault;+ disableEditing?: boolean;+ enableProcessFold?: boolean;+ messageIndex: number;+}++export const renderChainSegment = (+ view: GroupChainView,+ segment: GroupRenderSegment,+ options: ChainSegmentRenderOptions,+): ReactNode => {+ const { contentId, id, isGenerating, lastBlockId, segments } = view;+ const { defaultWorkflowExpandLevel, disableEditing, enableProcessFold, messageIndex } = options;+ const index = segments.indexOf(segment);++ if (segment.kind === 'workflow') {+ if (segment.blocks.length === 0) return null;++ if (segment.standalone || shouldInlineWorkflowSegment(segment.blocks)) {+ return segment.blocks.map((block, blockIndex) => {+ const item = withMarkdownStreamingState(block, lastBlockId);+ if (!isGenerating && isEmptyBlock(item)) return null;++ return (+ <GroupItem+ {...item}+ assistantId={id}+ contentId={contentId}+ disableEditing={disableEditing}+ key={item.renderKey ?? `${id}.workflow-inline.${index}.${blockIndex}`}+ messageIndex={messageIndex}+ />+ );+ });+ }++ return (+ <WorkflowCollapse+ assistantMessageId={id}+ blocks={segment.blocks.map((block) => withMarkdownStreamingState(block, lastBlockId))}+ defaultWorkflowExpandLevel={defaultWorkflowExpandLevel}+ disableEditing={disableEditing}+ key={segment.blocks[0]?.renderKey ?? `${id}.workflow.${index}`}+ // While the turn's operation is still running, process folding may+ // take over the moment it ends: the segment tree re-parents into+ // ProcessFold, which remounts WorkflowCollapse already collapsed —+ // one non-animated reflow. Letting the collapse also self-animate+ // from semi → collapsed first would shrink the layout twice and make+ // the conversation jitter. Once the op ends without a fold happening+ // (tool-only turn, no final answer), suppression releases and+ // WorkflowCollapse applies its completion level then.+ suppressAutoCollapse={!!enableProcessFold && view.hasActiveOperation}+ workflowChromeComplete={+ view.workflowChromeComplete ||+ (hasRenderedContentAfter(segments, index) && !hasPendingIntervention(segment.blocks))+ }+ />+ );+ }++ const item = segment.block;++ // AgentCouncil block: broadcast members rendered as parallel columns inside+ // the supervisor's bubble.+ if (item.council && item.council.length > 0) {+ return (+ <CouncilList+ activeTab={0}+ displayMode={'horizontal'}+ key={item.renderKey ?? `${id}.${item.id}.${index}`}+ members={item.council}+ />+ );+ }++ if (!isGenerating && isEmptyBlock(item)) return null;++ return (+ <GroupItem+ {...withMarkdownStreamingState(item, lastBlockId)}+ assistantId={id}+ contentId={contentId}+ disableEditing={disableEditing}+ key={item.renderKey ?? `${id}.${item.id}.${index}`}+ messageIndex={messageIndex}+ />+ );+};diff --git a/src/features/Conversation/Messages/AssistantGroup/index.tsx b/src/features/Conversation/Messages/AssistantGroup/index.tsxindex fb1619e5626..50ed6b5385f 100644--- a/src/features/Conversation/Messages/AssistantGroup/index.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/index.tsx@@ -31,6 +31,7 @@ import {messageStateSelectors,useConversationStore,} from '../../store';+import type { SteerContinuation } from '../../store/slices/data/steerChains';import { getOperationFinalRootId } from '../../store/slices/data/workSummaries';import InterruptedHint from '../Assistant/components/InterruptedHint';import Usage from '../components/Extras/Usage';@@ -49,6 +50,7 @@ import FileListViewer from '../User/components/FileListViewer';import Group from './components/Group';import { resolveWorkflowExpandLevel } from './components/segments';import type { WorkflowExpandLevelDefault } from './components/WorkflowCollapse';+import { buildContinuationChains, collectSignalCallbacks } from './utils/continuations';const EditState = dynamic(() => import('./components/EditState'), {ssr: false,@@ -77,6 +79,8 @@ const findLatestWorkRootOperationId = (};interface GroupMessageProps {+ /** Later turns steered onto this one, rendered as one continuous chain. */+ continuations?: SteerContinuation[];defaultWorkflowExpandLevel?: WorkflowExpandLevelDefault;disableEditing?: boolean;footerRender?: ReactNode;@@ -85,8 +89,18 @@ interface GroupMessageProps {isLatestItem?: boolean;}+const EMPTY_CONTINUATIONS: SteerContinuation[] = [];+const GroupMessage = memo<GroupMessageProps>(- ({ defaultWorkflowExpandLevel, id, index, disableEditing, footerRender, isLatestItem }) => {+ ({+ continuations = EMPTY_CONTINUATIONS,+ defaultWorkflowExpandLevel,+ id,+ index,+ disableEditing,+ footerRender,+ isLatestItem,+ }) => {// Get message and actionsConfig from ConversationStoreconst item = useConversationStore(dataSelectors.getDisplayMessageById(id), isEqual)!;@@ -104,6 +118,28 @@ const GroupMessage = memo<GroupMessageProps>(taskCompletions,} = item;const avatar = useAgentMeta(agentId);+ const continuationMessages = useConversationStore(+ (s) => continuations.map((c) => dataSelectors.getDisplayMessageById(c.groupId)(s)),+ isEqual,+ );+ const chains = useMemo(+ () => buildContinuationChains(continuations, continuationMessages),+ [continuationMessages, continuations],+ );+ const allSignalCallbacks = useMemo(+ () =>+ collectSignalCallbacks(+ signalCallbacks as UISignalCallbacksBlock[] | undefined,+ continuationMessages,+ ),+ [continuationMessages, signalCallbacks],+ );+ const tailMessage = continuationMessages.at(-1);+ const tailId = chains.at(-1)?.id ?? id;+ const allChildren = useMemo(+ () => [...(children ?? []), ...chains.flatMap((chain) => chain.blocks)],+ [chains, children],+ );// Supervisor messages render the GROUP's identity (avatar + name + 主管 badge)// rather than the supervisor agent's own bare meta (whose title is literally@@ -128,13 +164,13 @@ const GroupMessage = memo<GroupMessageProps>();// Collect fileList from all children blocks- const aggregatedFileList = useMemo(() => {- if (!children || children.length === 0) return [];- return children.flatMap((child: AssistantContentBlock) => child.fileList || []);- }, [children]);+ const aggregatedFileList = useMemo(+ () => allChildren.flatMap((child: AssistantContentBlock) => child.fileList || []),+ [allChildren],+ );const workRootOperationId = useMemo(- () => findLatestWorkRootOperationId(metadata, children, taskCompletions),- [children, metadata, taskCompletions],+ () => findLatestWorkRootOperationId(metadata, allChildren, taskCompletions),+ [allChildren, metadata, taskCompletions],);// Codex-style aggregate of files edited this round. Purely derived from the// group's tool calls (entity-format files are excluded — they surface as@@ -143,33 +179,45 @@ const GroupMessage = memo<GroupMessageProps>(// (or any child block) is still streaming: `children` changes on every token,// and the finished card is all users see anyway.const isGroupGenerating = useConversationStore(- messageStateSelectors.isAssistantGroupItemGenerating(id),+ messageStateSelectors.isAssistantGroupItemGenerating(tailId),);const editedFiles = useOperationEditedFiles(- isGroupGenerating ? undefined : children,+ isGroupGenerating ? undefined : allChildren,// The sandbox-entity → Work handoff only happens on server-runtime rounds// (the work anchor marks them); without it the card keeps every entry.!!workRootOperationId,);- const operationGoals = useOperationGoals(isGroupGenerating ? undefined : children);+ const operationGoals = useOperationGoals(isGroupGenerating ? undefined : allChildren);const isInbox = useAgentStore(builtinAgentSelectors.isInboxAgent);const [toggleSystemRole] = useGlobalStore((s) => [s.toggleSystemRole]);const openChatSettings = useOpenChatSettings();// Get the latest message block from the group that doesn't contain tools- const lastAssistantMsg = useConversationStore(- dataSelectors.getGroupLatestMessageWithoutTools(id),+ const groupLatestMsg = useConversationStore(+ dataSelectors.getGroupLatestMessageWithoutTools(tailId),);+ const lastAssistantMsg =+ tailMessage?.role === 'assistant'+ ? tailMessage.tools?.length+ ? undefined+ : tailMessage+ : groupLatestMsg;const contentId = lastAssistantMsg?.id;+ const groupChains = useMemo(+ () => chains.map((chain, i) => (i === chains.length - 1 ? { ...chain, contentId } : chain)),+ [chains, contentId],+ );// Get editing and interrupted state from ConversationStoreconst editing = useConversationStore(messageStateSelectors.isMessageEditing(contentId || ''));// Check interrupted on both the group root and the active block, because// continuation runs attach their operations to lastBlockId (contentId),// not the group root.- const groupInterrupted = useConversationStore(messageStateSelectors.isMessageInterrupted(id));+ const groupInterrupted = useConversationStore(+ messageStateSelectors.isMessageInterrupted(tailId),+ );const blockInterrupted = useConversationStore(messageStateSelectors.isMessageInterrupted(contentId || ''),);@@ -326,7 +374,8 @@ const GroupMessage = memo<GroupMessageProps>(enableProcessFoldblocks={children}content={lastAssistantMsg?.content}- contentId={contentId}+ contentId={groupChains.length > 0 ? undefined : contentId}+ continuations={groupChains}// Folding a finished turn's process is the default behavior now// (graduated from Labs) — always on for the conversation.defaultWorkflowExpandLevel={workflowExpandLevel}@@ -336,7 +385,7 @@ const GroupMessage = memo<GroupMessageProps>(messageIndex={index}/>)}- {(signalCallbacks as UISignalCallbacksBlock[] | undefined)?.map((block) => (+ {allSignalCallbacks.map((block) => (<SignalCallbacks block={block} key={block.sourceToolMessageId} />))}{taskCompletions && taskCompletions.length > 0 && (diff --git a/src/features/Conversation/Messages/AssistantGroup/utils/continuations.test.ts b/src/features/Conversation/Messages/AssistantGroup/utils/continuations.test.tsnew file mode 100644index 00000000000..3fd3655c2d6--- /dev/null+++ b/src/features/Conversation/Messages/AssistantGroup/utils/continuations.test.ts@@ -0,0 +1,63 @@+import type { AssistantContentBlock, UIChatMessage, UISignalCallbacksBlock } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { buildContinuationChains, collectSignalCallbacks } from './continuations';++const block = (id: string): AssistantContentBlock => ({ content: id, id });++const signalBlock = (id: string): UISignalCallbacksBlock => ({+ callbacks: [{ content: id, id }],+ sourceToolCallId: `${id}-tool`,+ sourceToolMessageId: id,+ sourceToolName: 'monitor',+});++const message = (input: Partial<UIChatMessage> & { id: string; role: UIChatMessage['role'] }) =>+ ({+ content: '',+ createdAt: 1,+ updatedAt: 1,+ ...input,+ }) as UIChatMessage;++describe('assistant group continuations', () => {+ it('keeps task completion summaries in continuation chains', () => {+ const chains = buildContinuationChains(+ [{ groupId: 'group-2', steerUserId: 'steer-1' }],+ [+ message({+ children: [block('child-1')],+ id: 'group-2',+ role: 'assistantGroup',+ taskCompletions: [block('task-summary-1')],+ }),+ ],+ );++ expect(chains).toEqual([+ {+ blocks: [+ expect.objectContaining({ id: 'child-1' }),+ expect.objectContaining({ id: 'task-summary-1' }),+ ],+ id: 'group-2',+ steerUserId: 'steer-1',+ },+ ]);+ });++ it('collects signal callbacks from the host and every continuation', () => {+ expect(+ collectSignalCallbacks(+ [signalBlock('host-signal')],+ [+ message({+ id: 'group-2',+ role: 'assistantGroup',+ signalCallbacks: [signalBlock('continuation-signal')],+ }),+ ],+ ).map((signal) => signal.sourceToolMessageId),+ ).toEqual(['host-signal', 'continuation-signal']);+ });+});diff --git a/src/features/Conversation/Messages/AssistantGroup/utils/continuations.ts b/src/features/Conversation/Messages/AssistantGroup/utils/continuations.tsnew file mode 100644index 00000000000..c1b67f637c9--- /dev/null+++ b/src/features/Conversation/Messages/AssistantGroup/utils/continuations.ts@@ -0,0 +1,36 @@+import type { UIChatMessage, UISignalCallbacksBlock } from '@lobechat/types';++import type { AssistantContentBlock } from '@/types/index';++import type { SteerContinuation } from '../../../store/slices/data/steerChains';+import type { GroupChainInput } from '../components/groupChain';++export const buildContinuationChains = (+ continuations: SteerContinuation[],+ continuationMessages: Array<UIChatMessage | undefined>,+): GroupChainInput[] =>+ continuations.flatMap((continuation, index) => {+ const message = continuationMessages[index];+ if (!message) return [];++ const blocks =+ message.role === 'assistant'+ ? [message as unknown as AssistantContentBlock]+ : [...(message.children ?? []), ...(message.taskCompletions ?? [])];++ return [+ {+ blocks,+ id: continuation.groupId,+ steerUserId: continuation.steerUserId,+ },+ ];+ });++export const collectSignalCallbacks = (+ signalCallbacks: UISignalCallbacksBlock[] | undefined,+ continuationMessages: Array<UIChatMessage | undefined>,+): UISignalCallbacksBlock[] => [+ ...(signalCallbacks ?? []),+ ...continuationMessages.flatMap((message) => message?.signalCallbacks ?? []),+];diff --git a/src/features/Conversation/Messages/User/index.tsx b/src/features/Conversation/Messages/User/index.tsxindex 674f5d098d8..d5914eb822a 100644--- a/src/features/Conversation/Messages/User/index.tsx+++ b/src/features/Conversation/Messages/User/index.tsx@@ -35,7 +35,7 @@ interface UserMessageProps {const UserMessage = memo<UserMessageProps>(({ id, disableEditing, index }) => {const item = useConversationStore(dataSelectors.getDisplayMessageById(id), isEqual)!;- const { content, createdAt, error, role, extra, targetId, sender } = item;+ const { content, createdAt, error, role, extra, targetId, sender, metadata } = item;const botSender = getBotSender(item);const { t } = useTranslation('chat');@@ -108,6 +108,7 @@ const UserMessage = memo<UserMessageProps>(({ id, disableEditing, index }) => {avatar={{ avatar, title }}belowMessage={<ScheduledRunFooter id={id} />}editing={editing}+ headerAddon={metadata?.steer ? <Tag>{t('steer.tag')}</Tag> : undefined}id={id}message={content}messageExtra={<UserMessageExtra content={content} extra={extra} id={id} />}diff --git a/src/features/Conversation/Messages/index.tsx b/src/features/Conversation/Messages/index.tsxindex fdbfaacc4be..1363aa028fb 100644--- a/src/features/Conversation/Messages/index.tsx+++ b/src/features/Conversation/Messages/index.tsx@@ -16,6 +16,7 @@ import History from '../components/History';import { useChatItemContextMenu } from '../hooks/useChatItemContextMenu';import MessageSelectionWrapper from '../MessageForward/MessageSelectionWrapper';import { dataSelectors, messageStateSelectors, useConversationStore } from '../store';+import type { SteerContinuation } from '../store/slices/data/steerChains';import AgentCouncilMessage from './AgentCouncil';import AssistantMessage from './Assistant';import AssistantGroupMessage from './AssistantGroup';@@ -49,6 +50,7 @@ const styles = createStaticStyles(({ css }) => ({export interface MessageItemProps {className?: string;+ continuations?: SteerContinuation[];defaultWorkflowExpandLevel?: WorkflowExpandLevelDefault;disableEditing?: boolean;enableHistoryDivider?: boolean;@@ -63,6 +65,7 @@ export interface MessageItemProps {const MessageItem = memo<MessageItemProps>(({className,+ continuations,defaultWorkflowExpandLevel,enableHistoryDivider,id,@@ -170,6 +173,7 @@ const MessageItem = memo<MessageItemProps>(case 'assistantGroup': {return (<AssistantGroupMessage+ continuations={continuations}defaultWorkflowExpandLevel={defaultWorkflowExpandLevel}disableEditing={effectiveDisableEditing}footerRender={footerRender}@@ -187,6 +191,7 @@ const MessageItem = memo<MessageItemProps>(// turn. Keeps a single code path instead of a thinner duplicate.return (<AssistantGroupMessage+ continuations={continuations}defaultWorkflowExpandLevel={defaultWorkflowExpandLevel}disableEditing={effectiveDisableEditing}footerRender={footerRender}@@ -239,6 +244,7 @@ const MessageItem = memo<MessageItemProps>(return null;}, [role,+ continuations,defaultWorkflowExpandLevel,effectiveDisableEditing,footerRender,diff --git a/src/features/Conversation/store/slices/data/messageIndex.ts b/src/features/Conversation/store/slices/data/messageIndex.tsnew file mode 100644index 00000000000..9eed6d8dc0e--- /dev/null+++ b/src/features/Conversation/store/slices/data/messageIndex.ts@@ -0,0 +1,32 @@+import type { UIChatMessage } from '@lobechat/types';++interface DisplayMessageIndex {+ byId: Map<string, UIChatMessage>;+ groupOfBlock: Map<string, UIChatMessage>;+}++const buildIndex = (messages: UIChatMessage[]): DisplayMessageIndex => {+ const byId = new Map<string, UIChatMessage>();+ const groupOfBlock = new Map<string, UIChatMessage>();++ for (const message of messages) {+ byId.set(message.id, message);+ if (message.role !== 'assistantGroup') continue;+ for (const block of message.children ?? []) groupOfBlock.set(block.id, message);+ }++ return { byId, groupOfBlock };+};++// Streaming swaps the displayMessages array on every chunk; keying on the array+// identity keeps the pass to once per snapshot no matter how many rows read it.+const indexCache = new WeakMap<UIChatMessage[], DisplayMessageIndex>();++export const indexDisplayMessages = (messages: UIChatMessage[]): DisplayMessageIndex => {+ let index = indexCache.get(messages);+ if (!index) {+ index = buildIndex(messages);+ indexCache.set(messages, index);+ }+ return index;+};diff --git a/src/features/Conversation/store/slices/data/selectors.ts b/src/features/Conversation/store/slices/data/selectors.tsindex c6d438edb2b..5c6854989ab 100644--- a/src/features/Conversation/store/slices/data/selectors.ts+++ b/src/features/Conversation/store/slices/data/selectors.ts@@ -9,6 +9,7 @@ import { topicSelectors } from '@/store/chat/selectors';import { type State } from '../../initialState';import { getPendingInterventions } from './pendingInterventions';+import { collectSteerChains } from './steerChains';import { getWorkSummariesByRootOperationId } from './workSummaries';const displayMessages = (s: State) => s.displayMessages;@@ -164,6 +165,38 @@ const workSummariesByRootOperationId = (rootOperationId?: string | null) => (s:const isSecondLastMessageFromUser = (s: State) => s.displayMessages.at(-2)?.role === 'user';+const rowMemberIds = (id: string) => (s: State) =>+ collectSteerChains(s.displayMessages).byHost.get(id)?.memberIds ?? [id];++const hostRowOf = (id: string) => (s: State) =>+ collectSteerChains(s.displayMessages).hostOf.get(id) ?? id;++const collectDeletableMessageIds = (message: UIChatMessage | undefined): string[] => {+ if (!message) return [];+ if ((message.role !== 'assistantGroup' && message.role !== 'supervisor') || !message.children) {+ return [message.id];+ }++ return [+ message.id,+ ...message.children.map((child) => child.id),+ ...message.children.flatMap(+ (child) => child.tools?.flatMap((tool) => (tool.result?.id ? [tool.result.id] : [])) ?? [],+ ),+ ];+};++// The server reparents survivors instead of cascading, so every folded+// continuation must be expanded the same way as the host or its later blocks+// resurface as a fresh turn under the original user message.+const deletableRowMessageIds = (id: string) => (s: State) => [+ ...new Set(+ rowMemberIds(id)(s).flatMap((memberId) =>+ collectDeletableMessageIds(getDisplayMessageById(memberId)(s)),+ ),+ ),+];+const toAssistantContentBlock = (message: UIChatMessage): AssistantContentBlock => ({content: message.content,error: message.error,@@ -274,6 +307,7 @@ const getVerifyOrdinal = (id: string) => (s: State) => {export const dataSelectors = {currentTopicSummary,dbMessages,+ deletableRowMessageIds,getVerifyOrdinal,displayMessageIds,displayMessages,@@ -288,9 +322,11 @@ export const dataSelectors = {getToolMessageCreatedAt,getToolsInBlock,hasNoRenderedReply,+ hostRowOf,isSecondLastMessageFromUser,messagesInit,pendingInterventions,+ rowMemberIds,skipFetch,taskCallbackTaskIds,workSummariesByRootOperationId,diff --git a/src/features/Conversation/store/slices/data/steerChains.test.ts b/src/features/Conversation/store/slices/data/steerChains.test.tsnew file mode 100644index 00000000000..d36d311ab04--- /dev/null+++ b/src/features/Conversation/store/slices/data/steerChains.test.ts@@ -0,0 +1,92 @@+import type { UIChatMessage } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { collectSteerChains } from './steerChains';++const msg = (+ id: string,+ role: UIChatMessage['role'],+ metadata?: UIChatMessage['metadata'],+): UIChatMessage => ({ content: '', createdAt: 0, id, metadata, role, updatedAt: 0 }) as any;++describe('collectSteerChains', () => {+ it('folds every steer turn into the host it interrupted', () => {+ const { byHost, hostOf } = collectSteerChains([+ msg('u1', 'user'),+ msg('g1', 'assistantGroup'),+ msg('s1', 'user', { steer: true }),+ msg('g2', 'assistantGroup'),+ msg('s2', 'user', { steer: true }),+ msg('a3', 'assistant'),+ ]);++ expect(byHost.get('g1')).toEqual({+ continuations: [+ { groupId: 'g2', steerUserId: 's1' },+ { groupId: 'a3', steerUserId: 's2' },+ ],+ hostId: 'g1',+ memberIds: ['g1', 's1', 'g2', 's2', 'a3'],+ });+ expect([...hostOf.entries()]).toEqual([+ ['s1', 'g1'],+ ['g2', 'g1'],+ ['s2', 'g1'],+ ['a3', 'g1'],+ ]);+ });++ it('indexes nothing for a plain conversation', () => {+ const { byHost, hostOf } = collectSteerChains([+ msg('u1', 'user'),+ msg('g1', 'assistantGroup'),+ msg('u2', 'user'),+ msg('g2', 'assistantGroup'),+ ]);++ expect(byHost.size).toBe(0);+ expect(hostOf.size).toBe(0);+ });++ it('leaves a steer message alone when nothing follows it or no host precedes it', () => {+ expect(+ collectSteerChains([+ msg('u1', 'user'),+ msg('g1', 'assistantGroup'),+ msg('s1', 'user', { steer: true }),+ ]).hostOf.size,+ ).toBe(0);++ expect(+ collectSteerChains([msg('s1', 'user', { steer: true }), msg('g1', 'assistantGroup')]).hostOf+ .size,+ ).toBe(0);++ expect(+ collectSteerChains([+ msg('a1', 'assistant'),+ msg('s1', 'user', { steer: true }),+ msg('g1', 'assistantGroup'),+ ]).hostOf.size,+ ).toBe(0);+ });++ it('breaks the chain at a regular user message', () => {+ const { hostOf } = collectSteerChains([+ msg('g1', 'assistantGroup'),+ msg('u2', 'user'),+ msg('g2', 'assistantGroup'),+ msg('s1', 'user', { steer: true }),+ msg('g3', 'assistantGroup'),+ ]);++ expect(hostOf.get('g3')).toBe('g2');+ });++ it('memoizes per messages array identity', () => {+ const messages = [msg('g1', 'assistantGroup')];++ expect(collectSteerChains(messages)).toBe(collectSteerChains(messages));+ expect(collectSteerChains([...messages])).not.toBe(collectSteerChains(messages));+ });+});diff --git a/src/features/Conversation/store/slices/data/steerChains.ts b/src/features/Conversation/store/slices/data/steerChains.tsnew file mode 100644index 00000000000..83743463ca0--- /dev/null+++ b/src/features/Conversation/store/slices/data/steerChains.ts@@ -0,0 +1,70 @@+import type { UIChatMessage } from '@lobechat/types';++export interface SteerContinuation {+ groupId: string;+ steerUserId: string;+}++export interface SteerChain {+ continuations: SteerContinuation[];+ hostId: string;+ memberIds: string[];+}++export interface SteerChainIndex {+ byHost: Map<string, SteerChain>;+ hostOf: Map<string, string>;+}++// A plain `assistant` reply (a turn that finished without tool calls) cannot host a+// chain: its row component has no continuation rendering, so a steer after it stays+// a separate row. Fixing that means promoting the reply to `assistantGroup` when it is+// interrupted, not widening this predicate.+const isTurnHost = (message?: UIChatMessage) =>+ message?.role === 'assistantGroup' || message?.role === 'supervisor';++const isTurnTail = (message?: UIChatMessage) =>+ isTurnHost(message) || message?.role === 'assistant';++const isSteerUser = (message?: UIChatMessage) =>+ message?.role === 'user' && !!message.metadata?.steer;++const buildSteerChainIndex = (messages: UIChatMessage[]): SteerChainIndex => {+ const byHost = new Map<string, SteerChain>();+ const hostOf = new Map<string, string>();+ let chain: SteerChain | undefined;++ for (let index = 0; index < messages.length; index += 1) {+ const message = messages[index]!;+ const next = messages[index + 1];++ if (chain && isSteerUser(message) && isTurnTail(next)) {+ chain.continuations.push({ groupId: next!.id, steerUserId: message.id });+ chain.memberIds.push(message.id, next!.id);+ hostOf.set(message.id, chain.hostId);+ hostOf.set(next!.id, chain.hostId);+ byHost.set(chain.hostId, chain);+ index += 1;+ continue;+ }++ chain = isTurnHost(message)+ ? { continuations: [], hostId: message.id, memberIds: [message.id] }+ : undefined;+ }++ return { byHost, hostOf };+};++// Streaming swaps the displayMessages array on every chunk; keying on the array+// identity keeps the pass to once per snapshot no matter how many rows read it.+const indexCache = new WeakMap<UIChatMessage[], SteerChainIndex>();++export const collectSteerChains = (messages: UIChatMessage[]): SteerChainIndex => {+ let index = indexCache.get(messages);+ if (!index) {+ index = buildSteerChainIndex(messages);+ indexCache.set(messages, index);+ }+ return index;+};diff --git a/src/features/Conversation/store/slices/message/action/crud.test.ts b/src/features/Conversation/store/slices/message/action/crud.test.tsindex b7cb2201913..8259d77e1ae 100644--- a/src/features/Conversation/store/slices/message/action/crud.test.ts+++ b/src/features/Conversation/store/slices/message/action/crud.test.ts@@ -269,6 +269,89 @@ describe('Message CRUD Actions', () => {);});+ it('deletes every turn folded into a steered host row', async () => {+ const removeMessagesSpy = vi+ .spyOn(messageServiceModule.messageService, 'removeMessages')+ .mockResolvedValue({ success: true, messages: [] });++ const store = createTestStore();+ const base = { content: '', updatedAt: 0 };++ act(() => {+ store.getState().replaceMessages([+ { ...base, createdAt: 1, id: 'u1', role: 'user' },+ {+ ...base,+ children: [{ content: 'first', id: 'c1' }],+ createdAt: 2,+ id: 'g1',+ role: 'assistantGroup',+ },+ { ...base, createdAt: 3, id: 's1', metadata: { steer: true }, role: 'user' },+ {+ ...base,+ children: [+ {+ content: 'second',+ id: 'c2',+ tools: [+ {+ apiName: 'test',+ arguments: '',+ id: 'tool-2',+ identifier: 'test',+ result: { content: '', id: 'tool-result-2' },+ type: 'default',+ },+ ],+ },+ ],+ createdAt: 4,+ id: 'g2',+ role: 'assistantGroup',+ },+ ] as UIChatMessage[]);+ });++ await act(async () => {+ await store.getState().deleteMessage('g1');+ });++ expect(removeMessagesSpy).toHaveBeenCalledWith(+ ['g1', 'c1', 's1', 'g2', 'c2', 'tool-result-2'],+ expect.any(Object),+ );+ });++ it('deletes a plain assistant continuation together with its steered host', async () => {+ const removeMessagesSpy = vi+ .spyOn(messageServiceModule.messageService, 'removeMessages')+ .mockResolvedValue({ success: true, messages: [] });++ const store = createTestStore();+ const base = { content: '', updatedAt: 0 };++ act(() => {+ store.getState().replaceMessages([+ {+ ...base,+ children: [{ content: 'first', id: 'c1' }],+ createdAt: 1,+ id: 'g1',+ role: 'assistantGroup',+ },+ { ...base, createdAt: 2, id: 's1', metadata: { steer: true }, role: 'user' },+ { ...base, content: 'plain reply', createdAt: 3, id: 'a2', role: 'assistant' },+ ] as UIChatMessage[]);+ });++ await act(async () => {+ await store.getState().deleteMessage('g1');+ });++ expect(removeMessagesSpy).toHaveBeenCalledWith(['g1', 'c1', 's1', 'a2'], expect.any(Object));+ });+it('should use removeMessage for single id and removeMessages for multiple ids', async () => {const removeMessageSpy = vi.spyOn(messageServiceModule.messageService, 'removeMessage')diff --git a/src/features/Conversation/store/slices/message/action/crud.ts b/src/features/Conversation/store/slices/message/action/crud.tsindex 95f60beeeea..f48f1f5eb06 100644--- a/src/features/Conversation/store/slices/message/action/crud.ts+++ b/src/features/Conversation/store/slices/message/action/crud.ts@@ -1,10 +1,8 @@import {- type AssistantContentBlock,type ChatImageItem,type ChatMessageError,type ChatMessagePluginError,type ChatToolPayload,- type ChatToolPayloadWithResult,type ChatVideoItem,type CreateMessageParams,type GroundingSearch,@@ -299,25 +297,9 @@ export const messageCRUDSlice: StateCreator<const state = get();const { internal_dispatchMessage, replaceMessages, context } = state;- const message = dataSelectors.getDisplayMessageById(id)(state);- if (!message) return;-- let ids = [message.id];+ if (!dataSelectors.getDisplayMessageById(id)(state)) return;- // Handle assistantGroup and supervisor messages: delete all child blocks and tool results- if ((message.role === 'assistantGroup' || message.role === 'supervisor') && message.children) {- const childIds = message.children.map((child: AssistantContentBlock) => child.id);- ids = ids.concat(childIds);-- // Collect all tool result IDs from children- const toolResultIds = message.children.flatMap((child: AssistantContentBlock) => {- if (!child.tools) return [];- return child.tools- .filter((tool: ChatToolPayloadWithResult) => tool.result?.id)- .map((tool: ChatToolPayloadWithResult) => tool.result!.id);- });- ids = ids.concat(toolResultIds);- }+ const ids = dataSelectors.deletableRowMessageIds(id)(state);// Optimistic updateinternal_dispatchMessage({ ids, type: 'deleteMessages' });diff --git a/src/features/Conversation/store/slices/messageState/action.test.ts b/src/features/Conversation/store/slices/messageState/action.test.tsnew file mode 100644index 00000000000..04f3c78e0af--- /dev/null+++ b/src/features/Conversation/store/slices/messageState/action.test.ts@@ -0,0 +1,52 @@+import { type UIChatMessage } from '@lobechat/types';+import { act } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';++import { createStore } from '../../index';++vi.mock('@lobechat/conversation-flow', () => ({+ parse: (messages: UIChatMessage[]) => ({+ flatList: [...messages].sort((a, b) => a.createdAt - b.createdAt),+ messageMap: Object.fromEntries(messages.map((m) => [m.id, m])),+ }),+}));++const base = { content: '', updatedAt: 0 };+const steered = [+ { ...base, createdAt: 1, id: 'u1', role: 'user' },+ { ...base, children: [], createdAt: 2, id: 'g1', role: 'assistantGroup' },+ { ...base, createdAt: 3, id: 's1', metadata: { steer: true }, role: 'user' },+ { ...base, children: [], createdAt: 4, id: 'g2', role: 'assistantGroup' },+ { ...base, createdAt: 5, id: 'u2', role: 'user' },+] as UIChatMessage[];++const createSteeredStore = () => {+ const store = createStore({ context: { agentId: 'agent', threadId: null, topicId: null } });+ act(() => {+ store.getState().replaceMessages(steered);+ });+ return store;+};++describe('selection actions', () => {+ it('selectToHere stores row ids only, never folded steer members', () => {+ const store = createSteeredStore();++ act(() => {+ store.getState().selectToHere('s1');+ });++ expect(store.getState().selectedMessageIds).toEqual(['u1', 'g1']);+ });++ it('selectRange skips folded steer members between the anchor and the target', () => {+ const store = createSteeredStore();++ act(() => {+ store.getState().enterSelectionMode('u1');+ store.getState().selectRange('u2');+ });++ expect(store.getState().selectedMessageIds).toEqual(['u1', 'g1', 'u2']);+ });+});diff --git a/src/features/Conversation/store/slices/messageState/action.ts b/src/features/Conversation/store/slices/messageState/action.tsindex 80bf1c263ea..ac00d48b27d 100644--- a/src/features/Conversation/store/slices/messageState/action.ts+++ b/src/features/Conversation/store/slices/messageState/action.ts@@ -3,6 +3,12 @@ import { type StateCreator } from 'zustand';import { isSelectableRole } from '../../../MessageForward/selectableRoles';import { type State } from '../../initialState';+import { collectSteerChains } from '../data/steerChains';++const selectableRowIds = (slice: State['displayMessages'], all: State['displayMessages']) => {+ const { hostOf } = collectSteerChains(all);+ return slice.filter((m) => isSelectableRole(m.role) && !hostOf.has(m.id)).map((m) => m.id);+};export interface MessageEditingAction {/**@@ -95,10 +101,7 @@ export const messageEditingSlice: StateCreator<const [lo, hi] =anchorIndex <= targetIndex ? [anchorIndex, targetIndex] : [targetIndex, anchorIndex];- const rangeIds = displayMessages- .slice(lo, hi + 1)- .filter((m) => isSelectableRole(m.role))- .map((m) => m.id);+ const rangeIds = selectableRowIds(displayMessages.slice(lo, hi + 1), displayMessages);const next = new Set(selectedMessageIds);for (const rangeId of rangeIds) next.add(rangeId);@@ -113,10 +116,7 @@ export const messageEditingSlice: StateCreator<: displayMessages.length - 1;if (anchorIndex < 0) return;- const ids = displayMessages- .slice(0, anchorIndex + 1)- .filter((m) => isSelectableRole(m.role))- .map((m) => m.id);+ const ids = selectableRowIds(displayMessages.slice(0, anchorIndex + 1), displayMessages);set({ selectedMessageIds: ids }, false, 'selectToHere');},diff --git a/src/features/Conversation/store/slices/messageState/selectors.test.ts b/src/features/Conversation/store/slices/messageState/selectors.test.tsnew file mode 100644index 00000000000..84c89e85731--- /dev/null+++ b/src/features/Conversation/store/slices/messageState/selectors.test.ts@@ -0,0 +1,98 @@+import { describe, expect, it, vi } from 'vitest';++import type { State } from '../../initialState';+import { messageStateSelectors } from './selectors';++const stateWith = (+ displayMessages: unknown[],+ generatingIds: string[],+ selectedMessageIds: string[] = [],+): State =>+ ({+ displayMessages,+ operationState: {+ getMessageOperationState: (id: string) => ({ isGenerating: generatingIds.includes(id) }),+ },+ selectedMessageIds,+ }) as unknown as State;++const steered = [+ { id: 'u1', role: 'user' },+ { children: [{ id: 'g1' }], id: 'g1', role: 'assistantGroup' },+ { id: 's1', metadata: { steer: true }, role: 'user' },+ { children: [{ id: 'g2' }, { id: 'g2-b' }], id: 'g2', role: 'assistantGroup' },+];++describe('isRowGenerating', () => {+ it('reports the host row generating while a folded continuation streams', () => {+ const state = stateWith(steered, ['g2-b']);++ expect(messageStateSelectors.isMessageGenerating('g1')(state)).toBe(false);+ expect(messageStateSelectors.isRowGenerating('g1')(state)).toBe(true);+ });++ it('sees a plain assistant continuation streaming behind its host', () => {+ const mixed = [+ ...steered,+ { id: 's2', metadata: { steer: true }, role: 'user' },+ { id: 'a3', role: 'assistant' },+ ];++ expect(messageStateSelectors.isRowGenerating('g1')(stateWith(mixed, ['a3']))).toBe(true);+ });++ it('falls back to the message itself for a plain row', () => {+ expect(messageStateSelectors.isRowGenerating('u1')(stateWith(steered, []))).toBe(false);+ expect(messageStateSelectors.isRowGenerating('g1')(stateWith(steered, ['g1']))).toBe(true);+ });+});++describe('isAssistantGroupItemGenerating', () => {+ it('resolves a block to its group without rescanning the message list', () => {+ const state = stateWith(steered, ['g2']);+ const scans = vi.spyOn(state.displayMessages, 'find');++ expect(messageStateSelectors.isAssistantGroupItemGenerating('g2-b')(state)).toBe(true);+ expect(messageStateSelectors.isAssistantGroupItemGenerating('g1')(state)).toBe(false);+ expect(scans).not.toHaveBeenCalled();+ });+});++describe('forwardableSelectedMessages', () => {+ it('expands the host row and drops members without forwardable text', () => {+ const messages = [+ { id: 'u1', role: 'user' },+ { children: [{ content: 'first', id: 'g1' }], id: 'g1', role: 'assistantGroup' },+ { content: 'steer', id: 's1', metadata: { steer: true }, role: 'user' },+ { children: [{ content: '', id: 'g2' }], id: 'g2', role: 'assistantGroup' },+ ];++ expect(+ messageStateSelectors+ .forwardableSelectedMessages(stateWith(messages, [], ['g1']))+ .map((m) => m.id),+ ).toEqual(['g1', 's1']);+ });+});++describe('selectedDeletableMessageIds', () => {+ it('expands selected rows to every member block and tool result without duplicates', () => {+ const messages = [+ { id: 'u1', role: 'user' },+ {+ children: [+ { id: 'g1' },+ { id: 'c2', tools: [{ id: 't1', result: { id: 'tool-result-1' } }] },+ ],+ id: 'g1',+ role: 'assistantGroup',+ },+ { id: 's1', metadata: { steer: true }, role: 'user' },+ { content: 'reply', id: 'a2', role: 'assistant' },+ ];++ expect(+ messageStateSelectors.selectedDeletableMessageIds(stateWith(messages, [], ['u1', 'g1'])),+ ).toEqual(['u1', 'g1', 'c2', 'tool-result-1', 's1', 'a2']);+ });+});diff --git a/src/features/Conversation/store/slices/messageState/selectors.ts b/src/features/Conversation/store/slices/messageState/selectors.tsindex 6ada36494e7..a0ce4242d9e 100644--- a/src/features/Conversation/store/slices/messageState/selectors.ts+++ b/src/features/Conversation/store/slices/messageState/selectors.ts@@ -1,7 +1,9 @@import { useChatStore } from '@/store/chat';import { threadSelectors } from '@/store/chat/selectors';+import { getForwardableMessages } from '@/store/chat/slices/forward/helpers';import { type State } from '../../initialState';+import { indexDisplayMessages } from '../data/messageIndex';import { dataSelectors } from '../data/selectors';/**@@ -93,19 +95,33 @@ const isMessageGenerating = (id: string) => (s: State) =>const isAssistantGroupItemGenerating = (id: string) => (s: State) => {if (isMessageGenerating(id)(s)) return true;- const message = s.displayMessages.find((item) => item.id === id);+ const { byId, groupOfBlock } = indexDisplayMessages(s.displayMessages);+ const message = byId.get(id);if (message?.role === 'assistantGroup') {return message.children?.some((block) => isMessageGenerating(block.id)(s)) ?? false;}- const parentMessage = s.displayMessages.find(- (message) =>- message.role === 'assistantGroup' && message.children?.some((block) => block.id === id),- );-+ const parentMessage = groupOfBlock.get(id);return parentMessage ? isMessageGenerating(parentMessage.id)(s) : false;};+const isRowGenerating = (id: string) => (s: State) =>+ dataSelectors+ .rowMemberIds(id)(s)+ .some((memberId) => isAssistantGroupItemGenerating(memberId)(s));++const selectedMemberMessageIds = (s: State) =>+ s.selectedMessageIds.flatMap((id) => dataSelectors.rowMemberIds(id)(s));++const selectedDeletableMessageIds = (s: State) => [+ ...new Set(s.selectedMessageIds.flatMap((id) => dataSelectors.deletableRowMessageIds(id)(s))),+];++const forwardableSelectedMessages = (s: State) => {+ const selected = new Set(selectedMemberMessageIds(s));+ return getForwardableMessages(s.displayMessages.filter((m) => selected.has(m.id)));+};+/*** Check if a message is being regenerated*/@@ -190,6 +206,7 @@ const isThreadMode = (_s: State) => {};export const messageStateSelectors = {+ forwardableSelectedMessages,hasThreadBySourceMsgId,isAIGenerating,isAssistantGroupItemGenerating,@@ -207,12 +224,14 @@ export const messageStateSelectors = {isMessageRegenerating,isMessageSelected,isPluginApiInvoking,+ isRowGenerating,isSelectionMode,isThreadMode,isToolApiNameShining,isToolCallStreaming,messageEditingIds,messageLoadingIds,+ selectedDeletableMessageIds,selectedMessageCount,sendMessageError,};diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.tsindex 9e6da72c749..004ca378a8d 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts@@ -782,7 +782,7 @@ export class ConversationLifecycleActionImpl {: undefined,...(merged.forceRuntime ? { forceRuntime: merged.forceRuntime } : {}),message: merged.content,- metadata: merged.metadata,+ metadata: { ...merged.metadata, steer: true },}).catch((error: unknown) => {console.error('[sendMessage] restarting queued content after Stop failed:', error);diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.tsindex 29cdc815318..5f9f4610905 100644--- a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.ts+++ b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.ts@@ -324,6 +324,39 @@ describe('buildRunLifecycle — sub-agent runs skip top-level effects', () => {expect(store.drainQueuedMessages).toHaveBeenCalled();});+ it('a drained queued follow-up is sent as a steer turn', async () => {+ vi.useFakeTimers();+ try {+ const { get, store } = makeStore();+ const sendMessage = vi.fn(async () => {});+ (store as any).sendMessage = sendMessage;+ store.drainQueuedMessages = vi.fn(() => [+ {+ content: 'queued',+ createdAt: 1,+ id: 'q1',+ interruptMode: 'soft',+ metadata: { scope: 'x' },+ } as any,+ ]);++ const { requeued } = await lifecycle('gateway', get, 'top_level').completeRun(+ completeEvent('gateway', { status: 'completed' }),+ );+ await vi.runAllTimersAsync();++ expect(requeued).toBe(true);+ expect(sendMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ message: 'queued',+ metadata: expect.objectContaining({ scope: 'x', steer: true }),+ }),+ );+ } finally {+ vi.useRealTimers();+ }+ });+it('afterRunComplete is a no-op for a sub_agent run (no notification)', async () => {const { get } = makeStore();// Resolves without touching the desktop notification path (early return ondiff --git a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.tsindex 21352ec10f2..2829b532259 100644--- a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts+++ b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts@@ -468,7 +468,7 @@ export const buildRunLifecycle = (files: mergedFiles,...(merged.forceRuntime ? { forceRuntime: merged.forceRuntime } : {}),message: mergedContent,- metadata: merged.metadata,+ metadata: { ...merged.metadata, steer: true },}).catch((e: unknown) => {console.error('[executeClientAgent] sendMessage for queued content failed:', e);diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.tsindex d4940a41e92..a23a6a3e952 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts@@ -2569,7 +2569,7 @@ export const executeHeterogeneousAgent = async (files: mergedFiles,...(merged.forceRuntime ? { forceRuntime: merged.forceRuntime } : {}),message: merged.content,- metadata: merged.metadata,+ metadata: { ...merged.metadata, steer: true },}).catch((e: unknown) => {console.error(diff --git a/src/store/chat/slices/forward/helpers.ts b/src/store/chat/slices/forward/helpers.tsindex 56965efe23c..51206e19713 100644--- a/src/store/chat/slices/forward/helpers.ts+++ b/src/store/chat/slices/forward/helpers.ts@@ -13,6 +13,14 @@ export const getForwardableMessages = (messages: UIChatMessage[]): UIChatMessage!!message.children?.some((child) => !!child.content?.trim())),);+export const getForwardedMessageText = (message: UIChatMessage): string =>+ message.role === 'assistantGroup'+ ? message.children+ ?.map((child) => child.content?.trim())+ .filter(Boolean)+ .join('\n\n') || ''+ : message.content;+const blockText = (label: string, body: string) => `**${label}**\n\n${body.trim()}`;export const buildForwardedContent = (@@ -20,16 +28,9 @@ export const buildForwardedContent = (options: ForwardContentOptions,): string => {const blocks = getForwardableMessages(messages).map((message) => {- const content =- message.role === 'assistantGroup'- ? message.children- ?.map((child) => child.content?.trim())- .filter(Boolean)- .join('\n\n') || ''- : message.content;const role = message.role === 'user' ? 'user' : 'assistant';- return blockText(options.roleLabel(role), content);+ return blockText(options.roleLabel(role), getForwardedMessageText(message));});return [options.header, ...blocks].join('\n\n---\n\n');