🤯 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
🔥 refactor(chat): remove orphaned client group-chat SSE and history-summary paths (#20180)
Arvin Xu0c9c4dc26922
diff --git a/packages/prompts/src/chains/__tests__/__snapshots__/summaryHistory.test.ts.snap b/packages/prompts/src/chains/__tests__/__snapshots__/summaryHistory.test.ts.snapdeleted file mode 100644index c7c021fd1d2..00000000000--- a/packages/prompts/src/chains/__tests__/__snapshots__/summaryHistory.test.ts.snap+++ /dev/null@@ -1,21 +0,0 @@-// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html--exports[`chainSummaryHistory > should use the default model if the token count is below the GPT-3.5 limit 1`] = `-{- "messages": [- {- "content": "You're an assistant who's good at extracting key takeaways from conversations and summarizing them. Please summarize according to the user's needs. The content you need to summarize is located in the <chat_history> </chat_history> group of xml tags. The summary needs to maintain the original language.",- "role": "system",- },- {- "content": "<chat_history>-<assistant>Hello, how can I assist you?</assistant>-<user>I need help with my account.</user>-</chat_history>--Please summarize the above conversation and retain key information. The summarized content will be used as context for subsequent prompts, and should be limited to 400 tokens.",- "role": "user",- },- ],-}-`;diff --git a/packages/prompts/src/chains/__tests__/summaryHistory.test.ts b/packages/prompts/src/chains/__tests__/summaryHistory.test.tsdeleted file mode 100644index d2c91dfd60c..00000000000--- a/packages/prompts/src/chains/__tests__/summaryHistory.test.ts+++ /dev/null@@ -1,20 +0,0 @@-import type { UIChatMessage } from '@lobechat/types';-import { describe, expect, it } from 'vitest';--import { chainSummaryHistory } from '../summaryHistory';--describe('chainSummaryHistory', () => {- it('should use the default model if the token count is below the GPT-3.5 limit', async () => {- // Arrange- const messages = [- { content: 'Hello, how can I assist you?', role: 'assistant' },- { content: 'I need help with my account.', role: 'user' },- ] as UIChatMessage[];-- // Act- const result = chainSummaryHistory(messages);-- // Assert- expect(result).toMatchSnapshot();- });-});diff --git a/packages/prompts/src/chains/index.ts b/packages/prompts/src/chains/index.tsindex 9121adf9b7c..84de004ac1c 100644--- a/packages/prompts/src/chains/index.ts+++ b/packages/prompts/src/chains/index.ts@@ -18,7 +18,6 @@ export * from './rewriteGenerationPrompt';export * from './summaryAgentName';export * from './summaryDescription';export * from './summaryGenerationTitle';-export * from './summaryHistory';export * from './summaryTags';export * from './summaryTitle';export * from './taskInstruction';diff --git a/packages/prompts/src/chains/summaryHistory.ts b/packages/prompts/src/chains/summaryHistory.tsdeleted file mode 100644index e94049a1ca3..00000000000--- a/packages/prompts/src/chains/summaryHistory.ts+++ /dev/null@@ -1,19 +0,0 @@-import type { ChatStreamPayload, UIChatMessage } from '@lobechat/types';--import { chatHistoryPrompts } from '../prompts';--export const chainSummaryHistory = (messages: UIChatMessage[]): Partial<ChatStreamPayload> => ({- messages: [- {- content: `You're an assistant who's good at extracting key takeaways from conversations and summarizing them. Please summarize according to the user's needs. The content you need to summarize is located in the <chat_history> </chat_history> group of xml tags. The summary needs to maintain the original language.`,- role: 'system',- },- {- content: `${chatHistoryPrompts(messages)}--Please summarize the above conversation and retain key information. The summarized content will be used as context for subsequent prompts, and should be limited to 400 tokens.`,-- role: 'user',- },- ],-});diff --git a/packages/prompts/src/index.test.ts b/packages/prompts/src/index.test.tsindex 80f43ef2506..b85ecf8547f 100644--- a/packages/prompts/src/index.test.ts+++ b/packages/prompts/src/index.test.ts@@ -27,7 +27,6 @@ describe('Main Index Export', () => {'chainSummaryAgentName','chainSummaryDescription','chainSummaryGenerationTitle',- 'chainSummaryHistory','chainSummaryTags','chainSummaryTitle','chainTranslate',diff --git a/packages/types/src/message/ui/params.ts b/packages/types/src/message/ui/params.tsindex af71d2e1f73..34fb7fbe90c 100644--- a/packages/types/src/message/ui/params.ts+++ b/packages/types/src/message/ui/params.ts@@ -1,6 +1,5 @@import { z } from 'zod';-import type { ConversationContext } from '../../conversation';import type { UploadFileItem } from '../../files';import type { MessageSemanticSearchChunk } from '../../rag';import type { ChatMessageError } from '../common/base';@@ -201,20 +200,6 @@ export interface SendMessageParams {signal?: AbortSignal;}-export interface SendGroupMessageParams {- context: ConversationContext;- files?: UploadFileItem[];- message: string;- /**- * Additional metadata for the message (e.g., mentioned users)- */- metadata?: Record<string, any>;- /**- * for group chat- */- targetMemberId?: string | null;-}-// ========== Zod Schemas ========== //const UIMessageRoleTypeSchema = z.enum([diff --git a/src/features/Conversation/utils/operationActivity.test.ts b/src/features/Conversation/utils/operationActivity.test.tsindex 7bfaf7766da..6d753554d06 100644--- a/src/features/Conversation/utils/operationActivity.test.ts+++ b/src/features/Conversation/utils/operationActivity.test.ts@@ -31,12 +31,7 @@ describe('resolveOperationActivity', () => {});it('maps generation ops to generating', () => {- const genOps: OperationType[] = [- 'callLLM',- 'groupAgentStream',- 'createAssistantMessage',- 'supervisorDecision',- ];+ const genOps: OperationType[] = ['callLLM', 'createAssistantMessage', 'supervisorDecision'];for (const type of genOps) {expect(resolveOperationActivity(type)).toBe('generating');}diff --git a/src/features/Conversation/utils/operationActivity.ts b/src/features/Conversation/utils/operationActivity.tsindex bae75e7924f..40a2af1bdea 100644--- a/src/features/Conversation/utils/operationActivity.ts+++ b/src/features/Conversation/utils/operationActivity.ts@@ -29,12 +29,7 @@ export const resolveOperationActivity = (type: OperationType): ActivityKey | undreturn 'toolCalling';if (type === 'rag' || type === 'searchWorkflow') return 'searching';if (type === 'contextCompression' || type === 'generateSummary') return 'compressing';- if (- type === 'callLLM' ||- type === 'groupAgentStream' ||- type === 'createAssistantMessage' ||- type === 'supervisorDecision'- )+ if (type === 'callLLM' || type === 'createAssistantMessage' || type === 'supervisorDecision')return 'generating';return undefined;};diff --git a/src/hooks/useOperationState.test.ts b/src/hooks/useOperationState.test.tsindex 7c414677fe0..edc3162a06a 100644--- a/src/hooks/useOperationState.test.ts+++ b/src/hooks/useOperationState.test.ts@@ -132,7 +132,7 @@ describe('useOperationState', () => {},'op-stream': {id: 'op-stream',- type: 'groupAgentStream',+ type: 'callLLM',status: 'running',context: { messageId },abortController: new AbortController(),diff --git a/src/services/agentRuntime/__tests__/client.test.ts b/src/services/agentRuntime/__tests__/client.test.tsdeleted file mode 100644index ecd919d5fc0..00000000000--- a/src/services/agentRuntime/__tests__/client.test.ts+++ /dev/null@@ -1,224 +0,0 @@-// @vitest-environment happy-dom-import { beforeEach, describe, expect, it, vi } from 'vitest';--import { agentRuntimeClient } from '../client';--// Mock fetchEventSource-const mockFetchEventSource = vi.fn();-vi.mock('@lobechat/utils/client', () => ({- fetchEventSource: (url: string, options: any) => mockFetchEventSource(url, options),-}));--describe('AgentRuntimeClient', () => {- beforeEach(() => {- vi.clearAllMocks();- });-- describe('createStreamConnection', () => {- it('should create connection with correct URL and parameters', () => {- const operationId = 'agent_1758302563222_0g28qmdmu';-- agentRuntimeClient.createStreamConnection(operationId, {- includeHistory: false,- lastEventId: '0',- });-- expect(mockFetchEventSource).toHaveBeenCalledWith(- '/api/agent/stream?includeHistory=false&lastEventId=0&operationId=agent_1758302563222_0g28qmdmu',- expect.objectContaining({- headers: {- 'Cache-Control': 'no-cache',- 'Last-Event-ID': '0',- },- signal: expect.any(AbortSignal),- }),- );- });-- it('should handle complete agent runtime lifecycle with real stream data', async () => {- const operationId = 'agent_1758302563222_abc';- const events: any[] = [];- let connectCalled = false;-- // Capture the callbacks passed to fetchEventSource- mockFetchEventSource.mockImplementation((url: string, options: any) => {- // Simulate connection opening- setTimeout(() => {- options.onopen?.({ ok: true, status: 200, statusText: 'OK' });- }, 10);-- // Simulate receiving events- setTimeout(() => {- const streamEvents = [- `{"lastEventId":"0","operationId":"${operationId}","timestamp":1758302567925,"type":"connected"}`,- `{"type":"agent_runtime_init","stepIndex":0,"operationId":"${operationId}","data":{"agentConfig":{"enableSearch":true}},"timestamp":1758302564421}`,- `{"type":"stream_start","stepIndex":0,"operationId":"${operationId}","data":{"messageId":"msg1","model":"gpt-4"},"timestamp":1758302574552}`,- `{"type":"stream_chunk","stepIndex":0,"operationId":"${operationId}","data":{"content":"Hello"},"timestamp":1758302578042}`,- `{"type":"stream_end","stepIndex":0,"operationId":"${operationId}","data":{"finalContent":"Hello world"},"timestamp":1758302626595}`,- `{"type":"agent_runtime_end","stepIndex":0,"operationId":"${operationId}","data":{"status":"completed"},"timestamp":1758302631030}`,- ];-- streamEvents.forEach((eventData) => {- options.onmessage?.({ data: eventData, event: 'message' });- });- }, 20);- });-- agentRuntimeClient.createStreamConnection(operationId, {- includeHistory: false,- onConnect: () => {- connectCalled = true;- },- onEvent: (event) => {- events.push(event);- },- });-- // Wait for all events- await new Promise((resolve) => setTimeout(resolve, 50));-- expect(connectCalled).toBe(true);- expect(events).toHaveLength(6);-- // Verify event sequence- expect(events[0].type).toBe('connected');- expect(events[1].type).toBe('agent_runtime_init');- expect(events[2].type).toBe('stream_start');- expect(events[3].type).toBe('stream_chunk');- expect(events[4].type).toBe('stream_end');- expect(events[5].type).toBe('agent_runtime_end');-- // Verify operationId consistency- events.forEach((event) => {- expect(event.operationId).toBe(operationId);- });- });-- it('should handle heartbeat events correctly', async () => {- const operationId = 'test-operation';- const events: any[] = [];-- mockFetchEventSource.mockImplementation((url: string, options: any) => {- setTimeout(() => {- const heartbeatData = `{"operationId":"${operationId}","timestamp":1758302597927,"type":"heartbeat"}`;- options.onmessage?.({ data: heartbeatData, event: 'message' });- }, 10);- });-- agentRuntimeClient.createStreamConnection(operationId, {- onEvent: (event) => {- events.push(event);- },- });-- await new Promise((resolve) => setTimeout(resolve, 30));-- expect(events).toHaveLength(1);- expect(events[0].type).toBe('heartbeat');- expect(events[0].operationId).toBe(operationId);- });-- it('should handle connection errors', async () => {- const operationId = 'test-operation';- let errorOccurred = false;-- mockFetchEventSource.mockImplementation((url: string, options: any) => {- setTimeout(() => {- options.onerror?.(new Error('Connection failed'));- }, 10);- });-- agentRuntimeClient.createStreamConnection(operationId, {- onError: (error) => {- errorOccurred = true;- expect(error.message).toBe('Connection failed');- },- });-- await new Promise((resolve) => setTimeout(resolve, 30));-- expect(errorOccurred).toBe(true);- });-- it('should handle malformed JSON gracefully', async () => {- const operationId = 'test-operation';- const events: any[] = [];- let errorOccurred = false;-- mockFetchEventSource.mockImplementation((url: string, options: any) => {- setTimeout(() => {- options.onmessage?.({ data: 'invalid json', event: 'message' });- }, 10);- });-- agentRuntimeClient.createStreamConnection(operationId, {- onEvent: (event) => {- events.push(event);- },- onError: () => {- errorOccurred = true;- },- });-- await new Promise((resolve) => setTimeout(resolve, 30));-- expect(events).toHaveLength(0);- expect(errorOccurred).toBe(true);- });-- it('should call onDisconnect when connection is closed', async () => {- const operationId = 'test-operation';- let disconnectCalled = false;-- mockFetchEventSource.mockImplementation((url: string, options: any) => {- setTimeout(() => {- options.onclose?.();- }, 10);- });-- agentRuntimeClient.createStreamConnection(operationId, {- onDisconnect: () => {- disconnectCalled = true;- },- });-- await new Promise((resolve) => setTimeout(resolve, 30));-- expect(disconnectCalled).toBe(true);- });-- it('should include correct parameters in URL', () => {- const operationId = 'test-operation-123';-- agentRuntimeClient.createStreamConnection(operationId, {- includeHistory: true,- lastEventId: '12345',- });-- expect(mockFetchEventSource).toHaveBeenCalledWith(- '/api/agent/stream?includeHistory=true&lastEventId=12345&operationId=test-operation-123',- expect.any(Object),- );- });-- it('should use default parameters when not provided', () => {- const operationId = 'test-operation';-- agentRuntimeClient.createStreamConnection(operationId);-- expect(mockFetchEventSource).toHaveBeenCalledWith(- '/api/agent/stream?includeHistory=false&lastEventId=0&operationId=test-operation',- expect.any(Object),- );- });-- it('should return AbortController for cancellation', () => {- const operationId = 'test-operation';-- const controller = agentRuntimeClient.createStreamConnection(operationId);-- expect(controller).toBeInstanceOf(AbortController);- expect(controller.signal).toBeInstanceOf(AbortSignal);- });- });-});diff --git a/src/services/agentRuntime/client.ts b/src/services/agentRuntime/client.tsdeleted file mode 100644index 2a3489c3e79..00000000000--- a/src/services/agentRuntime/client.ts+++ /dev/null@@ -1,77 +0,0 @@-import { fetchEventSource } from '@lobechat/utils/client';-import debug from 'debug';--import { type StreamConnectionOptions, type StreamEvent } from './type';--const log = debug('lobe-agent-runtime:client');--/**- * Agent Client Service for communicating with durable agents- */-class AgentRuntimeClient {- private baseUrl = '/api/agent';-- /**- * Create a streaming connection to receive real-time agent events- */- createStreamConnection(- operationId: string,- options: StreamConnectionOptions = {},- ): AbortController {- const {- includeHistory = false,- lastEventId = '0',- onEvent,- onError,- onConnect,- onDisconnect,- } = options;-- const params = new URLSearchParams({- includeHistory: includeHistory.toString(),- lastEventId,- operationId,- });-- const controller = new AbortController();-- fetchEventSource(`${this.baseUrl}/stream?${params}`, {- headers: {- 'Cache-Control': 'no-cache',- 'Last-Event-ID': lastEventId,- },- onclose: () => {- log(`Stream connection closed for operation ${operationId}`);- onDisconnect?.();- },- onerror: (error) => {- console.error(`[AgentClientService] Stream error for operation ${operationId}:`, error);- onError?.(error instanceof Error ? error : new Error('Stream connection error'));- },- onmessage: (event) => {- try {- const data = JSON.parse(event.data) as StreamEvent;- log(`Received event: ${event.event || 'message'}`, event.data);-- onEvent?.(data);- } catch (error) {- console.error('[AgentClientService] Failed to parse stream event:', error);- onError?.(new Error('Failed to parse stream event'));- }- },- onopen: async (response) => {- if (response.ok) {- log(`Stream connection opened for operation ${operationId}`);- onConnect?.();- } else {- throw new Error(`Failed to open stream: ${response.status} ${response.statusText}`);- }- },- signal: controller.signal,- });-- return controller;- }-}--export const agentRuntimeClient = new AgentRuntimeClient();diff --git a/src/services/agentRuntime/index.ts b/src/services/agentRuntime/index.tsdeleted file mode 100644index 8bde4fe6713..00000000000--- a/src/services/agentRuntime/index.ts+++ /dev/null@@ -1,22 +0,0 @@-import { lambdaClient } from '@/libs/trpc/client';-import { type HumanInterventionRequest } from '@/services/agentRuntime/type';--export { agentRuntimeClient } from './client';-export * from './type';--class AgentRuntimeService {- /**- * Handle human intervention- */- async handleHumanIntervention(request: HumanInterventionRequest): Promise<any> {- return await lambdaClient.aiAgent.processHumanIntervention.mutate({- action: request.action,- data: request.data,- operationId: request.operationId,- reason: request.reason,- stepIndex: 0, // Default to 0 since it's not provided in the request type- });- }-}--export const agentRuntimeService = new AgentRuntimeService();diff --git a/src/services/agentRuntime/type.ts b/src/services/agentRuntime/type.tsdeleted file mode 100644index df9fe233a06..00000000000--- a/src/services/agentRuntime/type.ts+++ /dev/null@@ -1,74 +0,0 @@-import { type OpenAIChatMessage } from '@/types/openai/chat';--export interface StreamEvent {- data?: any;- operationId?: string;- stepIndex?: number;- timestamp: number;- type:- | 'connected'- | 'agent_runtime_init' // Agent runtime initialization- | 'agent_runtime_end' // Agent runtime finished (signals stream should close)- | 'stream_start'- | 'stream_chunk'- | 'stream_end'- | 'visible_output_end'- | 'stream_retry'- | 'step_start'- | 'step_complete'- | 'error'- | 'heartbeat';-}--export interface StreamConnectionOptions {- includeHistory?: boolean;- lastEventId?: string;- onConnect?: () => void;- onDisconnect?: () => void;- onError?: (error: Error) => void;- onEvent?: (event: StreamEvent) => void;-}--export interface AgentOperationRequest {- agentConfig?: {- [key: string]: any;- costLimit?: {- currency: string;- maxTotalCost: number;- onExceeded: 'stop' | 'interrupt' | 'continue';- };- enableRAG?: boolean;- enableSearch?: boolean;- humanApprovalRequired?: boolean;- maxSteps?: number;- };- appSessionId?: string;- autoStart?: boolean;- messages: OpenAIChatMessage[];- modelRuntimeConfig: {- [key: string]: any;- model: string;- provider: string;- };- userMessageId: string;-}--export interface AgentOperationResponse {- autoStart: boolean;- createdAt: string;- firstStep?: {- context?: any;- messageId?: string;- scheduled: boolean;- };- operationId: string;- status: string;- success: boolean;-}--export interface HumanInterventionRequest {- action: 'approve' | 'reject' | 'input' | 'select';- data?: any;- operationId: string;- reason?: string;-}diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.tsindex d3f7764ede3..f2eab2caffe 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts@@ -16,7 +16,7 @@ import * as agentDispatcher from '../dispatch/agentDispatcher';import { createMockMessage, createMockResolvedAgentConfig, TEST_IDS } from './fixtures';import { resetTestEnvironment } from './helpers';-// Mock the tRPC client & agentRuntimeService so the import chain doesn't pull+// Mock the tRPC client so the import chain doesn't pull// server-only code (cloud business packages, redis envs) into the test env.vi.mock('@/libs/trpc/client', () => ({lambdaClient: {@@ -34,12 +34,6 @@ vi.mock('@/libs/trpc/client', () => ({},}));-vi.mock('@/services/agentRuntime', () => ({- agentRuntimeService: {- handleHumanIntervention: vi.fn().mockResolvedValue({ success: true }),- },-}));-vi.mock('@/utils/localStorage', () => {class AsyncLocalStorage<State> {getFromLocalStorageSync(): State {diff --git a/src/store/chat/slices/agentRun/actions/index.ts b/src/store/chat/slices/agentRun/actions/index.tsindex 75ab074fbf7..5786ada0caa 100644--- a/src/store/chat/slices/agentRun/actions/index.ts+++ b/src/store/chat/slices/agentRun/actions/index.ts@@ -11,8 +11,6 @@ import {type QuestionSubmissionAction,QuestionSubmissionActionImpl,} from './entries/questionSubmission';-import { type ChatMemoryAction } from './state/memory';-import { ChatMemoryActionImpl } from './state/memory';import { type StreamingStatesAction } from './state/streamingStates';import { StreamingStatesActionImpl } from './state/streamingStates';import { type ClientToolExecutionAction } from './transports/client/clientToolExecution';@@ -22,8 +20,7 @@ import { StreamingExecutorActionImpl } from './transports/client/streamingExecutimport { type GatewayAction } from './transports/gateway/gateway';import { GatewayActionImpl } from './transports/gateway/gateway';-export type ChatAgentRunAction = ChatMemoryAction &- ClientToolExecutionAction &+export type ChatAgentRunAction = ClientToolExecutionAction &ConversationLifecycleAction &ConversationControlAction &QuestionSubmissionAction &@@ -42,7 +39,6 @@ export const chatAgentRun: StateCreator<>) =>flattenActions<ChatAgentRunAction>([- new ChatMemoryActionImpl(...params),new ClientToolExecutionActionImpl(...params),new ConversationLifecycleActionImpl(...params),new ConversationControlActionImpl(...params),diff --git a/src/store/chat/slices/agentRun/actions/state/memory.ts b/src/store/chat/slices/agentRun/actions/state/memory.tsdeleted file mode 100644index 6aa7d5cb97a..00000000000--- a/src/store/chat/slices/agentRun/actions/state/memory.ts+++ /dev/null@@ -1,54 +0,0 @@-import { chainSummaryHistory } from '@lobechat/prompts';-import { type UIChatMessage } from '@lobechat/types';-import { RequestTrigger, TraceNameMap } from '@lobechat/types';--import { chatService } from '@/services/chat';-import { topicService } from '@/services/topic';-import { type ChatStore } from '@/store/chat';-import { type StoreSetter } from '@/store/types';-import { useUserStore } from '@/store/user';-import { systemAgentSelectors } from '@/store/user/selectors';--type Setter = StoreSetter<ChatStore>;-export const chatMemory = (set: Setter, get: () => ChatStore, _api?: unknown) =>- new ChatMemoryActionImpl(set, get, _api);--export class ChatMemoryActionImpl {- readonly #get: () => ChatStore;-- constructor(set: Setter, get: () => ChatStore, _api?: unknown) {- void _api;- void set;- this.#get = get;- }-- internal_summaryHistory = async (messages: UIChatMessage[]): Promise<void> => {- const topicId = this.#get().activeTopicId;- if (messages.length <= 1 || !topicId) return;-- const { model, provider } = systemAgentSelectors.historyCompress(useUserStore.getState());-- let historySummary = '';- await chatService.fetchPresetTaskResult({- onFinish: async (text) => {- historySummary = text;- },- params: { ...chainSummaryHistory(messages), model, provider, stream: false },- trace: {- sessionId: this.#get().activeAgentId,- topicId: this.#get().activeTopicId,- traceName: TraceNameMap.SummaryHistoryMessages,- },- trigger: RequestTrigger.HistorySummary,- });-- await topicService.updateTopic(topicId, {- historySummary,- metadata: { model, provider },- });- await this.#get().refreshTopic();- await this.#get().refreshMessages();- };-}--export type ChatMemoryAction = Pick<ChatMemoryActionImpl, keyof ChatMemoryActionImpl>;diff --git a/src/store/chat/slices/aiAgent/actions/__tests__/agentGroup.test.ts b/src/store/chat/slices/aiAgent/actions/__tests__/agentGroup.test.tsdeleted file mode 100644index 933b6b361c7..00000000000--- a/src/store/chat/slices/aiAgent/actions/__tests__/agentGroup.test.ts+++ /dev/null@@ -1,775 +0,0 @@-import { act, renderHook } from '@testing-library/react';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--import { lambdaClient } from '@/libs/trpc/client';-import { agentRuntimeClient } from '@/services/agentRuntime';-import { useChatStore } from '@/store/chat/store';--// Mock lambdaClient-vi.mock('@/libs/trpc/client', () => ({- lambdaClient: {- aiAgent: {- execGroupAgent: {- mutate: vi.fn(),- },- },- session: {- updateSession: {- mutate: vi.fn().mockResolvedValue(undefined),- },- },- },-}));--// Mock agentRuntimeClient-vi.mock('@/services/agentRuntime', () => ({- agentRuntimeClient: {- createStreamConnection: vi.fn(),- },- StreamEvent: {},-}));--// Test Constants-const TEST_IDS = {- AGENT_ID: 'test-agent-id',- ASSISTANT_MESSAGE_ID: 'test-assistant-message-id',- GROUP_ID: 'test-group-id',- OPERATION_ID: 'test-operation-id',- TOPIC_ID: 'test-topic-id',- USER_MESSAGE_ID: 'test-user-message-id',-} as const;--const TEST_CONTENT = {- GROUP_MESSAGE: 'Hello group!',- EMPTY: '',-} as const;--// Helper to reset test environment-const resetTestEnvironment = () => {- vi.clearAllMocks();- useChatStore.setState(- {- activeAgentId: TEST_IDS.AGENT_ID,- activeGroupId: TEST_IDS.GROUP_ID,- activeTopicId: undefined,- messagesMap: {},- dbMessagesMap: {},- operations: {},- messageOperationMap: {},- isCreatingMessage: false,- },- false,- );-};--// Helper to create test context-const createTestContext = (overrides: any = {}) => ({- agentId: TEST_IDS.AGENT_ID,- groupId: TEST_IDS.GROUP_ID,- topicId: null as string | null,- threadId: null as string | null,- ...overrides,-});--// Helper to create mock response from execGroupAgent-const createMockExecGroupAgentResponse = (overrides: any = {}) => ({- assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,- operationId: TEST_IDS.OPERATION_ID,- topicId: TEST_IDS.TOPIC_ID,- userMessageId: TEST_IDS.USER_MESSAGE_ID,- isCreateNewTopic: false,- messages: [- {- id: TEST_IDS.USER_MESSAGE_ID,- role: 'user' as const,- content: TEST_CONTENT.GROUP_MESSAGE,- createdAt: Date.now(),- updatedAt: Date.now(),- },- {- id: TEST_IDS.ASSISTANT_MESSAGE_ID,- role: 'assistant' as const,- content: '',- createdAt: Date.now(),- updatedAt: Date.now(),- },- ],- topics: {- items: [],- total: 0,- },- ...overrides,-});--describe('agentGroup actions', () => {- beforeEach(() => {- resetTestEnvironment();-- // Setup default mocks for store methods- act(() => {- useChatStore.setState({- optimisticCreateTmpMessage: vi.fn(),- internal_dispatchMessage: vi.fn(),- internal_handleAgentStreamEvent: vi.fn(),- internal_cleanupAgentOperation: vi.fn(),- internal_handleAgentError: vi.fn(),- internal_updateTopics: vi.fn(),- replaceMessages: vi.fn(),- startOperation: vi- .fn()- .mockReturnValueOnce({- operationId: 'op-exec',- abortController: new AbortController(),- }) // execServerAgentRuntime (first)- .mockReturnValueOnce({- operationId: TEST_IDS.OPERATION_ID,- abortController: new AbortController(),- }), // groupAgentStream (second)- completeOperation: vi.fn(),- failOperation: vi.fn(),- onOperationCancel: vi.fn(),- switchTopic: vi.fn(),- associateMessageWithOperation: vi.fn(),- });- });- });-- afterEach(() => {- vi.restoreAllMocks();- });-- describe('sendGroupMessage', () => {- describe('validation', () => {- it('should not send when message is empty and no files provided', async () => {- const { result } = renderHook(() => useChatStore());-- await act(async () => {- await result.current.sendGroupMessage({- context: createTestContext(),- message: TEST_CONTENT.EMPTY,- });- });-- expect(lambdaClient.aiAgent.execGroupAgent.mutate).not.toHaveBeenCalled();- });-- it('should not send when message is whitespace only', async () => {- const { result } = renderHook(() => useChatStore());-- await act(async () => {- await result.current.sendGroupMessage({- context: createTestContext(),- message: ' ',- });- });-- expect(lambdaClient.aiAgent.execGroupAgent.mutate).not.toHaveBeenCalled();- });-- it('should not send when message is empty with empty files array', async () => {- const { result } = renderHook(() => useChatStore());-- await act(async () => {- await result.current.sendGroupMessage({- context: createTestContext(),- message: TEST_CONTENT.EMPTY,- files: [],- });- });-- expect(lambdaClient.aiAgent.execGroupAgent.mutate).not.toHaveBeenCalled();- });-- it('should not send when agentId is missing', async () => {- const { result } = renderHook(() => useChatStore());-- await act(async () => {- await result.current.sendGroupMessage({- context: createTestContext({ agentId: '' }),- message: TEST_CONTENT.GROUP_MESSAGE,- });- });-- expect(lambdaClient.aiAgent.execGroupAgent.mutate).not.toHaveBeenCalled();- });-- it('should not send when groupId is missing', async () => {- const { result } = renderHook(() => useChatStore());-- await act(async () => {- await result.current.sendGroupMessage({- context: createTestContext({ groupId: '' }),- message: TEST_CONTENT.GROUP_MESSAGE,- });- });-- expect(lambdaClient.aiAgent.execGroupAgent.mutate).not.toHaveBeenCalled();- });- });-- describe('optimistic update', () => {- it('should create execServerAgentRuntime operation first for loading state', async () => {- const { result } = renderHook(() => useChatStore());-- vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockResolvedValue(- createMockExecGroupAgentResponse(),- );- vi.mocked(agentRuntimeClient.createStreamConnection).mockReturnValue({} as any);-- const context = createTestContext();-- await act(async () => {- await result.current.sendGroupMessage({- context,- message: TEST_CONTENT.GROUP_MESSAGE,- });- });-- // First call should be execServerAgentRuntime (created BEFORE mutate call for loading state)- expect(result.current.startOperation).toHaveBeenNthCalledWith(- 1,- expect.objectContaining({- type: 'execServerAgentRuntime',- context: expect.objectContaining({- agentId: TEST_IDS.AGENT_ID,- groupId: TEST_IDS.GROUP_ID,- }),- label: 'Execute Server Agent',- }),- );- });-- it('should create temp user and assistant messages without operationId (optimistic update)', async () => {- const { result } = renderHook(() => useChatStore());-- vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockResolvedValue(- createMockExecGroupAgentResponse(),- );- vi.mocked(agentRuntimeClient.createStreamConnection).mockReturnValue({} as any);-- await act(async () => {- await result.current.sendGroupMessage({- context: createTestContext(),- message: TEST_CONTENT.GROUP_MESSAGE,- });- });-- // Should create temp user message (no operationId for optimistic updates)- expect(result.current.optimisticCreateTmpMessage).toHaveBeenCalledWith(- expect.objectContaining({- content: TEST_CONTENT.GROUP_MESSAGE,- role: 'user',- groupId: TEST_IDS.GROUP_ID,- }),- expect.objectContaining({- tempMessageId: expect.any(String),- }),- );-- // Should create temp assistant message (no operationId for optimistic updates)- expect(result.current.optimisticCreateTmpMessage).toHaveBeenCalledWith(- expect.objectContaining({- role: 'assistant',- groupId: TEST_IDS.GROUP_ID,- }),- expect.objectContaining({- tempMessageId: expect.any(String),- }),- );- });-- it('should set isCreatingMessage state during operation', async () => {- const { result } = renderHook(() => useChatStore());-- let capturedState: boolean | undefined;- vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockImplementation(async () => {- // Capture state during the API call- capturedState = useChatStore.getState().isCreatingMessage;- return createMockExecGroupAgentResponse();- });- vi.mocked(agentRuntimeClient.createStreamConnection).mockReturnValue({} as any);-- await act(async () => {- await result.current.sendGroupMessage({- context: createTestContext(),- message: TEST_CONTENT.GROUP_MESSAGE,- });- });-- expect(capturedState).toBe(true);- // After completion, should be false- expect(useChatStore.getState().isCreatingMessage).toBe(false);- });- });-- describe('backend integration', () => {- it('should call execGroupAgent with correct parameters', async () => {- const { result } = renderHook(() => useChatStore());-- vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockResolvedValue(- createMockExecGroupAgentResponse(),- );- vi.mocked(agentRuntimeClient.createStreamConnection).mockReturnValue({} as any);-- const context = createTestContext({ topicId: TEST_IDS.TOPIC_ID });-- await act(async () => {- await result.current.sendGroupMessage({- context,- message: TEST_CONTENT.GROUP_MESSAGE,- files: [{ id: 'file-1' } as any],- });- });-- expect(lambdaClient.aiAgent.execGroupAgent.mutate).toHaveBeenCalledWith(- {- agentId: TEST_IDS.AGENT_ID,- groupId: TEST_IDS.GROUP_ID,- message: TEST_CONTENT.GROUP_MESSAGE,- topicId: TEST_IDS.TOPIC_ID,- files: ['file-1'],- },- expect.objectContaining({ signal: expect.any(AbortSignal) }),- );- });-- it('should replace messages with server response using correct context', async () => {- const { result } = renderHook(() => useChatStore());-- const mockResponse = createMockExecGroupAgentResponse();- vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockResolvedValue(mockResponse);- vi.mocked(agentRuntimeClient.createStreamConnection).mockReturnValue({} as any);-- const context = createTestContext();-- await act(async () => {- await result.current.sendGroupMessage({- context,- message: TEST_CONTENT.GROUP_MESSAGE,- });- });-- expect(result.current.replaceMessages).toHaveBeenCalledWith(- mockResponse.messages,- expect.objectContaining({- context: expect.objectContaining({- agentId: TEST_IDS.AGENT_ID,- groupId: TEST_IDS.GROUP_ID,- topicId: TEST_IDS.TOPIC_ID,- }),- }),- );- });-- it('should create groupAgentStream child operation with backend operationId', async () => {- const { result } = renderHook(() => useChatStore());-- vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockResolvedValue(- createMockExecGroupAgentResponse(),- );- vi.mocked(agentRuntimeClient.createStreamConnection).mockReturnValue({} as any);-- await act(async () => {- await result.current.sendGroupMessage({- context: createTestContext(),- message: TEST_CONTENT.GROUP_MESSAGE,- });- });-- // Verify that startOperation was called twice:- // 1. For execServerAgentRuntime operation (created BEFORE mutate for loading state)- // 2. For groupAgentStream operation (child, with backend operationId)- expect(result.current.startOperation).toHaveBeenCalledTimes(2);- expect(result.current.startOperation).toHaveBeenNthCalledWith(- 2,- expect.objectContaining({- type: 'groupAgentStream',- operationId: TEST_IDS.OPERATION_ID,- parentOperationId: 'op-exec',- }),- );- });-- it('should register cancel handler for SSE stream', async () => {- const { result } = renderHook(() => useChatStore());-- vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockResolvedValue(- createMockExecGroupAgentResponse(),- );- vi.mocked(agentRuntimeClient.createStreamConnection).mockReturnValue({} as any);-- await act(async () => {- await result.current.sendGroupMessage({- context: createTestContext(),- message: TEST_CONTENT.GROUP_MESSAGE,- });- });-- expect(result.current.onOperationCancel).toHaveBeenCalledWith(- TEST_IDS.OPERATION_ID,- expect.any(Function),- );- });-- it('should associate assistant message with both execServerAgentRuntime and groupAgentStream operations', async () => {- const { result } = renderHook(() => useChatStore());-- vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockResolvedValue(- createMockExecGroupAgentResponse(),- );- vi.mocked(agentRuntimeClient.createStreamConnection).mockReturnValue({} as any);-- await act(async () => {- await result.current.sendGroupMessage({- context: createTestContext(),- message: TEST_CONTENT.GROUP_MESSAGE,- });- });-- // Should associate assistant message with execServerAgentRuntime (for isGenerating detection)- expect(result.current.associateMessageWithOperation).toHaveBeenCalledWith(- TEST_IDS.ASSISTANT_MESSAGE_ID,- 'op-exec', // execServerAgentRuntime operationId- );-- // Should also associate assistant message with groupAgentStream (for stream cancel handling)- expect(result.current.associateMessageWithOperation).toHaveBeenCalledWith(- TEST_IDS.ASSISTANT_MESSAGE_ID,- TEST_IDS.OPERATION_ID, // groupAgentStream operationId- );-- // Total 2 calls for the assistant message- expect(result.current.associateMessageWithOperation).toHaveBeenCalledTimes(2);- });-- it('should create stream connection with operationId', async () => {- const { result } = renderHook(() => useChatStore());-- vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockResolvedValue(- createMockExecGroupAgentResponse(),- );- vi.mocked(agentRuntimeClient.createStreamConnection).mockReturnValue({} as any);-- await act(async () => {- await result.current.sendGroupMessage({- context: createTestContext(),- message: TEST_CONTENT.GROUP_MESSAGE,- });- });-- expect(agentRuntimeClient.createStreamConnection).toHaveBeenCalledWith(- TEST_IDS.OPERATION_ID,- expect.objectContaining({- includeHistory: false,- onConnect: expect.any(Function),- onDisconnect: expect.any(Function),- onError: expect.any(Function),- onEvent: expect.any(Function),- }),- );- });-- it('should complete operations on stream disconnect', async () => {- const { result } = renderHook(() => useChatStore());-- vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockResolvedValue(- createMockExecGroupAgentResponse(),- );-- let onDisconnectCallback: (() => void) | undefined;- vi.mocked(agentRuntimeClient.createStreamConnection).mockImplementation(- (_operationId, options) => {- onDisconnectCallback = options?.onDisconnect;- return {} as any;- },- );-- await act(async () => {- await result.current.sendGroupMessage({- context: createTestContext(),- message: TEST_CONTENT.GROUP_MESSAGE,- });- });-- // Simulate stream disconnect- await act(async () => {- onDisconnectCallback?.();- });-- // Should complete both the stream operation and the main execServerAgentRuntime operation- expect(result.current.completeOperation).toHaveBeenCalledWith(TEST_IDS.OPERATION_ID);- expect(result.current.completeOperation).toHaveBeenCalledWith('op-exec');- });-- it('should update topics when new topic is created', async () => {- const { result } = renderHook(() => useChatStore());-- const mockTopics = {- items: [{ id: 'topic-1', title: 'New Topic' }],- total: 1,- };- vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockResolvedValue(- createMockExecGroupAgentResponse({- isCreateNewTopic: true,- topics: mockTopics,- }),- );- vi.mocked(agentRuntimeClient.createStreamConnection).mockReturnValue({} as any);-- await act(async () => {- await result.current.sendGroupMessage({- context: createTestContext(),- message: TEST_CONTENT.GROUP_MESSAGE,- });- });-- expect(result.current.internal_updateTopics).toHaveBeenCalledWith(- TEST_IDS.AGENT_ID,- expect.objectContaining({- groupId: TEST_IDS.GROUP_ID,- items: mockTopics.items,- total: mockTopics.total,- }),- );- });-- it('should switch to new topic when isCreateNewTopic is true', async () => {- const { result } = renderHook(() => useChatStore());-- vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockResolvedValue(- createMockExecGroupAgentResponse({- isCreateNewTopic: true,- topics: { items: [], total: 1 },- }),- );- vi.mocked(agentRuntimeClient.createStreamConnection).mockReturnValue({} as any);-- await act(async () => {- await result.current.sendGroupMessage({- context: createTestContext(),- message: TEST_CONTENT.GROUP_MESSAGE,- });- });-- expect(result.current.switchTopic).toHaveBeenCalledWith(TEST_IDS.TOPIC_ID, {- clearNewKey: true,- skipRefreshMessage: true,- });- });-- it('should populate the new topic bucket BEFORE switching into it (no blank flicker)', async () => {- const { result } = renderHook(() => useChatStore());-- vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockResolvedValue(- createMockExecGroupAgentResponse({- isCreateNewTopic: true,- topics: { items: [], total: 1 },- }),- );- vi.mocked(agentRuntimeClient.createStreamConnection).mockReturnValue({} as any);-- await act(async () => {- await result.current.sendGroupMessage({- context: createTestContext(),- message: TEST_CONTENT.GROUP_MESSAGE,- });- });-- // The flicker bug: switchTopic both clears the optimistic (topicId: null)- // bucket and points the view at the new, still-empty topic bucket. If it runs- // before replaceMessages, the view lands on an empty key for a frame and the- // just-sent message visibly disappears then reappears. Guard the ordering:- // replaceMessages (populate new bucket) must precede switchTopic.- const replaceOrder = vi.mocked(result.current.replaceMessages).mock.invocationCallOrder[0];- const switchOrder = vi.mocked(result.current.switchTopic).mock.invocationCallOrder[0];- expect(replaceOrder).toBeLessThan(switchOrder);- });-- it('should not switch topic when using existing topic', async () => {- const { result } = renderHook(() => useChatStore());-- vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockResolvedValue(- createMockExecGroupAgentResponse({- isCreateNewTopic: false,- }),- );- vi.mocked(agentRuntimeClient.createStreamConnection).mockReturnValue({} as any);-- await act(async () => {- await result.current.sendGroupMessage({- context: createTestContext({ topicId: 'existing-topic-id' }),- message: TEST_CONTENT.GROUP_MESSAGE,- });- });-- expect(result.current.switchTopic).not.toHaveBeenCalled();- });- });-- describe('error handling', () => {- it('should remove temp messages on backend error with correct context', async () => {- const { result } = renderHook(() => useChatStore());-- const testError = new Error('Backend error');- vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockRejectedValue(testError);-- await act(async () => {- await result.current.sendGroupMessage({- context: createTestContext(),- message: TEST_CONTENT.GROUP_MESSAGE,- });- });-- // Should delete both temp user and assistant messages with operationId for correct context- // execServerAgentRuntime is now created BEFORE mutate, so use its operationId- expect(result.current.internal_dispatchMessage).toHaveBeenCalledWith(- expect.objectContaining({- type: 'deleteMessages',- ids: expect.arrayContaining([- expect.stringContaining('tmp_'),- expect.stringContaining('tmp_'),- ]),- }),- expect.objectContaining({- operationId: 'op-exec', // execServerAgentRuntime operation's ID- }),- );- // Verify exactly 2 messages are deleted- const deleteCall = vi- .mocked(result.current.internal_dispatchMessage)- .mock.calls.find((call) => call[0].type === 'deleteMessages');- expect((deleteCall?.[0] as { ids: string[] })?.ids).toHaveLength(2);- });-- it('should fail operation with error details', async () => {- const { result } = renderHook(() => useChatStore());-- const testError = new Error('Backend error');- vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockRejectedValue(testError);-- await act(async () => {- await result.current.sendGroupMessage({- context: createTestContext(),- message: TEST_CONTENT.GROUP_MESSAGE,- });- });-- // Fails the execServerAgentRuntime operation (created BEFORE mutate)- expect(result.current.failOperation).toHaveBeenCalledWith('op-exec', {- type: 'SendGroupMessageError',- message: 'Backend error',- });- });-- it('should reset isCreatingMessage state on error', async () => {- const { result } = renderHook(() => useChatStore());-- vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockRejectedValue(- new Error('Backend error'),- );-- await act(async () => {- await result.current.sendGroupMessage({- context: createTestContext(),- message: TEST_CONTENT.GROUP_MESSAGE,- });- });-- expect(useChatStore.getState().isCreatingMessage).toBe(false);- });-- it('should toggle loading state off on error', async () => {- const { result } = renderHook(() => useChatStore());-- vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockRejectedValue(- new Error('Backend error'),- );-- await act(async () => {- await result.current.sendGroupMessage({- context: createTestContext(),- message: TEST_CONTENT.GROUP_MESSAGE,- });- });- });-- it('should handle abort error without calling failOperation', async () => {- const { result } = renderHook(() => useChatStore());-- // Create an AbortError- const abortError = new Error('The operation was aborted');- abortError.name = 'AbortError';- vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockRejectedValue(abortError);-- await act(async () => {- await result.current.sendGroupMessage({- context: createTestContext(),- message: TEST_CONTENT.GROUP_MESSAGE,- });- });-- // Should NOT call failOperation for abort errors (status already updated by cancelOperation)- expect(result.current.failOperation).not.toHaveBeenCalled();-- // Should still clean up temp messages- expect(result.current.internal_dispatchMessage).toHaveBeenCalledWith(- expect.objectContaining({- type: 'deleteMessages',- }),- expect.any(Object),- );- });- });-- describe('with files', () => {- it('should send message with files when message is empty but files provided', async () => {- const { result } = renderHook(() => useChatStore());-- vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockResolvedValue(- createMockExecGroupAgentResponse(),- );- vi.mocked(agentRuntimeClient.createStreamConnection).mockReturnValue({} as any);-- await act(async () => {- await result.current.sendGroupMessage({- context: createTestContext(),- message: TEST_CONTENT.EMPTY,- files: [{ id: 'file-1' } as any, { id: 'file-2' } as any],- });- });-- expect(lambdaClient.aiAgent.execGroupAgent.mutate).toHaveBeenCalledWith(- expect.objectContaining({- files: ['file-1', 'file-2'],- }),- expect.objectContaining({ signal: expect.any(AbortSignal) }),- );- });-- it('should include file ids in temp user message', async () => {- const { result } = renderHook(() => useChatStore());-- vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockResolvedValue(- createMockExecGroupAgentResponse(),- );- vi.mocked(agentRuntimeClient.createStreamConnection).mockReturnValue({} as any);-- await act(async () => {- await result.current.sendGroupMessage({- context: createTestContext(),- message: TEST_CONTENT.GROUP_MESSAGE,- files: [{ id: 'file-1' } as any],- });- });-- expect(result.current.optimisticCreateTmpMessage).toHaveBeenCalledWith(- expect.objectContaining({- role: 'user',- files: ['file-1'],- }),- expect.any(Object),- );- });- });- });-});diff --git a/src/store/chat/slices/aiAgent/actions/__tests__/agentGroupFlicker.test.tsx b/src/store/chat/slices/aiAgent/actions/__tests__/agentGroupFlicker.test.tsxdeleted file mode 100644index cf6cb976a18..00000000000--- a/src/store/chat/slices/aiAgent/actions/__tests__/agentGroupFlicker.test.tsx+++ /dev/null@@ -1,214 +0,0 @@-import { act, render } from '@testing-library/react';-import { useEffect } from 'react';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--import {- createStore,- dataSelectors,- Provider,- useConversationStore,-} from '@/features/Conversation/store';-import StoreUpdater from '@/features/Conversation/StoreUpdater';-import { lambdaClient } from '@/libs/trpc/client';-import { agentRuntimeClient } from '@/services/agentRuntime';-import { useChatStore } from '@/store/chat/store';-import { messageMapKey } from '@/store/chat/utils/messageMapKey';--vi.mock('@/libs/trpc/client', () => ({- lambdaClient: {- aiAgent: { execGroupAgent: { mutate: vi.fn() } },- session: { updateSession: { mutate: vi.fn().mockResolvedValue(undefined) } },- },-}));--vi.mock('@/services/agentRuntime', () => ({- agentRuntimeClient: { createStreamConnection: vi.fn() },- StreamEvent: {},-}));--const IDS = {- AGENT_ID: 'agt_flicker',- GROUP_ID: 'grp_flicker',- NEW_TOPIC_ID: 'tpc_new_from_server',- OPERATION_ID: 'op_stream',- ASSISTANT_MESSAGE_ID: 'msg_assistant',- USER_MESSAGE_ID: 'msg_user',-} as const;--/**- * One committed render frame of the conversation surface, recorded at paint- * granularity (React useEffect = post-commit). `count` is how many messages the- * UI would show; `showSkeleton` mirrors ChatList's blank gate exactly.- */-interface Frame {- count: number;- messagesInit: boolean;- showSkeleton: boolean;- topicId: string | null | undefined;-}--let frames: Frame[] = [];--/**- * Probe replicates ChatList's blank-decision (src/features/Conversation/ChatList/index.tsx):- * const isNewConversation = !context.topicId;- * if (!messagesInit && !isNewConversation) return <SkeletonList />; // blank- * It records every committed frame so the test can assert the just-sent message- * never disappears (count drops to 0, or a skeleton replaces it) mid-flow.- */-const Probe = () => {- const messagesInit = useConversationStore(dataSelectors.messagesInit);- const displayMessageIds = useConversationStore(dataSelectors.displayMessageIds);- const topicId = useConversationStore((s) => s.context.topicId);-- const isNewConversation = !topicId;- const showSkeleton = !messagesInit && !isNewConversation;-- useEffect(() => {- frames.push({- count: displayMessageIds.length,- messagesInit,- showSkeleton,- topicId,- });- });-- return null;-};--/**- * Mirrors ConversationArea: derives the group context from the live ChatStore- * (topicId follows activeTopicId, exactly like useGroupContext), reads the raw- * bucket from dbMessagesMap, and feeds an isolated ConversationStore — keyed by- * contextKey so a topic switch remounts the store, just like ConversationProvider.- */-const GroupAreaHarness = () => {- const activeAgentId = useChatStore((s) => s.activeAgentId);- const activeGroupId = useChatStore((s) => s.activeGroupId);- const activeTopicId = useChatStore((s) => s.activeTopicId ?? null);- const replaceMessages = useChatStore((s) => s.replaceMessages);-- const context = {- agentId: activeAgentId!,- groupId: activeGroupId!,- isSupervisor: true,- scope: 'group' as const,- threadId: null,- topicId: activeTopicId,- };- const chatKey = messageMapKey(context);- const messages = useChatStore((s) => s.dbMessagesMap[chatKey]);-- return (- <Provider- key={chatKey}- createStore={() =>- createStore({ context, hooks: {}, initialMessages: messages, skipFetch: false })- }- >- <StoreUpdater- context={context}- hasInitMessages={!!messages}- messages={messages}- onMessagesChange={(m, ctx) => replaceMessages(m, { context: ctx })}- />- <Probe />- </Provider>- );-};--const sendContext = () => ({- agentId: IDS.AGENT_ID,- groupId: IDS.GROUP_ID,- threadId: null as string | null,- topicId: null as string | null,-});--const mockNewTopicResponse = () => ({- assistantMessageId: IDS.ASSISTANT_MESSAGE_ID,- isCreateNewTopic: true,- messages: [- {- content: 'Hello group!',- createdAt: Date.now(),- id: IDS.USER_MESSAGE_ID,- role: 'user' as const,- updatedAt: Date.now(),- },- {- content: '',- createdAt: Date.now(),- id: IDS.ASSISTANT_MESSAGE_ID,- role: 'assistant' as const,- updatedAt: Date.now(),- },- ],- operationId: IDS.OPERATION_ID,- topicId: IDS.NEW_TOPIC_ID,- topics: { items: [{ id: IDS.NEW_TOPIC_ID }], total: 1 },- userMessageId: IDS.USER_MESSAGE_ID,-});--describe('group chat — initial message flicker', () => {- beforeEach(() => {- frames = [];- vi.clearAllMocks();- // Real store actions (NOT mocked) — drive the genuine optimistic→switch→replace flow.- useChatStore.setState(- {- activeAgentId: IDS.AGENT_ID,- activeGroupId: IDS.GROUP_ID,- activeTopicId: undefined,- dbMessagesMap: {},- isCreatingMessage: false,- messageOperationMap: {},- messagesMap: {},- operations: {},- },- false,- );- vi.mocked(agentRuntimeClient.createStreamConnection).mockReturnValue({ abort: vi.fn() } as any);- });-- afterEach(() => {- vi.restoreAllMocks();- });-- it('sending the first message must never blank out across new-topic creation', async () => {- vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockResolvedValue(- mockNewTopicResponse() as any,- );-- render(<GroupAreaHarness />);-- await act(async () => {- await useChatStore.getState().sendGroupMessage({- context: sendContext(),- message: 'Hello group!',- });- });-- // Sanity: messages did show up at some point.- const firstVisibleIdx = frames.findIndex((f) => f.count >= 1);- expect(firstVisibleIdx).toBeGreaterThanOrEqual(0);-- // The flicker invariant: once the just-sent message is visible, no later- // committed frame may drop it (count → 0) or replace it with a skeleton,- // until the flow settles. A regression (switchTopic before replaceMessages)- // produces exactly such a frame: the remounted store lands on the empty- // new-topic bucket → showSkeleton true / count 0.- const framesAfterVisible = frames.slice(firstVisibleIdx);- const blankFrame = framesAfterVisible.find((f) => f.count === 0 || f.showSkeleton);-- expect(- blankFrame,- `Message disappeared mid-flow. Frame timeline: ${JSON.stringify(frames, null, 2)}`,- ).toBeUndefined();-- // Final state: the two server messages live under the new topic.- const lastFrame = frames.at(-1)!;- expect(lastFrame.topicId).toBe(IDS.NEW_TOPIC_ID);- expect(lastFrame.count).toBe(2);- expect(lastFrame.showSkeleton).toBe(false);- });-});diff --git a/src/store/chat/slices/aiAgent/actions/__tests__/runAgent.test.ts b/src/store/chat/slices/aiAgent/actions/__tests__/runAgent.test.tsdeleted file mode 100644index f426a44153c..00000000000--- a/src/store/chat/slices/aiAgent/actions/__tests__/runAgent.test.ts+++ /dev/null@@ -1,657 +0,0 @@-import { act, renderHook } from '@testing-library/react';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--import { type StreamEvent } from '@/services/agentRuntime';-import { useChatStore } from '@/store/chat/store';-import { notifyDesktopHumanApprovalRequired } from '@/store/chat/utils/desktopNotification';-import { messageMapKey } from '@/store/chat/utils/messageMapKey';--vi.mock('@/store/chat/utils/desktopNotification', () => ({- notifyDesktopAgentCompleted: vi.fn().mockResolvedValue(undefined),- notifyDesktopHumanApprovalRequired: vi.fn().mockResolvedValue(undefined),-}));--// Test Constants-const TEST_IDS = {- ASSISTANT_MESSAGE_ID: 'test-assistant-id',- OPERATION_ID: 'test-operation-id',- PARENT_OPERATION_ID: 'test-parent-operation-id',- TMP_ASSISTANT_ID: 'tmp-assistant-id',-} as const;--// Helper to reset test environment-const resetTestEnvironment = () => {- vi.clearAllMocks();- useChatStore.setState(- {- operations: {},- messageOperationMap: {},- messagesMap: {},- dbMessagesMap: {},- },- false,- );-};--// Helper to create streaming context-const createStreamingContext = (overrides: any = {}) => ({- assistantId: '',- content: '',- reasoning: '',- tmpAssistantId: TEST_IDS.TMP_ASSISTANT_ID,- ...overrides,-});--// Helper to create stream_start event-const createStreamStartEvent = (overrides = {}): StreamEvent => ({- type: 'stream_start',- timestamp: Date.now(),- operationId: TEST_IDS.OPERATION_ID,- data: {- assistantMessage: {- id: TEST_IDS.ASSISTANT_MESSAGE_ID,- role: 'assistant',- content: '',- createdAt: Date.now(),- updatedAt: Date.now(),- },- },- ...overrides,-});--describe('runAgent actions', () => {- beforeEach(() => {- resetTestEnvironment();-- // Setup default mocks for store methods- act(() => {- useChatStore.setState({- internal_dispatchMessage: vi.fn(),- completeOperation: vi.fn(),- optimisticUpdateMessageContent: vi.fn(),- refreshMessages: vi.fn(),- updateOperationMetadata: vi.fn(),- operations: {- [TEST_IDS.OPERATION_ID]: {- id: TEST_IDS.OPERATION_ID,- type: 'groupAgentGenerate',- status: 'running',- context: {},- abortController: new AbortController(),- metadata: {- startTime: Date.now(),- lastEventId: '0',- stepCount: 0,- },- },- },- });- });- });-- afterEach(() => {- vi.restoreAllMocks();- });-- describe('internal_handleAgentStreamEvent', () => {- describe('stream_start event', () => {- it('should skip message creation/deletion when assistantId is already set (Group Chat flow)', async () => {- const { result } = renderHook(() => useChatStore());-- // Context with assistantId already set (Group Chat scenario)- const context = createStreamingContext({- assistantId: TEST_IDS.ASSISTANT_MESSAGE_ID, // Already set from backend response- });-- const event = createStreamStartEvent();-- await act(async () => {- await result.current.internal_handleAgentStreamEvent(- TEST_IDS.OPERATION_ID,- event,- context,- );- });-- // Should NOT call dispatchMessage for delete or create- expect(result.current.internal_dispatchMessage).not.toHaveBeenCalled();-- // assistantId should remain unchanged- expect(context.assistantId).toBe(TEST_IDS.ASSISTANT_MESSAGE_ID);- });-- it('should delete temp message and create new message when assistantId is empty (normal Agent flow)', async () => {- const { result } = renderHook(() => useChatStore());-- // Context with empty assistantId (normal Agent scenario)- const context = createStreamingContext({- assistantId: '', // Empty, waiting for stream_start- });-- const event = createStreamStartEvent();-- await act(async () => {- await result.current.internal_handleAgentStreamEvent(- TEST_IDS.OPERATION_ID,- event,- context,- );- });-- // Should call dispatchMessage for deleteMessage- expect(result.current.internal_dispatchMessage).toHaveBeenCalledWith({- id: TEST_IDS.TMP_ASSISTANT_ID,- type: 'deleteMessage',- });-- // Should call dispatchMessage for createMessage- expect(result.current.internal_dispatchMessage).toHaveBeenCalledWith({- id: TEST_IDS.ASSISTANT_MESSAGE_ID,- type: 'createMessage',- value: expect.objectContaining({- id: TEST_IDS.ASSISTANT_MESSAGE_ID,- role: 'assistant',- }),- });-- // assistantId should be updated from event- expect(context.assistantId).toBe(TEST_IDS.ASSISTANT_MESSAGE_ID);- });-- it('should update assistantId in context from event data when empty', async () => {- const { result } = renderHook(() => useChatStore());-- const context = createStreamingContext({- assistantId: '',- });-- const customAssistantId = 'custom-assistant-id-from-event';- const event = createStreamStartEvent({- data: {- assistantMessage: {- id: customAssistantId,- role: 'assistant',- content: '',- createdAt: Date.now(),- updatedAt: Date.now(),- },- },- });-- await act(async () => {- await result.current.internal_handleAgentStreamEvent(- TEST_IDS.OPERATION_ID,- event,- context,- );- });-- // assistantId should be updated to the ID from event- expect(context.assistantId).toBe(customAssistantId);- });-- it('should NOT update assistantId when it is already set', async () => {- const { result } = renderHook(() => useChatStore());-- const originalAssistantId = 'original-assistant-id';- const context = createStreamingContext({- assistantId: originalAssistantId,- });-- const event = createStreamStartEvent({- data: {- assistantMessage: {- id: 'different-assistant-id',- role: 'assistant',- content: '',- createdAt: Date.now(),- updatedAt: Date.now(),- },- },- });-- await act(async () => {- await result.current.internal_handleAgentStreamEvent(- TEST_IDS.OPERATION_ID,- event,- context,- );- });-- // assistantId should remain unchanged- expect(context.assistantId).toBe(originalAssistantId);- });- });-- describe('stream_chunk event', () => {- it('should update content correctly using existing assistantId', async () => {- const { result } = renderHook(() => useChatStore());-- const context = createStreamingContext({- assistantId: TEST_IDS.ASSISTANT_MESSAGE_ID,- content: 'Hello ',- });-- const event: StreamEvent = {- type: 'stream_chunk',- timestamp: Date.now(),- operationId: TEST_IDS.OPERATION_ID,- data: {- chunkType: 'text',- content: 'World',- },- };-- await act(async () => {- await result.current.internal_handleAgentStreamEvent(- TEST_IDS.OPERATION_ID,- event,- context,- );- });-- // Should update message with accumulated content- expect(result.current.internal_dispatchMessage).toHaveBeenCalledWith({- id: TEST_IDS.ASSISTANT_MESSAGE_ID,- type: 'updateMessage',- value: { content: 'Hello World' },- });-- // Context content should be accumulated- expect(context.content).toBe('Hello World');- });-- it('should use tmpAssistantId when assistantId is not yet set', async () => {- const { result } = renderHook(() => useChatStore());-- const context = createStreamingContext({- assistantId: '', // Not yet set- content: '',- });-- const event: StreamEvent = {- type: 'stream_chunk',- timestamp: Date.now(),- operationId: TEST_IDS.OPERATION_ID,- data: {- chunkType: 'text',- content: 'Hello',- },- };-- await act(async () => {- await result.current.internal_handleAgentStreamEvent(- TEST_IDS.OPERATION_ID,- event,- context,- );- });-- // Should use tmpAssistantId as fallback- expect(result.current.internal_dispatchMessage).toHaveBeenCalledWith({- id: TEST_IDS.TMP_ASSISTANT_ID,- type: 'updateMessage',- value: { content: 'Hello' },- });- });- });-- describe('operation validation', () => {- it('should ignore events when operation is not found', async () => {- const { result } = renderHook(() => useChatStore());-- // Clear operations so no operation is found- act(() => {- useChatStore.setState({ operations: {} });- });-- const context = createStreamingContext();- const event = createStreamStartEvent();-- await act(async () => {- await result.current.internal_handleAgentStreamEvent(- 'non-existent-operation',- event,- context,- );- });-- // Should not process event- expect(result.current.internal_dispatchMessage).not.toHaveBeenCalled();- });- });-- describe('step_start event', () => {- it('should notify desktop when human approval is required', async () => {- const { result } = renderHook(() => useChatStore());-- act(() => {- useChatStore.setState({- operations: {- [TEST_IDS.OPERATION_ID]: {- abortController: new AbortController(),- context: { agentId: 'agent-1', groupId: 'group-1', topicId: 'topic-1' },- id: TEST_IDS.OPERATION_ID,- metadata: {- lastEventId: '0',- startTime: Date.now(),- stepCount: 0,- },- status: 'running',- type: 'groupAgentGenerate',- },- },- });- });-- const context = createStreamingContext({- assistantId: TEST_IDS.ASSISTANT_MESSAGE_ID,- });- const updateTopicStatusSpy = vi- .spyOn(result.current, 'updateTopicStatus')- .mockResolvedValue(undefined as any);-- const event: StreamEvent = {- type: 'step_start',- timestamp: Date.now(),- operationId: TEST_IDS.OPERATION_ID,- data: {- pendingToolsCalling: [{ id: 'tool-1' }],- phase: 'human_approval',- requiresApproval: true,- },- };-- await act(async () => {- await result.current.internal_handleAgentStreamEvent(- TEST_IDS.OPERATION_ID,- event,- context,- );- });-- expect(result.current.updateOperationMetadata).toHaveBeenCalledWith(TEST_IDS.OPERATION_ID, {- needsHumanInput: true,- pendingApproval: [{ id: 'tool-1' }],- });- expect(notifyDesktopHumanApprovalRequired).toHaveBeenCalledWith(- expect.any(Function),- expect.objectContaining({- agentId: 'agent-1',- groupId: 'group-1',- topicId: 'topic-1',- }),- );- expect(updateTopicStatusSpy).toHaveBeenCalledWith(- expect.objectContaining({- agentId: 'agent-1',- groupId: 'group-1',- status: 'waitingForHuman',- topicId: 'topic-1',- }),- );- });-- it('replaces messages from server-pushed uiMessages snapshot (SoT)', async () => {- const replaceMessages = vi.fn();- act(() => {- useChatStore.setState({- replaceMessages,- operations: {- [TEST_IDS.OPERATION_ID]: {- abortController: new AbortController(),- context: { agentId: 'agent-1', topicId: 'topic-1' },- id: TEST_IDS.OPERATION_ID,- metadata: { lastEventId: '0', startTime: Date.now(), stepCount: 0 },- status: 'running',- type: 'groupAgentGenerate',- },- },- });- });- const { result } = renderHook(() => useChatStore());- const context = createStreamingContext({ assistantId: TEST_IDS.ASSISTANT_MESSAGE_ID });- const uiMessages = [{ id: 'msg_a', role: 'user' }] as any;-- const event: StreamEvent = {- type: 'step_start',- timestamp: Date.now(),- operationId: TEST_IDS.OPERATION_ID,- data: { phase: 'tool_execution', uiMessages },- };-- await act(async () => {- await result.current.internal_handleAgentStreamEvent(- TEST_IDS.OPERATION_ID,- event,- context,- );- });-- expect(replaceMessages).toHaveBeenCalledWith(uiMessages, {- context: { agentId: 'agent-1', topicId: 'topic-1' },- });- });-- it('does not call replaceMessages when uiMessages absent on step_start', async () => {- const replaceMessages = vi.fn();- act(() => {- useChatStore.setState({ replaceMessages });- });- const { result } = renderHook(() => useChatStore());- const context = createStreamingContext({ assistantId: TEST_IDS.ASSISTANT_MESSAGE_ID });- const event: StreamEvent = {- type: 'step_start',- timestamp: Date.now(),- operationId: TEST_IDS.OPERATION_ID,- data: { phase: 'tool_execution' }, // no uiMessages- };-- await act(async () => {- await result.current.internal_handleAgentStreamEvent(- TEST_IDS.OPERATION_ID,- event,- context,- );- });-- expect(replaceMessages).not.toHaveBeenCalled();- });- });-- describe('agent_runtime_end event', () => {- it('replaces messages from terminal uiMessages snapshot (final-step SoT)', async () => {- const replaceMessages = vi.fn();- act(() => {- useChatStore.setState({- replaceMessages,- operations: {- [TEST_IDS.OPERATION_ID]: {- abortController: new AbortController(),- context: { agentId: 'agent-1', topicId: 'topic-1' },- id: TEST_IDS.OPERATION_ID,- metadata: { lastEventId: '0', startTime: Date.now(), stepCount: 0 },- status: 'running',- type: 'groupAgentGenerate',- },- },- });- });- const { result } = renderHook(() => useChatStore());- const uiMessages = [{ id: 'msg_final', role: 'assistantGroup' }] as any;-- const event: StreamEvent = {- type: 'agent_runtime_end',- timestamp: Date.now(),- operationId: TEST_IDS.OPERATION_ID,- data: { finalState: { status: 'done' }, reason: 'done', uiMessages },- };-- await act(async () => {- await result.current.internal_handleAgentStreamEvent(- TEST_IDS.OPERATION_ID,- event,- createStreamingContext({ assistantId: TEST_IDS.ASSISTANT_MESSAGE_ID }),- );- });-- expect(replaceMessages).toHaveBeenCalledWith(uiMessages, {- context: { agentId: 'agent-1', topicId: 'topic-1' },- });- });-- it('does not let a superseded run replace messages from a newer run', async () => {- const replaceMessages = vi.fn();- const operationContext = { agentId: 'agent-1', topicId: 'topic-1' };- const contextKey = messageMapKey(operationContext);- act(() => {- useChatStore.setState({- operationsByContext: {- [contextKey]: [TEST_IDS.OPERATION_ID, 'new-send-operation'],- },- replaceMessages,- operations: {- [TEST_IDS.OPERATION_ID]: {- abortController: new AbortController(),- context: operationContext,- id: TEST_IDS.OPERATION_ID,- metadata: { lastEventId: '0', startTime: 2, stepCount: 0 },- status: 'running',- type: 'groupAgentStream',- },- 'new-send-operation': {- abortController: new AbortController(),- context: operationContext,- id: 'new-send-operation',- metadata: { startTime: 1 },- status: 'running',- type: 'sendMessage',- },- },- });- });- const { result } = renderHook(() => useChatStore());- const uiMessages = [{ id: 'old-run-message', role: 'assistantGroup' }] as any;- const event: StreamEvent = {- data: { finalState: { status: 'done' }, reason: 'done', uiMessages },- operationId: TEST_IDS.OPERATION_ID,- timestamp: Date.now(),- type: 'agent_runtime_end',- };-- await act(async () => {- await result.current.internal_handleAgentStreamEvent(- TEST_IDS.OPERATION_ID,- event,- createStreamingContext({ assistantId: TEST_IDS.ASSISTANT_MESSAGE_ID }),- );- });-- expect(replaceMessages).not.toHaveBeenCalled();- });- });-- describe('visible_output_end event', () => {- it('clears visible loading without completing the operation', async () => {- const { result } = renderHook(() => useChatStore());- const event: StreamEvent = {- data: { reason: 'completed' },- operationId: TEST_IDS.OPERATION_ID,- stepIndex: 1,- timestamp: Date.now(),- type: 'visible_output_end',- };-- await act(async () => {- await result.current.internal_handleAgentStreamEvent(- TEST_IDS.OPERATION_ID,- event,- createStreamingContext({ assistantId: TEST_IDS.ASSISTANT_MESSAGE_ID }),- );- });-- expect(result.current.updateOperationMetadata).toHaveBeenCalledWith(TEST_IDS.OPERATION_ID, {- visibleLoadingDone: true,- });- expect(result.current.completeOperation).not.toHaveBeenCalled();- });-- it('also clears the parent server runtime visible loading for group SSE streams', async () => {- act(() => {- useChatStore.setState({- operations: {- [TEST_IDS.PARENT_OPERATION_ID]: {- abortController: new AbortController(),- context: { agentId: 'agent-1', groupId: 'group-1', topicId: 'topic-1' },- id: TEST_IDS.PARENT_OPERATION_ID,- metadata: { lastEventId: '0', startTime: Date.now(), stepCount: 0 },- status: 'running',- type: 'execServerAgentRuntime',- },- [TEST_IDS.OPERATION_ID]: {- abortController: new AbortController(),- context: { agentId: 'agent-1', groupId: 'group-1', topicId: 'topic-1' },- id: TEST_IDS.OPERATION_ID,- metadata: { lastEventId: '0', startTime: Date.now(), stepCount: 0 },- parentOperationId: TEST_IDS.PARENT_OPERATION_ID,- status: 'running',- type: 'groupAgentStream',- },- },- });- });-- const { result } = renderHook(() => useChatStore());- const event: StreamEvent = {- data: { reason: 'completed' },- operationId: TEST_IDS.OPERATION_ID,- stepIndex: 1,- timestamp: Date.now(),- type: 'visible_output_end',- };-- await act(async () => {- await result.current.internal_handleAgentStreamEvent(- TEST_IDS.OPERATION_ID,- event,- createStreamingContext({ assistantId: TEST_IDS.ASSISTANT_MESSAGE_ID }),- );- });-- expect(result.current.updateOperationMetadata).toHaveBeenCalledWith(TEST_IDS.OPERATION_ID, {- visibleLoadingDone: true,- });- expect(result.current.updateOperationMetadata).toHaveBeenCalledWith(- TEST_IDS.PARENT_OPERATION_ID,- { visibleLoadingDone: true },- );- expect(result.current.completeOperation).not.toHaveBeenCalled();- });- });-- describe('step_complete event', () => {- // The previous DB-refetch on tool_execution was the source of the- // assistantGroup-clobber regression — tool results are- // now reconciled via the next step_start's uiMessages snapshot.- it('does NOT refreshMessages on tool_execution phase', async () => {- const { result } = renderHook(() => useChatStore());- const event: StreamEvent = {- type: 'step_complete',- timestamp: Date.now(),- operationId: TEST_IDS.OPERATION_ID,- data: { executionTime: 10, phase: 'tool_execution', result: { ok: true } },- };-- await act(async () => {- await result.current.internal_handleAgentStreamEvent(- TEST_IDS.OPERATION_ID,- event,- createStreamingContext({ assistantId: TEST_IDS.ASSISTANT_MESSAGE_ID }),- );- });-- expect(result.current.refreshMessages).not.toHaveBeenCalled();- });- });- });-});diff --git a/src/store/chat/slices/aiAgent/actions/agentGroup.ts b/src/store/chat/slices/aiAgent/actions/agentGroup.tsdeleted file mode 100644index ce4e9579f1f..00000000000--- a/src/store/chat/slices/aiAgent/actions/agentGroup.ts+++ /dev/null@@ -1,271 +0,0 @@-// Disable the auto sort key eslint rule to make the code more logic and readable-import { LOADING_FLAT } from '@lobechat/const';-import { type SendGroupMessageParams } from '@lobechat/types';-import { nanoid } from '@lobechat/utils';-import debug from 'debug';--import { lambdaClient } from '@/libs/trpc/client';-import { type StreamEvent } from '@/services/agentRuntime';-import { agentRuntimeClient } from '@/services/agentRuntime';-import { type ChatStore } from '@/store/chat/store';-import { type StoreSetter } from '@/store/types';-import { setNamespace } from '@/utils/storeDebug';--const log = debug('store:chat:ai-agent:agentGroup');--const n = setNamespace('aiAgentGroup');--type Setter = StoreSetter<ChatStore>;-export const agentGroupSlice = (set: Setter, get: () => ChatStore, _api?: unknown) =>- new ChatGroupChatActionImpl(set, get, _api);--export class ChatGroupChatActionImpl {- readonly #get: () => ChatStore;- readonly #set: Setter;-- constructor(set: Setter, get: () => ChatStore, _api?: unknown) {- void _api;- this.#set = set;- this.#get = get;- }-- sendGroupMessage = async ({ context, message, files }: SendGroupMessageParams): Promise<void> => {- if (!message.trim() && (!files || files.length === 0)) return;-- const { agentId, groupId, topicId } = context;-- if (!agentId || !groupId) {- log('sendGroupMessage: missing agentId or groupId in context');- return;- }-- const { internal_handleAgentStreamEvent, optimisticCreateTmpMessage, startOperation } =- this.#get();-- log(- 'sendGroupMessage: agentId=%s, groupId=%s, message=%s',- agentId,- groupId,- message.slice(0, 50),- );-- this.#set({ isCreatingMessage: true }, false, n('sendGroupMessage/start'));-- // 0. Create execServerAgentRuntime operation FIRST for correct loading state- // This ensures isAgentRuntimeRunningByContext returns true during mutate call- const tempUserId = 'tmp_' + nanoid();- const tempAssistantId = 'tmp_' + nanoid();- const fileIds = files?.map((f) => f.id);-- const { operationId: execOperationId, abortController: execAbortController } = startOperation({- context: { ...context, messageId: tempUserId },- label: 'Execute Server Agent',- type: 'execServerAgentRuntime',- });-- // 1. Optimistic update - create temp messages immediately for instant UI feedback- // Pass operationId so internal_dispatchMessage uses the correct context- optimisticCreateTmpMessage(- {- agentId,- content: message,- files: fileIds,- groupId,- role: 'user',- topicId: topicId ?? undefined,- },- { operationId: execOperationId, tempMessageId: tempUserId },- );-- // Create temp assistant message (loading state)- optimisticCreateTmpMessage(- {- agentId,- content: LOADING_FLAT,- groupId,- role: 'assistant',- topicId: topicId ?? undefined,- },- { operationId: execOperationId, tempMessageId: tempAssistantId },- );-- try {- // 2. Call backend execGroupAgent - creates messages and triggers Agent- // Pass AbortSignal to allow cancellation during the API call- const result = await lambdaClient.aiAgent.execGroupAgent.mutate(- { agentId, files: fileIds, groupId, message, topicId },- { signal: execAbortController.signal },- );-- log(- 'execGroupAgent result: operationId=%s, topicId=%s, success=%s',- result.operationId,- result.topicId,- result.success,- );-- // 3. Update topics if new topic was created- if (result.topics) {- const pageSize = 20; // Default page size for topics- this.#get().internal_updateTopics(agentId, {- groupId,- items: result.topics.items as any, // Type from DB may have null vs undefined differences- pageSize,- total: result.topics.total,- });- }-- // 4. Create execContext with updated topicId from server response- const execContext = { ...context, topicId: result.topicId || topicId };-- // 5. Populate the new topic's message bucket BEFORE switching into it.- //- // Temp messages live under the original (topicId: null) bucket. switchTopic- // both clears that bucket (clearNewKey) AND points the active view at the new- // topicId. If we switched first, the view would land on the still-empty new- // bucket for a frame — StoreUpdater resets displayMessages/messagesInit and- // ChatList renders <SkeletonList/>, so the just-sent message visibly- // disappears and then reappears once replaceMessages runs. Writing the new- // bucket first means the view always finds messages already present on switch.- //- // Messages include assistant message with error if operation failed to start.- if (result.messages) {- this.#get().replaceMessages(result.messages, {- action: n('sendGroupMessage/syncMessages'),- context: execContext,- });- }-- // 6. Switch to new topic if created (its bucket is already populated above)- if (result.isCreateNewTopic && result.topicId) {- await this.#get().switchTopic(result.topicId, {- clearNewKey: true,- skipRefreshMessage: true,- });- }-- // 7. Clean up temp messages from the original bucket.- // For the new-topic path switchTopic's clearNewKey already wiped them; for the- // same-topic path replaceMessages above overwrote the bucket. This dispatch is- // a defensive no-op in both cases, kept to guard partial-result edge cases.- if (result.messages) {- this.#get().internal_dispatchMessage(- { ids: [tempUserId, tempAssistantId], type: 'deleteMessages' },- { operationId: execOperationId },- );- }-- // 8. Check if operation failed to start (e.g., QStash unavailable)- // In this case, messages are synced but we skip SSE connection- if (result.success === false) {- log('Agent operation failed to start: %s', result.error);- // Complete the operation with error status- this.#get().failOperation(execOperationId, {- message: result.error || 'Agent operation failed to start',- type: 'AgentStartupError',- });- return;- }-- // 9. Create streaming context - use assistantMessageId from backend response- const streamContext = {- assistantId: result.assistantMessageId,- content: '',- reasoning: '',- tmpAssistantId: tempAssistantId, // Used for cleanup if needed- };-- // 10. Start child operation for SSE stream using backend operationId- this.#get().startOperation({- context: { ...execContext, messageId: result.assistantMessageId },- label: 'Group Agent Stream',- operationId: result.operationId,- parentOperationId: execOperationId,- type: 'groupAgentStream',- });-- // Associate assistant message with both operations:- // - execServerAgentRuntime (parent) - for isGenerating detection- // - groupAgentStream (child) - for stream cancel handling- this.#get().associateMessageWithOperation(result.assistantMessageId, execOperationId);- this.#get().associateMessageWithOperation(result.assistantMessageId, result.operationId);-- // 11. Connect to SSE stream- // Server will automatically close the connection after sending agent_runtime_end event- const eventSource = agentRuntimeClient.createStreamConnection(result.operationId, {- includeHistory: false,- onConnect: () => {- log('Stream connected to %s', result.operationId);- },- onDisconnect: () => {- log('Stream disconnected from %s', result.operationId);- // Complete both operations when stream disconnects (either by server close or client abort)- this.#get().completeOperation(result.operationId);- this.#get().completeOperation(execOperationId);- },- onError: (error: Error) => {- log('Stream error for %s: %O', result.operationId, error);- // Fail the stream operation on error- this.#get().failOperation(result.operationId, {- message: error.message,- type: 'AgentStreamError',- });- if (streamContext.assistantId) {- this.#get().internal_handleAgentError(streamContext.assistantId, error.message);- }- },- onEvent: async (event: StreamEvent) => {- await internal_handleAgentStreamEvent(result.operationId, event, streamContext);- },- });-- // 12. Register cancel handler for aborting SSE stream- this.#get().onOperationCancel(result.operationId, () => {- log('Cancelling SSE stream for operation %s', result.operationId);- eventSource.abort();- });- } catch (error) {- // Check if this is an abort error (user cancelled the operation)- const isAbortError =- error instanceof Error &&- (error.name === 'AbortError' ||- error.message.includes('aborted') ||- error.message.includes('cancelled'));-- if (isAbortError) {- log('sendGroupMessage aborted by user');- // Operation was cancelled by user, status already updated by cancelOperation- // Just clean up temp messages- this.#get().internal_dispatchMessage(- {- ids: [tempUserId, tempAssistantId],- type: 'deleteMessages',- },- { operationId: execOperationId },- );- } else {- log('sendGroupMessage failed: %O', error);- console.error('Failed to send group message:', error);-- // Remove temp messages on error - use execOperationId for correct context- this.#get().internal_dispatchMessage(- {- ids: [tempUserId, tempAssistantId],- type: 'deleteMessages',- },- { operationId: execOperationId },- );-- // Fail the execServerAgentRuntime operation- this.#get().failOperation(execOperationId, {- message: error instanceof Error ? error.message : 'Unknown error',- type: 'SendGroupMessageError',- });- }- } finally {- this.#set({ isCreatingMessage: false }, false, n('sendGroupMessage/end'));- }- };-}--export type ChatGroupChatAction = Pick<ChatGroupChatActionImpl, keyof ChatGroupChatActionImpl>;diff --git a/src/store/chat/slices/aiAgent/actions/index.ts b/src/store/chat/slices/aiAgent/actions/index.tsindex 002ad960da7..1f81c99feec 100644--- a/src/store/chat/slices/aiAgent/actions/index.ts+++ b/src/store/chat/slices/aiAgent/actions/index.ts@@ -3,14 +3,10 @@ import { type StateCreator } from 'zustand/vanilla';import { type ChatStore } from '@/store/chat/store';import { flattenActions } from '@/store/utils/flattenActions';-import { type ChatGroupChatAction } from './agentGroup';-import { ChatGroupChatActionImpl } from './agentGroup';import { type GroupOrchestrationAction } from './groupOrchestration';import { GroupOrchestrationActionImpl } from './groupOrchestration';-import { type AgentAction } from './runAgent';-import { AgentActionImpl } from './runAgent';-export type ChatAIAgentAction = AgentAction & ChatGroupChatAction & GroupOrchestrationAction;+export type ChatAIAgentAction = GroupOrchestrationAction;export const chatAiAgent: StateCreator<ChatStore,@@ -21,9 +17,4 @@ export const chatAiAgent: StateCreator<...params: Parameters<StateCreator<ChatStore, [['zustand/devtools', never]], [], ChatAIAgentAction>>-) =>- flattenActions<ChatAIAgentAction>([- new AgentActionImpl(...params),- new ChatGroupChatActionImpl(...params),- new GroupOrchestrationActionImpl(...params),- ]);+) => flattenActions<ChatAIAgentAction>([new GroupOrchestrationActionImpl(...params)]);diff --git a/src/store/chat/slices/aiAgent/actions/runAgent.ts b/src/store/chat/slices/aiAgent/actions/runAgent.tsdeleted file mode 100644index 2826c69a872..00000000000--- a/src/store/chat/slices/aiAgent/actions/runAgent.ts+++ /dev/null@@ -1,419 +0,0 @@-import { type ChatToolPayload } from '@lobechat/types';-import debug from 'debug';--import { type StreamEvent } from '@/services/agentRuntime';-import { agentRuntimeService } from '@/services/agentRuntime';-import { operationSelectors } from '@/store/chat/slices/operation/selectors';-import { type ChatStore } from '@/store/chat/store';-import {- notifyDesktopAgentCompleted,- notifyDesktopHumanApprovalRequired,-} from '@/store/chat/utils/desktopNotification';-import { type StoreSetter } from '@/store/types';--const log = debug('store:chat:ai-agent:runAgent');--interface StreamingContext {- assistantId: string;- content: string;- reasoning: string;- tmpAssistantId: string;- toolsCalling?: ChatToolPayload[];-}--type Setter = StoreSetter<ChatStore>;-export const agentSlice = (set: Setter, get: () => ChatStore, _api?: unknown) =>- new AgentActionImpl(set, get, _api);--export class AgentActionImpl {- readonly #get: () => ChatStore;-- constructor(set: Setter, get: () => ChatStore, _api?: unknown) {- void _api;- void set;- this.#get = get;- }-- internal_cleanupAgentOperation = (assistantId: string): void => {- // Find operation by messageId (assistantId)- const messageOpId = this.#get().messageOperationMap[assistantId];- if (!messageOpId) {- log(`No operation found for assistant message ${assistantId}`);- return;- }-- log(`Cleaning up agent operation for ${assistantId} (operationId: ${messageOpId})`);-- // Cancel the operation (this will trigger the cancel handler which aborts the SSE stream)- this.#get().cancelOperation(messageOpId, 'Cleanup requested');- };-- internal_handleAgentError = (assistantId: string, errorMessage: string): void => {- log(`Agent error for ${assistantId}: ${errorMessage}`);-- // Find operation by messageId (assistantId) and fail it- const messageOpId = this.#get().messageOperationMap[assistantId];- if (messageOpId) {- this.#get().failOperation(messageOpId, {- message: errorMessage,- type: 'AgentExecutionError',- });- }-- // Update error state in frontend only (backend already persists the error)- this.#get().internal_dispatchMessage({- id: assistantId,- type: 'updateMessage',- value: {- error: {- message: errorMessage,- type: 'UnknownError' as any,- },- },- });-- // Stop loading state- // Clean up operation (this will cancel the operation)- this.#get().internal_cleanupAgentOperation(assistantId);- };-- internal_handleAgentStreamEvent = async (- operationId: string,- event: StreamEvent,- context: StreamingContext,- ): Promise<void> => {- const { internal_dispatchMessage } = this.#get();- const operation = this.#get().operations[operationId];- if (!operation) {- log(`No operation found for ${operationId}, ignoring event ${event.type}`);- return;- }-- // Update operation metadata- this.#get().updateOperationMetadata(operationId, {- lastEventId: event.timestamp.toString(),- stepCount: event.stepIndex,- });-- const assistantId = context.assistantId || context.tmpAssistantId;- log(`assistantMessageId: ${assistantId}`);-- switch (event.type) {- case 'connected': {- log(`Agent stream connected for ${assistantId}`);- break;- }-- case 'heartbeat': {- // Heartbeat event, keeps the connection alive- break;- }-- case 'agent_runtime_init': {- // Agent runtime initialization event- log(`Agent runtime initialized for ${assistantId}:`, event.data);- break;- }-- case 'agent_runtime_end': {- // Agent runtime finished - this is the definitive signal that generation is complete- const { reason, reasonDetail, finalState, uiMessages } = event.data || {};- log(`Agent runtime ended for ${assistantId}: reason=${reason}, detail=${reasonDetail}`);-- // Server pushes the canonical UIChatMessage[] snapshot for the- // topic as the Source of Truth on terminal-state. The last step- // has no later step_start to carry a fresh snapshot, so without- // this branch the streamed assistantGroup would only be reconciled- // with DB once a refetch fires — losing the SoT guarantee.- if (- Array.isArray(uiMessages) &&- !operationSelectors.hasNewerConversationOperation(- operationId,- operation.context,- )(this.#get())- ) {- log(`Replacing messages from agent_runtime_end uiMessages (${uiMessages.length} msgs)`);- this.#get().replaceMessages(uiMessages, { context: operation.context });- }-- // Update operation metadata with final state- if (finalState) {- this.#get().updateOperationMetadata(operationId, {- finalStatus: finalState.status || reason,- });- }-- // Stop loading state- log(`Stopping loading for completed agent runtime: ${assistantId}`);-- break;- }-- case 'stream_start': {- // If assistantId is already set (Group Chat flow), skip message creation/deletion- // In Group Chat, messages are already synced via replaceMessages from backend response- if (context.assistantId) {- log(`Stream started for ${context.assistantId} (message already synced from backend)`);- break;- }-- // Original logic for normal Agent flow- log(`Stream started for ${assistantId}:`, event.data);- internal_dispatchMessage({- id: context.tmpAssistantId,- type: 'deleteMessage',- });-- context.assistantId = event.data.assistantMessage.id;-- internal_dispatchMessage({- id: context.assistantId,- type: 'createMessage',- value: event.data.assistantMessage,- });-- break;- }-- case 'stream_chunk': {- // Handle streaming content chunk- const { chunkType } = event.data || {};-- switch (chunkType) {- case 'text': {- // Update text content- context.content += event.data.content;- log(`Stream(${event.operationId}) chunk type=${chunkType}: `, event.data.content);-- internal_dispatchMessage({- id: assistantId,- type: 'updateMessage',- value: { content: context.content },- });- break;- }-- case 'reasoning': {- // Update text content- context.reasoning += event.data.reasoning;- log(`Stream(${event.operationId}) chunk type=${chunkType}: `, event.data.reasoning);-- internal_dispatchMessage({- id: assistantId,- type: 'updateMessage',- value: { reasoning: { content: context.reasoning } },- });- break;- }-- case 'tools_calling': {- context.toolsCalling = event.data.toolsCalling;-- internal_dispatchMessage({- id: assistantId,- type: 'updateMessage',- value: { tools: context.toolsCalling },- });- break;- }- }-- break;- }-- case 'stream_end': {- // Stream ended, update final content- const { finalContent, toolCalls, reasoning, imageList, grounding } = event.data || {};- log(`Stream ended for ${assistantId}:`, {- hasFinalContent: !!finalContent,- hasGrounding: !!grounding,- hasImageList: !!(imageList && imageList.length > 0),- hasReasoning: !!reasoning,- hasToolCalls: !!(toolCalls && toolCalls.length > 0),- });-- // Update frontend UI only (backend already persists all data)- if (finalContent !== undefined) {- internal_dispatchMessage({- id: assistantId,- type: 'updateMessage',- value: {- content: finalContent,- ...(toolCalls && toolCalls.length > 0 ? { tools: toolCalls } : {}),- ...(reasoning ? { reasoning } : {}),- ...(imageList && imageList.length > 0 ? { imageList } : {}),- ...(grounding ? { search: grounding } : {}),- },- });- }-- // Stop loading state- log(`Stopping loading for ${assistantId}`);-- // Show desktop notification — unified completion notification: title =- // topic/agent name, body = the actual reply, click deep-links to the- // conversation. The helper no-ops off-desktop and resolves title/body- // from the operation context + final content.- await notifyDesktopAgentCompleted(this.#get, {- content: finalContent,- context: operation.context,- });-- // Mark unread completion for background agents- const op = this.#get().operations[operationId];- if (op?.context.agentId) {- this.#get().markTopicUnread({- agentId: op.context.agentId,- groupId: op.context.groupId,- topicId: op.context.topicId,- });- }- break;- }-- case 'visible_output_end': {- // Example: no-tool answers can finish visible text several seconds- // before agent_runtime_end reconciles cache, queue, unread, and- // notification side effects. Retire only visible loading here.- this.#get().updateOperationMetadata(operationId, { visibleLoadingDone: true });- if (operation.parentOperationId) {- this.#get().updateOperationMetadata(operation.parentOperationId, {- visibleLoadingDone: true,- });- }- break;- }-- case 'step_start': {- const { phase, toolCall, pendingToolsCalling, requiresApproval, uiMessages } =- event.data || {};-- // Server attaches the canonical UIChatMessage[] snapshot to- // step_start so the client uses the pushed payload as Source of- // Truth instead of refetching from DB (the DB fan-out from the- // previous step's stream chunks is async — a refetch here would- // return a stale assistant placeholder that clobbers the- // streamed assistantGroup).- if (Array.isArray(uiMessages)) {- log(`Replacing messages from step_start uiMessages (${uiMessages.length} msgs)`);- this.#get().replaceMessages(uiMessages, { context: operation.context });- }-- if (phase === 'human_approval' && requiresApproval) {- // Requires human approval- log(`Human approval required for ${assistantId}:`, pendingToolsCalling);- this.#get().updateOperationMetadata(operationId, {- needsHumanInput: true,- pendingApproval: pendingToolsCalling,- });-- await notifyDesktopHumanApprovalRequired(this.#get, operation.context);- if (operation.context.topicId) {- const statusWrite = this.#get().updateTopicStatus?.({- agentId: operation.context.agentId,- groupId: operation.context.groupId,- ...(operation.context.scope === 'group' || operation.context.scope === 'group_agent'- ? { scope: operation.context.scope }- : {}),- status: 'waitingForHuman',- topicId: operation.context.topicId,- });- void statusWrite?.catch((error) => {- console.error('[runAgent] updateTopicStatus failed:', error);- });- }-- // Stop loading state, waiting for human intervention- log(`Stopping loading for human approval: ${assistantId}`);- } else if (phase === 'tool_execution' && toolCall) {- log(`Tool execution started for ${assistantId}: ${toolCall.function?.name}`);- }- break;- }-- case 'step_complete': {- const { phase, result, executionTime, finalState } = event.data || {};-- if (phase === 'tool_execution' && result) {- log(`Tool execution completed for ${assistantId} in ${executionTime}ms:`, result);- // Tool results are reconciled via the canonical uiMessages- // snapshot the server pushes on the next step_start; no need- // to refetch from DB here (the refetch was the source of the- // assistantGroup-clobber regression.- } else if (phase === 'execution_complete' && finalState) {- // Agent execution complete- log(`Agent execution completed for ${assistantId}:`, finalState);- this.#get().updateOperationMetadata(operationId, {- finalStatus: finalState.status,- });-- log(`Stopping loading for completed agent: ${assistantId}`);- }- break;- }-- case 'error': {- const { error, message, phase } = event.data || {};- log(`Error in ${phase} for ${assistantId}:`, error);- this.#get().internal_handleAgentError(- assistantId,- message || error || 'Unknown agent error',- );- break;- }-- default: {- log(`Handling event ${event.type} for ${assistantId}:`, event);- break;- }- }- };-- internal_handleHumanIntervention = async (- assistantId: string,- action: string,- data?: any,- ): Promise<void> => {- // Find operation by messageId (assistantId)- const messageOpId = this.#get().messageOperationMap[assistantId];- if (!messageOpId) {- log(`No operation found for assistant message ${assistantId}`);- return;- }-- const operation = this.#get().operations[messageOpId];- if (!operation || !operation.metadata.needsHumanInput) {- log(`No human intervention needed for operation ${messageOpId}`);- return;- }-- try {- log(`Handling human intervention ${action} for operation ${messageOpId}:`, data);-- // Send human intervention request- await agentRuntimeService.handleHumanIntervention({- action: action as any,- data,- operationId: messageOpId,- });-- // Clear human intervention state- this.#get().updateOperationMetadata(messageOpId, {- needsHumanInput: false,- pendingApproval: undefined,- pendingPrompt: undefined,- pendingSelect: undefined,- });-- log(`Human intervention ${action} processed for operation ${messageOpId}`);- } catch (error) {- log(`Failed to handle human intervention for operation ${messageOpId}:`, error);- this.#get().internal_handleAgentError(- assistantId,- `Human intervention failed: ${(error as Error).message}`,- );- }- };-}--export type AgentAction = Pick<AgentActionImpl, keyof AgentActionImpl>;diff --git a/src/store/chat/slices/operation/types.ts b/src/store/chat/slices/operation/types.tsindex 35ea6f9ff00..bce8b0d2607 100644--- a/src/store/chat/slices/operation/types.ts+++ b/src/store/chat/slices/operation/types.ts@@ -61,8 +61,6 @@ export type OperationType =// === Group Chat ===| 'supervisorDecision' // Supervisor decision- | 'groupAgentGenerate' // Group agent generate (deprecated, use groupAgentStream)- | 'groupAgentStream' // Group agent SSE stream (sub-operation of execServerAgentRuntime)// === Sub-Agent (Desktop only) ===| 'execClientSubAgent' // Dispatch single sub-agent on the desktop clientdiff --git a/src/store/chat/utils/messageMapKey.test.ts b/src/store/chat/utils/messageMapKey.test.tsindex bf2f2f2d63b..6e42cd3518f 100644--- a/src/store/chat/utils/messageMapKey.test.ts+++ b/src/store/chat/utils/messageMapKey.test.ts@@ -437,7 +437,6 @@ describe('messageMapKey', () => {});it('Scenario: User sends message to group using groupId parameter', () => {- // This is the new pattern used in sendGroupMessageconst result = messageMapKey({agentId: 'agt_agent001',groupId: 'grp_group001',