🤯 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
✅ test(store): refactor generateAIChatV2 tests following V1 patterns (#9714)
Arvin Xu317df489cea3
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/generateAIChatV2.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/generateAIChatV2.test.tsindex 9501ae58e36..a34f87ec758 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/generateAIChatV2.test.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/generateAIChatV2.test.ts@@ -3,29 +3,22 @@ import { TRPCClientError } from '@trpc/client';import { Mock, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { LOADING_FLAT } from '@/const/message';-import {- DEFAULT_AGENT_CHAT_CONFIG,- DEFAULT_AGENT_CONFIG,- DEFAULT_MODEL,- DEFAULT_PROVIDER,-} from '@/const/settings';+import { DEFAULT_MODEL, DEFAULT_PROVIDER } from '@/const/settings';import { aiChatService } from '@/services/aiChat';import { chatService } from '@/services/chat';import { messageService } from '@/services/message';-import { agentChatConfigSelectors, agentSelectors } from '@/store/agent/selectors';-import { sessionMetaSelectors } from '@/store/session/selectors';import { UploadFileItem } from '@/types/files/upload';import { ChatMessage } from '@/types/message';import { useChatStore } from '../../../../store';import { messageMapKey } from '../../../../utils/messageMapKey';+import { TEST_CONTENT, TEST_IDS } from './fixtures';+import { resetTestEnvironment, setupMockSelectors, spyOnMessageService } from './helpers';-vi.stubGlobal(- 'fetch',- vi.fn(() => Promise.resolve(new Response('mock'))),-);-+// Keep zustand mock as it's needed globallyvi.mock('zustand/traditional');++// Mock server mode for V2 testsvi.mock('@/const/version', async (importOriginal) => {const module = await importOriginal();return {@@ -34,26 +27,28 @@ vi.mock('@/const/version', async (importOriginal) => {isDesktop: false,};});++// Mock aiChatService for V2 server flowvi.mock('@/services/aiChat', () => ({aiChatService: {sendMessageInServer: vi.fn(async (params: any) => {- const userId = 'user-message-id';- const assistantId = 'assistant-message-id';- const topicId = params.topicId ?? 'topic-id';+ const userId = TEST_IDS.USER_MESSAGE_ID;+ const assistantId = TEST_IDS.ASSISTANT_MESSAGE_ID;+ const topicId = params.topicId ?? TEST_IDS.TOPIC_ID;return {messages: [{id: userId,role: 'user',content: params.newUserMessage?.content ?? '',- sessionId: params.sessionId ?? 'session-id',+ sessionId: params.sessionId ?? TEST_IDS.SESSION_ID,topicId,} as any,{id: assistantId,role: 'assistant',content: LOADING_FLAT,- sessionId: params.sessionId ?? 'session-id',+ sessionId: params.sessionId ?? TEST_IDS.SESSION_ID,topicId,} as any,],@@ -66,391 +61,269 @@ vi.mock('@/services/aiChat', () => ({}),},}));-// Mock service-vi.mock('@/services/message', () => ({- messageService: {- getMessages: vi.fn(),- updateMessageError: vi.fn(),- removeMessage: vi.fn(),- removeMessagesByAssistant: vi.fn(),- removeMessages: vi.fn(() => Promise.resolve()),- createMessage: vi.fn(() => Promise.resolve('new-message-id')),- updateMessage: vi.fn(),- removeAllMessages: vi.fn(() => Promise.resolve()),- },-}));-vi.mock('@/services/topic', () => ({- topicService: {- createTopic: vi.fn(() => Promise.resolve()),- removeTopic: vi.fn(() => Promise.resolve()),- },-}));-vi.mock('@/services/chat', async (importOriginal) => {- const module = await importOriginal();-- return {- chatService: {- createAssistantMessage: vi.fn(() => Promise.resolve('assistant-message')),- createAssistantMessageStream: (module as any).chatService.createAssistantMessageStream,- },- };-});-vi.mock('@/services/session', async (importOriginal) => {- const module = await importOriginal();-- return {- sessionService: {- updateSession: vi.fn(),- },- };-});-const realCoreProcessMessage = useChatStore.getState().internal_execAgentRuntime;--// Mock state-const mockState = {- activeId: 'session-id',- activeTopicId: 'topic-id',- messages: [],- messagesMap: {},- mainSendMessageOperations: {},- refreshMessages: vi.fn(),- refreshTopic: vi.fn(),- internal_execAgentRuntime: vi.fn(),- saveToTopic: vi.fn(),- switchTopic: vi.fn(),- internal_shouldUseRAG: () => false,- internal_retrieveChunks: vi.fn(),-} as any;+const realExecAgentRuntime = useChatStore.getState().internal_execAgentRuntime;beforeEach(() => {- vi.clearAllMocks();- useChatStore.setState(mockState, false);- vi.spyOn(agentSelectors, 'currentAgentConfig').mockImplementation(() => DEFAULT_AGENT_CONFIG);- vi.spyOn(agentChatConfigSelectors, 'currentChatConfig').mockImplementation(- () => DEFAULT_AGENT_CHAT_CONFIG,- );- vi.spyOn(sessionMetaSelectors, 'currentAgentMeta').mockImplementation(() => ({ tags: [] }));+ resetTestEnvironment();+ setupMockSelectors();++ // Setup default spies that most tests need+ spyOnMessageService();++ // Setup common mock methods that most V2 tests need+ act(() => {+ useChatStore.setState({+ activeId: TEST_IDS.SESSION_ID,+ activeTopicId: TEST_IDS.TOPIC_ID,+ mainSendMessageOperations: {},+ refreshMessages: vi.fn(),+ refreshTopic: vi.fn(),+ internal_execAgentRuntime: vi.fn(),+ saveToTopic: vi.fn(),+ switchTopic: vi.fn(),+ });+ });});afterEach(() => {process.env.NEXT_PUBLIC_BASE_PATH = undefined;-vi.restoreAllMocks();});describe('generateAIChatV2 actions', () => {describe('sendMessageInServer', () => {- it('should not send message if there is no active session', async () => {- const { result } = renderHook(() => useChatStore());- const message = 'Test message';+ describe('validation', () => {+ it('should not send when there is no active session', async () => {+ act(() => {+ useChatStore.setState({ activeId: undefined });+ });- await act(async () => {- useChatStore.setState({ activeId: undefined });- await result.current.sendMessage({ message });+ const { result } = renderHook(() => useChatStore());++ await act(async () => {+ await result.current.sendMessage({ message: TEST_CONTENT.USER_MESSAGE });+ });++ expect(messageService.createMessage).not.toHaveBeenCalled();+ expect(result.current.internal_execAgentRuntime).not.toHaveBeenCalled();});- expect(messageService.createMessage).not.toHaveBeenCalled();- expect(result.current.refreshMessages).not.toHaveBeenCalled();- expect(result.current.internal_execAgentRuntime).not.toHaveBeenCalled();- });+ it('should not send when message is empty and no files are provided', async () => {+ const { result } = renderHook(() => useChatStore());- it('should not send message if message is empty and there are no files', async () => {- const { result } = renderHook(() => useChatStore());- const message = '';+ await act(async () => {+ await result.current.sendMessage({ message: TEST_CONTENT.EMPTY });+ });- await act(async () => {- await result.current.sendMessage({ message });+ expect(messageService.createMessage).not.toHaveBeenCalled();});- expect(messageService.createMessage).not.toHaveBeenCalled();- expect(result.current.refreshMessages).not.toHaveBeenCalled();- expect(result.current.internal_execAgentRuntime).not.toHaveBeenCalled();- });+ it('should not send when message is empty with empty files array', async () => {+ const { result } = renderHook(() => useChatStore());- it('should not send message if message is empty and there are empty files', async () => {- const { result } = renderHook(() => useChatStore());- const message = '';+ await act(async () => {+ await result.current.sendMessage({ message: TEST_CONTENT.EMPTY, files: [] });+ });- await act(async () => {- await result.current.sendMessage({ message, files: [] });+ expect(messageService.createMessage).not.toHaveBeenCalled();});-- expect(messageService.createMessage).not.toHaveBeenCalled();- expect(result.current.refreshMessages).not.toHaveBeenCalled();- expect(result.current.internal_execAgentRuntime).not.toHaveBeenCalled();});- it('should create message and call internal_execAgentRuntime if message or files are provided', async () => {- const { result } = renderHook(() => useChatStore());- const message = 'Test message';- const files = [{ id: 'file-id' } as UploadFileItem];-- // Mock messageService.create to resolve with a message id- (messageService.createMessage as Mock).mockResolvedValue('new-message-id');+ describe('message creation', () => {+ it('should create user message and trigger AI processing', async () => {+ const { result } = renderHook(() => useChatStore());- await act(async () => {- await result.current.sendMessage({ message, files });- });+ await act(async () => {+ await result.current.sendMessage({ message: TEST_CONTENT.USER_MESSAGE });+ });- expect(aiChatService.sendMessageInServer).toHaveBeenCalledWith(- {- newAssistantMessage: {- model: DEFAULT_MODEL,- provider: DEFAULT_PROVIDER,- },- newUserMessage: {- content: message,- files: files.map((f) => f.id),+ expect(aiChatService.sendMessageInServer).toHaveBeenCalledWith(+ {+ newAssistantMessage: {+ model: DEFAULT_MODEL,+ provider: DEFAULT_PROVIDER,+ },+ newUserMessage: {+ content: TEST_CONTENT.USER_MESSAGE,+ files: undefined,+ },+ sessionId: TEST_IDS.SESSION_ID,+ topicId: TEST_IDS.TOPIC_ID,},- sessionId: mockState.activeId,- topicId: mockState.activeTopicId,- },- expect.anything(),- );- expect(result.current.internal_execAgentRuntime).toHaveBeenCalled();- });+ expect.anything(),+ );+ expect(result.current.internal_execAgentRuntime).toHaveBeenCalled();+ });- it('should handle RAG query when internal_shouldUseRAG returns true', async () => {- const { result } = renderHook(() => useChatStore());- const message = 'Test RAG query';+ it('should send message with files attached', async () => {+ const { result } = renderHook(() => useChatStore());+ const files = [{ id: TEST_IDS.FILE_ID } as UploadFileItem];- vi.spyOn(result.current, 'internal_shouldUseRAG').mockReturnValue(true);+ await act(async () => {+ await result.current.sendMessage({ message: TEST_CONTENT.USER_MESSAGE, files });+ });- await act(async () => {- await result.current.sendMessage({ message });+ expect(aiChatService.sendMessageInServer).toHaveBeenCalledWith(+ {+ newAssistantMessage: {+ model: DEFAULT_MODEL,+ provider: DEFAULT_PROVIDER,+ },+ newUserMessage: {+ content: TEST_CONTENT.USER_MESSAGE,+ files: [TEST_IDS.FILE_ID],+ },+ sessionId: TEST_IDS.SESSION_ID,+ topicId: TEST_IDS.TOPIC_ID,+ },+ expect.anything(),+ );});- expect(result.current.internal_execAgentRuntime).toHaveBeenCalledWith(- expect.objectContaining({- ragQuery: message,- }),- );- });-- it('should not use RAG when internal_shouldUseRAG returns false', async () => {- const { result } = renderHook(() => useChatStore());- const message = 'Test without RAG';+ it('should send files without message content', async () => {+ const { result } = renderHook(() => useChatStore());+ const files = [{ id: TEST_IDS.FILE_ID } as UploadFileItem];- vi.spyOn(result.current, 'internal_shouldUseRAG').mockReturnValue(false);- vi.spyOn(result.current, 'internal_retrieveChunks');+ await act(async () => {+ await result.current.sendMessage({ message: TEST_CONTENT.EMPTY, files });+ });- await act(async () => {- await result.current.sendMessage({ message });+ expect(aiChatService.sendMessageInServer).toHaveBeenCalledWith(+ {+ newAssistantMessage: {+ model: DEFAULT_MODEL,+ provider: DEFAULT_PROVIDER,+ },+ newUserMessage: {+ content: TEST_CONTENT.EMPTY,+ files: [TEST_IDS.FILE_ID],+ },+ sessionId: TEST_IDS.SESSION_ID,+ topicId: TEST_IDS.TOPIC_ID,+ },+ expect.anything(),+ );});- expect(result.current.internal_retrieveChunks).not.toHaveBeenCalled();- expect(result.current.internal_execAgentRuntime).toHaveBeenCalledWith(- expect.objectContaining({- ragQuery: undefined,- }),- );- });+ it('should not process AI when onlyAddUserMessage is true', async () => {+ const { result } = renderHook(() => useChatStore());- it('should add user message and not call internal_execAgentRuntime if onlyAddUserMessage = true', async () => {- const { result } = renderHook(() => useChatStore());+ await act(async () => {+ await result.current.sendMessage({+ message: TEST_CONTENT.USER_MESSAGE,+ onlyAddUserMessage: true,+ });+ });- await act(async () => {- await result.current.sendMessage({ message: 'test', onlyAddUserMessage: true });+ expect(messageService.createMessage).toHaveBeenCalled();+ expect(result.current.internal_execAgentRuntime).not.toHaveBeenCalled();});- expect(messageService.createMessage).toHaveBeenCalled();- expect(result.current.internal_execAgentRuntime).not.toHaveBeenCalled();- });+ it('should handle message creation errors gracefully', async () => {+ const { result } = renderHook(() => useChatStore());+ vi.spyOn(aiChatService, 'sendMessageInServer').mockRejectedValue(+ new Error('create message error'),+ );- it('should pass isWelcomeQuestion correctly to internal_execAgentRuntime when isWelcomeQuestion is true', async () => {- const { result } = renderHook(() => useChatStore());+ await act(async () => {+ try {+ await result.current.sendMessage({ message: TEST_CONTENT.USER_MESSAGE });+ } catch {+ // Expected to throw+ }+ });- await act(async () => {- await result.current.sendMessage({ message: 'test', isWelcomeQuestion: true });+ expect(result.current.internal_execAgentRuntime).not.toHaveBeenCalled();});-- expect(result.current.internal_execAgentRuntime).toHaveBeenCalledWith(- expect.objectContaining({- isWelcomeQuestion: true,- }),- );});- it('should send message correctly when only files are provided without message content', async () => {- const { result } = renderHook(() => useChatStore());+ describe('RAG integration', () => {+ it('should include RAG query when RAG is enabled', async () => {+ const { result } = renderHook(() => useChatStore());+ vi.spyOn(result.current, 'internal_shouldUseRAG').mockReturnValue(true);- await act(async () => {- await result.current.sendMessage({ message: '', files: [{ id: 'file-1' }] as any });+ await act(async () => {+ await result.current.sendMessage({ message: TEST_CONTENT.RAG_QUERY });+ });++ expect(result.current.internal_execAgentRuntime).toHaveBeenCalledWith(+ expect.objectContaining({+ ragQuery: TEST_CONTENT.RAG_QUERY,+ }),+ );});- expect(aiChatService.sendMessageInServer).toHaveBeenCalledWith(- {- newAssistantMessage: {- model: DEFAULT_MODEL,- provider: DEFAULT_PROVIDER,- },- newUserMessage: {- content: '',- files: ['file-1'],- },- sessionId: 'session-id',- topicId: 'topic-id',- },- expect.anything(),- );- });+ it('should not use RAG when feature is disabled', async () => {+ const { result } = renderHook(() => useChatStore());+ vi.spyOn(result.current, 'internal_shouldUseRAG').mockReturnValue(false);+ const retrieveChunksSpy = vi.spyOn(result.current, 'internal_retrieveChunks');- it('should send message correctly when both files and message content are provided', async () => {- const { result } = renderHook(() => useChatStore());+ await act(async () => {+ await result.current.sendMessage({ message: TEST_CONTENT.USER_MESSAGE });+ });- await act(async () => {- await result.current.sendMessage({ message: 'test', files: [{ id: 'file-1' }] as any });+ expect(retrieveChunksSpy).not.toHaveBeenCalled();+ expect(result.current.internal_execAgentRuntime).toHaveBeenCalledWith(+ expect.objectContaining({+ ragQuery: undefined,+ }),+ );});-- expect(aiChatService.sendMessageInServer).toHaveBeenCalledWith(- {- newAssistantMessage: {- model: DEFAULT_MODEL,- provider: DEFAULT_PROVIDER,- },- newUserMessage: {- content: 'test',- files: ['file-1'],- },- sessionId: 'session-id',- topicId: 'topic-id',- },- expect.anything(),- );});- it('should handle errors correctly when createMessage throws error without affecting the app', async () => {- const { result } = renderHook(() => useChatStore());- vi.spyOn(aiChatService, 'sendMessageInServer').mockRejectedValue(- new Error('create message error'),- );+ describe('special flags', () => {+ it('should pass isWelcomeQuestion flag to processing', async () => {+ const { result } = renderHook(() => useChatStore());- try {- await result.current.sendMessage({ message: 'test' });- } catch (e) {}+ await act(async () => {+ await result.current.sendMessage({+ message: TEST_CONTENT.USER_MESSAGE,+ isWelcomeQuestion: true,+ });+ });- expect(result.current.internal_execAgentRuntime).not.toHaveBeenCalled();+ expect(result.current.internal_execAgentRuntime).toHaveBeenCalledWith(+ expect.objectContaining({+ isWelcomeQuestion: true,+ }),+ );+ });});-- // it('自动创建主题成功后,正确地将消息复制到新主题,并删除之前的临时消息', async () => {- // const { result } = renderHook(() => useChatStore());- // act(() => {- // useAgentStore.setState({- // agentConfig: { enableAutoCreateTopic: true, autoCreateTopicThreshold: 1 },- // });- //- // useChatStore.setState({- // // Mock the currentChats selector to return a list that does not reach the threshold- // messagesMap: {- // [messageMapKey('inbox')]: [{ id: '1' }, { id: '2' }] as ChatMessage[],- // },- // activeId: 'inbox',- // });- // });- // vi.spyOn(topicService, 'createTopic').mockResolvedValue('new-topic');- //- // await act(async () => {- // await result.current.sendMessage({ message: 'test' });- // });- //- // expect(result.current.messagesMap[messageMapKey('inbox')]).toEqual([- // // { id: '1' },- // // { id: '2' },- // // { id: 'temp-id', content: 'test', role: 'user' },- // ]);- // // expect(result.current.getMessages('session-id')).toEqual([]);- // });-- // it('自动创建主题失败时,正确地处理错误,不会影响后续的消息发送', async () => {- // const { result } = renderHook(() => useChatStore());- // result.current.setAgentConfig({ enableAutoCreateTopic: true, autoCreateTopicThreshold: 1 });- // result.current.setMessages([{ id: '1' }, { id: '2' }] as any);- // vi.spyOn(topicService, 'createTopic').mockRejectedValue(new Error('create topic error'));- //- // await act(async () => {- // await result.current.sendMessage({ message: 'test' });- // });- //- // expect(result.current.getMessages('session-id')).toEqual([- // { id: '1' },- // { id: '2' },- // { id: 'new-message-id', content: 'test', role: 'user' },- // ]);- // });-- // it('当 activeTopicId 不存在且 autoCreateTopic 为 true,但消息数量未达到阈值时,正确地总结主题标题', async () => {- // const { result } = renderHook(() => useChatStore());- // result.current.setAgentConfig({ enableAutoCreateTopic: true, autoCreateTopicThreshold: 10 });- // result.current.setMessages([{ id: '1' }, { id: '2' }] as any);- // result.current.setActiveTopic({ id: 'topic-1', title: '' });- //- // await act(async () => {- // await result.current.sendMessage({ message: 'test' });- // });- //- // expect(result.current.summaryTopicTitle).toHaveBeenCalledWith('topic-1', [- // { id: '1' },- // { id: '2' },- // { id: 'new-message-id', content: 'test', role: 'user' },- // { id: 'assistant-message', role: 'assistant' },- // ]);- // });- //- // it('当 activeTopicId 存在且主题标题为空时,正确地总结主题标题', async () => {- // const { result } = renderHook(() => useChatStore());- // result.current.setActiveTopic({ id: 'topic-1', title: '' });- // result.current.setMessages([{ id: '1' }, { id: '2' }] as any, 'session-id', 'topic-1');- //- // await act(async () => {- // await result.current.sendMessage({ message: 'test' });- // });- //- // expect(result.current.summaryTopicTitle).toHaveBeenCalledWith('topic-1', [- // { id: '1' },- // { id: '2' },- // { id: 'new-message-id', content: 'test', role: 'user' },- // { id: 'assistant-message', role: 'assistant' },- // ]);- // });});describe('internal_execAgentRuntime', () => {it('should handle the core AI message processing', async () => {- useChatStore.setState({ internal_execAgentRuntime: realCoreProcessMessage });+ act(() => {+ useChatStore.setState({ internal_execAgentRuntime: realExecAgentRuntime });+ });const { result } = renderHook(() => useChatStore());const userMessage = {- id: 'user-message-id',+ id: TEST_IDS.USER_MESSAGE_ID,role: 'user',- content: 'Hello, world!',- sessionId: mockState.activeId,- topicId: mockState.activeTopicId,+ content: TEST_CONTENT.USER_MESSAGE,+ sessionId: TEST_IDS.SESSION_ID,+ topicId: TEST_IDS.TOPIC_ID,} as ChatMessage;const messages = [userMessage];- // 模拟 AI 响应- const aiResponse = 'Hello, human!';- (chatService.createAssistantMessage as Mock).mockResolvedValue(aiResponse);- const spy = vi.spyOn(chatService, 'createAssistantMessageStream');+ const streamSpy = vi.spyOn(chatService, 'createAssistantMessageStream');await act(async () => {await result.current.internal_execAgentRuntime({messages,userMessageId: userMessage.id,- assistantMessageId: 'abc',+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,});});- // 验证 AI 服务是否被调用- expect(spy).toHaveBeenCalled();-- // 验证消息列表是否刷新- expect(mockState.refreshMessages).toHaveBeenCalled();+ expect(streamSpy).toHaveBeenCalled();+ expect(result.current.refreshMessages).toHaveBeenCalled();});});- describe('Error handling tests', () => {+ describe('error handling', () => {it('should set error message when sendMessageInServer throws a regular error', async () => {const { result } = renderHook(() => useChatStore());const errorMessage = 'Network error';@@ -460,10 +333,10 @@ describe('generateAIChatV2 actions', () => {vi.spyOn(aiChatService, 'sendMessageInServer').mockRejectedValue(mockError);await act(async () => {- await result.current.sendMessage({ message: 'test' });+ await result.current.sendMessage({ message: TEST_CONTENT.USER_MESSAGE });});- const operationKey = messageMapKey('session-id', 'topic-id');+ const operationKey = messageMapKey(TEST_IDS.SESSION_ID, TEST_IDS.TOPIC_ID);expect(result.current.mainSendMessageOperations[operationKey]?.inputSendErrorMsg).toBe(errorMessage,);@@ -477,92 +350,88 @@ describe('generateAIChatV2 actions', () => {vi.spyOn(aiChatService, 'sendMessageInServer').mockRejectedValue(abortError);await act(async () => {- await result.current.sendMessage({ message: 'test' });+ await result.current.sendMessage({ message: TEST_CONTENT.USER_MESSAGE });});- const operationKey = messageMapKey('session-id', 'topic-id');+ const operationKey = messageMapKey(TEST_IDS.SESSION_ID, TEST_IDS.TOPIC_ID);expect(result.current.mainSendMessageOperations[operationKey]?.inputSendErrorMsg,).toBeUndefined();});});- describe('Temporary message cleanup tests', () => {+ describe('topic creation and switching', () => {it('should remove temporary message when creating new topic in default state', async () => {const { result } = renderHook(() => useChatStore());- const message = 'Test message for new topic';vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValueOnce({isCreatNewTopic: true,- topicId: 'topic-id',+ topicId: TEST_IDS.TOPIC_ID,messages: [{}, {}] as any,topics: [{}] as any,- assistantMessageId: 'abc',- userMessageId: 'user-',+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ userMessageId: TEST_IDS.USER_MESSAGE_ID,});await act(async () => {- // Set up default state (no activeTopicId, simulating inbox)useChatStore.setState({- ...mockState,- activeTopicId: undefined, // This is the default state+ activeId: TEST_IDS.SESSION_ID,+ activeTopicId: undefined,messagesMap: {},+ switchTopic: vi.fn(),});- await result.current.sendMessage({ message });+ await result.current.sendMessage({ message: TEST_CONTENT.USER_MESSAGE });});- // Verify that deleteMessage was called for temporary message cleanup- // This should happen because the mock aiChatService returns isCreatNewTopic: true- expect(useChatStore.getState().messagesMap['session-id_null']).toEqual([]);+ expect(useChatStore.getState().messagesMap[`${TEST_IDS.SESSION_ID}_null`]).toEqual([]);});- });- describe('Topic switching tests', () => {it('should automatically switch to newly created topic when no active topic exists', async () => {const { result } = renderHook(() => useChatStore());const mockSwitchTopic = vi.fn();await act(async () => {useChatStore.setState({- ...mockState,+ activeId: TEST_IDS.SESSION_ID,activeTopicId: undefined,switchTopic: mockSwitchTopic,});- await result.current.sendMessage({ message: 'test' });+ await result.current.sendMessage({ message: TEST_CONTENT.USER_MESSAGE });});- expect(mockSwitchTopic).toHaveBeenCalledWith('topic-id', true);+ expect(mockSwitchTopic).toHaveBeenCalledWith(TEST_IDS.TOPIC_ID, true);});- it('should not need to switch topic when active topic exists', async () => {+ it('should not switch topic when active topic already exists', async () => {const { result } = renderHook(() => useChatStore());const mockSwitchTopic = vi.fn();await act(async () => {useChatStore.setState({- ...mockState,+ activeId: TEST_IDS.SESSION_ID,+ activeTopicId: TEST_IDS.TOPIC_ID,switchTopic: mockSwitchTopic,});- await result.current.sendMessage({ message: 'test' });+ await result.current.sendMessage({ message: TEST_CONTENT.USER_MESSAGE });});expect(mockSwitchTopic).not.toHaveBeenCalled();});});- describe('Cancel send message tests', () => {- it('should correctly cancel the current active send operation', () => {+ describe('cancelSendMessageInServer', () => {+ it('should abort operation and restore editor state when cancelling', () => {const { result } = renderHook(() => useChatStore());const mockAbort = vi.fn();const mockSetJSONState = vi.fn();act(() => {useChatStore.setState({- activeId: 'session-1',- activeTopicId: 'topic-1',+ activeId: TEST_IDS.SESSION_ID,+ activeTopicId: TEST_IDS.TOPIC_ID,mainSendMessageOperations: {- [messageMapKey('session-1', 'topic-1')]: {+ [messageMapKey(TEST_IDS.SESSION_ID, TEST_IDS.TOPIC_ID)]: {isLoading: true,abortController: { abort: mockAbort, signal: {} as any },inputEditorTempState: { content: 'saved content' },@@ -578,19 +447,23 @@ describe('generateAIChatV2 actions', () => {expect(mockAbort).toHaveBeenCalledWith('User cancelled sendMessageInServer operation');expect(- result.current.mainSendMessageOperations[messageMapKey('session-1', 'topic-1')]?.isLoading,+ result.current.mainSendMessageOperations[+ messageMapKey(TEST_IDS.SESSION_ID, TEST_IDS.TOPIC_ID)+ ]?.isLoading,).toBe(false);+ expect(mockSetJSONState).toHaveBeenCalledWith({ content: 'saved content' });});- it('should cancel the operation for the corresponding topic when topic ID is specified', () => {+ it('should cancel operation for specified topic ID', () => {const { result } = renderHook(() => useChatStore());const mockAbort = vi.fn();+ const customTopicId = 'custom-topic-id';act(() => {useChatStore.setState({- activeId: 'session-1',+ activeId: TEST_IDS.SESSION_ID,mainSendMessageOperations: {- [messageMapKey('session-1', 'topic-2')]: {+ [messageMapKey(TEST_IDS.SESSION_ID, customTopicId)]: {isLoading: true,abortController: { abort: mockAbort, signal: {} as any },},@@ -599,13 +472,13 @@ describe('generateAIChatV2 actions', () => {});act(() => {- result.current.cancelSendMessageInServer('topic-2');+ result.current.cancelSendMessageInServer(customTopicId);});expect(mockAbort).toHaveBeenCalledWith('User cancelled sendMessageInServer operation');});- it('should handle safely without throwing error when operation does not exist', () => {+ it('should handle gracefully when operation does not exist', () => {const { result } = renderHook(() => useChatStore());act(() => {@@ -620,16 +493,16 @@ describe('generateAIChatV2 actions', () => {});});- describe('Clear send error tests', () => {- it('should correctly clear error state for current topic', () => {+ describe('clearSendMessageError', () => {+ it('should clear error state for current topic', () => {const { result } = renderHook(() => useChatStore());act(() => {useChatStore.setState({- activeId: 'session-1',- activeTopicId: 'topic-1',+ activeId: TEST_IDS.SESSION_ID,+ activeTopicId: TEST_IDS.TOPIC_ID,mainSendMessageOperations: {- [messageMapKey('session-1', 'topic-1')]: {+ [messageMapKey(TEST_IDS.SESSION_ID, TEST_IDS.TOPIC_ID)]: {isLoading: false,inputSendErrorMsg: 'Some error',},@@ -642,11 +515,13 @@ describe('generateAIChatV2 actions', () => {});expect(- result.current.mainSendMessageOperations[messageMapKey('session-1', 'topic-1')],+ result.current.mainSendMessageOperations[+ messageMapKey(TEST_IDS.SESSION_ID, TEST_IDS.TOPIC_ID)+ ],).toBeUndefined();});- it('should handle safely when no error operation exists', () => {+ it('should handle gracefully when no error operation exists', () => {const { result } = renderHook(() => useChatStore());act(() => {@@ -661,8 +536,8 @@ describe('generateAIChatV2 actions', () => {});});- describe('Operation state management tests', () => {- it('should correctly create new send operation', () => {+ describe('internal_toggleSendMessageOperation', () => {+ it('should create new send operation with abort controller', () => {const { result } = renderHook(() => useChatStore());let abortController: AbortController | undefined;@@ -677,7 +552,7 @@ describe('generateAIChatV2 actions', () => {);});- it('should correctly stop send operation', () => {+ it('should stop send operation and clear abort controller', () => {const { result } = renderHook(() => useChatStore());const mockAbortController = { abort: vi.fn() } as any;@@ -696,16 +571,18 @@ describe('generateAIChatV2 actions', () => {expect(result.current.mainSendMessageOperations['test-key']?.abortController).toBeNull();});- it('should correctly handle cancel reason and call abort method', () => {+ it('should call abort with cancel reason when stopping', () => {const { result } = renderHook(() => useChatStore());const mockAbortController = { abort: vi.fn() } as any;- result.current.internal_updateSendMessageOperation('test-key', {- isLoading: true,- abortController: mockAbortController,- });+ act(() => {+ result.current.internal_updateSendMessageOperation('test-key', {+ isLoading: true,+ abortController: mockAbortController,+ });- result.current.internal_toggleSendMessageOperation('test-key', false, 'Test cancel reason');+ result.current.internal_toggleSendMessageOperation('test-key', false, 'Test cancel reason');+ });expect(mockAbortController.abort).toHaveBeenCalledWith('Test cancel reason');});@@ -715,30 +592,30 @@ describe('generateAIChatV2 actions', () => {let abortController1, abortController2;act(() => {- abortController1 = result.current.internal_toggleSendMessageOperation('pkey1', true);- abortController2 = result.current.internal_toggleSendMessageOperation('pkey2', true);+ abortController1 = result.current.internal_toggleSendMessageOperation('key1', true);+ abortController2 = result.current.internal_toggleSendMessageOperation('key2', true);});- expect(result.current.mainSendMessageOperations['pkey1']?.isLoading).toBe(true);- expect(result.current.mainSendMessageOperations['pkey2']?.isLoading).toBe(true);+ expect(result.current.mainSendMessageOperations['key1']?.isLoading).toBe(true);+ expect(result.current.mainSendMessageOperations['key2']?.isLoading).toBe(true);expect(abortController1).not.toBe(abortController2);});});- describe('Send operation state update tests', () => {- it('should correctly update operation state', () => {+ describe('internal_updateSendMessageOperation', () => {+ it('should update operation state', () => {const { result } = renderHook(() => useChatStore());const mockAbortController = new AbortController();act(() => {- result.current.internal_updateSendMessageOperation('abc', {+ result.current.internal_updateSendMessageOperation('test-key', {isLoading: true,abortController: mockAbortController,inputSendErrorMsg: 'test error',});});- expect(result.current.mainSendMessageOperations['abc']).toEqual({+ expect(result.current.mainSendMessageOperations['test-key']).toEqual({isLoading: true,abortController: mockAbortController,inputSendErrorMsg: 'test error',@@ -755,7 +632,6 @@ describe('generateAIChatV2 actions', () => {abortController: initialController,});- // Only update error messageresult.current.internal_updateSendMessageOperation('test-key', {inputSendErrorMsg: 'new error',});@@ -768,56 +644,4 @@ describe('generateAIChatV2 actions', () => {});});});-- describe('Editor state recovery tests', () => {- it('should restore editor content when cancelling operation', () => {- const { result } = renderHook(() => useChatStore());- const mockSetJSONState = vi.fn();- const mockAbort = vi.fn();-- act(() => {- useChatStore.setState({- activeId: 'session-1',- activeTopicId: 'topic-1',- mainSendMessageOperations: {- [messageMapKey('session-1', 'topic-1')]: {- isLoading: true,- abortController: { abort: mockAbort, signal: {} as any },- inputEditorTempState: { content: 'saved content' },- },- },- mainInputEditor: { setJSONState: mockSetJSONState } as any,- });- });-- act(() => {- result.current.cancelSendMessageInServer();- });-- expect(mockSetJSONState).toHaveBeenCalledWith({ content: 'saved content' });- });-- it('should not restore when no saved editor state exists', () => {- const { result } = renderHook(() => useChatStore());- const mockSetJSONState = vi.fn();- const mockAbort = vi.fn();-- act(() => {- useChatStore.setState({- activeId: 'session-1',- activeTopicId: 'topic-1',- mainSendMessageOperations: {- [messageMapKey('session-1', 'topic-1')]: {- isLoading: true,- abortController: { abort: mockAbort, signal: {} as any },- },- },- mainInputEditor: { setJSONState: mockSetJSONState } as any,- });- result.current.cancelSendMessageInServer();- });-- expect(mockSetJSONState).not.toHaveBeenCalled();- });- });});