Files
syops/frontend/src/features/chat/shipping/useShippingNoticeWorkflow.spec.ts
T

550 lines
19 KiB
TypeScript

/**
* features/chat/shipping/useShippingNoticeWorkflow.spec.ts
* 用途:覆盖 ShippingProcessing 恢复、轮询退避与跨会话迟到响应隔离。
* 依赖:Vitest、vue、shipping.api mock。
* 逻辑:co8 后仅验证统一 shipping-processing 读源与轮询策略;无 Workflow 空壳字段。
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { nextTick, ref } from 'vue';
import {
resolveProcessingPollIntervalMs,
resolveProcessingPollBackoffMs,
shouldContinueProcessingPolling,
useShippingNoticeWorkflow,
} from './useShippingNoticeWorkflow';
import type { ConversationProcessingProjection } from '../types/shipping.api.types';
const api = vi.hoisted(() => ({
getShippingProcessing: vi.fn(async () => {
throw new Error('unified_unavailable');
}),
focusTask: vi.fn(),
markViewed: vi.fn(),
}));
vi.mock('../api/shipping.api', () => ({
getWorkspaceShippingProcessing: api.getShippingProcessing,
focusWorkspaceConversationTask: api.focusTask,
markWorkspaceConversationTaskViewed: api.markViewed,
}));
/**
* 构造历史会话右侧任务投影。
*/
function buildProcessing(conversationId = 'conv-1'): ConversationProcessingProjection {
const needsAction = {
user_task_no: `OT-${conversationId}`,
group: 'needs_action' as const,
can_append: false,
file_count: 2,
};
return {
conversation_id: conversationId,
summary: {
total_tasks: 1,
total_files: 2,
processing: 0,
needs_action: 1,
completed: 0,
history: 0,
},
processing: [],
needs_action: [needsAction],
completed: [],
history: [],
status_groups: {
failed: [], waiting_human: [needsAction], processing: [], completed: [], cancelled: [], archived: [],
},
};
}
/**
* 构造统一 shipping-processing 响应(内嵌 conversation_processing)。
*/
function buildUnifiedProcessing(conversationId = 'conv-1') {
return {
conversation_id: conversationId,
work_items: [],
conversation_processing: buildProcessing(conversationId),
};
}
function buildOrderTaskWorkItem(
taskNo = 'OT-conv-1',
patch: Record<string, unknown> = {},
) {
return {
workItemType: 'order_task',
workItemNo: taskNo,
sourceType: 'direct_pdf',
rootOrderTaskNo: taskNo,
shippingNoticeNo: null,
conversationId: 'conv-1',
submissionNo: 'SOS-1',
intakeNo: 'SNI-1',
status: 'processing',
stage: 'document_parsing',
progressVersion: 1,
lastActivityAt: '2026-08-05T00:00:00Z',
currentGate: null,
availableActions: [],
sourceSummary: {
emailSubject: null,
filename: 'po.pdf',
documentCount: 1,
parsedDocumentCount: 1,
candidateCount: 1,
customerName: null,
poNumber: 'PO-1',
},
childOrderTasks: [],
...patch,
};
}
/**
* 创建可手动完成的 Promise。
*/
function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (reason?: unknown) => void;
const promise = new Promise<T>((resolvePromise, rejectPromise) => {
resolve = resolvePromise;
reject = rejectPromise;
});
return { promise, resolve, reject };
}
describe('useShippingNoticeWorkflow helpers', () => {
it('uses the specified 10s, 20s, 30s failure backoff', () => {
expect(resolveProcessingPollBackoffMs(1)).toBe(10000);
expect(resolveProcessingPollBackoffMs(2)).toBe(20000);
expect(resolveProcessingPollBackoffMs(3)).toBe(30000);
expect(resolveProcessingPollBackoffMs(10)).toBe(30000);
});
it('tiers active polling by elapsed time and page visibility', () => {
expect(resolveProcessingPollIntervalMs({ elapsedMs: 0, visibility: 'visible', hasProcessing: true, failureCount: 0 })).toBe(2000);
expect(resolveProcessingPollIntervalMs({ elapsedMs: 15000, visibility: 'visible', hasProcessing: true, failureCount: 0 })).toBe(5000);
expect(resolveProcessingPollIntervalMs({ elapsedMs: 60000, visibility: 'visible', hasProcessing: true, failureCount: 0 })).toBe(10000);
expect(resolveProcessingPollIntervalMs({ elapsedMs: 0, visibility: 'hidden', hasProcessing: true, failureCount: 0 })).toBe(30000);
expect(resolveProcessingPollIntervalMs({ elapsedMs: 0, visibility: 'visible', hasProcessing: false, failureCount: 0 })).toBeNull();
});
it('stops when processing idle', () => {
expect(shouldContinueProcessingPolling(null)).toBe(false);
expect(shouldContinueProcessingPolling({
summary: { total_tasks: 0, processing: 0, needs_action: 0, history: 0 },
processing: [],
needs_action: [],
history: [],
})).toBe(false);
});
it('continues when processing projection is active', () => {
expect(shouldContinueProcessingPolling({
summary: { total_tasks: 1, processing: 1, needs_action: 0, history: 0 },
processing: [{
user_task_no: 'OT-1',
group: 'processing',
can_append: true,
}],
needs_action: [],
history: [],
})).toBe(true);
});
});
describe('useShippingNoticeWorkflow', () => {
beforeEach(() => {
api.getShippingProcessing.mockReset();
api.getShippingProcessing.mockRejectedValue(new Error('unified_unavailable'));
api.focusTask.mockReset();
api.markViewed.mockReset();
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
it('loads processing projection without workflow shells', async () => {
api.getShippingProcessing.mockResolvedValue(buildUnifiedProcessing());
const conversationId = ref('conv-1');
const ctl = useShippingNoticeWorkflow({ conversationId });
await vi.advanceTimersByTimeAsync(0);
await nextTick();
await Promise.resolve();
expect(api.getShippingProcessing).toHaveBeenCalled();
expect(ctl.processing.value?.summary.needs_action).toBe(1);
expect(ctl.processingWorkItems.value).toEqual([]);
expect(ctl.error.value).toBeNull();
ctl.stop();
});
it('coalesces concurrent refreshes for the same conversation', async () => {
const pending = deferred<ReturnType<typeof buildUnifiedProcessing>>();
api.getShippingProcessing.mockImplementation(() => pending.promise);
const ctl = useShippingNoticeWorkflow({ conversationId: ref('conv-1') });
const manualRefresh = ctl.refresh();
await nextTick();
// 首轮恢复、页面刷新和可见性触发命中同一会话时只能产生一个网络请求。
expect(api.getShippingProcessing).toHaveBeenCalledTimes(1);
pending.resolve(buildUnifiedProcessing());
await manualRefresh;
expect(ctl.processing.value?.summary.needs_action).toBe(1);
ctl.stop();
});
it('uses summary PDF leaves as the minimal live work items for the batch center', async () => {
api.getShippingProcessing.mockResolvedValue({
conversation_id: 'conv-1',
work_items: [{
workItemType: 'order_task', workItemNo: 'DOCUMENT:1', rootOrderTaskNo: 'OT-1',
sourceType: 'direct_pdf', status: 'processing', stage: 'document_parsing',
sourceSummary: { documentId: 1, filename: 'po.pdf', documentCount: 1 },
}],
conversation_processing: buildProcessing(),
});
const ctl = useShippingNoticeWorkflow({ conversationId: ref('conv-1') });
await vi.advanceTimersByTimeAsync(0);
await Promise.resolve();
expect(ctl.processingWorkItems.value[0]?.sourceSummary.filename).toBe('po.pdf');
ctl.stop();
});
it('applies a current conversation response that completes after 10 seconds', async () => {
const pending = deferred<ReturnType<typeof buildUnifiedProcessing>>();
api.getShippingProcessing.mockImplementation(() => pending.promise);
const ctl = useShippingNoticeWorkflow({ conversationId: ref('conv-1') });
await vi.advanceTimersByTimeAsync(0);
// API 层拥有共享请求的 30 秒超时;10 秒后当前会话不能先把消费者标为取消。
await vi.advanceTimersByTimeAsync(10_001);
pending.resolve(buildUnifiedProcessing('conv-1'));
await Promise.resolve();
await nextTick();
expect(ctl.processing.value?.conversation_id).toBe('conv-1');
expect(ctl.initialLoading.value).toBe(false);
expect(ctl.error.value).toBeNull();
ctl.stop();
});
it('records recoverable error without throwing', async () => {
const conversationId = ref('conv-1');
const ctl = useShippingNoticeWorkflow({ conversationId });
await vi.advanceTimersByTimeAsync(0);
await nextTick();
await Promise.resolve();
expect(ctl.error.value).toBe('network_recoverable');
ctl.stop();
});
it('restores processing tasks from unified shipping-processing', async () => {
api.getShippingProcessing.mockResolvedValue(buildUnifiedProcessing());
const ctl = useShippingNoticeWorkflow({ conversationId: ref('conv-1') });
await vi.advanceTimersByTimeAsync(0);
await nextTick();
await Promise.resolve();
expect(ctl.processing.value?.summary.needs_action).toBe(1);
expect(ctl.processing.value?.summary.total_files).toBe(2);
expect(ctl.error.value).toBeNull();
ctl.stop();
});
it('ignores external refresh triggers once only manual Gate tasks remain', async () => {
const refreshTrigger = ref(0);
api.getShippingProcessing.mockResolvedValue(buildUnifiedProcessing());
const ctl = useShippingNoticeWorkflow({ conversationId: ref('conv-1'), refreshTrigger });
await vi.advanceTimersByTimeAsync(0);
await nextTick();
await Promise.resolve();
expect(api.getShippingProcessing).toHaveBeenCalledTimes(1);
refreshTrigger.value += 1;
await nextTick();
await vi.advanceTimersByTimeAsync(0);
// 仅待人工处理时,Run 轮询的旁路 refreshTrigger 不得重复唤醒右侧 GET。
expect(api.getShippingProcessing).toHaveBeenCalledTimes(1);
ctl.stop();
});
it('does not rebuild conversation processing from work_items without status_groups', async () => {
api.getShippingProcessing.mockResolvedValue({
conversation_id: 'conv-1',
work_items: [buildOrderTaskWorkItem('OT-UNIFIED', {
status: 'waiting_review',
stage: 'waiting_review',
currentGate: {
gateCode: 'order_freeze_readiness',
status: 'blocked',
nextActionCode: 'open_order_review',
},
availableActions: ['open_order_review'],
})],
conversation_processing: null,
});
const ctl = useShippingNoticeWorkflow({ conversationId: ref('conv-1') });
await vi.advanceTimersByTimeAsync(0);
await nextTick();
await Promise.resolve();
expect(api.getShippingProcessing).toHaveBeenCalled();
expect(ctl.processingWorkItems.value).toHaveLength(0);
expect(ctl.processing.value).toBeNull();
ctl.stop();
});
it('does not retain a legacy work_items-derived projection across sparse responses', async () => {
api.getShippingProcessing
.mockResolvedValueOnce({
conversation_id: 'conv-1',
work_items: [buildOrderTaskWorkItem('OT-STABLE')],
conversation_processing: null,
})
.mockResolvedValueOnce({
conversation_id: 'conv-1',
work_items: [{
workItemType: 'order_intake',
workItemNo: 'SNI-1',
sourceType: 'eml',
conversationId: 'conv-1',
intakeNo: 'SNI-1',
status: 'processing',
stage: 'parsing',
progressVersion: 1,
lastActivityAt: '2026-08-05T00:00:01Z',
currentGate: null,
availableActions: [],
sourceSummary: {
emailSubject: 'mail',
filename: 'po.pdf',
documentCount: 1,
parsedDocumentCount: 0,
candidateCount: 0,
customerName: null,
poNumber: null,
},
childOrderTasks: [],
}],
conversation_processing: buildProcessing(),
});
const ctl = useShippingNoticeWorkflow({ conversationId: ref('conv-1') });
await vi.advanceTimersByTimeAsync(0);
await nextTick();
await Promise.resolve();
expect(ctl.processing.value).toBeNull();
await vi.advanceTimersByTimeAsync(2000);
await nextTick();
await Promise.resolve();
expect(ctl.processing.value).toBeNull();
ctl.stop();
});
it('does not aggregate sibling work_items in the browser when status_groups is absent', async () => {
api.getShippingProcessing.mockResolvedValue({
conversation_id: 'conv-1',
work_items: [
{
workItemType: 'order_task',
workItemNo: 'OT-ROOT',
sourceType: 'eml',
rootOrderTaskNo: 'OT-ROOT',
shippingNoticeNo: null,
conversationId: 'conv-1',
submissionNo: 'SOS-1',
intakeNo: 'SNI-1',
status: 'waiting_review',
stage: 'waiting_review',
progressVersion: 1,
lastActivityAt: '2026-08-05T00:00:00Z',
currentGate: null,
availableActions: ['open_order_review'],
sourceSummary: {
emailSubject: null,
filename: 'root.pdf',
documentCount: 1,
parsedDocumentCount: 1,
candidateCount: 1,
customerName: null,
poNumber: 'PO-ROOT',
},
childOrderTasks: [],
},
{
workItemType: 'order_task',
workItemNo: 'OT-SIBLING',
sourceType: 'eml',
rootOrderTaskNo: 'OT-ROOT',
shippingNoticeNo: null,
conversationId: 'conv-1',
submissionNo: 'SOS-1',
intakeNo: 'SNI-1',
status: 'processing',
stage: 'candidate_creating',
progressVersion: 1,
lastActivityAt: '2026-08-05T01:00:00Z',
currentGate: null,
availableActions: ['view_details'],
sourceSummary: {
emailSubject: null,
filename: 'sibling.pdf',
documentCount: 1,
parsedDocumentCount: 1,
candidateCount: 1,
customerName: null,
poNumber: 'PO-SIB',
},
childOrderTasks: [],
},
],
conversation_processing: {
summary: {
total_tasks: 1,
total_files: 1,
processing: 0,
needs_action: 1,
completed: 0,
history: 0,
},
focused_task_no: 'OT-ROOT',
recent_task_no: 'OT-SIBLING',
needs_action: [{
user_task_no: 'OT-ROOT',
group: 'needs_action',
can_append: false,
file_count: 1,
}],
processing: [],
completed: [],
history: [],
},
});
const ctl = useShippingNoticeWorkflow({ conversationId: ref('conv-1') });
await vi.advanceTimersByTimeAsync(0);
await nextTick();
await Promise.resolve();
expect(ctl.processing.value).toBeNull();
expect(ctl.processingWorkItems.value).toEqual([]);
ctl.stop();
});
it('retries a failed initial processing restore instead of freezing at empty state', async () => {
api.getShippingProcessing
.mockRejectedValueOnce(new Error('temporary auth recovery'))
.mockResolvedValue(buildUnifiedProcessing());
const ctl = useShippingNoticeWorkflow({ conversationId: ref('conv-1') });
await vi.advanceTimersByTimeAsync(0);
await nextTick();
expect(ctl.error.value).toBe('network_recoverable');
await vi.advanceTimersByTimeAsync(10000);
await nextTick();
await Promise.resolve();
expect(api.getShippingProcessing).toHaveBeenCalledTimes(2);
expect(ctl.processing.value?.status_groups?.waiting_human[0]?.user_task_no).toBe('OT-conv-1');
expect(ctl.error.value).toBeNull();
ctl.stop();
});
it('ignores an old conversation response that completes after the restored conversation', async () => {
const oldUnified = deferred<ReturnType<typeof buildUnifiedProcessing>>();
api.getShippingProcessing
.mockImplementationOnce(() => oldUnified.promise)
.mockResolvedValueOnce(buildUnifiedProcessing('conv-new'));
const conversationId = ref('conv-old');
const ctl = useShippingNoticeWorkflow({ conversationId });
await vi.advanceTimersByTimeAsync(0);
conversationId.value = 'conv-new';
await nextTick();
await vi.advanceTimersByTimeAsync(0);
await Promise.resolve();
expect(ctl.processing.value?.conversation_id).toBe('conv-new');
oldUnified.resolve(buildUnifiedProcessing('conv-old'));
await Promise.resolve();
await nextTick();
expect(ctl.processing.value?.conversation_id).toBe('conv-new');
ctl.stop();
});
it('immediately restores a cached conversation projection while it revalidates', async () => {
const revalidate = deferred<ReturnType<typeof buildUnifiedProcessing>>();
api.getShippingProcessing
.mockResolvedValueOnce(buildUnifiedProcessing('conv-a'))
.mockResolvedValueOnce(buildUnifiedProcessing('conv-b'))
.mockImplementationOnce(() => revalidate.promise);
const conversationId = ref('conv-a');
const ctl = useShippingNoticeWorkflow({ conversationId });
await vi.advanceTimersByTimeAsync(0);
await Promise.resolve();
conversationId.value = 'conv-b';
await nextTick();
await vi.advanceTimersByTimeAsync(0);
await Promise.resolve();
conversationId.value = 'conv-a';
await nextTick();
// 已访问会话首帧使用本会话最后成功 Projection,不会退回骨架或 B 的数据。
expect(ctl.processing.value?.conversation_id).toBe('conv-a');
expect(ctl.initialLoading.value).toBe(false);
expect(ctl.isRefreshing.value).toBe(true);
revalidate.resolve(buildUnifiedProcessing('conv-a'));
ctl.stop();
});
it('drops a response whose server conversation id differs from the request target', async () => {
api.getShippingProcessing.mockResolvedValue(buildUnifiedProcessing('wrong-conversation'));
const ctl = useShippingNoticeWorkflow({ conversationId: ref('conv-a') });
await vi.advanceTimersByTimeAsync(0);
await Promise.resolve();
expect(ctl.processing.value).toBeNull();
ctl.stop();
});
it('marks the restored conversation as initial loading after aborting an old poll', async () => {
const oldPoll = deferred<ReturnType<typeof buildUnifiedProcessing>>();
const newInitial = deferred<ReturnType<typeof buildUnifiedProcessing>>();
api.getShippingProcessing
.mockImplementationOnce(() => oldPoll.promise)
.mockImplementationOnce(() => newInitial.promise);
const conversationId = ref('conv-old');
const ctl = useShippingNoticeWorkflow({ conversationId });
await vi.advanceTimersByTimeAsync(0);
conversationId.value = 'conv-new';
await nextTick();
await vi.advanceTimersByTimeAsync(0);
expect(ctl.initialLoading.value).toBe(true);
expect(ctl.manualRefreshing.value).toBe(false);
expect(ctl.polling.value).toBe(false);
newInitial.resolve(buildUnifiedProcessing('conv-new'));
await Promise.resolve();
ctl.stop();
});
});