/** * features/chat/page/useChatPageConversation.spec.ts * 用途:验证新建聊天与 Agent 切换时清理发货通知外围状态。 * 依赖:vitest、vue refs/computed、useChatPageConversation、useChatShippingUploadHandler。 * 逻辑:覆盖 createNewChatView / Agent 切换调用 peripheral reset;建批幂等已随 co8 下线。 */ import { computed, ref } from 'vue'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import { createChatPageConversationApi } from './useChatPageConversation'; import { clearPendingNoticeBatchRetry, createShippingUploadHandlers, resetShippingNoticeBatchSubmitStateForTests, type ShippingUploadHandlerContext, } from '../shipping/useChatShippingUploadHandler'; const { listChatMessages } = vi.hoisted(() => ({ listChatMessages: vi.fn(), })); vi.mock('../api/chat.api', () => ({ listChatMessages, })); const createConversationContext = () => { const conversationId = ref('conv-a'); const messages = ref([{ role: 'assistant', content: 'old-a' }]); const createNewChatView = vi.fn(() => { conversationId.value = null; messages.value = []; }); const resetPeripheralState = vi.fn(); return { conversationId, messages, createNewChatView, api: createChatPageConversationApi({ deps: { t: (key: string) => key, msg: { warning: vi.fn() } }, route: { path: '/chat/42', query: {} } as never, router: { replace: vi.fn() } as never, currentAgentId: computed(() => 42), conversationId, activeRunId: ref(null), messages, isThinking: ref(false), loadConversationState: (id, loaded) => { conversationId.value = id; messages.value = loaded; }, createNewChatView, clearPendingNoticeBatchRetry, onConversationIdChanging: vi.fn(), onConversationLoadedEmpty: vi.fn(async () => undefined), onConversationLoadFailed: vi.fn(async () => undefined), isShippingNoticeAgent: computed(() => true), shippingTaskIdFromQuery: computed(() => ''), shippingBatchNoFromQuery: computed(() => ''), clearHistory: vi.fn(), clearAttachments: vi.fn(), input: ref(''), resetCurrentAgent: vi.fn(), copiedIndex: ref(null), resetPeripheralState, filePreviewVisible: ref(false), previewFile: ref(null), previewFiles: ref([]), currentPreviewIndex: ref(0), }), resetPeripheralState, }; }; const createUploadContext = ( conversationId: ReturnType>, enqueueNoticeFiles: ReturnType, ): ShippingUploadHandlerContext => ({ conversationId, currentAgentId: computed(() => 42), attachments: ref([]), input: ref(''), shippingAutoFlowRequested: ref(false), shippingInventoryPickerRef: ref({ click: vi.fn() } as unknown as HTMLInputElement), shippingNoticePickerRef: ref({ click: vi.fn() } as unknown as HTMLInputElement), pendingShippingUploadTaskId: ref(''), pendingShippingNoticeTaskId: ref(''), pendingShippingInventoryFile: ref(null), resolvedShippingTaskId: ref(''), resolvedShippingBatchNo: ref(''), shippingBatchSummary: ref(null), shippingBatchTasks: ref([]), shippingInventorySelectionActive: ref(false), shippingInventorySelectionTaskId: ref(''), getActiveShippingTaskId: () => '', startChatTurn: vi.fn(async () => true), refreshShippingActions: vi.fn(async () => undefined), msg: { warning: vi.fn(), info: vi.fn() }, t: (key: string) => key, enqueueNoticeFiles, startOrderExtractionRun: vi.fn(async () => true), sendTemporaryInventoryMessage: vi.fn(async () => undefined), }); describe('useChatPageConversation', () => { beforeEach(() => { listChatMessages.mockReset(); resetShippingNoticeBatchSubmitStateForTests(); }); it('startNewChat clears peripheral state and subsequent notice upload still enqueues intakes', async () => { const enqueueNoticeFiles = vi.fn(async () => undefined); const { conversationId, createNewChatView, api } = createConversationContext(); const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers( createUploadContext(conversationId, enqueueNoticeFiles), ); const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' }); await handleShippingAutoUploadNoticeBatch([file]); expect(enqueueNoticeFiles).toHaveBeenCalledTimes(1); api.startNewChat(); expect(createNewChatView).toHaveBeenCalledTimes(1); expect(conversationId.value).toBeNull(); await handleShippingAutoUploadNoticeBatch([file]); expect(enqueueNoticeFiles).toHaveBeenCalledTimes(2); }); it('startNewChat calls peripheral reset so a shipping Run cannot remain visible in the blank view', () => { const { api, resetPeripheralState } = createConversationContext(); api.startNewChat(); // 关键断言:Shipping 状态在 useChatShipping.resetShippingConversationState 中随该回调清理。 expect(resetPeripheralState).toHaveBeenCalledTimes(1); }); it('resetChatStateForAgentChange clears peripheral state and subsequent notice upload still enqueues intakes', async () => { const enqueueNoticeFiles = vi.fn(async () => undefined); const { conversationId, createNewChatView, api } = createConversationContext(); const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers( createUploadContext(conversationId, enqueueNoticeFiles), ); const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' }); await handleShippingAutoUploadNoticeBatch([file]); expect(enqueueNoticeFiles).toHaveBeenCalledTimes(1); api.resetChatStateForAgentChange(); expect(createNewChatView).toHaveBeenCalledTimes(1); expect(conversationId.value).toBeNull(); await handleShippingAutoUploadNoticeBatch([file]); expect(enqueueNoticeFiles).toHaveBeenCalledTimes(2); }); it('clears the previous conversation messages before an uncached history request resolves', async () => { let resolveMessages!: (value: any[]) => void; listChatMessages.mockImplementation(() => new Promise((resolve) => { resolveMessages = resolve; })); const { api, messages, conversationId } = createConversationContext(); const pending = api.loadConversation('conv-b', { force: true }); // 会话已切换但 B 尚无本地快照时,绝不能继续显示 A 的消息/订单卡。 expect(conversationId.value).toBe('conv-b'); expect(messages.value).toEqual([]); resolveMessages([{ role: 'assistant', content: 'loaded-b' }]); await pending; expect(messages.value[0]?.content).toBe('loaded-b'); }); it('restores cached messages immediately and discards a late response from an older selection', async () => { const pending = new Map void }>(); listChatMessages.mockImplementation((id: string) => new Promise((resolve) => { pending.set(id, { resolve }); })); const { api, messages, conversationId } = createConversationContext(); const firstB = api.loadConversation('conv-b', { force: true }); pending.get('conv-b')!.resolve([{ role: 'assistant', content: 'cached-b' }]); await firstB; const selectA = api.loadConversation('conv-a', { force: true }); const returnB = api.loadConversation('conv-b', { force: true }); expect(messages.value[0]?.content).toBe('cached-b'); pending.get('conv-a')!.resolve([{ role: 'assistant', content: 'late-a' }]); pending.get('conv-b')!.resolve([{ role: 'assistant', content: 'cached-b' }]); await Promise.all([selectA, returnB]); expect(conversationId.value).toBe('conv-b'); expect(messages.value[0]?.content).toBe('cached-b'); }); it('keeps the rendered cached message array when revalidation is semantically unchanged', async () => { const pending = new Map void }>(); listChatMessages.mockImplementation((id: string) => new Promise((resolve) => { pending.set(id, { resolve }); })); const { api, messages } = createConversationContext(); const initial = api.loadConversation('conv-b', { force: true }); pending.get('conv-b')!.resolve([{ chat_log_id: 91, role: 'assistant', content: 'stable-b' }]); await initial; const revalidate = api.loadConversation('conv-b', { force: true }); const renderedCache = messages.value; pending.get('conv-b')!.resolve([{ chat_log_id: 91, role: 'assistant', content: 'stable-b' }]); await revalidate; expect(messages.value).toBe(renderedCache); }); });