Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix: isolate thread conversation cancellation (#17719)

Arvin Xu4174fd562675
diff --git a/src/features/Conversation/store/slices/generation/action.test.ts b/src/features/Conversation/store/slices/generation/action.test.ts
index 0dfaae8d3e1..42e4f56c388 100644
--- a/src/features/Conversation/store/slices/generation/action.test.ts
+++ b/src/features/Conversation/store/slices/generation/action.test.ts
@@ -84,15 +84,49 @@ describe('Generation Actions', () => {
expect(mockCancelOperations).toHaveBeenCalledWith(
{
- type: INPUT_LOADING_OPERATION_TYPES,
- status: 'running',
agentId: 'session-1',
+ groupId: undefined,
+ isNew: undefined,
+ scope: undefined,
+ status: 'running',
+ threadId: null,
topicId: 'topic-1',
+ type: INPUT_LOADING_OPERATION_TYPES,
},
expect.any(String),
);
});
+ it('should isolate a creating thread from the main conversation in the same topic', () => {
+ const editor = { setJSONState: vi.fn() };
+ const context: ConversationContext = {
+ agentId: 'session-1',
+ isNew: true,
+ scope: 'thread',
+ threadId: null,
+ topicId: 'topic-1',
+ };
+
+ const store = createStore({ context });
+ store.setState({ editor });
+
+ act(() => {
+ store.getState().stopGenerating();
+ });
+
+ expect(mockCancelOperations).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentId: 'session-1',
+ isNew: true,
+ scope: 'thread',
+ threadId: null,
+ topicId: 'topic-1',
+ }),
+ expect.any(String),
+ );
+ expect(mockCancelSendMessageInServer).toHaveBeenCalledWith(context, editor);
+ });
+
it('should call onGenerationStop hook', () => {
const onGenerationStop = vi.fn();
const context: ConversationContext = {
diff --git a/src/features/Conversation/store/slices/generation/action.ts b/src/features/Conversation/store/slices/generation/action.ts
index 58266caa6de..9e3756ffdd8 100644
--- a/src/features/Conversation/store/slices/generation/action.ts
+++ b/src/features/Conversation/store/slices/generation/action.ts
@@ -1068,20 +1068,29 @@ export const generationSlice: StateCreator<
stopGenerating: () => {
const state = get();
- const { context, hooks } = state;
- const { agentId, topicId } = context;
+ const { context, editor, hooks } = state;
+ const { agentId, groupId, isNew, scope, threadId, topicId } = context;
const chatStore = useChatStore.getState();
// Cancel all running operations in this conversation context
// Includes sendMessage, AI runtime (client-side and server-side), and agent mode stream
chatStore.cancelOperations(
- { agentId, status: 'running', topicId, type: INPUT_LOADING_OPERATION_TYPES },
+ {
+ agentId,
+ groupId,
+ isNew,
+ scope,
+ status: 'running',
+ threadId,
+ topicId,
+ type: INPUT_LOADING_OPERATION_TYPES,
+ },
MESSAGE_CANCEL_FLAT,
);
// Restore editor content if a sendMessage operation was cancelled
- chatStore.cancelSendMessageInServer(topicId ?? undefined);
+ chatStore.cancelSendMessageInServer(context, editor);
// ===== Hook: onGenerationStop =====
if (hooks.onGenerationStop) {
diff --git a/src/features/Conversation/store/slices/message/action/sendMessage.ts b/src/features/Conversation/store/slices/message/action/sendMessage.ts
index 4646402897c..75e8e76be70 100644
--- a/src/features/Conversation/store/slices/message/action/sendMessage.ts
+++ b/src/features/Conversation/store/slices/message/action/sendMessage.ts
@@ -21,7 +21,7 @@ export const sendMessage = (
) => {
return async (params: SendMessageParams) => {
const state = get();
- const { context, hooks, displayMessages } = state;
+ const { context, editor, hooks, displayMessages } = state;
// ===== Hook: onBeforeSendMessage =====
if (hooks.onBeforeSendMessage) {
@@ -52,6 +52,7 @@ export const sendMessage = (
const result = await chatStore.sendMessage({
...params,
context,
+ inputEditor: editor,
messages,
onTopicCreated: hooks.onTopicCreated,
});
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts
index 8847e2722f4..22063079627 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts
@@ -242,6 +242,49 @@ describe('ConversationControl actions', () => {
expect(result.current.operations[operationId!].status).toBe('cancelled');
});
+ it('should cancel and restore a creating thread without touching the active main conversation', () => {
+ const { result } = renderHook(() => useChatStore());
+ const mainEditor = { setJSONState: vi.fn() };
+ const threadEditor = { setJSONState: vi.fn() };
+ const threadEditorState = { content: 'thread draft' };
+ const agentId = TEST_IDS.SESSION_ID;
+ const topicId = TEST_IDS.TOPIC_ID;
+
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: agentId,
+ activeTopicId: topicId,
+ mainInputEditor: mainEditor as any,
+ });
+ });
+
+ let mainOperationId: string;
+ let threadOperationId: string;
+ act(() => {
+ mainOperationId = result.current.startOperation({
+ context: { agentId, scope: 'main', topicId },
+ type: 'sendMessage',
+ }).operationId;
+ threadOperationId = result.current.startOperation({
+ context: { agentId, isNew: true, scope: 'thread', threadId: null, topicId },
+ metadata: { inputEditorTempState: threadEditorState },
+ type: 'sendMessage',
+ }).operationId;
+ });
+
+ act(() => {
+ result.current.cancelSendMessageInServer(
+ { agentId, isNew: true, scope: 'thread', threadId: null, topicId },
+ threadEditor as any,
+ );
+ });
+
+ expect(result.current.operations[threadOperationId!].status).toBe('cancelled');
+ expect(result.current.operations[mainOperationId!].status).toBe('running');
+ expect(threadEditor.setJSONState).toHaveBeenCalledWith(threadEditorState);
+ expect(mainEditor.setJSONState).not.toHaveBeenCalled();
+ });
+
it('should handle gracefully when operation does not exist', () => {
const { result } = renderHook(() => useChatStore());
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
index 715b029788f..94ba7b4a590 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
@@ -2037,6 +2037,81 @@ describe('ConversationLifecycle actions', () => {
);
});
+ it('should clear isNew on the runtime operation after a new thread is persisted', async () => {
+ const { result } = renderHook(() => useChatStore());
+ const topicId = 'topic-existing';
+ const createdThreadId = 'thread-created';
+ const draftContext = {
+ agentId: TEST_IDS.SESSION_ID,
+ isNew: true,
+ scope: 'thread' as const,
+ sourceMessageId: 'source-message',
+ threadId: null,
+ threadType: 'continuation' as const,
+ topicId,
+ };
+ const userMessage = createMockMessage({
+ id: TEST_IDS.USER_MESSAGE_ID,
+ role: 'user',
+ });
+ const assistantMessage = createMockMessage({
+ id: TEST_IDS.ASSISTANT_MESSAGE_ID,
+ role: 'assistant',
+ });
+
+ vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({
+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
+ createdThreadId,
+ messages: [userMessage, assistantMessage],
+ topicId,
+ topics: [],
+ userMessageId: TEST_IDS.USER_MESSAGE_ID,
+ } as any);
+ useChatStore.setState({
+ executeClientAgent: vi.fn(async ({ context, parentMessageId, parentOperationId }) => {
+ useChatStore.getState().startOperation({
+ context: { ...context, messageId: parentMessageId },
+ parentOperationId,
+ type: 'execAgentRuntime',
+ });
+ }),
+ });
+
+ await act(async () => {
+ await result.current.sendMessage({
+ context: draftContext,
+ message: 'create thread and keep streaming',
+ });
+ });
+
+ const runtimeOperation = Object.values(result.current.operations).find(
+ (operation) => operation.type === 'execAgentRuntime',
+ );
+ expect(runtimeOperation?.context).toEqual(
+ expect.objectContaining({
+ agentId: TEST_IDS.SESSION_ID,
+ isNew: false,
+ scope: 'thread',
+ threadId: createdThreadId,
+ topicId,
+ }),
+ );
+
+ act(() => {
+ const cancelled = result.current.cancelOperations({
+ agentId: TEST_IDS.SESSION_ID,
+ isNew: false,
+ scope: 'thread',
+ status: 'running',
+ threadId: createdThreadId,
+ topicId,
+ type: 'execAgentRuntime',
+ });
+ expect(cancelled).toEqual([runtimeOperation!.id]);
+ });
+ expect(result.current.operations[runtimeOperation!.id].status).toBe('cancelled');
+ });
+
it('should recover heterogeneous context selections from the persisted user message metadata', async () => {
mockConstEnv.isDesktop = true;
setupMockSelectors({
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts b/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts
index 99bf83055b3..6818f66e69c 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts
@@ -8,6 +8,7 @@ import {
type UIChatMessage,
} from '@lobechat/types';
+import { type ChatInputEditor } from '@/features/ChatInput';
import { lambdaClient } from '@/libs/trpc/client';
import { getAgentStoreState } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
@@ -239,19 +240,26 @@ export class ConversationControlActionImpl {
);
};
- cancelSendMessageInServer = (topicId?: string): void => {
+ cancelSendMessageInServer = (
+ target?: string | ConversationContext,
+ editor?: ChatInputEditor | null,
+ ): void => {
const { activeAgentId, activeGroupId, activeThreadId, activeTopicId } = this.#get();
- // Determine which operation to cancel
- const targetTopicId = topicId ?? activeTopicId;
- // Include groupId/threadId so the key matches how the operation was stored
- // (operationsByContext is keyed by the full messageMapKey).
- const contextKey = messageMapKey({
+ const activeContext: ConversationContext = {
agentId: activeAgentId,
groupId: activeGroupId,
threadId: activeThreadId,
- topicId: targetTopicId,
- });
+ topicId: activeTopicId,
+ };
+ const targetContext =
+ typeof target === 'object'
+ ? target
+ : {
+ ...activeContext,
+ topicId: target ?? activeTopicId,
+ };
+ const contextKey = messageMapKey(targetContext);
// Cancel operations in the operation system
const operationIds = this.#get().operationsByContext[contextKey] || [];
@@ -263,21 +271,18 @@ export class ConversationControlActionImpl {
}
});
- // Restore editor state if it's the active session
- if (
- contextKey ===
- messageMapKey({
- agentId: activeAgentId,
- groupId: activeGroupId,
- threadId: activeThreadId,
- topicId: activeTopicId,
- })
- ) {
+ // An embedded conversation (for example the create-thread portal) owns a
+ // separate editor even though ChatStore only tracks the most recently
+ // mounted editor globally. Prefer the explicitly supplied editor. The
+ // active-conversation fallback preserves the legacy call sites.
+ const targetEditor =
+ editor ?? (contextKey === messageMapKey(activeContext) ? this.#get().mainInputEditor : null);
+ if (targetEditor) {
// Find the latest sendMessage operation with editor state
for (const opId of [...operationIds].reverse()) {
const op = this.#get().operations[opId];
if (op && op.type === 'sendMessage' && op.metadata.inputEditorTempState) {
- this.#get().mainInputEditor?.setJSONState(op.metadata.inputEditorTempState);
+ targetEditor.setJSONState(op.metadata.inputEditorTempState);
break;
}
}
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
index 50976be96d3..d28a8b3561f 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
@@ -31,6 +31,7 @@ import { TRPCClientError } from '@trpc/client';
import { t } from 'i18next';
import { message as antdMessage } from '@/components/AntdStaticMethods';
+import { type ChatInputEditor } from '@/features/ChatInput';
import {
resolveAgentWorkingDirectory,
resolveAgentWorkingDirectoryConfig,
@@ -113,6 +114,12 @@ export interface SendMessageWithContextParams extends SendMessageParams {
* Contains sessionId, topicId, and threadId
*/
context: ConversationContext;
+ /**
+ * Editor owned by the calling ConversationProvider. Embedded conversations
+ * must not fall back to ChatStore's global editor, which may belong to a
+ * sibling panel.
+ */
+ inputEditor?: ChatInputEditor | null;
/**
* Called as soon as the backend reports a newly created topic id, so callers
* with an isolated topic scope (e.g. Task Manager) can switch their UI to the
@@ -254,6 +261,7 @@ export class ConversationLifecycleActionImpl {
onlyAddUserMessage,
context,
contextSelections,
+ inputEditor,
messages: inputMessages,
parentId: inputParentId,
pageSelections,
@@ -261,6 +269,7 @@ export class ConversationLifecycleActionImpl {
}: SendMessageWithContextParams): Promise<SendMessageResult | undefined> => {
let editorData = inputEditorData;
const { executeClientAgent, mainInputEditor } = this.#get();
+ const targetInputEditor = inputEditor ?? mainInputEditor;
const { agentId } = context;
const selectedSkills = parseSelectedSkillsFromEditorData(editorData);
const selectedTools = parseSelectedToolsFromEditorData(editorData);
@@ -825,7 +834,7 @@ export class ConversationLifecycleActionImpl {
}
// Store editor state in operation metadata for cancel restoration
- const jsonState = inputEditorData ?? mainInputEditor?.getJSONState();
+ const jsonState = inputEditorData ?? targetInputEditor?.getJSONState();
this.#get().updateOperationMetadata(operationId, {
inputEditorTempState: jsonState,
inputSendErrorMsg: undefined,
@@ -1337,6 +1346,7 @@ export class ConversationLifecycleActionImpl {
// Create final context with updated topicId/threadId from server response
const finalContext = {
...operationContext,
+ isNew: data.createdThreadId || isCreateNewTopic ? false : operationContext.isNew,
threadId: finalThreadId,
topicId: finalTopicId,
};
@@ -1392,9 +1402,9 @@ export class ConversationLifecycleActionImpl {
this.#get().updateOperationMetadata(operationId, { inputSendErrorMsg: e.message });
const op = this.#get().operations[operationId];
if (op?.metadata.inputEditorTempState) {
- this.#get().mainInputEditor?.setJSONState(op.metadata.inputEditorTempState);
+ targetInputEditor?.setJSONState(op.metadata.inputEditorTempState);
} else {
- this.#get().mainInputEditor?.setDocument('markdown', message);
+ targetInputEditor?.setDocument('markdown', message);
}
}
}
@@ -1448,6 +1458,10 @@ export class ConversationLifecycleActionImpl {
const execContext = {
...operationContext,
+ // The persisted topic/thread is now the identity of this conversation.
+ // Clear the draft marker before creating the child runtime operation so
+ // Stop from the re-rendered ConversationProvider matches it.
+ isNew: data.createdThreadId || isCreatedTopicResponse(data) ? false : operationContext.isNew,
topicId: data.topicId ?? operationContext.topicId,
threadId: data.createdThreadId ?? operationContext.threadId,
};
diff --git a/src/store/chat/slices/operation/__tests__/actions.test.ts b/src/store/chat/slices/operation/__tests__/actions.test.ts
index c5389711b53..62a9f44e232 100644
--- a/src/store/chat/slices/operation/__tests__/actions.test.ts
+++ b/src/store/chat/slices/operation/__tests__/actions.test.ts
@@ -538,6 +538,50 @@ describe('Operation Actions', () => {
expect(result.current.operations[operationId!].status).toBe('cancelled');
});
+
+ it('should not cancel a creating thread when cancelling the main conversation', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ let mainOperationId: string;
+ let threadOperationId: string;
+
+ act(() => {
+ mainOperationId = result.current.startOperation({
+ context: {
+ agentId: 'session1',
+ scope: 'main',
+ threadId: null,
+ topicId: 'topic1',
+ },
+ type: 'execAgentRuntime',
+ }).operationId;
+ threadOperationId = result.current.startOperation({
+ context: {
+ agentId: 'session1',
+ isNew: true,
+ scope: 'thread',
+ threadId: null,
+ topicId: 'topic1',
+ },
+ type: 'execAgentRuntime',
+ }).operationId;
+ });
+
+ act(() => {
+ const cancelled = result.current.cancelOperations({
+ agentId: 'session1',
+ scope: 'main',
+ status: 'running',
+ threadId: null,
+ topicId: 'topic1',
+ type: 'execAgentRuntime',
+ });
+ expect(cancelled).toEqual([mainOperationId!]);
+ });
+
+ expect(result.current.operations[mainOperationId!].status).toBe('cancelled');
+ expect(result.current.operations[threadOperationId!].status).toBe('running');
+ });
});
describe('cleanupCompletedOperations', () => {
diff --git a/src/store/chat/slices/operation/actions.ts b/src/store/chat/slices/operation/actions.ts
index 8a321a856a3..013ed6b5a3d 100644
--- a/src/store/chat/slices/operation/actions.ts
+++ b/src/store/chat/slices/operation/actions.ts
@@ -66,7 +66,7 @@ export class OperationActionsImpl {
context.operationId,
);
} else {
- const { agentId, topicId, threadId, scope, isNew, groupId, documentId } = operation.context;
+ const { agentId, topicId, threadId, scope, groupId, documentId } = operation.context;
log(
'[internal_getConversationContext] get from operation %s: agentId=%s, topicId=%s, threadId=%s, scope=%s, groupId=%s, documentId=%s',
context.operationId,
@@ -531,8 +531,11 @@ export class OperationActionsImpl {
if (filter.groupId !== undefined) {
matches = matches && op.context.groupId === filter.groupId;
}
- if (filter.agentId !== undefined) {
- matches = matches && op.context.agentId === filter.agentId;
+ if (filter.scope !== undefined) {
+ matches = matches && op.context.scope === filter.scope;
+ }
+ if (filter.isNew !== undefined) {
+ matches = matches && op.context.isNew === filter.isNew;
}
if (matches) {
diff --git a/src/store/chat/slices/operation/types.ts b/src/store/chat/slices/operation/types.ts
index 8bd15815384..3f6f4086dcb 100644
--- a/src/store/chat/slices/operation/types.ts
+++ b/src/store/chat/slices/operation/types.ts
@@ -1,4 +1,9 @@
-import type { ConversationContext, MessageMetadata, UploadFileItem } from '@lobechat/types';
+import type {
+ ConversationContext,
+ MessageMapScope,
+ MessageMetadata,
+ UploadFileItem,
+} from '@lobechat/types';
/**
* Operation Type Definitions
@@ -406,9 +411,11 @@ export const mergeQueuedMessages = (messages: QueuedMessage[]): MergedQueuedMess
export interface OperationFilter {
agentId?: string;
groupId?: string;
+ isNew?: boolean;
messageId?: string;
+ scope?: MessageMapScope;
status?: OperationStatus | OperationStatus[];
- threadId?: string;
+ threadId?: string | null;
topicId?: string | null;
type?: OperationType | OperationType[];
}