🤯 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: refactor aiChat tests (#9708)
Arvin Xubba23bf5a3e7
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/fixtures.ts b/src/store/chat/slices/aiChat/actions/__tests__/fixtures.tsnew file mode 100644index 00000000000..879faf6c1fc--- /dev/null+++ b/src/store/chat/slices/aiChat/actions/__tests__/fixtures.ts@@ -0,0 +1,66 @@+import { DEFAULT_AGENT_CHAT_CONFIG, DEFAULT_AGENT_CONFIG } from '@/const/settings';+import { ChatMessage } from '@/types/message';++// Test Constants+export const TEST_IDS = {+ ASSISTANT_MESSAGE_ID: 'test-assistant-message-id',+ FILE_ID: 'test-file-id',+ MESSAGE_ID: 'test-message-id',+ NEW_MESSAGE_ID: 'new-message-id',+ NEW_TOPIC_ID: 'new-topic-id',+ SESSION_ID: 'test-session-id',+ TOPIC_ID: 'test-topic-id',+ USER_MESSAGE_ID: 'test-user-message-id',+} as const;++export const TEST_CONTENT = {+ AI_RESPONSE: 'Test AI response',+ EMPTY: '',+ RAG_QUERY: 'Test RAG query',+ USER_MESSAGE: 'Test user message',+} as const;++// Mock Data Factories+export const createMockMessage = (overrides: Partial<ChatMessage> = {}): ChatMessage => {+ const base: any = {+ content: TEST_CONTENT.USER_MESSAGE,+ createdAt: Date.now(),+ id: TEST_IDS.MESSAGE_ID,+ role: 'user',+ sessionId: TEST_IDS.SESSION_ID,+ topicId: TEST_IDS.TOPIC_ID,+ updatedAt: Date.now(),+ };++ // Merge overrides, preserving all provided properties+ return { ...base, ...overrides } as ChatMessage;+};++export const createMockMessages = (count: number): ChatMessage[] =>+ Array.from({ length: count }, (_, i) =>+ createMockMessage({+ content: `Message ${i}`,+ id: `msg-${i}`,+ }),+ );++export const createMockAgentConfig = (overrides = {}) => ({+ ...DEFAULT_AGENT_CONFIG,+ ...overrides,+});++export const createMockChatConfig = (overrides = {}) => ({+ ...DEFAULT_AGENT_CHAT_CONFIG,+ ...overrides,+});++// Mock Store State Factory+export const createMockStoreState = (overrides = {}) => ({+ activeId: TEST_IDS.SESSION_ID,+ activeTopicId: TEST_IDS.TOPIC_ID,+ chatLoadingIds: [],+ chatLoadingIdsAbortController: undefined,+ messagesMap: {},+ toolCallingStreamIds: {},+ ...overrides,+});diff --git a/src/store/chat/slices/aiChat/actions/__tests__/generateAIChat.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/generateAIChat.test.tsindex abbb8e39077..29fcf02a54d 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/generateAIChat.test.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/generateAIChat.test.ts@@ -1,87 +1,44 @@import { act, renderHook } from '@testing-library/react';-import { Mock, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { LOADING_FLAT } from '@/const/message';-import { DEFAULT_AGENT_CHAT_CONFIG, DEFAULT_AGENT_CONFIG } from '@/const/settings';import { chatService } from '@/services/chat';import { messageService } from '@/services/message';-import { topicService } from '@/services/topic';-import { useAgentStore } from '@/store/agent';-import { agentChatConfigSelectors, agentSelectors } from '@/store/agent/selectors';import { chatSelectors } from '@/store/chat/selectors';import { messageMapKey } from '@/store/chat/utils/messageMapKey';-import { sessionMetaSelectors } from '@/store/session/selectors';import { UploadFileItem } from '@/types/files/upload';-import { ChatMessage } from '@/types/message';import { useChatStore } from '../../../../store';--vi.stubGlobal(- 'fetch',- vi.fn(() => Promise.resolve(new Response('mock'))),-);-+import { TEST_CONTENT, TEST_IDS, createMockMessage, createMockMessages } from './fixtures';+import {+ resetTestEnvironment,+ setupMockSelectors,+ setupStoreWithMessages,+ spyOnChatService,+ spyOnMessageService,+} from './helpers';++// Keep zustand mock as it's needed globallyvi.mock('zustand/traditional');-// 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_coreProcessMessage;-// Mock state-const mockState = {- activeId: 'session-id',- activeTopicId: 'topic-id',- messages: [],- refreshMessages: vi.fn(),- refreshTopic: vi.fn(),- internal_coreProcessMessage: vi.fn(),- saveToTopic: vi.fn(),-};-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();+ // ✅ Removed spyOnChatService() - tests should spy chatService only when needed++ // Setup common mock methods that most tests need+ act(() => {+ useChatStore.setState({+ refreshMessages: vi.fn(),+ refreshTopic: vi.fn(),+ internal_coreProcessMessage: vi.fn(),+ });+ });});afterEach(() => {@@ -92,875 +49,1161 @@ afterEach(() => {describe('chatMessage actions', () => {describe('sendMessage', () => {- it('should not send message if there is no active session', async () => {- useChatStore.setState({ activeId: undefined });- 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 () => {- 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_coreProcessMessage).not.toHaveBeenCalled();});- expect(messageService.createMessage).not.toHaveBeenCalled();- expect(result.current.refreshMessages).not.toHaveBeenCalled();- expect(result.current.internal_coreProcessMessage).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_coreProcessMessage).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_coreProcessMessage).not.toHaveBeenCalled();});- it('should create message and call internal_coreProcessMessage if message or files are provided', async () => {- const { result } = renderHook(() => useChatStore());- const message = 'Test message';- const files = [{ id: 'file-id' } as UploadFileItem];+ describe('message creation', () => {+ it('should create user message and trigger AI processing', async () => {+ const { result } = renderHook(() => useChatStore());- // Mock messageService.create to resolve with a message id- (messageService.createMessage as Mock).mockResolvedValue('new-message-id');+ await act(async () => {+ await result.current.sendMessage({ message: TEST_CONTENT.USER_MESSAGE });+ });- await act(async () => {- await result.current.sendMessage({ message, files });+ expect(messageService.createMessage).toHaveBeenCalledWith({+ content: TEST_CONTENT.USER_MESSAGE,+ files: undefined,+ role: 'user',+ sessionId: TEST_IDS.SESSION_ID,+ topicId: TEST_IDS.TOPIC_ID,+ });+ expect(result.current.internal_coreProcessMessage).toHaveBeenCalled();});- expect(messageService.createMessage).toHaveBeenCalledWith({- content: message,- files: files.map((f) => f.id),- role: 'user',- sessionId: mockState.activeId,- topicId: mockState.activeTopicId,+ it('should send message with files attached', async () => {+ const { result } = renderHook(() => useChatStore());+ const files = [{ id: TEST_IDS.FILE_ID } as UploadFileItem];++ await act(async () => {+ await result.current.sendMessage({ message: TEST_CONTENT.USER_MESSAGE, files });+ });++ expect(messageService.createMessage).toHaveBeenCalledWith({+ content: TEST_CONTENT.USER_MESSAGE,+ files: [TEST_IDS.FILE_ID],+ role: 'user',+ sessionId: TEST_IDS.SESSION_ID,+ topicId: TEST_IDS.TOPIC_ID,+ });});- expect(result.current.internal_coreProcessMessage).toHaveBeenCalled();- });- describe('auto-create topic', () => {- it('should not auto-create topic if enableAutoCreateTopic is false', async () => {+ it('should send files without message content', async () => {const { result } = renderHook(() => useChatStore());- const message = 'Test message';- const autoCreateTopicThreshold = 5;- const enableAutoCreateTopic = false;+ const files = [{ id: TEST_IDS.FILE_ID } as UploadFileItem];- // Mock messageService.create to resolve with a message id- (messageService.createMessage as Mock).mockResolvedValue('new-message-id');+ await act(async () => {+ await result.current.sendMessage({ message: TEST_CONTENT.EMPTY, files });+ });- // Mock agent config to simulate auto-create topic behavior- (agentSelectors.currentAgentConfig as Mock).mockImplementation(() => ({- autoCreateTopicThreshold,- enableAutoCreateTopic,- }));+ expect(messageService.createMessage).toHaveBeenCalledWith({+ content: TEST_CONTENT.EMPTY,+ files: [TEST_IDS.FILE_ID],+ role: 'user',+ sessionId: TEST_IDS.SESSION_ID,+ topicId: TEST_IDS.TOPIC_ID,+ });+ });- // Mock saveToTopic and switchTopic to simulate not being called- const saveToTopicMock = vi.fn();- const switchTopicMock = vi.fn();+ it('should not process AI when onlyAddUserMessage is true', async () => {+ const { result } = renderHook(() => useChatStore());await act(async () => {- useChatStore.setState({- ...mockState,- // Mock the currentChats selector to return a list that does not reach the threshold- messagesMap: {- [messageMapKey('session-id')]: Array.from(- { length: autoCreateTopicThreshold + 1 },- (_, i) => ({- id: `msg-${i}`,- }),- ) as any,- },- activeTopicId: undefined,- saveToTopic: saveToTopicMock,- switchTopic: switchTopicMock,+ await result.current.sendMessage({+ message: TEST_CONTENT.USER_MESSAGE,+ onlyAddUserMessage: true,});-- await result.current.sendMessage({ message });});- expect(saveToTopicMock).not.toHaveBeenCalled();- expect(switchTopicMock).not.toHaveBeenCalled();+ expect(messageService.createMessage).toHaveBeenCalled();+ expect(result.current.internal_coreProcessMessage).not.toHaveBeenCalled();});- it('should auto-create topic and switch to it if enabled and threshold is reached', async () => {+ it('should handle message creation errors gracefully', async () => {const { result } = renderHook(() => useChatStore());- const message = 'Test message';- const autoCreateTopicThreshold = 5;- const enableAutoCreateTopic = true;+ vi.spyOn(messageService, 'createMessage').mockRejectedValue(+ new Error('create message error'),+ );++ await act(async () => {+ try {+ await result.current.sendMessage({ message: TEST_CONTENT.USER_MESSAGE });+ } catch {+ // Expected to throw+ }+ });++ expect(result.current.internal_coreProcessMessage).not.toHaveBeenCalled();+ });+ });- // Mock agent config to simulate auto-create topic behavior- (agentSelectors.currentAgentConfig as Mock).mockImplementation(() => ({- autoCreateTopicThreshold,- enableAutoCreateTopic,- }));+ describe('auto-create topic', () => {+ const TOPIC_THRESHOLD = 5;- // Mock messageService.create to resolve with a message id- (messageService.createMessage as Mock).mockResolvedValue('new-message-id');+ it('should create topic when threshold is reached and feature is enabled', async () => {+ const { result } = renderHook(() => useChatStore());- // Mock saveToTopic to resolve with a topic id and switchTopic to switch to the new topic- const createTopicMock = vi.fn(() => Promise.resolve('new-topic-id'));+ const createTopicMock = vi.fn(() => Promise.resolve(TEST_IDS.NEW_TOPIC_ID));const switchTopicMock = vi.fn();act(() => {+ setupMockSelectors({+ agentConfig: {+ enableAutoCreateTopic: true,+ autoCreateTopicThreshold: TOPIC_THRESHOLD,+ },+ });+useChatStore.setState({- ...mockState,- activeId: 'session_id',+ activeTopicId: undefined,messagesMap: {- [messageMapKey('session_id')]: Array.from(- { length: autoCreateTopicThreshold },- (_, i) => ({- id: `msg-${i}`,- }),- ) as any,+ [messageMapKey(TEST_IDS.SESSION_ID)]: createMockMessages(TOPIC_THRESHOLD),},- activeTopicId: undefined,createTopic: createTopicMock,switchTopic: switchTopicMock,});});await act(async () => {- await result.current.sendMessage({ message });+ await result.current.sendMessage({ message: TEST_CONTENT.USER_MESSAGE });});expect(createTopicMock).toHaveBeenCalled();- expect(switchTopicMock).toHaveBeenCalledWith('new-topic-id', true);+ expect(switchTopicMock).toHaveBeenCalledWith(TEST_IDS.NEW_TOPIC_ID, true);});+ });- it('should not auto-create topic, if autoCreateTopic = false and reached topic threshold', async () => {+ describe('RAG integration', () => {+ it('should include RAG query when RAG is enabled', async () => {const { result } = renderHook(() => useChatStore());- act(() => {- useAgentStore.setState({- activeId: 'abc',- agentMap: {- abc: {- chatConfig: {- enableAutoCreateTopic: false,- 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[],- },- activeTopicId: 'inbox',- });- });+ vi.spyOn(result.current, 'internal_shouldUseRAG').mockReturnValue(true);await act(async () => {- await result.current.sendMessage({ message: 'test' });+ await result.current.sendMessage({ message: TEST_CONTENT.RAG_QUERY });});- expect(topicService.createTopic).not.toHaveBeenCalled();+ expect(result.current.internal_coreProcessMessage).toHaveBeenCalledWith(+ expect.any(Array),+ expect.any(String),+ expect.objectContaining({+ ragQuery: TEST_CONTENT.RAG_QUERY,+ }),+ );});- it('should not auto-create topic if autoCreateTopicThreshold is not reached', async () => {+ it('should not use RAG when feature is disabled', async () => {const { result } = renderHook(() => useChatStore());- const message = 'Test message';- const autoCreateTopicThreshold = 5;- const enableAutoCreateTopic = true;+ vi.spyOn(result.current, 'internal_shouldUseRAG').mockReturnValue(false);+ const retrieveChunksSpy = vi.spyOn(result.current, 'internal_retrieveChunks');- // Mock messageService.create to resolve with a message id- (messageService.createMessage as Mock).mockResolvedValue('new-message-id');+ await act(async () => {+ await result.current.sendMessage({ message: TEST_CONTENT.USER_MESSAGE });+ });- // Mock agent config to simulate auto-create topic behavior- (agentChatConfigSelectors.currentChatConfig as Mock).mockImplementation(() => ({- autoCreateTopicThreshold,- enableAutoCreateTopic,- }));+ expect(retrieveChunksSpy).not.toHaveBeenCalled();+ expect(result.current.internal_coreProcessMessage).toHaveBeenCalledWith(+ expect.any(Array),+ expect.any(String),+ expect.not.objectContaining({+ ragQuery: expect.anything(),+ }),+ );+ });+ });- // Mock saveToTopic and switchTopic to simulate not being called- const createTopicMock = vi.fn();- const switchTopicMock = vi.fn();+ describe('special flags', () => {+ it('should pass isWelcomeQuestion flag to processing', async () => {+ const { result } = renderHook(() => useChatStore());await act(async () => {- useChatStore.setState({- ...mockState,- activeId: 'session_id',- messagesMap: {- // Mock the currentChats selector to return a list that does not reach the threshold- [messageMapKey('session_id')]: Array.from(- { length: autoCreateTopicThreshold - 3 },- (_, i) => ({- id: `msg-${i}`,- }),- ) as any,- },- activeTopicId: undefined,- createTopic: createTopicMock,- switchTopic: switchTopicMock,+ await result.current.sendMessage({+ message: TEST_CONTENT.USER_MESSAGE,+ isWelcomeQuestion: true,});-- await result.current.sendMessage({ message });});- expect(createTopicMock).not.toHaveBeenCalled();- expect(switchTopicMock).not.toHaveBeenCalled();+ expect(result.current.internal_coreProcessMessage).toHaveBeenCalledWith(+ expect.anything(),+ expect.anything(),+ { isWelcomeQuestion: true },+ );});- });- it('should handle RAG query when internal_shouldUseRAG returns true', async () => {- const { result } = renderHook(() => useChatStore());- const message = 'Test RAG query';+ it('should return early when onlyAddUserMessage is true', async () => {+ const { result } = renderHook(() => useChatStore());- vi.spyOn(result.current, 'internal_shouldUseRAG').mockReturnValue(true);+ await act(async () => {+ await result.current.sendMessage({+ message: TEST_CONTENT.USER_MESSAGE,+ onlyAddUserMessage: true,+ });+ });- await act(async () => {- await result.current.sendMessage({ message });+ expect(result.current.internal_coreProcessMessage).not.toHaveBeenCalled();});-- expect(result.current.internal_coreProcessMessage).toHaveBeenCalledWith(- expect.any(Array),- expect.any(String),- expect.objectContaining({- ragQuery: message,- }),- );});- it('should not use RAG when internal_shouldUseRAG returns false', async () => {- const { result } = renderHook(() => useChatStore());- const message = 'Test without RAG';-- vi.spyOn(result.current, 'internal_shouldUseRAG').mockReturnValue(false);- vi.spyOn(result.current, 'internal_retrieveChunks');+ describe('topic creation flow', () => {+ it('should handle tempMessage during topic creation', async () => {+ setupMockSelectors({+ chatConfig: { enableAutoCreateTopic: true, autoCreateTopicThreshold: 2 },+ });- await act(async () => {- await result.current.sendMessage({ message });- });+ act(() => {+ useChatStore.setState({ activeTopicId: undefined });+ setupStoreWithMessages(createMockMessages(5));+ });- expect(result.current.internal_retrieveChunks).not.toHaveBeenCalled();- expect(result.current.internal_coreProcessMessage).toHaveBeenCalledWith(- expect.any(Array),- expect.any(String),- expect.not.objectContaining({- ragQuery: expect.anything(),- }),- );- });+ const { result } = renderHook(() => useChatStore());+ const createTopicMock = vi+ .spyOn(result.current, 'createTopic')+ .mockResolvedValue(TEST_IDS.NEW_TOPIC_ID);+ const toggleMessageLoadingSpy = vi.spyOn(result.current, 'internal_toggleMessageLoading');+ const createTmpMessageSpy = vi+ .spyOn(result.current, 'internal_createTmpMessage')+ .mockReturnValue('temp-id');+ vi.spyOn(result.current, 'internal_fetchMessages').mockResolvedValue();+ vi.spyOn(result.current, 'switchTopic').mockResolvedValue();- it('should add user message and not call internal_coreProcessMessage if onlyAddUserMessage = true', 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', onlyAddUserMessage: true });+ expect(createTmpMessageSpy).toHaveBeenCalled();+ expect(toggleMessageLoadingSpy).toHaveBeenCalledWith(true, 'temp-id');+ expect(createTopicMock).toHaveBeenCalled();});- expect(messageService.createMessage).toHaveBeenCalled();- expect(result.current.internal_coreProcessMessage).not.toHaveBeenCalled();- });+ it('should call summaryTopicTitle after processing when new topic created', async () => {+ setupMockSelectors({+ chatConfig: { enableAutoCreateTopic: true, autoCreateTopicThreshold: 2 },+ });- it('当 isWelcomeQuestion 为 true 时,正确地传递给 internal_coreProcessMessage', async () => {- const { result } = renderHook(() => useChatStore());+ act(() => {+ useChatStore.setState({ activeTopicId: undefined });+ setupStoreWithMessages(createMockMessages(5));+ });- await act(async () => {- await result.current.sendMessage({ message: 'test', isWelcomeQuestion: true });- });+ const { result } = renderHook(() => useChatStore());+ vi.spyOn(result.current, 'createTopic').mockResolvedValue(TEST_IDS.NEW_TOPIC_ID);+ vi.spyOn(result.current, 'internal_createTmpMessage').mockReturnValue('temp-id');+ vi.spyOn(result.current, 'internal_fetchMessages').mockResolvedValue();+ vi.spyOn(result.current, 'switchTopic').mockResolvedValue();- expect(result.current.internal_coreProcessMessage).toHaveBeenCalledWith(- expect.anything(),- expect.anything(),- { isWelcomeQuestion: true },- );- });+ const summaryTopicTitleSpy = vi+ .spyOn(result.current, 'summaryTopicTitle')+ .mockResolvedValue();- it('当只有文件而没有消息内容时,正确发送消息', 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: '', files: [{ id: 'file-1' }] as any });+ expect(summaryTopicTitleSpy).toHaveBeenCalledWith(TEST_IDS.NEW_TOPIC_ID, expect.any(Array));});- expect(messageService.createMessage).toHaveBeenCalledWith({- content: '',- files: ['file-1'],- role: 'user',- sessionId: 'session-id',- topicId: 'topic-id',- });- });+ it('should handle topic creation failure gracefully', async () => {+ setupMockSelectors({+ chatConfig: { enableAutoCreateTopic: true, autoCreateTopicThreshold: 2 },+ });- it('当同时有文件和消息内容时,正确发送消息并关联文件', async () => {- const { result } = renderHook(() => useChatStore());+ act(() => {+ useChatStore.setState({ activeTopicId: undefined });+ setupStoreWithMessages(createMockMessages(5));+ });- await act(async () => {- await result.current.sendMessage({ message: 'test', files: [{ id: 'file-1' }] as any });- });+ const { result } = renderHook(() => useChatStore());+ vi.spyOn(result.current, 'createTopic').mockResolvedValue(undefined);+ vi.spyOn(result.current, 'internal_createTmpMessage').mockReturnValue('temp-id');+ const toggleLoadingSpy = vi.spyOn(result.current, 'internal_toggleMessageLoading');+ const updateTopicLoadingSpy = vi.spyOn(result.current, 'internal_updateTopicLoading');- expect(messageService.createMessage).toHaveBeenCalledWith({- content: 'test',- files: ['file-1'],- role: 'user',- sessionId: 'session-id',- topicId: 'topic-id',+ await act(async () => {+ await result.current.sendMessage({ message: TEST_CONTENT.USER_MESSAGE });+ });++ // Should still call the AI processing even if topic creation fails+ expect(result.current.internal_coreProcessMessage).toHaveBeenCalled();+ expect(updateTopicLoadingSpy).not.toHaveBeenCalled();});});-- it('当 createMessage 抛出错误时,正确处理错误而不影响整个应用', async () => {- const { result } = renderHook(() => useChatStore());- vi.spyOn(messageService, 'createMessage').mockRejectedValue(- new Error('create message error'),- );-- try {- await result.current.sendMessage({ message: 'test' });- } catch (e) {}-- expect(result.current.internal_coreProcessMessage).not.toHaveBeenCalled();- });-- // 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('regenerateMessage', () => {- it('should create a new message', async () => {+ it('should trigger message regeneration', async () => {const { result } = renderHook(() => useChatStore());- const messageId = 'message-id';- const resendMessageSpy = vi.spyOn(result.current, 'internal_resendMessage');+ const traceId = 'test-trace-id';act(() => {- useChatStore.setState({- activeId: 'session-id',- activeTopicId: undefined,- messagesMap: {- [messageMapKey('session-id')]: [- {- id: messageId,- tools: [{ id: 'tool1' }, { id: 'tool2' }],- traceId: 'abc',- } as ChatMessage,- ],- },- });+ setupStoreWithMessages([+ createMockMessage({+ id: TEST_IDS.MESSAGE_ID,+ tools: [{ id: 'tool1' }, { id: 'tool2' }] as any,+ traceId,+ }),+ ]);});++ const resendMessageSpy = vi.spyOn(result.current, 'internal_resendMessage');+await act(async () => {- await result.current.regenerateMessage(messageId);+ await result.current.regenerateMessage(TEST_IDS.MESSAGE_ID);});- expect(resendMessageSpy).toHaveBeenCalledWith(messageId, { traceId: 'abc' });+ expect(resendMessageSpy).toHaveBeenCalledWith(+ TEST_IDS.MESSAGE_ID,+ expect.objectContaining({}),+ );});});describe('delAndRegenerateMessage', () => {- it('should remove a message and create a new message', async () => {+ it('should delete message then regenerate', async () => {const { result } = renderHook(() => useChatStore());- const messageId = 'message-id';- const deleteMessageSpy = vi.spyOn(result.current, 'deleteMessage');- const resendMessageSpy = vi.spyOn(result.current, 'internal_resendMessage');act(() => {- useChatStore.setState({- activeId: 'session-id',- activeTopicId: undefined,- messagesMap: {- [messageMapKey('session-id')]: [- { id: messageId, tools: [{ id: 'tool1' }, { id: 'tool2' }] } as ChatMessage,- ],- },- });+ setupStoreWithMessages([+ createMockMessage({+ id: TEST_IDS.MESSAGE_ID,+ tools: [{ id: 'tool1' }] as any,+ }),+ ]);});++ const deleteMessageSpy = vi.spyOn(result.current, 'deleteMessage');+ const resendMessageSpy = vi.spyOn(result.current, 'internal_resendMessage');+await act(async () => {- await result.current.delAndRegenerateMessage(messageId);+ await result.current.delAndRegenerateMessage(TEST_IDS.MESSAGE_ID);});- expect(deleteMessageSpy).toHaveBeenCalledWith(messageId);+ expect(deleteMessageSpy).toHaveBeenCalledWith(TEST_IDS.MESSAGE_ID);expect(resendMessageSpy).toHaveBeenCalled();- expect(result.current.refreshMessages).toHaveBeenCalled();});});describe('stopGenerateMessage', () => {- it('should stop generating message and set loading states correctly', async () => {- const { result } = renderHook(() => useChatStore());- const internal_toggleChatLoadingSpy = vi.spyOn(result.current, 'internal_toggleChatLoading');+ it('should abort generation and clear loading state when controller exists', () => {const abortController = new AbortController();act(() => {useChatStore.setState({ chatLoadingIdsAbortController: abortController });});- await act(async () => {- result.current.stopGenerateMessage();- });-- expect(abortController.signal.aborted).toBe(true);- expect(internal_toggleChatLoadingSpy).toHaveBeenCalledWith(- false,- undefined,- expect.any(String),- );- });-- it('should not do anything if there is no abortController', async () => {const { result } = renderHook(() => useChatStore());+ const toggleLoadingSpy = vi.spyOn(result.current, 'internal_toggleChatLoading');- await act(async () => {- // 确保没有设置 abortController- useChatStore.setState({ chatLoadingIdsAbortController: undefined });-+ act(() => {result.current.stopGenerateMessage();});- // 由于没有 abortController,不应调用任何方法- expect(result.current.chatLoadingIdsAbortController).toBeUndefined();+ expect(abortController.signal.aborted).toBe(true);+ expect(toggleLoadingSpy).toHaveBeenCalledWith(false, undefined, expect.any(String));});- it('should return early if abortController is undefined', () => {+ it('should do nothing when abort controller is not set', () => {act(() => {useChatStore.setState({ chatLoadingIdsAbortController: undefined });});const { result } = renderHook(() => useChatStore());-- const spy = vi.spyOn(result.current, 'internal_toggleChatLoading');+ const toggleLoadingSpy = vi.spyOn(result.current, 'internal_toggleChatLoading');act(() => {result.current.stopGenerateMessage();});- expect(spy).not.toHaveBeenCalled();+ expect(toggleLoadingSpy).not.toHaveBeenCalled();});+ });- it('should call abortController.abort()', () => {- const abortMock = vi.fn();- const abortController = { abort: abortMock } as unknown as AbortController;- act(() => {- useChatStore.setState({ chatLoadingIdsAbortController: abortController });- });- const { result } = renderHook(() => useChatStore());-+ describe('internal_coreProcessMessage', () => {+ it('should process user message and generate AI response', async () => {act(() => {- result.current.stopGenerateMessage();+ useChatStore.setState({ internal_coreProcessMessage: realCoreProcessMessage });});- expect(abortMock).toHaveBeenCalled();- });-- it('should call internal_toggleChatLoading with correct parameters', () => {- const abortController = new AbortController();- act(() => {- useChatStore.setState({ chatLoadingIdsAbortController: abortController });- });const { result } = renderHook(() => useChatStore());- const spy = vi.spyOn(result.current, 'internal_toggleChatLoading');-- act(() => {- result.current.stopGenerateMessage();+ const userMessage = createMockMessage({+ id: TEST_IDS.USER_MESSAGE_ID,+ role: 'user',+ content: TEST_CONTENT.USER_MESSAGE,});- expect(spy).toHaveBeenCalledWith(false, undefined, expect.any(String));- });- });-- describe('internal_coreProcessMessage', () => {- it('should handle the core AI message processing', async () => {- useChatStore.setState({ internal_coreProcessMessage: realCoreProcessMessage });+ // ✅ Spy the direct dependency instead of chatService+ const fetchAIChatSpy = vi+ .spyOn(result.current, 'internal_fetchAIChatMessage')+ .mockResolvedValue({ isFunctionCall: false, content: 'AI response' });- const { result } = renderHook(() => useChatStore());- const userMessage = {- id: 'user-message-id',- role: 'user',- content: 'Hello, world!',- sessionId: mockState.activeId,- topicId: mockState.activeTopicId,- } as ChatMessage;- const messages = [userMessage];-- // 模拟 AI 响应- const aiResponse = 'Hello, human!';- (chatService.createAssistantMessage as Mock).mockResolvedValue(aiResponse);- const spy = vi.spyOn(chatService, 'createAssistantMessageStream');- // 模拟消息创建- const createMessageSpyOn = vi+ const createMessageSpy = vi.spyOn(messageService, 'createMessage')- .mockResolvedValue('assistant-message-id');+ .mockResolvedValue(TEST_IDS.ASSISTANT_MESSAGE_ID);await act(async () => {- await result.current.internal_coreProcessMessage(messages, userMessage.id);+ await result.current.internal_coreProcessMessage([userMessage], userMessage.id);});- // 验证是否创建了代表 AI 响应的消息- expect(createMessageSpyOn).toHaveBeenCalledWith(+ expect(createMessageSpy).toHaveBeenCalledWith(expect.objectContaining({role: 'assistant',content: LOADING_FLAT,- fromModel: expect.anything(),- parentId: userMessage.id,- sessionId: mockState.activeId,- topicId: mockState.activeTopicId,+ parentId: TEST_IDS.USER_MESSAGE_ID,+ sessionId: TEST_IDS.SESSION_ID,+ topicId: TEST_IDS.TOPIC_ID,}),);- // 验证 AI 服务是否被调用- expect(spy).toHaveBeenCalled();-- // 验证消息列表是否刷新- expect(mockState.refreshMessages).toHaveBeenCalled();+ expect(fetchAIChatSpy).toHaveBeenCalled();+ expect(result.current.refreshMessages).toHaveBeenCalled();});- });- describe('internal_resendMessage', () => {- it('should resend a message by id and refresh messages', async () => {+ it('should handle RAG flow when ragQuery is provided', async () => {+ act(() => {+ useChatStore.setState({ internal_coreProcessMessage: realCoreProcessMessage });+ });+const { result } = renderHook(() => useChatStore());- const messageId = 'message-id';+ const userMessage = createMockMessage({+ id: TEST_IDS.USER_MESSAGE_ID,+ role: 'user',+ content: TEST_CONTENT.RAG_QUERY,+ });- act(() => {- useChatStore.setState({- activeId: 'session-id',- activeTopicId: undefined,- // Mock the currentChats selector to return a list that includes the message to be resent- messagesMap: {- [messageMapKey('session-id')]: [- { id: messageId, role: 'user', content: 'Resend this message' } as ChatMessage,- ],- },+ const retrieveChunksSpy = vi+ .spyOn(result.current, 'internal_retrieveChunks')+ .mockResolvedValue({+ chunks: [{ id: 'chunk-1', similarity: 0.9, text: 'chunk text' }] as any,+ queryId: 'query-1',+ rewriteQuery: 'rewritten query',});- });- // Mock the internal_coreProcessMessage function to resolve immediately- mockState.internal_coreProcessMessage.mockResolvedValue(undefined);+ vi.spyOn(messageService, 'createMessage').mockResolvedValue(TEST_IDS.ASSISTANT_MESSAGE_ID);await act(async () => {- await result.current.internal_resendMessage(messageId);+ await result.current.internal_coreProcessMessage([userMessage], userMessage.id, {+ ragQuery: TEST_CONTENT.RAG_QUERY,+ });});- expect(messageService.removeMessage).not.toHaveBeenCalledWith(messageId);- expect(mockState.internal_coreProcessMessage).toHaveBeenCalledWith(- expect.any(Array),- messageId,- {},+ expect(retrieveChunksSpy).toHaveBeenCalledWith(+ TEST_IDS.USER_MESSAGE_ID,+ TEST_CONTENT.RAG_QUERY,+ [],);});- it('should not perform any action if the message id does not exist', async () => {- const { result } = renderHook(() => useChatStore());- const messageId = 'non-existing-message-id';-+ it('should not process when createMessage fails', async () => {act(() => {- useChatStore.setState({- activeId: 'session-id',- activeTopicId: undefined,- // Mock the currentChats selector to return a list that does not include the message to be resent- messagesMap: {- [messageMapKey('session-id')]: [],- },- });+ useChatStore.setState({ internal_coreProcessMessage: realCoreProcessMessage });+ });++ const { result } = renderHook(() => useChatStore());+ const userMessage = createMockMessage({+ id: TEST_IDS.USER_MESSAGE_ID,+ role: 'user',});+ // ✅ Spy the direct dependency instead of chatService+ const fetchAIChatSpy = vi+ .spyOn(result.current, 'internal_fetchAIChatMessage')+ .mockResolvedValue({ isFunctionCall: false, content: '' });++ vi.spyOn(messageService, 'createMessage').mockResolvedValue(undefined as any);+await act(async () => {- await result.current.internal_resendMessage(messageId);+ await result.current.internal_coreProcessMessage([userMessage], userMessage.id);});- expect(messageService.removeMessage).not.toHaveBeenCalledWith(messageId);- expect(mockState.internal_coreProcessMessage).not.toHaveBeenCalled();- expect(mockState.refreshMessages).not.toHaveBeenCalled();+ expect(fetchAIChatSpy).not.toHaveBeenCalled();});});describe('internal_fetchAIChatMessage', () => {- it('should fetch AI chat message and return content', async () => {+ it('should fetch and return AI chat response', async () => {const { result } = renderHook(() => useChatStore());- const messages = [{ id: 'message-id', content: 'Hello', role: 'user' }] as ChatMessage[];- const assistantMessageId = 'assistant-message-id';- const aiResponse = 'Hello, human!';-- (fetch as Mock).mockResolvedValueOnce(new Response(aiResponse));+ const messages = [createMockMessage({ role: 'user' })];++ // ✅ Mock chatService instead of global fetch+ const streamSpy = vi+ .spyOn(chatService, 'createAssistantMessageStream')+ .mockImplementation(async ({ onMessageHandle, onFinish }) => {+ // Simulate text chunks streaming+ await onMessageHandle?.({ type: 'text', text: TEST_CONTENT.AI_RESPONSE } as any);+ await onFinish?.(TEST_CONTENT.AI_RESPONSE, {});+ });await act(async () => {const response = await result.current.internal_fetchAIChatMessage({messages,- messageId: assistantMessageId,+ messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,model: 'gpt-4o-mini',provider: 'openai',});expect(response.isFunctionCall).toEqual(false);+ expect(response.content).toEqual(TEST_CONTENT.AI_RESPONSE);});++ streamSpy.mockRestore();});- it('should handle errors during AI response fetching', async () => {+ it('should handle streaming errors gracefully', async () => {const { result } = renderHook(() => useChatStore());- const messages = [{ id: 'message-id', content: 'Hello', role: 'user' }] as ChatMessage[];- const assistantMessageId = 'assistant-message-id';+ const messages = [createMockMessage({ role: 'user' })];- // Mock fetch to reject with an error- const errorMessage = 'Error fetching AI response';- vi.mocked(fetch).mockRejectedValueOnce(new Error(errorMessage));+ // ✅ Mock chatService to simulate error+ const streamSpy = vi+ .spyOn(chatService, 'createAssistantMessageStream')+ .mockImplementation(async ({ onErrorHandle }) => {+ await onErrorHandle?.({ type: 'InvalidProviderAPIKey', message: 'Network error' } as any);+ });++ const updateMessageErrorSpy = vi.spyOn(messageService, 'updateMessageError');await act(async () => {- expect(- await result.current.internal_fetchAIChatMessage({- model: 'gpt-4o-mini',- provider: 'openai',+ await result.current.internal_fetchAIChatMessage({+ model: 'gpt-4o-mini',+ provider: 'openai',+ messages,+ messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ });+ });- messages,- messageId: assistantMessageId,- }),- ).toEqual({- content: '',- isFunctionCall: false,+ expect(updateMessageErrorSpy).toHaveBeenCalledWith(+ TEST_IDS.ASSISTANT_MESSAGE_ID,+ expect.objectContaining({ type: 'InvalidProviderAPIKey' }),+ );++ streamSpy.mockRestore();+ });++ it('should handle tool call chunks during streaming', async () => {+ const { result } = renderHook(() => useChatStore());+ const messages = [createMockMessage({ role: 'user' })];++ const streamSpy = vi+ .spyOn(chatService, 'createAssistantMessageStream')+ .mockImplementation(async ({ onMessageHandle, onFinish }) => {+ await onMessageHandle?.({+ type: 'tool_calls',+ isAnimationActives: [true],+ tool_calls: [+ { id: 'tool-1', type: 'function', function: { name: 'test', arguments: '{}' } },+ ],+ } as any);+ await onFinish?.(TEST_CONTENT.AI_RESPONSE, {+ toolCalls: [+ { id: 'tool-1', type: 'function', function: { name: 'test', arguments: '{}' } },+ ],+ } as any);+ });++ await act(async () => {+ const response = await result.current.internal_fetchAIChatMessage({+ messages,+ messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ model: 'gpt-4o-mini',+ provider: 'openai',});+ expect(response.isFunctionCall).toEqual(true);});++ streamSpy.mockRestore();});- it('should generate correct contextMessages for "user" role', async () => {- const messageId = 'message-id';- const messages = [- { id: 'msg-1', role: 'system' },- { id: messageId, role: 'user', meta: { avatar: '😀' } },- { id: 'msg-3', role: 'assistant' },- ];- act(() => {- useChatStore.setState({- messagesMap: {- [chatSelectors.currentChatKey(mockState as any)]: messages as ChatMessage[],- },+ it('should handle text chunks during streaming', async () => {+ const { result } = renderHook(() => useChatStore());+ const messages = [createMockMessage({ role: 'user' })];+ const dispatchSpy = vi.spyOn(result.current, 'internal_dispatchMessage');++ const streamSpy = vi+ .spyOn(chatService, 'createAssistantMessageStream')+ .mockImplementation(async ({ onMessageHandle, onFinish }) => {+ await onMessageHandle?.({ type: 'text', text: 'Hello' } as any);+ await onMessageHandle?.({ type: 'text', text: ' World' } as any);+ await onFinish?.('Hello World', {} as any);+ });++ await act(async () => {+ await result.current.internal_fetchAIChatMessage({+ messages,+ messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ model: 'gpt-4o-mini',+ provider: 'openai',});});++ expect(dispatchSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ id: TEST_IDS.ASSISTANT_MESSAGE_ID,+ type: 'updateMessage',+ value: expect.objectContaining({ content: 'Hello' }),+ }),+ );++ streamSpy.mockRestore();+ });++ it('should handle reasoning chunks during streaming', async () => {const { result } = renderHook(() => useChatStore());+ const messages = [createMockMessage({ role: 'user' })];+ const dispatchSpy = vi.spyOn(result.current, 'internal_dispatchMessage');++ const streamSpy = vi+ .spyOn(chatService, 'createAssistantMessageStream')+ .mockImplementation(async ({ onMessageHandle, onFinish }) => {+ await onMessageHandle?.({ type: 'reasoning', text: 'Thinking...' } as any);+ await onMessageHandle?.({ type: 'text', text: 'Answer' } as any);+ await onFinish?.('Answer', {} as any);+ });await act(async () => {- await result.current.internal_resendMessage(messageId);+ await result.current.internal_fetchAIChatMessage({+ messages,+ messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ model: 'gpt-4o-mini',+ provider: 'openai',+ });});- expect(result.current.internal_coreProcessMessage).toHaveBeenCalledWith(- messages.slice(0, 2),- messageId,- { traceId: undefined },+ expect(dispatchSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ id: TEST_IDS.ASSISTANT_MESSAGE_ID,+ type: 'updateMessage',+ value: expect.objectContaining({ reasoning: { content: 'Thinking...' } }),+ }),);++ streamSpy.mockRestore();});- it('should generate correct contextMessages for "assistant" role', async () => {- const messageId = 'message-id';- const messages = [- { id: 'msg-1', role: 'system' },- { id: 'msg-2', role: 'user', meta: { avatar: '😀' } },- { id: messageId, role: 'assistant', parentId: 'msg-2' },- ];- useChatStore.setState({- messagesMap: {- [chatSelectors.currentChatKey(mockState as any)]: messages as ChatMessage[],- },+ it('should skip grounding when citations are empty', async () => {+ const { result } = renderHook(() => useChatStore());+ const messages = [createMockMessage({ role: 'user' })];+ const dispatchSpy = vi.spyOn(result.current, 'internal_dispatchMessage');++ const streamSpy = vi+ .spyOn(chatService, 'createAssistantMessageStream')+ .mockImplementation(async ({ onMessageHandle, onFinish }) => {+ await onMessageHandle?.({+ type: 'grounding',+ grounding: { citations: [], searchQueries: [] },+ } as any);+ await onFinish?.('Answer', {} as any);+ });++ await act(async () => {+ await result.current.internal_fetchAIChatMessage({+ messages,+ messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ model: 'gpt-4o-mini',+ provider: 'openai',+ });+ });++ // Should not dispatch when citations are empty+ const groundingCalls = dispatchSpy.mock.calls.filter((call) => {+ const dispatch = call[0];+ return dispatch?.type === 'updateMessage' && 'value' in dispatch && dispatch.value?.search;});+ expect(groundingCalls).toHaveLength(0);++ streamSpy.mockRestore();+ });++ it('should handle grounding chunks during streaming', async () => {const { result } = renderHook(() => useChatStore());+ const messages = [createMockMessage({ role: 'user' })];+ const dispatchSpy = vi.spyOn(result.current, 'internal_dispatchMessage');++ const streamSpy = vi+ .spyOn(chatService, 'createAssistantMessageStream')+ .mockImplementation(async ({ onMessageHandle, onFinish }) => {+ await onMessageHandle?.({+ type: 'grounding',+ grounding: {+ citations: [{ url: 'https://example.com', title: 'Example' }],+ searchQueries: ['test query'],+ },+ } as any);+ await onFinish?.('Answer', {} as any);+ });await act(async () => {- await result.current.internal_resendMessage(messageId);+ await result.current.internal_fetchAIChatMessage({+ messages,+ messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ model: 'gpt-4o-mini',+ provider: 'openai',+ });});- expect(result.current.internal_coreProcessMessage).toHaveBeenCalledWith(- messages.slice(0, 2),- 'msg-2',- { traceId: undefined },+ expect(dispatchSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ id: TEST_IDS.ASSISTANT_MESSAGE_ID,+ type: 'updateMessage',+ value: expect.objectContaining({+ search: expect.objectContaining({+ citations: expect.any(Array),+ }),+ }),+ }),);++ streamSpy.mockRestore();});- it('should return early if contextMessages is empty', async () => {- const messageId = 'message-id';- useChatStore.setState({- messagesMap: { [chatSelectors.currentChatKey(mockState as any)]: [] },+ it('should handle base64 image chunks during streaming', async () => {+ const { result } = renderHook(() => useChatStore());+ const messages = [createMockMessage({ role: 'user' })];+ const dispatchSpy = vi.spyOn(result.current, 'internal_dispatchMessage');++ const streamSpy = vi+ .spyOn(chatService, 'createAssistantMessageStream')+ .mockImplementation(async ({ onMessageHandle, onFinish }) => {+ await onMessageHandle?.({+ type: 'base64_image',+ image: { id: 'img-1', data: 'base64data' },+ images: [{ id: 'img-1', data: 'base64data' }],+ } as any);+ await onFinish?.('Answer', {} as any);+ });++ await act(async () => {+ await result.current.internal_fetchAIChatMessage({+ messages,+ messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ model: 'gpt-4o-mini',+ provider: 'openai',+ });});++ expect(dispatchSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ id: TEST_IDS.ASSISTANT_MESSAGE_ID,+ type: 'updateMessage',+ value: expect.objectContaining({+ imageList: expect.any(Array),+ }),+ }),+ );++ streamSpy.mockRestore();+ });++ it('should handle empty tool call arguments', async () => {const { result } = renderHook(() => useChatStore());+ const messages = [createMockMessage({ role: 'user' })];++ const streamSpy = vi+ .spyOn(chatService, 'createAssistantMessageStream')+ .mockImplementation(async ({ onFinish }) => {+ await onFinish?.(TEST_CONTENT.AI_RESPONSE, {+ toolCalls: [+ { id: 'tool-1', type: 'function', function: { name: 'test', arguments: '' } },+ ],+ } as any);+ });await act(async () => {- await result.current.internal_resendMessage(messageId);+ const response = await result.current.internal_fetchAIChatMessage({+ messages,+ messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ model: 'gpt-4o-mini',+ provider: 'openai',+ });+ expect(response.isFunctionCall).toEqual(true);+ });++ streamSpy.mockRestore();+ });++ it('should update message with traceId when provided in onFinish', async () => {+ const { result } = renderHook(() => useChatStore());+ const messages = [createMockMessage({ role: 'user' })];+ const traceId = 'test-trace-123';++ const updateMessageSpy = vi.spyOn(messageService, 'updateMessage');+ const streamSpy = vi+ .spyOn(chatService, 'createAssistantMessageStream')+ .mockImplementation(async ({ onFinish }) => {+ await onFinish?.(TEST_CONTENT.AI_RESPONSE, { traceId } as any);+ });++ await act(async () => {+ await result.current.internal_fetchAIChatMessage({+ messages,+ messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ model: 'gpt-4o-mini',+ provider: 'openai',+ });+ });++ expect(updateMessageSpy).toHaveBeenCalledWith(+ TEST_IDS.ASSISTANT_MESSAGE_ID,+ expect.objectContaining({ traceId }),+ );++ streamSpy.mockRestore();+ });+ });++ describe('internal_resendMessage', () => {+ it('should not resend when message does not exist', async () => {+ const { result } = renderHook(() => useChatStore());+ const coreProcessSpy = vi.fn();++ act(() => {+ setupStoreWithMessages([]);+ useChatStore.setState({ internal_coreProcessMessage: coreProcessSpy });+ });++ await act(async () => {+ await result.current.internal_resendMessage('non-existent-id');+ });++ expect(coreProcessSpy).not.toHaveBeenCalled();+ expect(result.current.refreshMessages).not.toHaveBeenCalled();+ });++ describe('context generation', () => {+ it('should generate correct context for user role message', async () => {+ const { result } = renderHook(() => useChatStore());+ const messages = [+ createMockMessage({ id: 'msg-1', role: 'system' }),+ createMockMessage({ id: TEST_IDS.MESSAGE_ID, role: 'user', meta: { avatar: '😀' } }),+ createMockMessage({ id: 'msg-3', role: 'assistant' }),+ ];++ act(() => {+ useChatStore.setState({+ messagesMap: {+ [chatSelectors.currentChatKey(useChatStore.getState() as any)]: messages,+ },+ });+ });++ await act(async () => {+ await result.current.internal_resendMessage(TEST_IDS.MESSAGE_ID);+ });++ expect(result.current.internal_coreProcessMessage).toHaveBeenCalledWith(+ expect.arrayContaining([+ expect.objectContaining({ id: 'msg-1' }),+ expect.objectContaining({ id: TEST_IDS.MESSAGE_ID }),+ ]),+ TEST_IDS.MESSAGE_ID,+ expect.objectContaining({ traceId: undefined }),+ );+ });++ it('should generate correct context for assistant role message', async () => {+ const { result } = renderHook(() => useChatStore());+ const parentId = 'msg-2';+ const messages = [+ createMockMessage({ id: 'msg-1', role: 'system' }),+ createMockMessage({ id: parentId, role: 'user', meta: { avatar: '😀' } }),+ createMockMessage({ id: TEST_IDS.MESSAGE_ID, role: 'assistant', parentId }),+ ];++ act(() => {+ useChatStore.setState({+ messagesMap: {+ [chatSelectors.currentChatKey(useChatStore.getState() as any)]: messages,+ },+ });+ });++ await act(async () => {+ await result.current.internal_resendMessage(TEST_IDS.MESSAGE_ID);+ });++ expect(result.current.internal_coreProcessMessage).toHaveBeenCalledWith(+ expect.arrayContaining([+ expect.objectContaining({ id: 'msg-1' }),+ expect.objectContaining({ id: parentId }),+ ]),+ parentId,+ expect.objectContaining({ traceId: undefined }),+ );+ });++ it('should not process when context is empty', async () => {+ const { result } = renderHook(() => useChatStore());++ act(() => {+ useChatStore.setState({+ messagesMap: {+ [chatSelectors.currentChatKey(useChatStore.getState() as any)]: [],+ },+ });+ });++ await act(async () => {+ await result.current.internal_resendMessage(TEST_IDS.MESSAGE_ID);+ });++ expect(result.current.internal_coreProcessMessage).not.toHaveBeenCalled();});- expect(result.current.internal_coreProcessMessage).not.toHaveBeenCalled();+ it('should generate correct context for tool role message', async () => {+ const { result } = renderHook(() => useChatStore());+ const messages = [+ createMockMessage({ id: 'msg-1', role: 'user' }),+ createMockMessage({ id: 'msg-2', role: 'assistant' }),+ createMockMessage({ id: TEST_IDS.MESSAGE_ID, role: 'tool' }),+ ];++ act(() => {+ useChatStore.setState({+ messagesMap: {+ [chatSelectors.currentChatKey(useChatStore.getState() as any)]: messages,+ },+ });+ });++ await act(async () => {+ await result.current.internal_resendMessage(TEST_IDS.MESSAGE_ID);+ });++ // For tool role, it processes all messages up to tool but uses last user message as parentId+ expect(result.current.internal_coreProcessMessage).toHaveBeenCalledWith(+ expect.any(Array),+ 'msg-1', // parentId is the last user message+ expect.objectContaining({ traceId: undefined }),+ );+ });});});describe('internal_toggleChatLoading', () => {- it('should set loading state and create an AbortController when loading is true', () => {+ it('should enable loading state with new abort controller', () => {const { result } = renderHook(() => useChatStore());- const action = 'loading-action';act(() => {- result.current.internal_toggleChatLoading(true, 'message-id', action);+ result.current.internal_toggleChatLoading(true, TEST_IDS.MESSAGE_ID, 'test-action');});const state = useChatStore.getState();expect(state.chatLoadingIdsAbortController).toBeInstanceOf(AbortController);- expect(state.chatLoadingIds).toEqual(['message-id']);+ expect(state.chatLoadingIds).toEqual([TEST_IDS.MESSAGE_ID]);+ });++ it('should disable loading state and clear abort controller', () => {+ const { result } = renderHook(() => useChatStore());++ act(() => {+ result.current.internal_toggleChatLoading(true, TEST_IDS.MESSAGE_ID, 'start');+ result.current.internal_toggleChatLoading(false, undefined, 'stop');+ });++ const state = useChatStore.getState();+ expect(state.chatLoadingIdsAbortController).toBeUndefined();+ expect(state.chatLoadingIds).toEqual([]);});- it('should clear loading state and abort controller when loading is false', () => {+ it('should manage beforeunload event listener', () => {const { result } = renderHook(() => useChatStore());- const action = 'stop-loading-action';+ const addListenerSpy = vi.spyOn(window, 'addEventListener');+ const removeListenerSpy = vi.spyOn(window, 'removeEventListener');- // Set initial loading stateact(() => {- result.current.internal_toggleChatLoading(true, 'message-id', 'start-loading-action');+ result.current.internal_toggleChatLoading(true, TEST_IDS.MESSAGE_ID, 'start');});- // Stop loading+ expect(addListenerSpy).toHaveBeenCalledWith('beforeunload', expect.any(Function));++ act(() => {+ result.current.internal_toggleChatLoading(false, undefined, 'stop');+ });++ expect(removeListenerSpy).toHaveBeenCalledWith('beforeunload', expect.any(Function));+ });++ it('should reuse existing abort controller', () => {+ const existingController = new AbortController();+act(() => {- result.current.internal_toggleChatLoading(false, undefined, action);+ useChatStore.setState({ chatLoadingIdsAbortController: existingController });+ });++ const { result } = renderHook(() => useChatStore());++ act(() => {+ result.current.internal_toggleChatLoading(true, TEST_IDS.MESSAGE_ID, 'test');});const state = useChatStore.getState();- expect(state.chatLoadingIdsAbortController).toBeUndefined();- expect(state.chatLoadingIds).toEqual([]);+ expect(state.chatLoadingIdsAbortController).toStrictEqual(existingController);});+ });- it('should attach beforeunload event listener when loading starts', () => {+ describe('internal_toggleToolCallingStreaming', () => {+ it('should track tool calling stream status', () => {const { result } = renderHook(() => useChatStore());- const addEventListenerSpy = vi.spyOn(window, 'addEventListener');act(() => {- result.current.internal_toggleChatLoading(true, 'message-id', 'loading-action');+ result.current.internal_toggleToolCallingStreaming(TEST_IDS.MESSAGE_ID, [true]);});- expect(addEventListenerSpy).toHaveBeenCalledWith('beforeunload', expect.any(Function));+ expect(result.current.toolCallingStreamIds[TEST_IDS.MESSAGE_ID]).toEqual([true]);});- it('should remove beforeunload event listener when loading stops', () => {+ it('should clear tool calling stream status', () => {const { result } = renderHook(() => useChatStore());- const removeEventListenerSpy = vi.spyOn(window, 'removeEventListener');- // Start and then stop loading to trigger the removal of the event listeneract(() => {- result.current.internal_toggleChatLoading(true, 'message-id', 'start-loading-action');- result.current.internal_toggleChatLoading(false, undefined, 'stop-loading-action');+ result.current.internal_toggleToolCallingStreaming(TEST_IDS.MESSAGE_ID, [true]);+ result.current.internal_toggleToolCallingStreaming(TEST_IDS.MESSAGE_ID, undefined);});- expect(removeEventListenerSpy).toHaveBeenCalledWith('beforeunload', expect.any(Function));+ expect(result.current.toolCallingStreamIds[TEST_IDS.MESSAGE_ID]).toBeUndefined();});+ });- it('should not create a new AbortController if one already exists', () => {+ describe('internal_toggleSearchWorkflow', () => {+ it('should enable search workflow loading state', () => {const { result } = renderHook(() => useChatStore());- const abortController = new AbortController();act(() => {- useChatStore.setState({ chatLoadingIdsAbortController: abortController });- result.current.internal_toggleChatLoading(true, 'message-id', 'loading-action');+ result.current.internal_toggleSearchWorkflow(true, TEST_IDS.MESSAGE_ID);+ });++ const state = useChatStore.getState();+ expect(state.searchWorkflowLoadingIds).toEqual([TEST_IDS.MESSAGE_ID]);+ });++ it('should disable search workflow loading state', () => {+ const { result } = renderHook(() => useChatStore());++ act(() => {+ result.current.internal_toggleSearchWorkflow(true, TEST_IDS.MESSAGE_ID);+ result.current.internal_toggleSearchWorkflow(false, TEST_IDS.MESSAGE_ID);});const state = useChatStore.getState();- expect(state.chatLoadingIdsAbortController).toStrictEqual(abortController);+ expect(state.searchWorkflowLoadingIds).toEqual([]);});});- describe('internal_toggleToolCallingStreaming', () => {- it('should add message id to messageLoadingIds when loading is true', () => {+ describe('internal_toggleChatReasoning', () => {+ it('should enable reasoning loading state', () => {const { result } = renderHook(() => useChatStore());- const messageId = 'message-id';act(() => {- result.current.internal_toggleToolCallingStreaming(messageId, [true]);+ result.current.internal_toggleChatReasoning(true, TEST_IDS.MESSAGE_ID, 'test-action');});- expect(result.current.toolCallingStreamIds[messageId]).toEqual([true]);+ const state = useChatStore.getState();+ expect(state.reasoningLoadingIds).toEqual([TEST_IDS.MESSAGE_ID]);});- it('should remove message id from messageLoadingIds when loading is false', () => {+ it('should disable reasoning loading state', () => {const { result } = renderHook(() => useChatStore());- const messageId = 'ddd-id';act(() => {- result.current.internal_toggleToolCallingStreaming(messageId, [true]);- result.current.internal_toggleToolCallingStreaming(messageId, undefined);+ result.current.internal_toggleChatReasoning(true, TEST_IDS.MESSAGE_ID, 'start');+ result.current.internal_toggleChatReasoning(false, TEST_IDS.MESSAGE_ID, 'stop');});- expect(result.current.toolCallingStreamIds[messageId]).toBeUndefined();+ const state = useChatStore.getState();+ expect(state.reasoningLoadingIds).toEqual([]);+ });+ });++ describe('internal_toggleMessageInToolsCalling', () => {+ it('should enable tools calling state', () => {+ const { result } = renderHook(() => useChatStore());++ act(() => {+ result.current.internal_toggleMessageInToolsCalling(true, TEST_IDS.MESSAGE_ID);+ });++ const state = useChatStore.getState();+ expect(state.messageInToolsCallingIds).toEqual([TEST_IDS.MESSAGE_ID]);+ });++ it('should disable tools calling state', () => {+ const { result } = renderHook(() => useChatStore());++ act(() => {+ result.current.internal_toggleMessageInToolsCalling(true, TEST_IDS.MESSAGE_ID);+ result.current.internal_toggleMessageInToolsCalling(false, TEST_IDS.MESSAGE_ID);+ });++ const state = useChatStore.getState();+ expect(state.messageInToolsCallingIds).toEqual([]);+ });+ });++ describe('internal_resendMessage with custom params', () => {+ it('should use provided messages instead of store messages', async () => {+ const { result } = renderHook(() => useChatStore());+ const customMessages = [createMockMessage({ id: 'custom-msg', role: 'user' })];++ await act(async () => {+ await result.current.internal_resendMessage('custom-msg', { messages: customMessages });+ });++ expect(result.current.internal_coreProcessMessage).toHaveBeenCalledWith(+ expect.arrayContaining([expect.objectContaining({ id: 'custom-msg' })]),+ 'custom-msg',+ expect.anything(),+ );+ });++ it('should handle assistant message without parentId', async () => {+ const { result } = renderHook(() => useChatStore());+ const messages = [+ createMockMessage({ id: 'msg-1', role: 'user' }),+ createMockMessage({ id: TEST_IDS.MESSAGE_ID, role: 'assistant', parentId: undefined }),+ ];++ act(() => {+ useChatStore.setState({+ messagesMap: {+ [chatSelectors.currentChatKey(useChatStore.getState() as any)]: messages,+ },+ });+ });++ await act(async () => {+ await result.current.internal_resendMessage(TEST_IDS.MESSAGE_ID);+ });++ // Should handle the case where parentId is not found+ expect(result.current.internal_coreProcessMessage).toHaveBeenCalled();});});});diff --git a/src/store/chat/slices/aiChat/actions/__tests__/helpers.ts b/src/store/chat/slices/aiChat/actions/__tests__/helpers.tsnew file mode 100644index 00000000000..d3d69be84e7--- /dev/null+++ b/src/store/chat/slices/aiChat/actions/__tests__/helpers.ts@@ -0,0 +1,106 @@+import { vi } from 'vitest';++import { chatService } from '@/services/chat';+import { messageService } from '@/services/message';+import { agentChatConfigSelectors, agentSelectors } from '@/store/agent/selectors';+import { sessionMetaSelectors } from '@/store/session/selectors';++import { useChatStore } from '../../../../store';+import { messageMapKey } from '../../../../utils/messageMapKey';+import { TEST_IDS, createMockAgentConfig, createMockChatConfig } from './fixtures';++/**+ * Setup mock selectors with default or custom values+ */+export const setupMockSelectors = (+ options: {+ agentConfig?: Record<string, any>;+ agentMeta?: Record<string, any>;+ chatConfig?: Record<string, any>;+ } = {},+) => {+ vi.spyOn(agentSelectors, 'currentAgentConfig').mockImplementation(() =>+ createMockAgentConfig(options.agentConfig),+ );++ vi.spyOn(agentChatConfigSelectors, 'currentChatConfig').mockImplementation(() =>+ createMockChatConfig(options.chatConfig),+ );++ vi.spyOn(sessionMetaSelectors, 'currentAgentMeta').mockImplementation(+ () => options.agentMeta || { tags: [] },+ );+};++/**+ * Setup store state with messages+ */+export const setupStoreWithMessages = (messages: any[], sessionId = TEST_IDS.SESSION_ID) => {+ useChatStore.setState({+ activeId: sessionId,+ messagesMap: {+ [messageMapKey(sessionId)]: messages,+ },+ });+};++/**+ * Create a mock AbortController for testing+ */+export const createMockAbortController = () => {+ const controller = new AbortController();+ vi.spyOn(controller, 'abort');+ return controller;+};++/**+ * Setup spies for message service methods+ */+export const spyOnMessageService = () => {+ const createMessageSpy = vi+ .spyOn(messageService, 'createMessage')+ .mockResolvedValue(TEST_IDS.NEW_MESSAGE_ID);+ const updateMessageSpy = vi.spyOn(messageService, 'updateMessage').mockResolvedValue(undefined);+ const removeMessageSpy = vi.spyOn(messageService, 'removeMessage').mockResolvedValue(undefined);+ const updateMessageErrorSpy = vi+ .spyOn(messageService, 'updateMessageError')+ .mockResolvedValue(undefined);++ return {+ createMessageSpy,+ removeMessageSpy,+ updateMessageErrorSpy,+ updateMessageSpy,+ };+};++/**+ * Setup spies for chat service methods+ */+export const spyOnChatService = () => {+ const createAssistantMessageSpy = vi+ .spyOn(chatService, 'createAssistantMessage')+ .mockResolvedValue(new Response(TEST_IDS.ASSISTANT_MESSAGE_ID));++ return {+ createAssistantMessageSpy,+ };+};++/**+ * Reset all mocks and store state to clean state+ */+export const resetTestEnvironment = () => {+ vi.clearAllMocks();+ useChatStore.setState(+ {+ activeId: TEST_IDS.SESSION_ID,+ activeTopicId: TEST_IDS.TOPIC_ID,+ chatLoadingIds: [],+ chatLoadingIdsAbortController: undefined,+ messagesMap: {},+ toolCallingStreamIds: {},+ },+ false,+ );+};