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.

🔨 chore: implement unified operation state management (#10275)

Arvin Xuc5e0ecd31ed7
diff --git a/packages/agent-runtime/src/types/instruction.ts b/packages/agent-runtime/src/types/instruction.ts
index 3ea8dcc4ec6..39b7dcc27d1 100644
--- a/packages/agent-runtime/src/types/instruction.ts
+++ b/packages/agent-runtime/src/types/instruction.ts
@@ -9,6 +9,10 @@ import type { Cost, CostCalculationContext, Usage } from './usage';
*/
export interface AgentRuntimeContext {
metadata?: Record<string, unknown>;
+
+ /** Operation ID (links to Operation for business context) */
+ operationId?: string;
+
/** Phase-specific payload/context */
payload?: unknown;
/** Current execution phase */
@@ -21,8 +25,9 @@ export interface AgentRuntimeContext {
| 'human_response'
| 'human_approved_tool'
| 'error';
- /** Session */
- session: {
+
+ /** Session info (kept for backward compatibility, will be optional in the future) */
+ session?: {
messageCount: number;
sessionId: string;
status: AgentState['status'];
diff --git a/src/store/chat/initialState.ts b/src/store/chat/initialState.ts
index 66637589660..d3b0f22076c 100644
--- a/src/store/chat/initialState.ts
+++ b/src/store/chat/initialState.ts
@@ -5,13 +5,15 @@ import { ChatMessageState, initialMessageState } from './slices/message/initialS
import { ChatTopicState, initialTopicState } from './slices/topic/initialState';
import { ChatAIChatState, initialAiChatState } from './slices/aiChat/initialState';
import { ChatThreadState, initialThreadState } from './slices/thread/initialState';
+import { ChatOperationState, initialOperationState } from './slices/operation/initialState';
export type ChatStoreState = ChatTopicState &
ChatMessageState &
ChatAIChatState &
ChatToolState &
ChatThreadState &
- ChatPortalState;
+ ChatPortalState &
+ ChatOperationState;
export const initialState: ChatStoreState = {
...initialMessageState,
@@ -20,6 +22,7 @@ export const initialState: ChatStoreState = {
...initialToolState,
...initialThreadState,
...initialChatPortalState,
+ ...initialOperationState,
// cloud
};
diff --git a/src/store/chat/slices/operation/__tests__/actions.test.ts b/src/store/chat/slices/operation/__tests__/actions.test.ts
new file mode 100644
index 00000000000..6173170f508
--- /dev/null
+++ b/src/store/chat/slices/operation/__tests__/actions.test.ts
@@ -0,0 +1,353 @@
+import { act, renderHook } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useChatStore } from '@/store/chat/store';
+
+describe('Operation Actions', () => {
+ beforeEach(() => {
+ useChatStore.setState(useChatStore.getInitialState());
+ });
+
+ afterEach(() => {
+ vi.clearAllTimers();
+ });
+
+ describe('startOperation', () => {
+ it('should create a new operation with correct initial state', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ let operationId: string;
+ let abortController: AbortController;
+
+ act(() => {
+ const res = result.current.startOperation({
+ type: 'generateAI',
+ context: { sessionId: 'session1', topicId: 'topic1', messageId: 'msg1' },
+ label: 'Generating...',
+ });
+ operationId = res.operationId;
+ abortController = res.abortController;
+ });
+
+ const operation = result.current.operations[operationId!];
+
+ expect(operation).toBeDefined();
+ expect(operation.type).toBe('generateAI');
+ expect(operation.status).toBe('running');
+ expect(operation.context.sessionId).toBe('session1');
+ expect(operation.context.topicId).toBe('topic1');
+ expect(operation.context.messageId).toBe('msg1');
+ expect(operation.label).toBe('Generating...');
+ expect(operation.abortController).toBe(abortController!);
+ });
+
+ it('should inherit context from parent operation', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ let parentOpId: string;
+ let childOpId: string;
+
+ act(() => {
+ // Create parent operation
+ const parent = result.current.startOperation({
+ type: 'sendMessage',
+ context: { sessionId: 'session1', topicId: 'topic1' },
+ });
+ parentOpId = parent.operationId;
+
+ // Create child operation (inherits context)
+ const child = result.current.startOperation({
+ type: 'generateAI',
+ context: { messageId: 'msg1' }, // Only override messageId
+ parentOperationId: parentOpId,
+ });
+ childOpId = child.operationId;
+ });
+
+ const childOp = result.current.operations[childOpId!];
+
+ expect(childOp.context.sessionId).toBe('session1'); // Inherited
+ expect(childOp.context.topicId).toBe('topic1'); // Inherited
+ expect(childOp.context.messageId).toBe('msg1'); // Overridden
+ expect(childOp.parentOperationId).toBe(parentOpId!);
+ });
+
+ it('should fully inherit parent context when child context is undefined', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ let parentOpId: string;
+ let childOpId: string;
+
+ act(() => {
+ // Create parent operation with full context
+ const parent = result.current.startOperation({
+ type: 'sendMessage',
+ context: { sessionId: 'session1', topicId: 'topic1', messageId: 'msg1' },
+ });
+ parentOpId = parent.operationId;
+
+ // Create child operation without context (undefined)
+ const child = result.current.startOperation({
+ type: 'generateAI',
+ parentOperationId: parentOpId,
+ });
+ childOpId = child.operationId;
+ });
+
+ const childOp = result.current.operations[childOpId!];
+
+ // Should fully inherit parent's context
+ expect(childOp.context.sessionId).toBe('session1');
+ expect(childOp.context.topicId).toBe('topic1');
+ expect(childOp.context.messageId).toBe('msg1');
+ expect(childOp.parentOperationId).toBe(parentOpId!);
+ });
+
+ it('should update indexes correctly', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ let operationId: string;
+
+ act(() => {
+ operationId = result.current.startOperation({
+ type: 'generateAI',
+ context: { sessionId: 'session1', topicId: 'topic1', messageId: 'msg1' },
+ }).operationId;
+ });
+
+ // Check type index
+ expect(result.current.operationsByType.generateAI).toContain(operationId!);
+
+ // Check message index
+ expect(result.current.operationsByMessage.msg1).toContain(operationId!);
+
+ // Check context index
+ const contextKey = 'session1_topic1';
+ expect(result.current.operationsByContext[contextKey]).toContain(operationId!);
+ });
+ });
+
+ describe('completeOperation', () => {
+ it('should mark operation as completed with correct metadata', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ let operationId: string;
+
+ act(() => {
+ operationId = result.current.startOperation({
+ type: 'generateAI',
+ context: { sessionId: 'session1' },
+ }).operationId;
+ });
+
+ const startTime = result.current.operations[operationId!].metadata.startTime;
+
+ act(() => {
+ result.current.completeOperation(operationId!);
+ });
+
+ const operation = result.current.operations[operationId!];
+
+ expect(operation.status).toBe('completed');
+ expect(operation.metadata.endTime).toBeDefined();
+ expect(operation.metadata.duration).toBeDefined();
+ expect(operation.metadata.duration).toBeGreaterThanOrEqual(0);
+ });
+ });
+
+ describe('cancelOperation', () => {
+ it('should cancel operation and abort controller', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ let operationId: string;
+ let abortController: AbortController;
+
+ act(() => {
+ const res = result.current.startOperation({
+ type: 'generateAI',
+ context: { sessionId: 'session1' },
+ });
+ operationId = res.operationId;
+ abortController = res.abortController;
+ });
+
+ act(() => {
+ result.current.cancelOperation(operationId!, 'User cancelled');
+ });
+
+ const operation = result.current.operations[operationId!];
+
+ expect(operation.status).toBe('cancelled');
+ expect(operation.metadata.cancelReason).toBe('User cancelled');
+ expect(abortController!.signal.aborted).toBe(true);
+ });
+
+ it('should recursively cancel child operations', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ let parentOpId: string;
+ let child1OpId: string;
+ let child2OpId: string;
+
+ act(() => {
+ parentOpId = result.current.startOperation({
+ type: 'generateAI',
+ context: { sessionId: 'session1' },
+ }).operationId;
+
+ child1OpId = result.current.startOperation({
+ type: 'reasoning',
+ parentOperationId: parentOpId,
+ }).operationId;
+
+ child2OpId = result.current.startOperation({
+ type: 'toolCalling',
+ parentOperationId: parentOpId,
+ }).operationId;
+ });
+
+ act(() => {
+ result.current.cancelOperation(parentOpId!);
+ });
+
+ expect(result.current.operations[parentOpId!].status).toBe('cancelled');
+ expect(result.current.operations[child1OpId!].status).toBe('cancelled');
+ expect(result.current.operations[child2OpId!].status).toBe('cancelled');
+ });
+ });
+
+ describe('failOperation', () => {
+ it('should mark operation as failed with error', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ let operationId: string;
+
+ act(() => {
+ operationId = result.current.startOperation({
+ type: 'generateAI',
+ context: { sessionId: 'session1' },
+ }).operationId;
+ });
+
+ act(() => {
+ result.current.failOperation(operationId!, {
+ type: 'NetworkError',
+ message: 'Connection failed',
+ code: 'ERR_NETWORK',
+ });
+ });
+
+ const operation = result.current.operations[operationId!];
+
+ expect(operation.status).toBe('failed');
+ expect(operation.metadata.error).toEqual({
+ type: 'NetworkError',
+ message: 'Connection failed',
+ code: 'ERR_NETWORK',
+ });
+ });
+ });
+
+ describe('cancelOperations (batch)', () => {
+ it('should cancel operations matching filter', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ let op1: string;
+ let op2: string;
+ let op3: string;
+
+ act(() => {
+ op1 = result.current.startOperation({
+ type: 'generateAI',
+ context: { sessionId: 'session1' },
+ }).operationId;
+
+ op2 = result.current.startOperation({
+ type: 'generateAI',
+ context: { sessionId: 'session1' },
+ }).operationId;
+
+ op3 = result.current.startOperation({
+ type: 'reasoning',
+ context: { sessionId: 'session1' },
+ }).operationId;
+ });
+
+ act(() => {
+ const cancelled = result.current.cancelOperations({ type: 'generateAI' });
+ expect(cancelled).toHaveLength(2);
+ });
+
+ expect(result.current.operations[op1!].status).toBe('cancelled');
+ expect(result.current.operations[op2!].status).toBe('cancelled');
+ expect(result.current.operations[op3!].status).toBe('running'); // Not cancelled
+ });
+ });
+
+ describe('associateMessageWithOperation', () => {
+ it('should create message-operation mapping', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ let operationId: string;
+
+ act(() => {
+ operationId = result.current.startOperation({
+ type: 'generateAI',
+ context: { sessionId: 'session1' },
+ }).operationId;
+
+ result.current.associateMessageWithOperation('msg1', operationId!);
+ });
+
+ expect(result.current.messageOperationMap.msg1).toBe(operationId!);
+ });
+ });
+
+ describe('cleanupCompletedOperations', () => {
+ it('should remove old completed operations', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ let op1: string;
+ let op2: string;
+
+ act(() => {
+ op1 = result.current.startOperation({
+ type: 'generateAI',
+ context: { sessionId: 'session1' },
+ }).operationId;
+
+ op2 = result.current.startOperation({
+ type: 'generateAI',
+ context: { sessionId: 'session1' },
+ }).operationId;
+ });
+
+ act(() => {
+ result.current.completeOperation(op1!);
+ });
+
+ // Manually set endTime to past
+ act(() => {
+ useChatStore.setState({
+ operations: {
+ ...result.current.operations,
+ [op1!]: {
+ ...result.current.operations[op1!],
+ metadata: {
+ ...result.current.operations[op1!].metadata,
+ endTime: Date.now() - 120000, // 2 minutes ago
+ },
+ },
+ },
+ });
+ });
+
+ act(() => {
+ result.current.cleanupCompletedOperations(60000); // 1 minute threshold
+ });
+
+ expect(result.current.operations[op1!]).toBeUndefined(); // Cleaned up
+ expect(result.current.operations[op2!]).toBeDefined(); // Still running
+ });
+ });
+});
diff --git a/src/store/chat/slices/operation/__tests__/selectors.test.ts b/src/store/chat/slices/operation/__tests__/selectors.test.ts
new file mode 100644
index 00000000000..532aaa3d013
--- /dev/null
+++ b/src/store/chat/slices/operation/__tests__/selectors.test.ts
@@ -0,0 +1,273 @@
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { useChatStore } from '@/store/chat/store';
+
+import { operationSelectors } from '../selectors';
+
+describe('Operation Selectors', () => {
+ beforeEach(() => {
+ useChatStore.setState(useChatStore.getInitialState());
+ });
+
+ describe('getOperationsByType', () => {
+ it('should return operations of specific type', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ act(() => {
+ result.current.startOperation({
+ type: 'generateAI',
+ context: { sessionId: 'session1' },
+ });
+
+ result.current.startOperation({
+ type: 'generateAI',
+ context: { sessionId: 'session1' },
+ });
+
+ result.current.startOperation({
+ type: 'reasoning',
+ context: { sessionId: 'session1' },
+ });
+ });
+
+ const generateOps = operationSelectors.getOperationsByType('generateAI')(result.current);
+ const reasoningOps = operationSelectors.getOperationsByType('reasoning')(result.current);
+
+ expect(generateOps).toHaveLength(2);
+ expect(reasoningOps).toHaveLength(1);
+ });
+ });
+
+ describe('getCurrentContextOperations', () => {
+ it('should return operations for current active session/topic', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ act(() => {
+ // Set active session and topic
+ useChatStore.setState({ activeId: 'session1', activeTopicId: 'topic1' });
+
+ result.current.startOperation({
+ type: 'generateAI',
+ context: { sessionId: 'session1', topicId: 'topic1' },
+ });
+
+ result.current.startOperation({
+ type: 'reasoning',
+ context: { sessionId: 'session1', topicId: 'topic1' },
+ });
+
+ // Operation in different context
+ result.current.startOperation({
+ type: 'generateAI',
+ context: { sessionId: 'session2', topicId: 'topic2' },
+ });
+ });
+
+ const currentOps = operationSelectors.getCurrentContextOperations(result.current);
+
+ expect(currentOps).toHaveLength(2);
+ expect(currentOps.every((op) => op.context.sessionId === 'session1')).toBe(true);
+ expect(currentOps.every((op) => op.context.topicId === 'topic1')).toBe(true);
+ });
+ });
+
+ describe('hasAnyRunningOperation', () => {
+ it('should return true if any operation is running', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ expect(operationSelectors.hasAnyRunningOperation(result.current)).toBe(false);
+
+ let opId: string;
+
+ act(() => {
+ opId = result.current.startOperation({
+ type: 'generateAI',
+ context: { sessionId: 'session1' },
+ }).operationId;
+ });
+
+ expect(operationSelectors.hasAnyRunningOperation(result.current)).toBe(true);
+
+ act(() => {
+ result.current.completeOperation(opId!);
+ });
+
+ expect(operationSelectors.hasAnyRunningOperation(result.current)).toBe(false);
+ });
+ });
+
+ describe('hasRunningOperationType', () => {
+ it('should return true if specific type is running', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ act(() => {
+ result.current.startOperation({
+ type: 'generateAI',
+ context: { sessionId: 'session1' },
+ });
+ });
+
+ expect(operationSelectors.hasRunningOperationType('generateAI')(result.current)).toBe(true);
+ expect(operationSelectors.hasRunningOperationType('reasoning')(result.current)).toBe(false);
+ });
+ });
+
+ describe('canSendMessage', () => {
+ it('should return false when operations are running in current context', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ act(() => {
+ useChatStore.setState({ activeId: 'session1', activeTopicId: 'topic1' });
+ });
+
+ expect(operationSelectors.canSendMessage(result.current)).toBe(true);
+
+ act(() => {
+ result.current.startOperation({
+ type: 'generateAI',
+ context: { sessionId: 'session1', topicId: 'topic1' },
+ });
+ });
+
+ expect(operationSelectors.canSendMessage(result.current)).toBe(false);
+ });
+ });
+
+ describe('canInterrupt', () => {
+ it('should return true when operations can be cancelled', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ act(() => {
+ useChatStore.setState({ activeId: 'session1', activeTopicId: 'topic1' });
+ });
+
+ expect(operationSelectors.canInterrupt(result.current)).toBe(false);
+
+ act(() => {
+ result.current.startOperation({
+ type: 'generateAI',
+ context: { sessionId: 'session1', topicId: 'topic1' },
+ });
+ });
+
+ expect(operationSelectors.canInterrupt(result.current)).toBe(true);
+ });
+ });
+
+ describe('getCurrentOperationLabel', () => {
+ it('should return label of most recent running operation', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ act(() => {
+ useChatStore.setState({ activeId: 'session1', activeTopicId: 'topic1' });
+
+ result.current.startOperation({
+ type: 'generateAI',
+ context: { sessionId: 'session1', topicId: 'topic1' },
+ label: 'Generating response...',
+ });
+
+ // Simulate some time passing
+ setTimeout(() => {
+ result.current.startOperation({
+ type: 'reasoning',
+ context: { sessionId: 'session1', topicId: 'topic1' },
+ label: 'Thinking...',
+ });
+ }, 10);
+ });
+
+ // Should return the most recent operation's label
+ const label = operationSelectors.getCurrentOperationLabel(result.current);
+ expect(label).toBeTruthy();
+ });
+ });
+
+ describe('isMessageProcessing', () => {
+ it('should return true if message has running operations', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ act(() => {
+ result.current.startOperation({
+ type: 'generateAI',
+ context: { sessionId: 'session1', messageId: 'msg1' },
+ });
+ });
+
+ expect(operationSelectors.isMessageProcessing('msg1')(result.current)).toBe(true);
+ expect(operationSelectors.isMessageProcessing('msg2')(result.current)).toBe(false);
+ });
+ });
+
+ describe('getOperationContextFromMessage', () => {
+ it('should return operation context from message ID', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ let opId: string;
+
+ act(() => {
+ opId = result.current.startOperation({
+ type: 'generateAI',
+ context: { sessionId: 'session1', topicId: 'topic1', messageId: 'msg1' },
+ }).operationId;
+
+ result.current.associateMessageWithOperation('msg1', opId!);
+ });
+
+ const context = operationSelectors.getOperationContextFromMessage('msg1')(result.current);
+
+ expect(context).toBeDefined();
+ expect(context?.sessionId).toBe('session1');
+ expect(context?.topicId).toBe('topic1');
+ expect(context?.messageId).toBe('msg1');
+ });
+ });
+
+ describe('backward compatibility selectors', () => {
+ it('isAIGenerating should work', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ expect(operationSelectors.isAIGenerating(result.current)).toBe(false);
+
+ act(() => {
+ result.current.startOperation({
+ type: 'generateAI',
+ context: { sessionId: 'session1' },
+ });
+ });
+
+ expect(operationSelectors.isAIGenerating(result.current)).toBe(true);
+ });
+
+ it('isSendingMessage should work', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ expect(operationSelectors.isSendingMessage(result.current)).toBe(false);
+
+ act(() => {
+ result.current.startOperation({
+ type: 'sendMessage',
+ context: { sessionId: 'session1' },
+ });
+ });
+
+ expect(operationSelectors.isSendingMessage(result.current)).toBe(true);
+ });
+
+ it('isInRAGFlow should work', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ expect(operationSelectors.isInRAGFlow(result.current)).toBe(false);
+
+ act(() => {
+ result.current.startOperation({
+ type: 'rag',
+ context: { sessionId: 'session1' },
+ });
+ });
+
+ expect(operationSelectors.isInRAGFlow(result.current)).toBe(true);
+ });
+ });
+});
diff --git a/src/store/chat/slices/operation/actions.ts b/src/store/chat/slices/operation/actions.ts
new file mode 100644
index 00000000000..11137e1a3c8
--- /dev/null
+++ b/src/store/chat/slices/operation/actions.ts
@@ -0,0 +1,451 @@
+/* eslint-disable sort-keys-fix/sort-keys-fix */
+import { nanoid } from '@lobechat/utils';
+import { produce } from 'immer';
+import { StateCreator } from 'zustand/vanilla';
+
+import { ChatStore } from '@/store/chat/store';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
+import { setNamespace } from '@/utils/storeDebug';
+
+import type {
+ Operation,
+ OperationContext,
+ OperationFilter,
+ OperationMetadata,
+ OperationStatus,
+ OperationType,
+} from './types';
+
+const n = setNamespace('operation');
+
+/**
+ * Operation Actions
+ */
+export interface OperationActions {
+ /**
+ * Associate message with operation (for automatic context retrieval)
+ */
+ associateMessageWithOperation: (messageId: string, operationId: string) => void;
+
+ /**
+ * Cancel all operations
+ */
+ cancelAllOperations: (reason?: string) => void;
+
+ /**
+ * Cancel operation (recursively cancel all child operations)
+ */
+ cancelOperation: (operationId: string, reason?: string) => void;
+
+ /**
+ * Cancel operations by filter
+ */
+ cancelOperations: (filter: OperationFilter, reason?: string) => string[];
+
+ /**
+ * Cleanup completed operations (prevent memory leak)
+ */
+ cleanupCompletedOperations: (olderThan?: number) => void;
+
+ /**
+ * Complete operation
+ */
+ completeOperation: (operationId: string, metadata?: Partial<OperationMetadata>) => void;
+
+ /**
+ * Mark operation as failed
+ */
+ failOperation: (
+ operationId: string,
+ error: { code?: string; details?: any; message: string; type: string },
+ ) => void;
+
+ /**
+ * Start an operation (supports auto-inheriting context from parent operation)
+ */
+ startOperation: (params: {
+ context?: Partial<OperationContext>;
+ description?: string;
+ label?: string;
+ metadata?: Partial<OperationMetadata>;
+ parentOperationId?: string;
+ type: OperationType;
+ }) => { abortController: AbortController; operationId: string };
+
+ /**
+ * Update operation progress
+ */
+ updateOperationProgress: (operationId: string, current: number, total?: number) => void;
+
+ /**
+ * Update operation status
+ */
+ updateOperationStatus: (
+ operationId: string,
+ status: OperationStatus,
+ metadata?: Partial<OperationMetadata>,
+ ) => void;
+}
+
+export const operationActions: StateCreator<
+ ChatStore,
+ [['zustand/devtools', never]],
+ [],
+ OperationActions
+> = (set, get) => ({
+ startOperation: (params) => {
+ const {
+ type,
+ context: partialContext,
+ parentOperationId,
+ label,
+ description,
+ metadata,
+ } = params;
+
+ const operationId = `op_${nanoid()}`;
+
+ // If parent operation exists and context is not fully provided, inherit from parent
+ let context: OperationContext = partialContext || {};
+
+ if (parentOperationId) {
+ const parentOp = get().operations[parentOperationId];
+ if (parentOp) {
+ // Inherit parent's context, allow partial override
+ context = { ...parentOp.context, ...(partialContext ?? {}) };
+ }
+ }
+
+ const abortController = new AbortController();
+ const now = Date.now();
+
+ const operation: Operation = {
+ id: operationId,
+ type,
+ status: 'running',
+ context,
+ abortController,
+ metadata: {
+ startTime: now,
+ ...metadata,
+ },
+ parentOperationId,
+ childOperationIds: [],
+ label,
+ description,
+ };
+
+ set(
+ produce((state: ChatStore) => {
+ // Add to operations map
+ state.operations[operationId] = operation;
+
+ // Update type index
+ if (!state.operationsByType[type]) {
+ state.operationsByType[type] = [];
+ }
+ state.operationsByType[type].push(operationId);
+
+ // Update message index (if messageId exists)
+ if (context.messageId) {
+ if (!state.operationsByMessage[context.messageId]) {
+ state.operationsByMessage[context.messageId] = [];
+ }
+ state.operationsByMessage[context.messageId].push(operationId);
+ }
+
+ // Update context index (if sessionId exists)
+ if (context.sessionId) {
+ const contextKey = messageMapKey(
+ context.sessionId,
+ context.topicId !== undefined ? context.topicId : null,
+ );
+ if (!state.operationsByContext[contextKey]) {
+ state.operationsByContext[contextKey] = [];
+ }
+ state.operationsByContext[contextKey].push(operationId);
+ }
+
+ // Update parent's childOperationIds
+ if (parentOperationId && state.operations[parentOperationId]) {
+ if (!state.operations[parentOperationId].childOperationIds) {
+ state.operations[parentOperationId].childOperationIds = [];
+ }
+ state.operations[parentOperationId].childOperationIds!.push(operationId);
+ }
+ }),
+ false,
+ n(`startOperation/${type}/${operationId}`),
+ );
+
+ return { operationId, abortController };
+ },
+
+ updateOperationStatus: (operationId, status, metadata) => {
+ set(
+ produce((state: ChatStore) => {
+ const operation = state.operations[operationId];
+ if (!operation) return;
+
+ operation.status = status;
+
+ if (metadata) {
+ operation.metadata = {
+ ...operation.metadata,
+ ...metadata,
+ };
+ }
+ }),
+ false,
+ n(`updateOperationStatus/${operationId}/${status}`),
+ );
+ },
+
+ updateOperationProgress: (operationId, current, total) => {
+ set(
+ produce((state: ChatStore) => {
+ const operation = state.operations[operationId];
+ if (!operation) return;
+
+ operation.metadata.progress = {
+ current,
+ total: total ?? operation.metadata.progress?.total ?? current,
+ percentage: total ? Math.round((current / total) * 100) : undefined,
+ };
+ }),
+ false,
+ n(`updateOperationProgress/${operationId}`),
+ );
+ },
+
+ completeOperation: (operationId, metadata) => {
+ set(
+ produce((state: ChatStore) => {
+ const operation = state.operations[operationId];
+ if (!operation) return;
+
+ const now = Date.now();
+ operation.status = 'completed';
+ operation.metadata.endTime = now;
+ operation.metadata.duration = now - operation.metadata.startTime;
+
+ if (metadata) {
+ operation.metadata = {
+ ...operation.metadata,
+ ...metadata,
+ };
+ }
+ }),
+ false,
+ n(`completeOperation/${operationId}`),
+ );
+ },
+
+ cancelOperation: (operationId, reason = 'User cancelled') => {
+ const operation = get().operations[operationId];
+ if (!operation) return;
+
+ // Cancel all child operations recursively
+ if (operation.childOperationIds && operation.childOperationIds.length > 0) {
+ operation.childOperationIds.forEach((childId) => {
+ get().cancelOperation(childId, 'Parent operation cancelled');
+ });
+ }
+
+ // Abort the operation
+ try {
+ operation.abortController.abort(reason);
+ } catch {
+ // Ignore abort errors
+ }
+
+ // Update status
+ set(
+ produce((state: ChatStore) => {
+ const op = state.operations[operationId];
+ if (!op) return;
+
+ const now = Date.now();
+ op.status = 'cancelled';
+ op.metadata.endTime = now;
+ op.metadata.duration = now - op.metadata.startTime;
+ op.metadata.cancelReason = reason;
+ }),
+ false,
+ n(`cancelOperation/${operationId}`),
+ );
+ },
+
+ failOperation: (operationId, error) => {
+ set(
+ produce((state: ChatStore) => {
+ const operation = state.operations[operationId];
+ if (!operation) return;
+
+ const now = Date.now();
+ operation.status = 'failed';
+ operation.metadata.endTime = now;
+ operation.metadata.duration = now - operation.metadata.startTime;
+ operation.metadata.error = error;
+ }),
+ false,
+ n(`failOperation/${operationId}`),
+ );
+ },
+
+ cancelOperations: (filter, reason = 'Batch cancelled') => {
+ const operations = Object.values(get().operations);
+ const matchedIds: string[] = [];
+
+ operations.forEach((op) => {
+ if (op.status !== 'running') return;
+
+ let matches = true;
+
+ // Type filter
+ if (filter.type) {
+ const types = Array.isArray(filter.type) ? filter.type : [filter.type];
+ matches = matches && types.includes(op.type);
+ }
+
+ // Status filter
+ if (filter.status) {
+ const statuses = Array.isArray(filter.status) ? filter.status : [filter.status];
+ matches = matches && statuses.includes(op.status);
+ }
+
+ // Context filters
+ if (filter.sessionId !== undefined) {
+ matches = matches && op.context.sessionId === filter.sessionId;
+ }
+ if (filter.topicId !== undefined) {
+ matches = matches && op.context.topicId === filter.topicId;
+ }
+ if (filter.messageId !== undefined) {
+ matches = matches && op.context.messageId === filter.messageId;
+ }
+ if (filter.threadId !== undefined) {
+ matches = matches && op.context.threadId === filter.threadId;
+ }
+ if (filter.groupId !== undefined) {
+ matches = matches && op.context.groupId === filter.groupId;
+ }
+ if (filter.agentId !== undefined) {
+ matches = matches && op.context.agentId === filter.agentId;
+ }
+
+ if (matches) {
+ matchedIds.push(op.id);
+ }
+ });
+
+ // Cancel all matched operations
+ matchedIds.forEach((id) => {
+ get().cancelOperation(id, reason);
+ });
+
+ return matchedIds;
+ },
+
+ cancelAllOperations: (reason = 'Cancel all operations') => {
+ const operations = Object.values(get().operations);
+
+ operations.forEach((op) => {
+ if (op.status === 'running') {
+ get().cancelOperation(op.id, reason);
+ }
+ });
+ },
+
+ cleanupCompletedOperations: (olderThan = 60_000) => {
+ // Default: cleanup operations completed more than 1 minute ago
+ const now = Date.now();
+
+ // Collect operations to delete first
+ const operationsToDelete: string[] = [];
+ Object.values(get().operations).forEach((op) => {
+ const isCompleted =
+ op.status === 'completed' || op.status === 'cancelled' || op.status === 'failed';
+ const isOld = op.metadata.endTime && now - op.metadata.endTime > olderThan;
+
+ if (isCompleted && isOld) {
+ operationsToDelete.push(op.id);
+ }
+ });
+
+ if (operationsToDelete.length === 0) return;
+
+ set(
+ produce((state: ChatStore) => {
+ // Delete operations and update indexes
+ operationsToDelete.forEach((operationId) => {
+ const op = state.operations[operationId];
+ if (!op) return;
+
+ // Remove from operations map
+ delete state.operations[operationId];
+
+ // Remove from type index
+ const typeIndex = state.operationsByType[op.type];
+ if (typeIndex) {
+ state.operationsByType[op.type] = typeIndex.filter((id) => id !== operationId);
+ }
+
+ // Remove from message index
+ if (op.context.messageId) {
+ const msgIndex = state.operationsByMessage[op.context.messageId];
+ if (msgIndex) {
+ state.operationsByMessage[op.context.messageId] = msgIndex.filter(
+ (id) => id !== operationId,
+ );
+ }
+ }
+
+ // Remove from context index
+ if (op.context.sessionId) {
+ const contextKey = messageMapKey(
+ op.context.sessionId,
+ op.context.topicId !== undefined ? op.context.topicId : null,
+ );
+ const contextIndex = state.operationsByContext[contextKey];
+ if (contextIndex) {
+ state.operationsByContext[contextKey] = contextIndex.filter(
+ (id) => id !== operationId,
+ );
+ }
+ }
+
+ // Remove from parent's childOperationIds
+ if (op.parentOperationId && state.operations[op.parentOperationId]) {
+ const parent = state.operations[op.parentOperationId];
+ if (parent.childOperationIds) {
+ parent.childOperationIds = parent.childOperationIds.filter(
+ (id) => id !== operationId,
+ );
+ }
+ }
+
+ // Remove from messageOperationMap
+ const messageEntry = Object.entries(state.messageOperationMap).find(
+ ([, opId]) => opId === operationId,
+ );
+ if (messageEntry) {
+ delete state.messageOperationMap[messageEntry[0]];
+ }
+ });
+ }),
+ false,
+ n(`cleanupCompletedOperations/count=${operationsToDelete.length}`),
+ );
+ },
+
+ associateMessageWithOperation: (messageId, operationId) => {
+ set(
+ produce((state: ChatStore) => {
+ state.messageOperationMap[messageId] = operationId;
+ }),
+ false,
+ n(`associateMessageWithOperation/${messageId}/${operationId}`),
+ );
+ },
+});
diff --git a/src/store/chat/slices/operation/index.ts b/src/store/chat/slices/operation/index.ts
new file mode 100644
index 00000000000..6a1bbb645c3
--- /dev/null
+++ b/src/store/chat/slices/operation/index.ts
@@ -0,0 +1,4 @@
+export * from './actions';
+export * from './initialState';
+export * from './selectors';
+export * from './types';
diff --git a/src/store/chat/slices/operation/initialState.ts b/src/store/chat/slices/operation/initialState.ts
new file mode 100644
index 00000000000..4f5a2cf54d8
--- /dev/null
+++ b/src/store/chat/slices/operation/initialState.ts
@@ -0,0 +1,44 @@
+import type { Operation, OperationType } from './types';
+
+/**
+ * Chat Operation State
+ * Unified state for all async operations
+ */
+export interface ChatOperationState {
+ /**
+ * Message to operation mapping (for automatic context retrieval)
+ * key: messageId, value: operationId
+ */
+ messageOperationMap: Record<string, string>;
+
+ /**
+ * All operations map, key is operationId
+ */
+ operations: Record<string, Operation>;
+
+ /**
+ * Operations indexed by session/topic
+ * key: messageMapKey(sessionId, topicId), value: operationId[]
+ */
+ operationsByContext: Record<string, string[]>;
+
+ /**
+ * Operations indexed by message
+ * key: messageId, value: operationId[]
+ */
+ operationsByMessage: Record<string, string[]>;
+
+ /**
+ * Operations indexed by type (for fast querying)
+ * key: OperationType, value: operationId[]
+ */
+ operationsByType: Record<OperationType, string[]>;
+}
+
+export const initialOperationState: ChatOperationState = {
+ messageOperationMap: {},
+ operations: {},
+ operationsByContext: {},
+ operationsByMessage: {},
+ operationsByType: {} as Record<OperationType, string[]>,
+};
diff --git a/src/store/chat/slices/operation/selectors.ts b/src/store/chat/slices/operation/selectors.ts
new file mode 100644
index 00000000000..a084fa78697
--- /dev/null
+++ b/src/store/chat/slices/operation/selectors.ts
@@ -0,0 +1,246 @@
+import type { ChatStoreState } from '@/store/chat/initialState';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
+
+import type { Operation, OperationType } from './types';
+
+// === Basic Queries ===
+/**
+ * Get all operations
+ */
+const getAllOperations = (s: ChatStoreState): Operation[] => {
+ return Object.values(s.operations);
+};
+
+/**
+ * Get operations for current context (active session and topic)
+ */
+const getCurrentContextOperations = (s: ChatStoreState): Operation[] => {
+ const { activeId, activeTopicId } = s;
+ if (!activeId) return [];
+
+ const contextKey = messageMapKey(activeId, activeTopicId);
+ const operationIds = s.operationsByContext[contextKey] || [];
+ return operationIds.map((id) => s.operations[id]).filter(Boolean);
+};
+
+/**
+ * Get all running operations
+ */
+const getRunningOperations = (s: ChatStoreState): Operation[] => {
+ return Object.values(s.operations).filter((op) => op.status === 'running');
+};
+
+/**
+ * Get operation by ID
+ */
+const getOperationById =
+ (operationId: string) =>
+ (s: ChatStoreState): Operation | undefined => {
+ return s.operations[operationId];
+ };
+
+/**
+ * Get operation context from message ID
+ * Useful for automatic context retrieval
+ */
+const getOperationContextFromMessage =
+ (messageId: string) =>
+ (s: ChatStoreState): Operation['context'] | undefined => {
+ const operationId = s.messageOperationMap[messageId];
+ if (!operationId) return undefined;
+
+ const operation = s.operations[operationId];
+ return operation?.context;
+ };
+
+/**
+ * Get operations by message ID
+ */
+const getOperationsByMessage =
+ (messageId: string) =>
+ (s: ChatStoreState): Operation[] => {
+ const operationIds = s.operationsByMessage[messageId] || [];
+ return operationIds.map((id) => s.operations[id]).filter(Boolean);
+ };
+
+/**
+ * Get operations by type
+ */
+const getOperationsByType =
+ (type: OperationType) =>
+ (s: ChatStoreState): Operation[] => {
+ const operationIds = s.operationsByType[type] || [];
+ return operationIds.map((id) => s.operations[id]).filter(Boolean);
+ };
+
+// === Status Checks ===
+/**
+ * Check if there's any running operation
+ */
+const hasAnyRunningOperation = (s: ChatStoreState): boolean => {
+ return Object.values(s.operations).some((op) => op.status === 'running');
+};
+
+/**
+ * Check if there's a running operation of specific type
+ */
+const hasRunningOperationType =
+ (type: OperationType) =>
+ (s: ChatStoreState): boolean => {
+ const operationIds = s.operationsByType[type] || [];
+ return operationIds.some((id) => {
+ const op = s.operations[id];
+ return op && op.status === 'running';
+ });
+ };
+
+/**
+ * Check if can interrupt (has running operations that can be cancelled)
+ */
+const canInterrupt = (s: ChatStoreState): boolean => {
+ const currentOps = getCurrentContextOperations(s);
+ return currentOps.some((op) => op.status === 'running');
+};
+
+/**
+ * Check if can send message (no blocking operations running)
+ */
+const canSendMessage = (s: ChatStoreState): boolean => {
+ // Cannot send if there's any running operation in current context
+ const currentOps = getCurrentContextOperations(s);
+ const hasRunningOp = currentOps.some((op) => op.status === 'running');
+
+ return !hasRunningOp;
+};
+
+// === UI Helpers ===
+/**
+ * Get active operation types (for debugging/display)
+ */
+const getActiveOperationTypes = (s: ChatStoreState): OperationType[] => {
+ const runningOps = getRunningOperations(s);
+ const types = new Set(runningOps.map((op) => op.type));
+ return Array.from(types);
+};
+
+/**
+ * Get current operation label for UI display
+ * Returns the label of the most recent running operation in current context
+ */
+const getCurrentOperationLabel = (s: ChatStoreState): string => {
+ const currentOps = getCurrentContextOperations(s);
+ const runningOps = currentOps.filter((op) => op.status === 'running');
+
+ if (runningOps.length === 0) return '';
+
+ // Get the most recent running operation
+ const latestOp = runningOps.reduce((latest, op) => {
+ return op.metadata.startTime > latest.metadata.startTime ? op : latest;
+ });
+
+ return latestOp.label || latestOp.type;
+};
+
+/**
+ * Get current operation progress
+ * Returns the progress of the most recent running operation with progress info
+ */
+const getCurrentOperationProgress = (s: ChatStoreState): number | undefined => {
+ const currentOps = getCurrentContextOperations(s);
+ const runningOps = currentOps.filter((op) => op.status === 'running');
+
+ if (runningOps.length === 0) return undefined;
+
+ // Find the most recent operation with progress
+ const opsWithProgress = runningOps.filter((op) => op.metadata.progress);
+
+ if (opsWithProgress.length === 0) return undefined;
+
+ const latestOp = opsWithProgress.reduce((latest, op) => {
+ return op.metadata.startTime > latest.metadata.startTime ? op : latest;
+ });
+
+ return latestOp.metadata.progress?.percentage;
+};
+
+// === Backward Compatibility ===
+/**
+ * Check if AI is generating (for backward compatibility)
+ * Equivalent to: hasRunningOperationType('generateAI')
+ */
+const isAIGenerating = (s: ChatStoreState): boolean => {
+ return hasRunningOperationType('generateAI')(s);
+};
+
+/**
+ * Check if continuing (for backward compatibility)
+ */
+const isContinuing = (s: ChatStoreState): boolean => {
+ return hasRunningOperationType('continue')(s);
+};
+
+/**
+ * Check if in RAG flow (for backward compatibility)
+ */
+const isInRAGFlow = (s: ChatStoreState): boolean => {
+ return hasRunningOperationType('rag')(s);
+};
+
+/**
+ * Check if in search workflow (for backward compatibility)
+ */
+const isInSearchWorkflow = (s: ChatStoreState): boolean => {
+ return hasRunningOperationType('searchWorkflow')(s);
+};
+
+/**
+ * Check if a specific message is being processed
+ */
+const isMessageProcessing =
+ (messageId: string) =>
+ (s: ChatStoreState): boolean => {
+ const operations = getOperationsByMessage(messageId)(s);
+ return operations.some((op) => op.status === 'running');
+ };
+
+/**
+ * Check if regenerating (for backward compatibility)
+ */
+const isRegenerating = (s: ChatStoreState): boolean => {
+ return hasRunningOperationType('regenerate')(s);
+};
+
+/**
+ * Check if sending message (for backward compatibility)
+ * Equivalent to: hasRunningOperationType('sendMessage')
+ */
+const isSendingMessage = (s: ChatStoreState): boolean => {
+ return hasRunningOperationType('sendMessage')(s);
+};
+
+/**
+ * Operation Selectors
+ */
+export const operationSelectors = {
+ canInterrupt,
+ canSendMessage,
+ getActiveOperationTypes,
+ getAllOperations,
+ getCurrentContextOperations,
+ getCurrentOperationLabel,
+ getCurrentOperationProgress,
+ getOperationById,
+ getOperationContextFromMessage,
+ getOperationsByMessage,
+ getOperationsByType,
+ getRunningOperations,
+ hasAnyRunningOperation,
+ hasRunningOperationType,
+ isAIGenerating,
+ isContinuing,
+ isInRAGFlow,
+ isInSearchWorkflow,
+ isMessageProcessing,
+ isRegenerating,
+ isSendingMessage,
+};
diff --git a/src/store/chat/slices/operation/types.ts b/src/store/chat/slices/operation/types.ts
new file mode 100644
index 00000000000..de8b9ceb40d
--- /dev/null
+++ b/src/store/chat/slices/operation/types.ts
@@ -0,0 +1,134 @@
+/* eslint-disable typescript-sort-keys/interface, sort-keys-fix/sort-keys-fix */
+/**
+ * Operation Type Definitions
+ * Unified operation state management for all async operations
+ */
+
+/**
+ * Operation type enumeration - covers all async operations
+ */
+export type OperationType =
+ // === Message sending ===
+ | 'sendMessage' // Send message to server
+ | 'createTopic' // Auto create topic
+
+ // === AI generation ===
+ | 'generateAI' // AI generate response (entire agent runtime execution)
+ | 'reasoning' // AI reasoning process (child operation)
+ | 'regenerate' // Regenerate message
+ | 'continue' // Continue generation
+
+ // === RAG and retrieval ===
+ | 'rag' // RAG retrieval flow (child operation)
+ | 'searchWorkflow' // Search workflow
+
+ // === Tool calling ===
+ | 'toolCalling' // Tool calling (streaming, child operation)
+ | 'pluginApi' // Plugin API call
+ | 'builtinToolSearch' // Builtin tool: search
+ | 'builtinToolInterpreter' // Builtin tool: code interpreter
+ | 'builtinToolLocalSystem' // Builtin tool: local system
+
+ // === Group Chat ===
+ | 'supervisorDecision' // Supervisor decision
+ | 'groupAgentGenerate' // Group agent generate
+
+ // === Others ===
+ | 'topicSummary' // Topic summary
+ | 'historySummary'; // History summary
+
+/**
+ * Operation status
+ */
+export type OperationStatus =
+ | 'pending' // Waiting to start (not currently used)
+ | 'running' // Executing
+ | 'paused' // Paused (for user intervention scenarios)
+ | 'completed' // Successfully completed
+ | 'cancelled' // User cancelled
+ | 'failed'; // Execution failed
+
+/**
+ * Operation context - business entity associations
+ * Captured when Operation is created, never changes afterwards
+ */
+export interface OperationContext {
+ sessionId?: string; // Associated session ID (normal session or group)
+ topicId?: string | null; // Associated topic ID (null means default topic)
+ messageId?: string; // Associated message ID
+ threadId?: string; // Associated thread ID (Portal Thread)
+ groupId?: string; // Associated group ID (Group Chat)
+ agentId?: string; // Associated agent ID (specific agent in Group Chat)
+}
+
+/**
+ * Operation metadata
+ */
+export interface OperationMetadata {
+ // Progress information
+ progress?: {
+ current: number;
+ total: number;
+ percentage?: number;
+ };
+
+ // Performance information
+ startTime: number;
+ endTime?: number;
+ duration?: number;
+
+ // Error information
+ error?: {
+ type: string;
+ message: string;
+ code?: string;
+ details?: any;
+ };
+
+ // Cancel information
+ cancelReason?: string;
+
+ // Other metadata (extensible)
+ [key: string]: any;
+}
+
+/**
+ * Operation definition
+ */
+export interface Operation {
+ // === Basic information ===
+ id: string; // Unique operation ID (using nanoid)
+ type: OperationType; // Operation type
+ status: OperationStatus; // Operation status
+
+ // === Context (core: capture and fix business context) ===
+ context: OperationContext; // Associated entities, captured at creation
+
+ // === Control ===
+ abortController: AbortController; // Abort controller
+
+ // === Metadata ===
+ metadata: OperationMetadata;
+
+ // === Dependencies ===
+ parentOperationId?: string; // Parent operation ID (for operation nesting)
+ childOperationIds?: string[]; // Child operation IDs
+
+ // === UI display ===
+ label?: string; // Operation display label (for UI)
+ description?: string; // Operation description (for tooltip)
+}
+
+/**
+ * Operation filter for querying operations
+ */
+export interface OperationFilter {
+ type?: OperationType | OperationType[];
+ status?: OperationStatus | OperationStatus[];
+ sessionId?: string;
+ topicId?: string | null;
+ messageId?: string;
+ threadId?: string;
+ groupId?: string;
+ agentId?: string;
+}
diff --git a/src/store/chat/store.ts b/src/store/chat/store.ts
index 18b4cb2f48e..6814bad0077 100644
--- a/src/store/chat/store.ts
+++ b/src/store/chat/store.ts
@@ -16,6 +16,7 @@ import { ChatAIChatAction, chatAiChat } from './slices/aiChat/actions';
import { ChatTTSAction, chatTTS } from './slices/tts/action';
import { ChatThreadAction, chatThreadMessage } from './slices/thread/action';
import { chatAiGroupChat, ChatGroupChatAction } from './slices/aiChat/actions/generateAIGroupChat';
+import { OperationActions, operationActions } from './slices/operation/actions';
export interface ChatStoreAction
extends ChatMessageAction,
@@ -27,7 +28,8 @@ export interface ChatStoreAction
ChatTTSAction,
ChatPluginAction,
ChatBuiltinToolAction,
- ChatPortalAction {}
+ ChatPortalAction,
+ OperationActions {}
export type ChatStore = ChatStoreAction & ChatStoreState;
@@ -46,6 +48,7 @@ const createStore: StateCreator<ChatStore, [['zustand/devtools', never]]> = (...
...chatToolSlice(...params),
...chatPlugin(...params),
...chatPortalSlice(...params),
+ ...operationActions(...params),
// cloud
});