🤯 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): queue follow-up sends during running CC turns (#14179)
Arvin Xu9b48e24ded16
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 9a9022cdc65..9833bfc70e4 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -204,6 +204,9 @@"input.stop": "Stop","input.warp": "New Line","input.warpWithKey": "Press <key/> to insert a line break",+ "inputQueue.delete": "Delete",+ "inputQueue.edit": "Edit",+ "inputQueue.sendNow": "Send now (interrupts current run)","intentUnderstanding.title": "Understanding your intent...","inviteMembers": "Invite members","knowledgeBase.all": "All Content",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex d80c3b3f6f0..d129dc8bf00 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -204,6 +204,9 @@"input.stop": "停止","input.warp": "换行","input.warpWithKey": "按 <key/> 换行",+ "inputQueue.delete": "删除",+ "inputQueue.edit": "编辑",+ "inputQueue.sendNow": "立即发送(中断当前运行)","intentUnderstanding.title": "正在理解你的意图…","inviteMembers": "邀请成员","knowledgeBase.all": "全部内容",diff --git a/src/features/Conversation/ChatInput/QueueTray.tsx b/src/features/Conversation/ChatInput/QueueTray.tsxindex 84777d6bd39..c662532697f 100644--- a/src/features/Conversation/ChatInput/QueueTray.tsx+++ b/src/features/Conversation/ChatInput/QueueTray.tsx@@ -2,11 +2,16 @@import { ActionIcon, Flexbox, Icon } from '@lobehub/ui';import { createStaticStyles } from 'antd-style';-import { ListEnd, Pencil, Trash2 } from 'lucide-react';+import { ListEnd, Pencil, SendHorizontal, Trash2 } from 'lucide-react';import { memo, useCallback, useMemo } from 'react';+import { useTranslation } from 'react-i18next';import { useChatStore } from '@/store/chat';import { operationSelectors } from '@/store/chat/selectors';+import {+ AI_RUNTIME_OPERATION_TYPES,+ type QueuedMessage,+} from '@/store/chat/slices/operation/types';import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { useConversationStore } from '../store';@@ -40,6 +45,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({}));const QueueTray = memo(() => {+ const { t } = useTranslation('chat');const context = useConversationStore((s) => s.context);const contextKey = useMemo(@@ -65,6 +71,36 @@ const QueueTray = memo(() => {[contextKey, editor, removeQueuedMessage],);+ // "Send now": cancel the currently running agent run for this context, then+ // immediately fire a fresh sendMessage with this queued item's payload. The+ // remaining queue (if any) stays in place — the new turn's onComplete drain+ // will pick them up after it finishes. Reads chatStore inline so we don't+ // re-subscribe the whole tray to the operations map.+ const handleSendNow = useCallback(+ (msg: QueuedMessage) => {+ const chat = useChatStore.getState();+ const runningOpId = chat.operationsByContext[contextKey]?.find((id) => {+ const op = chat.operations[id];+ return op && AI_RUNTIME_OPERATION_TYPES.includes(op.type) && op.status === 'running';+ });+ if (runningOpId) chat.cancelOperation(runningOpId, 'send_now');+ removeQueuedMessage(contextKey, msg.id);++ const filesArray = msg.files?.length ? msg.files.map((id) => ({ id }) as any) : undefined;+ chat+ .sendMessage({+ context,+ editorData: msg.editorData,+ files: filesArray,+ message: msg.content,+ })+ .catch((e: unknown) => {+ console.error('[QueueTray] sendNow failed:', e);+ });+ },+ [context, contextKey, removeQueuedMessage],+ );+if (queuedMessages.length === 0) return null;return (@@ -81,10 +117,22 @@ const QueueTray = memo(() => {<Flexbox className={styles.text} flex={1}>{msg.content}</Flexbox>- <ActionIcon icon={Pencil} size="small" onClick={() => handleEdit(msg.id, msg.content)} />+ <ActionIcon+ icon={Pencil}+ size="small"+ title={t('inputQueue.edit')}+ onClick={() => handleEdit(msg.id, msg.content)}+ />+ <ActionIcon+ icon={SendHorizontal}+ size="small"+ title={t('inputQueue.sendNow')}+ onClick={() => handleSendNow(msg)}+ /><ActionIconicon={Trash2}size="small"+ title={t('inputQueue.delete')}onClick={() => removeQueuedMessage(contextKey, msg.id)}/></Flexbox>diff --git a/src/features/Conversation/ChatInput/utils.test.ts b/src/features/Conversation/ChatInput/utils.test.tsindex ab9c6022f70..97970c3e265 100644--- a/src/features/Conversation/ChatInput/utils.test.ts+++ b/src/features/Conversation/ChatInput/utils.test.ts@@ -16,7 +16,11 @@ describe('getConversationChatInputUiState', () => {});});- it('restores the send button once the user starts a follow-up during loading', () => {+ it('keeps the stop button visible while the user types a follow-up during loading', () => {+ // Regression: flipping to Send the moment the composer had any text read+ // as "agent finished" and made queued sends look like fresh sends. Stop+ // must stay up for the whole loading window — Enter still enqueues, and+ // the QueueTray exposes Send-now per item.expect(getConversationChatInputUiState({isInputEmpty: false,@@ -25,7 +29,7 @@ describe('getConversationChatInputUiState', () => {).toEqual({placeholderVariant: 'default',showSendMenu: false,- showStopButton: false,+ showStopButton: true,});});diff --git a/src/features/Conversation/ChatInput/utils.ts b/src/features/Conversation/ChatInput/utils.tsindex 0111cec17af..182eccf8c68 100644--- a/src/features/Conversation/ChatInput/utils.ts+++ b/src/features/Conversation/ChatInput/utils.ts@@ -15,11 +15,14 @@ export const getConversationChatInputUiState = ({isInputEmpty,isInputLoading,}: GetConversationChatInputUiStateParams): ConversationChatInputUiState => {- const showFollowUpComposer = isInputLoading && isInputEmpty;-+ // Keep the Stop button up for the entire loading window — including when the+ // user starts typing a follow-up. Previously this flipped to Send the moment+ // the composer had any text, which read as "agent finished" and made queued+ // sends look like fresh sends. Pressing Enter still enqueues; the QueueTray+ // exposes per-item Send-now and Edit/Delete for explicit control.return {- placeholderVariant: showFollowUpComposer ? 'followUp' : 'default',+ placeholderVariant: isInputLoading && isInputEmpty ? 'followUp' : 'default',showSendMenu: !isInputLoading,- showStopButton: showFollowUpComposer,+ showStopButton: isInputLoading,};};diff --git a/src/locales/default/chat.ts b/src/locales/default/chat.tsindex 012d93815ee..e841e26d455 100644--- a/src/locales/default/chat.ts+++ b/src/locales/default/chat.ts@@ -180,6 +180,9 @@ export default {'input.stop': 'Stop','input.warp': 'New Line','input.warpWithKey': 'Press <key/> to insert a line break',+ 'inputQueue.delete': 'Delete',+ 'inputQueue.edit': 'Edit',+ 'inputQueue.sendNow': 'Send now (interrupts current run)','intentUnderstanding.title': 'Understanding your intent...','inviteMembers': 'Invite members','knowledgeBase.all': 'All Content',diff --git a/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.tsindex ba5fdcc33fa..9733495d31d 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.ts@@ -574,6 +574,51 @@ describe('ConversationLifecycle actions', () => {'op-running',);});++ it('should enqueue when an execHeterogeneousAgent op is running (CC queue mode)', async () => {+ // LOBE-7346: With Plan A, sends during a running CC turn must hit the+ // same queue path used by client mode — without this we'd spawn a+ // second `claude` process in parallel.+ const { result } = renderHook(() => useChatStore());+ const context = createTestContext();+ const contextKey = messageMapKey(context);++ act(() => {+ useChatStore.setState({+ operations: {+ 'op-cc-running': {+ childOperationIds: [],+ context,+ id: 'op-cc-running',+ metadata: {},+ status: 'running',+ type: 'execHeterogeneousAgent',+ },+ } as any,+ operationsByContext: {+ [contextKey]: ['op-cc-running'],+ },+ });+ });++ const enqueueMessageSpy = vi.spyOn(result.current, 'enqueueMessage');++ await act(async () => {+ await result.current.sendMessage({+ context,+ message: 'follow-up during CC run',+ });+ });++ expect(enqueueMessageSpy).toHaveBeenCalledWith(+ contextKey,+ expect.objectContaining({+ content: 'follow-up during CC run',+ interruptMode: 'soft',+ }),+ 'op-cc-running',+ );+ });});describe('group chat supervisor metadata', () => {diff --git a/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.tsindex 403d035a4c4..a5f6f0d4dda 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.ts@@ -111,11 +111,15 @@ function createMockStore(overrides: Record<string, any> = {}) {return {associateMessageWithOperation: vi.fn(),completeOperation: vi.fn(),+ drainQueuedMessages: vi.fn(() => []),internal_dispatchMessage: vi.fn(),internal_toggleToolCallingStreaming: vi.fn(),+ markUnreadCompleted: vi.fn(),+ operations: {} as Record<string, any>,refreshMessages: vi.fn(async () => {}),refreshThreads: vi.fn(async () => {}),replaceMessages: vi.fn(),+ sendMessage: vi.fn(async () => {}),startOperation: vi.fn(() => {subOpCounter += 1;return {diff --git a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts b/src/store/chat/slices/aiChat/actions/conversationLifecycle.tsindex 65b7bb16165..d01aade6b38 100644--- a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts+++ b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts@@ -46,6 +46,7 @@ import { useUserMemoryStore } from '@/store/userMemory';import { dbMessageSelectors, displayMessageSelectors, topicSelectors } from '../../../selectors';import { messageMapKey } from '../../../utils/messageMapKey';+import { AI_RUNTIME_OPERATION_TYPES } from '../../operation/types';import {type CommandSendOverrides,hasNonActionContent,@@ -234,13 +235,16 @@ export class ConversationLifecycleActionImpl {if (!message && !hasFile) return;// ━━━ Message Queue: enqueue if agent is currently running ━━━- // Check if there's a running execAgentRuntime operation in the current context.- // If so, enqueue the message instead of starting a new operation.+ // Check if there's a running agent-runtime operation in the current context.+ // If so, enqueue the message instead of starting a new operation. Covers all+ // three runtime paths (`AI_RUNTIME_OPERATION_TYPES`) — Client, heterogeneous+ // agent / CC, and Gateway — so a follow-up send never spawns a parallel+ // `claude` process or a second server-side run.const currentContextKey = messageMapKey(operationContext);const contextOpIds = this.#get().operationsByContext[currentContextKey] || [];const runningAgentOp = contextOpIds.map((id) => this.#get().operations[id])- .find((op) => op && op.type === 'execAgentRuntime' && op.status === 'running');+ .find((op) => op && AI_RUNTIME_OPERATION_TYPES.includes(op.type) && op.status === 'running');if (runningAgentOp) {this.#get().enqueueMessage(diff --git a/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts b/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.tsindex c6ec4fa859b..f4683d6a3e2 100644--- a/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts+++ b/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts@@ -28,9 +28,11 @@ import { message as antdMessage } from '@/components/AntdStaticMethods';import { heterogeneousAgentService } from '@/services/electron/heterogeneousAgent';import { messageService } from '@/services/message';import { threadService } from '@/services/thread';-import type { ChatStore } from '@/store/chat/store';+import { type ChatStore, useChatStore } from '@/store/chat/store';import { markdownToTxt } from '@/utils/markdownToTxt';+import { messageMapKey } from '../../../utils/messageMapKey';+import { mergeQueuedMessages } from '../../operation/types';import { createGatewayEventHandler } from './gatewayEventHandler';/** Mirrors `idGenerator('threads', 16)` on the server so sync-allocated ids have the same shape. */@@ -1776,6 +1778,55 @@ export const executeHeterogeneousAgent = async (workingDirectory: workingDirectory ?? '',});}++ // ━━━ Drain queued messages after a successful CC turn ━━━+ // Mirrors the client-mode drain in streamingExecutor.ts. With Plan A we+ // don't extend CC's stdin lifetime — a follow-up message just spawns a+ // new `claude` (with --resume via topic metadata) once the current run+ // exits. Must run AFTER the `updateTopicMetadata` await above so the next+ // sendMessage's `resolveHeteroResume` reads the just-finished session id+ // instead of starting a fresh CLI session and breaking turn-to-turn+ // continuity. Skip on abort/error so a manual stop preserves the queue+ // for the user to manage via QueueTray; "send now" = stop + send.+ // Cast: TS narrows the closure-mutated `deferredTerminalEvent` back to+ // `null` in linear flow (it can't see writes from the async IPC handler).+ const terminalEvent = deferredTerminalEvent as HeterogeneousAgentEvent | null;+ if (!isAborted() && terminalEvent?.type !== 'error') {+ const contextKey = messageMapKey(context);+ const remainingQueued = get().drainQueuedMessages?.(contextKey) ?? [];+ if (remainingQueued.length > 0) {+ // Force-complete this op + mark unread BEFORE the next sendMessage,+ // otherwise its queue check (covering all AI_RUNTIME_OPERATION_TYPES)+ // would still see this op as "running" and re-queue the merged content+ // into a now-orphaned operation.+ get().completeOperation(operationId);+ const completedOp = get().operations?.[operationId];+ if (completedOp?.context.agentId) {+ get().markUnreadCompleted?.(completedOp.context.agentId, completedOp.context.topicId);+ }++ const merged = mergeQueuedMessages(remainingQueued);+ const mergedFiles =+ merged.files.length > 0 ? merged.files.map((id) => ({ id }) as any) : undefined;++ setTimeout(() => {+ useChatStore+ .getState()+ .sendMessage({+ context: { ...context },+ editorData: merged.editorData,+ files: mergedFiles,+ message: merged.content,+ })+ .catch((e: unknown) => {+ console.error(+ '[heterogeneousAgentExecutor] sendMessage for queued content failed:',+ e,+ );+ });+ }, 100);+ }+ }} catch (error) {if (!completed) {if (retryWithoutResume(error)) {