π€― 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
π fix(chat): queue sends during topic creation (#16473)
YuTengjing35eff9bae29c
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.tsindex aae523d5dfb..4a764d56a1a 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts@@ -999,6 +999,114 @@ describe('ConversationLifecycle actions', () => {'op-cc-running',);});++ it('should enqueue while the first new-topic message is still being persisted', async () => {+ const { result } = renderHook(() => useChatStore());+ const context = createTestContext();+ const contextKey = messageMapKey(context);++ act(() => {+ useChatStore.setState({+ operations: {+ 'op-send-running': {+ childOperationIds: [],+ context: { ...context, messageId: 'tmp-first-user-message' },+ id: 'op-send-running',+ metadata: {},+ status: 'running',+ type: 'sendMessage',+ },+ } as any,+ operationsByContext: {+ [contextKey]: ['op-send-running'],+ },+ });+ });++ const enqueueMessageSpy = vi.spyOn(result.current, 'enqueueMessage');+ const sendMessageInServerSpy = vi+ .spyOn(aiChatService, 'sendMessageInServer')+ .mockResolvedValue({+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ isCreateNewTopic: true,+ messages: [+ createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),+ createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),+ ],+ topicId: TEST_IDS.TOPIC_ID,+ userMessageId: TEST_IDS.USER_MESSAGE_ID,+ } as any);++ await act(async () => {+ await result.current.sendMessage({+ context,+ message: 'fast follow-up before topic is created',+ });+ });++ expect(enqueueMessageSpy).toHaveBeenCalledWith(+ contextKey,+ expect.objectContaining({+ content: 'fast follow-up before topic is created',+ interruptMode: 'soft',+ }),+ 'op-send-running',+ );+ expect(sendMessageInServerSpy).not.toHaveBeenCalled();+ });++ it('should move queued follow-ups from the new-topic key to the created topic key', async () => {+ const { result } = renderHook(() => useChatStore());+ const agentId = TEST_IDS.SESSION_ID;+ const createdTopicId = 'created-topic-id';+ const newTopicKey = messageMapKey({ agentId, topicId: null });+ const createdTopicKey = messageMapKey({ agentId, topicId: createdTopicId });+ const queuedMessage = {+ content: 'queued while topic is being created',+ createdAt: Date.now(),+ id: 'queued-before-topic-created',+ interruptMode: 'soft' as const,+ };++ act(() => {+ useChatStore.setState({+ activeAgentId: agentId,+ activeTopicId: undefined,+ queuedMessages: {+ [newTopicKey]: [queuedMessage],+ },+ });+ });++ vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ isCreateNewTopic: true,+ messages: [+ createMockMessage({+ id: TEST_IDS.USER_MESSAGE_ID,+ role: 'user',+ topicId: createdTopicId,+ }),+ createMockMessage({+ id: TEST_IDS.ASSISTANT_MESSAGE_ID,+ role: 'assistant',+ topicId: createdTopicId,+ }),+ ],+ topicId: createdTopicId,+ userMessageId: TEST_IDS.USER_MESSAGE_ID,+ } as any);++ await act(async () => {+ await result.current.sendMessage({+ context: { agentId, threadId: null, topicId: null },+ message: TEST_CONTENT.USER_MESSAGE,+ });+ });++ expect(useChatStore.getState().queuedMessages[newTopicKey] ?? []).toEqual([]);+ expect(useChatStore.getState().queuedMessages[createdTopicKey]).toEqual([queuedMessage]);+ });});describe('page scope documentId injection', () => {diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.tsindex 484c857dc5b..3bb3a1af451 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type * as ConstVersion from '@/const/version';import { aiAgentService } from '@/services/aiAgent';import { topicService } from '@/services/topic';+import { messageMapKey } from '@/store/chat/utils/messageMapKey';import type { GatewayConnection } from '../transports/gateway/gateway';import { GatewayActionImpl } from '../transports/gateway/gateway';@@ -508,6 +509,7 @@ describe('GatewayActionImpl', () => {describe('executeGatewayAgent', () => {function createExecuteTestAction() {const mockClient = createMockClient();+ const moveQueuedMessages = vi.fn();const state: Record<string, any> = { gatewayConnections: {}, topicDataMap: {} };const associateMessageWithOperation = vi.fn();const connectToGateway = vi.fn();@@ -535,6 +537,7 @@ describe('GatewayActionImpl', () => {internal_dispatchTopic: internalDispatchTopic,internal_replaceTopicId: internalReplaceTopicId,internal_updateTopicLoading: internalUpdateTopicLoading,+ moveQueuedMessages,onOperationCancel,replaceMessages,refreshTopic,@@ -564,6 +567,7 @@ describe('GatewayActionImpl', () => {internalReplaceTopicId,internalUpdateTopicLoading,mockClient,+ moveQueuedMessages,onOperationCancel,replaceMessages,refreshTopic,@@ -644,6 +648,36 @@ describe('GatewayActionImpl', () => {);});+ it('should move queued follow-ups from the new-topic key to the server-created topic key', async () => {+ const { action, moveQueuedMessages } = createExecuteTestAction();+ const context = { agentId: 'agent-1', topicId: null, threadId: null };++ vi.mocked(aiAgentService.execAgentTask).mockResolvedValue({+ agentId: 'agent-1',+ assistantMessageId: 'ast-1',+ autoStarted: true,+ createdAt: new Date().toISOString(),+ message: 'ok',+ operationId: 'server-op-1',+ status: 'created',+ success: true,+ timestamp: new Date().toISOString(),+ token: 'test-token',+ topicId: 'topic-created',+ userMessageId: 'usr-1',+ });++ await action.executeGatewayAgent({+ context,+ message: 'Hello',+ });++ expect(moveQueuedMessages).toHaveBeenCalledWith(+ messageMapKey(context),+ messageMapKey({ ...context, topicId: 'topic-created' }),+ );+ });+it('should replace the optimistic topic placeholder with the server topic id', async () => {const { action, internalReplaceTopicId } = createExecuteTestAction();@@ -927,6 +961,7 @@ describe('GatewayActionImpl', () => {connectToGateway: vi.fn(),internal_dispatchTopic: vi.fn(),internal_updateTopicLoading: vi.fn(),+ moveQueuedMessages: vi.fn(),onOperationCancel,replaceMessages: vi.fn(),startOperation,diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.tsindex 7a76cd893f5..84bae9839a6 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts@@ -47,7 +47,8 @@ import { dispatchNonHeteroSubAgent } from '@/store/chat/slices/agentRun/actions/import { buildRunLifecycle } from '@/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle';import type { RunScope } from '@/store/chat/slices/agentRun/actions/lifecycle/types';import { resolveHeteroResume } from '@/store/chat/slices/agentRun/actions/transports/hetero/heteroResume';-import { AI_RUNTIME_OPERATION_TYPES, type QueuedFile } from '@/store/chat/slices/operation/types';+import type { OperationType, QueuedFile } from '@/store/chat/slices/operation/types';+import { AI_RUNTIME_OPERATION_TYPES } from '@/store/chat/slices/operation/types';import { PortalViewType } from '@/store/chat/slices/portal/initialState';import { chatPortalSelectors } from '@/store/chat/slices/portal/selectors';import { type ChatStore } from '@/store/chat/store';@@ -145,6 +146,11 @@ const isAbortError = (error: unknown, abortController?: AbortController) =>const createAbortError = () =>Object.assign(new Error('Compression cancelled'), { name: 'AbortError' });+const QUEUE_BLOCKING_OPERATION_TYPES = new Set<OperationType>([+ ...AI_RUNTIME_OPERATION_TYPES,+ 'sendMessage',+]);+const attachSendTimeMetadataToUserMessage = (messages: UIChatMessage[],userMessageId: string,@@ -399,19 +405,18 @@ export class ConversationLifecycleActionImpl {const newTopicTitle = markdownToTxt(message).slice(0, 80) || t('defaultTitle', { ns: 'topic' });- // βββ Message Queue: enqueue if agent is currently running βββ- // 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.+ // βββ Message Queue: enqueue if this context is already busy βββ+ // Include the initial `sendMessage` persist/create-topic phase. Example:+ // first send from a blank chat is still creating topic A (`topicId=null`);+ // a fast second Enter must queue on `main_<agent>_new` instead of starting+ // topic B.const currentContextKey = messageMapKey(operationContext);const contextOpIds = this.#get().operationsByContext[currentContextKey] || [];- const runningAgentOp = contextOpIds+ const runningQueueBlockingOp = contextOpIds.map((id) => this.#get().operations[id])- .find((op) => op && AI_RUNTIME_OPERATION_TYPES.includes(op.type) && op.status === 'running');+ .find((op) => op && QUEUE_BLOCKING_OPERATION_TYPES.has(op.type) && op.status === 'running');- if (runningAgentOp) {+ if (runningQueueBlockingOp) {// Snapshot file previews so the tray can render thumbnails AND the// resumed sendMessage can rebuild imageList/videoList β by the time// we drain, chatUploadFileList has long been cleared.@@ -435,7 +440,7 @@ export class ConversationLifecycleActionImpl {metadata: userMessageMetadata,createdAt: Date.now(),},- runningAgentOp.id,+ runningQueueBlockingOp.id,);return;}@@ -724,6 +729,7 @@ export class ConversationLifecycleActionImpl {};const heteroResponseMeta = heteroData as SendMessageServerResponseMeta;const heteroMessageKey = messageMapKey(heteroContext);+ this.#get().moveQueuedMessages(currentContextKey, heteroMessageKey);const heteroMessages = heteroResponseMeta.__isPartialMessages? mergePartialPersistedMessages(this.#get().messagesMap[heteroMessageKey] || [],@@ -1071,13 +1077,18 @@ export class ConversationLifecycleActionImpl {}// Create final context with updated topicId/threadId from server response- const finalContext = { ...operationContext, topicId: finalTopicId, threadId: finalThreadId };+ const finalContext = {+ ...operationContext,+ threadId: finalThreadId,+ topicId: finalTopicId,+ };+ const finalMessageKey = messageMapKey(finalContext);+ this.#get().moveQueuedMessages(currentContextKey, finalMessageKey);const persistedMessages = attachSendTimeMetadataToUserMessage(data.messages,data.userMessageId,userMessageMetadata,);- const finalMessageKey = messageMapKey(finalContext);data = {...data,messages: responseMeta.__isPartialMessagesdiff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.tsindex 65cf8338355..89b97a418db 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts@@ -16,6 +16,7 @@ import { chatConfigByIdSelectors } from '@/store/agent/selectors';import { consumePendingTopicRepos, getPendingTopicRepos } from '@/store/chat/pendingTopicRepos';import { topicSelectors } from '@/store/chat/selectors';import type { ChatStore } from '@/store/chat/store';+import { messageMapKey } from '@/store/chat/utils/messageMapKey';import type { StoreSetter } from '@/store/types';import { useUserStore } from '@/store/user';import { settingsSelectors, toolInterventionSelectors } from '@/store/user/selectors';@@ -533,6 +534,7 @@ export class GatewayActionImpl {// Use the server-created topicId for the execution contextconst execContext = { ...context, topicId: result.topicId };+ this.#get().moveQueuedMessages(messageMapKey(context), messageMapKey(execContext));if (result.topicId) {if (!optimisticTopic) this.#get().internal_updateTopicLoading(result.topicId, true);diff --git a/src/store/chat/slices/operation/actions.ts b/src/store/chat/slices/operation/actions.tsindex a252d25c232..8a321a856a3 100644--- a/src/store/chat/slices/operation/actions.ts+++ b/src/store/chat/slices/operation/actions.ts@@ -790,6 +790,33 @@ export class OperationActionsImpl {return messages;};+ moveQueuedMessages = (fromContextKey: string, toContextKey: string): void => {+ if (fromContextKey === toContextKey) return;++ const queue = this.#get().queuedMessages[fromContextKey];+ if (!queue || queue.length === 0) return;++ this.#set(+ produce((state: ChatStore) => {+ const fromQueue = state.queuedMessages[fromContextKey];+ if (!fromQueue || fromQueue.length === 0) return;++ const toQueue = state.queuedMessages[toContextKey] ?? [];+ state.queuedMessages[toContextKey] = [...toQueue, ...fromQueue];+ state.queuedMessages[fromContextKey] = [];+ }),+ false,+ n(`moveQueuedMessages/${fromContextKey}/${toContextKey}`),+ );++ log(+ '[moveQueuedMessages] fromContextKey=%s, toContextKey=%s, moved %d',+ fromContextKey,+ toContextKey,+ queue.length,+ );+ };+removeQueuedMessage = (contextKey: string, messageId: string): void => {this.#set(produce((state: ChatStore) => {