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

1622 lines
68 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* features/chat/shipping/conversationProcessingProjection.spec.ts
* 用途:验收「本次处理中」对象投影——Run/Candidate/Task/Gate 聚合与聚焦。
* 依赖:Vitest、conversationProcessingProjection。
* 逻辑:构造 WorkflowItem;断言去重、聚焦标记与 Gate 行。
*/
import { describe, expect, it } from 'vitest';
import {
mapLifecycleToNodeStatus,
mapShippingProcessingStatusToTaskGroup,
mergeConversationProcessingFocusMetadata,
projectConversationProcessingFromWorkItems,
projectConversationProcessingObjects,
projectConversationProcessingTasks,
groupConversationProcessingTasks,
mapUserTaskObjectsToFileRows,
resolveConversationProcessingFromUnified,
normalizeActionCodes,
normalizeLifecycleStatus,
normalizeConversationProcessingProjection,
createIntakeOtStabilizer,
buildTaskSemanticKey,
buildProcessingSemanticKey,
stabilizeTaskObjects,
flattenBusinessFileProjections,
businessFileKeys,
} from './conversationProcessingProjection';
import { normalizeShippingProcessingProjection } from './normalizeShippingProcessing';
import type {
ConversationProcessingProjection,
ShippingProcessingProjection,
ShippingWorkflowItem,
} from '@/features/chat/types/shipping.api.types';
describe('EML business-file projection', () => {
it('excludes the EML container and keeps its PDF/XLSX leaf attachments', () => {
const eml = {
workItemType: 'order_task', workItemNo: 'INTAKE:SNI-1', sourceType: 'eml',
sourceSummary: { filename: 'mail.eml', documentCount: 2 },
aggregateChildren: [
{ workItemType: 'order_task', workItemNo: 'OT-1', sourceType: 'eml', sourceSummary: { filename: 'notice-a.pdf', documentId: 101, documentCount: 1 } },
{ workItemType: 'order_task', workItemNo: 'OT-2', sourceType: 'eml', sourceSummary: { filename: 'items.xlsx', documentId: 102, documentCount: 1 } },
],
} as ShippingProcessingProjection;
const directPdf = {
workItemType: 'order_task', workItemNo: 'OT-3', sourceType: 'direct_pdf',
sourceSummary: { filename: 'direct.pdf', documentId: 103, documentCount: 1 },
} as ShippingProcessingProjection;
// EML 仅为来源分组,3 个业务附件才是唯一文件集合。
expect(flattenBusinessFileProjections([eml, directPdf]).map((row) => row.sourceSummary.filename))
.toEqual(['notice-a.pdf', 'items.xlsx', 'direct.pdf']);
expect(businessFileKeys([eml, directPdf])).toEqual(['document:101', 'document:102', 'document:103']);
});
});
function item(partial: Partial<ShippingWorkflowItem>): ShippingWorkflowItem {
return {
item_no: 'WI-1',
workflow_no: 'WF-1',
conversation_id: 'conv-1',
root_document_id: 1,
current_document_id: 1,
current_version_no: 1,
lifecycle_status: 'pending_review',
current_stage: 'pending_review',
lock_version: 1,
...partial,
};
}
describe('conversationProcessingProjection', () => {
it('maps lifecycle to node status without inventing percentages', () => {
expect(mapLifecycleToNodeStatus('inventory_matching')).toBe('running');
expect(mapLifecycleToNodeStatus('failed')).toBe('failed');
expect(mapLifecycleToNodeStatus('closed')).toBe('succeeded');
});
it('projects run / candidate / task / process_gate rows and focus', () => {
const rows = projectConversationProcessingObjects([
item({
item_no: 'WI-1',
current_run_no: 'RUN-1',
current_case_no: 'CASE-1',
current_task_no: 'SN-1',
lifecycle_status: 'pending_review',
process_gate: {
execution_no: 'EX-1',
status: 'blocked',
current_blocking_gate: {
gate_code: 'inventory_matching',
sequence_no: 1,
status: 'blocked_manual',
evaluation_version: 1,
},
task_no: 'SN-1',
},
}),
item({
item_no: 'WI-2',
current_run_no: 'RUN-1',
current_task_no: 'SN-1',
lifecycle_status: 'inventory_matching',
}),
], { focusTaskNo: 'SN-1', focusRunNo: 'RUN-1' });
// 关键断言:同 Run/Task 去重;聚焦 Task;含 Gate。
expect(rows.filter((row) => row.kind === 'run')).toHaveLength(1);
expect(rows.filter((row) => row.kind === 'task')).toHaveLength(1);
expect(rows.find((row) => row.kind === 'task')?.focused).toBe(true);
expect(rows.some((row) => row.kind === 'candidate')).toBe(true);
expect(rows.some((row) => row.kind === 'process_gate')).toBe(true);
});
it('prefers backend node_status over lifecycle mapping for tasks', () => {
const rows = projectConversationProcessingObjects([
item({
current_run_no: 'RUN-2',
current_task_no: 'SN-2',
lifecycle_status: 'inventory_matching',
node_status: 'manual_takeover',
progress_nodes: [
{ code: 'freight_upload', label: '货代上传', status: 'manual_takeover' },
],
}),
]);
// 关键断言:侧栏 Task 使用后端权威 node_status,不覆盖为 running。
expect(rows.find((row) => row.kind === 'task')?.node_status).toBe('manual_takeover');
});
it('groups tasks into needs_action / processing / completed; closed stays history', () => {
const tasks = projectConversationProcessingTasks([
item({
item_no: 'WI-A',
current_run_no: 'RUN-A',
root_document_id: 1,
lifecycle_status: 'pending_review',
current_document_filename: 'a.pdf',
}),
item({
item_no: 'WI-B',
current_run_no: 'RUN-B',
root_document_id: 2,
lifecycle_status: 'extracting',
current_document_filename: 'b.pdf',
}),
item({
item_no: 'WI-DONE',
current_run_no: 'RUN-DONE',
root_document_id: 3,
lifecycle_status: 'completed',
current_document_filename: 'done.pdf',
}),
item({
item_no: 'WI-C',
current_run_no: 'RUN-C',
root_document_id: 4,
lifecycle_status: 'closed',
current_document_filename: 'c.pdf',
}),
item({
item_no: 'WI-NO-NAME',
current_run_no: 'RUN-NO-NAME',
root_document_id: 5,
lifecycle_status: 'extracting',
current_document_filename: null,
}),
]);
const projection = groupConversationProcessingTasks(tasks, { focusedTaskNo: 'OT-RUN-A' });
// summary.total_* 含 history(正式 OT 全量);合成路径无截断。
expect(projection.summary).toEqual({
total_tasks: 5,
total_files: 5,
processing: 2,
needs_action: 1,
completed: 1,
history: 1,
returned: {
needs_action: 1,
processing: 2,
completed: 1,
history: 1,
},
truncated: { active: false, history: false },
has_more_active: false,
has_more_history: false,
});
expect(projection.needs_action[0]?.user_task_no).toBe('OT-RUN-A');
expect(projection.processing.map((t) => t.user_task_no).sort()).toEqual([
'OT-RUN-B',
'OT-RUN-NO-NAME',
]);
expect(projection.completed?.[0]?.user_task_no).toBe('OT-RUN-DONE');
expect(projection.history[0]?.user_task_no).toBe('OT-RUN-C');
// title 为空,卡片统一展示「订单识别任务」。
const unnamed = projection.processing.find((t) => t.user_task_no === 'OT-RUN-NO-NAME');
expect(unnamed?.title).toBeNull();
});
it('uses multi_document_task when one run has two different PDFs', () => {
const tasks = projectConversationProcessingTasks([
item({
item_no: 'WI-1',
current_run_no: 'RUN-MULTI',
root_document_id: 91,
current_document_id: 91,
content_hash: 'hash-a',
user_task_no: 'OT-MULTI',
lifecycle_status: 'extracting',
current_document_filename: '4518838152.pdf',
}),
item({
item_no: 'WI-2',
current_run_no: 'RUN-MULTI',
root_document_id: 92,
current_document_id: 92,
content_hash: 'hash-b',
user_task_no: 'OT-MULTI',
lifecycle_status: 'layout_parsing',
current_document_filename: '4518838154.pdf',
}),
]);
expect(tasks).toHaveLength(1);
expect(tasks[0]?.title).toBeNull();
expect(tasks[0]?.display_kind).toBe('multi_document_task');
expect(tasks[0]?.file_count).toBe(2);
expect(tasks[0]?.document_names).toEqual(['4518838152.pdf', '4518838154.pdf']);
const docs = (tasks[0]?.objects || []).filter((row) => row.kind === 'document');
expect(docs).toHaveLength(2);
});
it('keeps multi PDF when same OT spans different run_nos', () => {
const tasks = projectConversationProcessingTasks([
item({
item_no: 'WI-1',
current_run_no: 'RUN-A',
root_document_id: 91,
current_document_id: 91,
content_hash: 'hash-a',
user_task_no: 'OT-SHARED',
lifecycle_status: 'pending_review',
current_document_filename: 'a.pdf',
last_activity_at: '2026-08-04T01:00:00Z',
}),
item({
item_no: 'WI-2',
current_run_no: 'RUN-B',
root_document_id: 92,
current_document_id: 92,
content_hash: 'hash-b',
user_task_no: 'OT-SHARED',
lifecycle_status: 'pending_review',
current_document_filename: 'b.pdf',
last_activity_at: '2026-08-04T02:00:00Z',
}),
]);
// 同 OT 跨 Run 时按 PDF 身份选最新版;未在新 Run 重识别的 PDF 继续有效。
expect(tasks).toHaveLength(1);
expect(tasks[0]?.file_count).toBe(2);
expect(tasks[0]?.display_kind).toBe('multi_document_task');
expect(tasks[0]?.title).toBeNull();
expect(tasks[0]?.document_names).toEqual(['a.pdf', 'b.pdf']);
expect(tasks[0]?.run_no).toBe('RUN-B');
const documents = tasks[0]?.objects.filter((row) => row.kind === 'document') || [];
expect(documents.map((row) => row.current_run_no)).toEqual(['RUN-A', 'RUN-B']);
});
it('keeps only latest version when same PDF spans different run_nos', () => {
const tasks = projectConversationProcessingTasks([
item({
item_no: 'WI-OLD',
current_run_no: 'RUN-A',
root_document_id: 91,
current_document_id: 91,
content_hash: 'hash-a',
user_task_no: 'OT-SHARED',
lifecycle_status: 'failed',
current_document_filename: 'old.pdf',
last_activity_at: '2026-08-04T01:00:00Z',
}),
item({
item_no: 'WI-NEW',
current_run_no: 'RUN-B',
root_document_id: 91,
current_document_id: 191,
content_hash: 'hash-a',
user_task_no: 'OT-SHARED',
lifecycle_status: 'pending_review',
current_document_filename: 'latest.pdf',
last_activity_at: '2026-08-04T02:00:00Z',
}),
]);
expect(tasks).toHaveLength(1);
expect(tasks[0]?.file_count).toBe(1);
expect(tasks[0]?.title).toBe('latest.pdf');
const document = tasks[0]?.objects.find((row) => row.kind === 'document');
expect(document?.document_id).toBe(191);
expect(document?.current_run_no).toBe('RUN-B');
});
it('keeps single PDF filename title for one-document run', () => {
const tasks = projectConversationProcessingTasks([
item({
item_no: 'WI-1',
current_run_no: 'RUN-ONE',
root_document_id: 7,
content_hash: 'solo',
user_task_no: 'OT-ONE',
lifecycle_status: 'extracting',
current_document_filename: 'solo.pdf',
}),
]);
expect(tasks[0]?.title).toBe('solo.pdf');
expect(tasks[0]?.display_kind).toBe('single_document_task');
expect(tasks[0]?.file_count).toBe(1);
});
it('merges same root_document_id across runs into one fallback task', () => {
const tasks = projectConversationProcessingTasks([
item({
item_no: 'WI-OLD',
current_run_no: 'RUN-OLD',
root_document_id: 42,
lifecycle_status: 'failed',
current_document_filename: 'order.pdf',
last_activity_at: '2026-08-03T10:00:00Z',
}),
item({
item_no: 'WI-NEW',
current_run_no: 'RUN-NEW',
root_document_id: 42,
lifecycle_status: 'extracting',
current_document_filename: 'order.pdf',
last_activity_at: '2026-08-03T11:00:00Z',
}),
]);
const projection = groupConversationProcessingTasks(tasks);
// [UI-01] 同 root 只保留当前有效版本(处理中),旧失败不再单独出卡。
expect(projection.summary.total_tasks).toBe(1);
expect(projection.processing).toHaveLength(1);
expect(projection.needs_action).toHaveLength(0);
expect(projection.processing[0]?.run_no).toBe('RUN-NEW');
expect(projection.processing[0]?.title).toBe('order.pdf');
});
it('merges different root_document_id with same content_hash into one fallback task', () => {
const tasks = projectConversationProcessingTasks([
item({
item_no: 'WI-A',
current_run_no: 'RUN-A',
root_document_id: 101,
content_hash: 'aaa111',
lifecycle_status: 'failed',
current_document_filename: 'order.pdf',
last_activity_at: '2026-08-03T10:00:00Z',
}),
item({
item_no: 'WI-B',
current_run_no: 'RUN-B',
root_document_id: 202,
content_hash: 'aaa111',
lifecycle_status: 'extracting',
current_document_filename: 'order.pdf',
last_activity_at: '2026-08-03T11:00:00Z',
}),
]);
const projection = groupConversationProcessingTasks(tasks);
// [UI-01] 普通重传换 root,但同内容哈希只保留当前有效版本。
expect(projection.summary.total_tasks).toBe(1);
expect(projection.processing).toHaveLength(1);
expect(projection.processing[0]?.run_no).toBe('RUN-B');
});
it('merges different root_document_id with same user_task_no into one fallback task', () => {
const tasks = projectConversationProcessingTasks([
item({
item_no: 'WI-A',
current_run_no: 'RUN-A',
root_document_id: 301,
user_task_no: 'OT-SHARED',
content_hash: 'hash-a',
lifecycle_status: 'failed',
current_document_filename: 'order.pdf',
last_activity_at: '2026-08-03T10:00:00Z',
}),
item({
item_no: 'WI-B',
current_run_no: 'RUN-B',
root_document_id: 302,
user_task_no: 'OT-SHARED',
content_hash: 'hash-b',
lifecycle_status: 'extracting',
current_document_filename: 'order.pdf',
last_activity_at: '2026-08-03T11:00:00Z',
}),
]);
const projection = groupConversationProcessingTasks(tasks);
// user_task_no 优先于 content_hash / root;输出必须原样保留真实 OT。
expect(projection.summary.total_tasks).toBe(1);
expect(projection.processing[0]?.run_no).toBe('RUN-B');
expect(projection.processing[0]?.user_task_no).toBe('OT-SHARED');
expect(projection.processing[0]?.user_task_authoritative).toBe(true);
});
it('preserves authoritative user_task_no for focus/viewed APIs', () => {
const tasks = projectConversationProcessingTasks([
item({
item_no: 'WI-1',
current_run_no: 'RUN-XXX',
root_document_id: 55,
user_task_no: 'OT-REAL-001',
content_hash: 'abc',
lifecycle_status: 'extracting',
current_document_filename: 'order.pdf',
last_activity_at: '2026-08-03T11:00:00Z',
}),
]);
// [UI-01] 禁止输出伪造 OT-${runNo},否则 focus/viewed 会打到不存在的任务号。
expect(tasks).toHaveLength(1);
expect(tasks[0]?.user_task_no).toBe('OT-REAL-001');
expect(tasks[0]?.user_task_no).not.toBe('OT-RUN-XXX');
expect(tasks[0]?.user_task_authoritative).toBe(true);
});
it('marks fabricated fallback task no as non-authoritative', () => {
const tasks = projectConversationProcessingTasks([
item({
item_no: 'WI-1',
current_run_no: 'RUN-LOCAL',
root_document_id: 66,
lifecycle_status: 'extracting',
current_document_filename: 'order.pdf',
}),
]);
expect(tasks[0]?.user_task_no).toBe('OT-RUN-LOCAL');
expect(tasks[0]?.user_task_authoritative).toBe(false);
});
it('does not merge different root_document_id with same filename', () => {
const tasks = projectConversationProcessingTasks([
item({
item_no: 'WI-A',
current_run_no: 'RUN-A',
root_document_id: 101,
lifecycle_status: 'extracting',
current_document_filename: 'order.pdf',
last_activity_at: '2026-08-03T10:00:00Z',
}),
item({
item_no: 'WI-B',
current_run_no: 'RUN-B',
root_document_id: 202,
lifecycle_status: 'extracting',
current_document_filename: 'order.pdf',
last_activity_at: '2026-08-03T11:00:00Z',
}),
]);
const projection = groupConversationProcessingTasks(tasks);
// [UI-01] 同名不同内容(不同 root)不得合并成一张卡。
expect(projection.summary.total_tasks).toBe(2);
expect(projection.processing).toHaveLength(2);
});
it('prefers newer failed over older processing for same identity', () => {
const tasks = projectConversationProcessingTasks([
item({
item_no: 'WI-OLD',
current_run_no: 'RUN-OLD',
root_document_id: 77,
lifecycle_status: 'extracting',
current_document_filename: 'order.pdf',
last_activity_at: '2026-08-03T10:00:00Z',
}),
item({
item_no: 'WI-NEW',
current_run_no: 'RUN-NEW',
root_document_id: 77,
lifecycle_status: 'failed',
current_document_filename: 'order.pdf',
last_activity_at: '2026-08-03T11:00:00Z',
}),
]);
const projection = groupConversationProcessingTasks(tasks);
// [UI-02] 最新有效版本按活动时间,不按 processing 严重度遮盖新失败。
expect(projection.summary.total_tasks).toBe(1);
expect(projection.processing).toHaveLength(0);
expect(projection.needs_action).toHaveLength(1);
expect(projection.needs_action[0]?.run_no).toBe('RUN-NEW');
expect(projection.needs_action[0]?.status_label).toBe('failed');
});
it('synthesizes conversation groups from unified order_task work_items', () => {
const workItems: ShippingProcessingProjection[] = [
{
workItemType: 'order_intake',
workItemNo: 'SNI-1',
sourceType: 'direct_pdf',
rootOrderTaskNo: null,
shippingNoticeNo: null,
conversationId: 'conv-1',
submissionNo: 'SOS-1',
intakeNo: 'SNI-1',
status: 'failed',
stage: 'document_parsing',
progressVersion: 1,
lastActivityAt: '2026-08-05T00:00:00Z',
currentGate: null,
availableActions: ['retry_parse'],
sourceSummary: {
emailSubject: null,
filename: 'a.pdf',
documentCount: 1,
parsedDocumentCount: 0,
candidateCount: 0,
customerName: null,
poNumber: null,
},
childOrderTasks: [],
},
{
workItemType: 'order_task',
workItemNo: 'OT-WAIT',
sourceType: 'eml',
rootOrderTaskNo: 'OT-WAIT',
shippingNoticeNo: null,
runNo: 'RUN-WAIT',
caseNo: 'CASE-WAIT',
conversationId: 'conv-1',
submissionNo: 'SOS-1',
intakeNo: 'SNI-2',
status: 'waiting_review',
stage: 'waiting_review',
progressVersion: 2,
lastActivityAt: '2026-08-05T01:00:00Z',
currentGate: {
gateCode: 'order_freeze_readiness',
status: 'blocked',
nextActionCode: 'open_order_review',
blockingReasonCode: 'review_case_draft',
attemptNo: 0,
},
availableActions: ['open_order_review'],
sourceSummary: {
emailSubject: null,
filename: 'po.pdf',
documentCount: 2,
parsedDocumentCount: 2,
candidateCount: 1,
customerName: 'ACME',
poNumber: 'PO-1',
},
childOrderTasks: [],
},
{
workItemType: 'order_task',
workItemNo: 'OT-RUN',
sourceType: 'direct_pdf',
rootOrderTaskNo: 'OT-RUN',
shippingNoticeNo: null,
conversationId: 'conv-1',
submissionNo: 'SOS-2',
intakeNo: 'SNI-3',
status: 'processing',
stage: 'document_parsing',
progressVersion: 1,
lastActivityAt: '2026-08-05T02:00:00Z',
currentGate: null,
availableActions: ['view_details'],
sourceSummary: {
emailSubject: null,
filename: 'solo.pdf',
documentCount: 1,
parsedDocumentCount: 1,
candidateCount: 0,
customerName: null,
poNumber: null,
},
childOrderTasks: [],
},
];
expect(mapShippingProcessingStatusToTaskGroup(workItems[1]!)).toBe('needs_action');
expect(mapShippingProcessingStatusToTaskGroup(workItems[2]!)).toBe('processing');
const projection = projectConversationProcessingFromWorkItems(workItems);
// 关键断言:仅 order_task 入组;intake 不进入 conversation groups。
expect(projection).not.toBeNull();
expect(projection!.needs_action.map((t) => t.user_task_no)).toEqual(['OT-WAIT']);
expect(projection!.processing.map((t) => t.user_task_no)).toEqual(['OT-RUN']);
expect(projection!.needs_action[0]?.file_count).toBe(2);
expect(projection!.needs_action[0]?.display_kind).toBe('multi_document_task');
// [P0] 合成任务必须透传 run_no,禁止写死 null。
expect(projection!.needs_action[0]?.run_no).toBe('RUN-WAIT');
});
it('deduplicates conversation total_files by authoritative PDF id', () => {
const base = {
sourceType: 'direct_pdf' as const,
shippingNoticeNo: null,
conversationId: 'conv-1',
submissionNo: 'SOS-1',
intakeNo: 'SNI-1',
status: 'waiting_review' as const,
stage: 'waiting_review' as const,
progressVersion: 1,
lastActivityAt: '2026-08-06T00:00:00Z',
currentGate: null,
availableActions: ['open_order_review'],
childOrderTasks: [],
};
const workItems: ShippingProcessingProjection[] = [
{
...base,
workItemType: 'order_task',
workItemNo: 'OT-A',
rootOrderTaskNo: 'OT-A',
sourceSummary: {
emailSubject: null, filename: 'a.pdf', documentId: 17,
documentCount: 1, parsedDocumentCount: 1, candidateCount: 1,
customerName: null, poNumber: 'PO-A',
},
},
{
...base,
workItemType: 'order_task',
workItemNo: 'OT-B',
rootOrderTaskNo: 'OT-A',
sourceSummary: {
emailSubject: null, filename: 'a.pdf', documentId: 17,
documentCount: 1, parsedDocumentCount: 1, candidateCount: 1,
customerName: null, poNumber: 'PO-B',
},
},
];
const projection = projectConversationProcessingFromWorkItems(workItems);
// 异常重复绑定同一主 PDF 时,顶部必须仍显示 1 个文件。
expect(projection?.summary.total_files).toBe(1);
});
it('aggregates mixed order tasks from one EML intake into one card', () => {
const base = {
sourceType: 'eml' as const,
rootOrderTaskNo: null,
shippingNoticeNo: null,
conversationId: 'conv-eml',
submissionNo: 'SOS-EML',
intakeNo: 'INTAKE-EML-1',
progressVersion: 1,
currentGate: null,
childOrderTasks: [],
};
const items: ShippingProcessingProjection[] = [
{
...base, workItemType: 'order_task', workItemNo: 'OT-DONE', status: 'completed', stage: 'completed',
userStatus: 'completed', userStage: 'completed', lastActivityAt: '2026-08-06T00:00:00Z', availableActions: [],
sourceSummary: { emailSubject: 'Shipment', filename: 'a.pdf', documentCount: 1, parsedDocumentCount: 1, candidateCount: 1, customerName: null, poNumber: null },
},
{
...base, workItemType: 'order_task', workItemNo: 'OT-RUN', status: 'processing', stage: 'inventory_matching',
userStatus: 'running', userStage: 'inventory_match', lastActivityAt: '2026-08-06T00:00:01Z', availableActions: [],
sourceSummary: { emailSubject: 'Shipment', filename: 'b.pdf', documentCount: 1, parsedDocumentCount: 1, candidateCount: 1, customerName: null, poNumber: null },
},
{
...base, workItemType: 'order_task', workItemNo: 'OT-FAIL', status: 'failed', stage: 'freight_uploading',
userStatus: 'failed', userStage: 'freight_upload', lastActivityAt: '2026-08-06T00:00:02Z', availableActions: [],
blockingReason: { code: 'upload_rpa_failed' },
sourceSummary: { emailSubject: 'Shipment', filename: 'c.pdf', documentCount: 1, parsedDocumentCount: 1, candidateCount: 1, customerName: null, poNumber: null },
},
];
const projection = projectConversationProcessingFromWorkItems(items);
expect(projection?.needs_action).toHaveLength(1);
expect(projection?.processing).toHaveLength(0);
expect(projection?.completed).toHaveLength(0);
expect(projection?.needs_action[0]?.aggregateSummary).toEqual(expect.objectContaining({
intakeNo: 'INTAKE-EML-1', total: 3, completed: 1, processing: 1, needsAction: 1, failed: 1,
}));
expect(projection?.needs_action[0]?.file_count).toBe(3);
expect(projection?.needs_action[0]?.aggregateSummary?.reasonCodes).toContain('upload_rpa_failed');
});
it('does not reuse an empty EML task when a later poll returns aggregate children', () => {
const base = {
workItemType: 'order_task' as const, sourceType: 'eml' as const, rootOrderTaskNo: 'OT-ROOT',
shippingNoticeNo: null, conversationId: 'conv-stable', submissionNo: 'SOS-1', intakeNo: 'SNI-STABLE',
progressVersion: 1, currentGate: null, availableActions: [], status: 'processing' as const,
stage: 'document_parsing' as const, userStatus: 'running' as const, userStage: 'document_parsing' as const,
lastActivityAt: '2026-08-06T00:00:00Z',
sourceSummary: { emailSubject: 'mail', filename: 'stable.eml', documentCount: 1, parsedDocumentCount: 1, candidateCount: 0, customerName: null, poNumber: null },
};
const first = projectConversationProcessingFromWorkItems([{ ...base, workItemNo: 'INTAKE:SNI-STABLE', aggregateSummary: { intakeNo: 'SNI-STABLE', total: 1, completed: 0, processing: 1, needsAction: 0, failed: 0, stages: [], reasonCodes: [] }, aggregateChildren: [] }]);
const child = { ...base, workItemNo: 'OT-CHILD', sourceSummary: { ...base.sourceSummary, filename: 'attachment.pdf' } };
const second = projectConversationProcessingFromWorkItems([{ ...base, workItemNo: 'INTAKE:SNI-STABLE', aggregateSummary: { intakeNo: 'SNI-STABLE', total: 1, completed: 0, processing: 1, needsAction: 0, failed: 0, stages: [], reasonCodes: [] }, aggregateChildren: [child] }], first);
expect(second?.processing[0]?.aggregateChildren?.map((item) => item.sourceSummary.filename)).toEqual(['attachment.pdf']);
expect(second?.processing[0]).not.toBe(first?.processing[0]);
});
it('puts an EML with review-required children into needs_action even when parent says processing', () => {
const parent = {
workItemType: 'order_task' as const, workItemNo: 'INTAKE:SNI-STATUS', sourceType: 'eml' as const,
rootOrderTaskNo: null, shippingNoticeNo: null, conversationId: 'conv-status', submissionNo: 'SOS-1', intakeNo: 'SNI-STATUS',
status: 'processing' as const, stage: 'document_parsing' as const, userStatus: 'running' as const, userGroup: 'processing' as const,
userStage: 'document_parsing' as const, progressVersion: 1, lastActivityAt: '', currentGate: null, availableActions: [],
sourceSummary: { emailSubject: null, filename: 'mail.eml', documentCount: 2, parsedDocumentCount: 2, candidateCount: 0, customerName: null, poNumber: null },
aggregateChildren: [
{ workItemType: 'order_task', workItemNo: 'OT-1', sourceType: 'eml', rootOrderTaskNo: null, shippingNoticeNo: null, conversationId: 'conv-status', submissionNo: 'SOS-1', intakeNo: 'SNI-STATUS', status: 'review_required', stage: 'review_required', userStatus: 'waiting_human', userStage: 'review_required', progressVersion: 1, lastActivityAt: '', currentGate: null, availableActions: [], sourceSummary: { emailSubject: null, filename: 'a.pdf', documentCount: 1, parsedDocumentCount: 1, candidateCount: 0, customerName: null, poNumber: null }, childOrderTasks: [], facts: { uploadState: 'not_created' } },
{ workItemType: 'order_task', workItemNo: 'OT-2', sourceType: 'eml', rootOrderTaskNo: null, shippingNoticeNo: null, conversationId: 'conv-status', submissionNo: 'SOS-1', intakeNo: 'SNI-STATUS', status: 'processing', stage: 'document_parsing', userStatus: 'running', userStage: 'document_parsing', progressVersion: 1, lastActivityAt: '', currentGate: null, availableActions: [], sourceSummary: { emailSubject: null, filename: 'b.pdf', documentCount: 1, parsedDocumentCount: 1, candidateCount: 0, customerName: null, poNumber: null }, childOrderTasks: [], facts: { uploadState: 'not_created' } },
],
} as any;
const projection = projectConversationProcessingFromWorkItems([parent]);
expect(projection?.needs_action).toHaveLength(1);
expect(projection?.processing).toHaveLength(0);
});
it('does not aggregate direct PDFs with matching intake numbers', () => {
const common = {
workItemType: 'order_task' as const, rootOrderTaskNo: null, shippingNoticeNo: null,
conversationId: 'conv-pdf', submissionNo: 'SOS-PDF', intakeNo: 'INTAKE-SAME', progressVersion: 1,
currentGate: null, childOrderTasks: [], status: 'processing' as const, stage: 'document_parsing' as const,
userStatus: 'running' as const, userStage: 'document_parsing' as const, lastActivityAt: '2026-08-06T00:00:00Z', availableActions: [],
};
const projection = projectConversationProcessingFromWorkItems([
{ ...common, workItemNo: 'OT-1', sourceType: 'direct_pdf', sourceSummary: { emailSubject: null, filename: 'a.pdf', documentCount: 1, parsedDocumentCount: 0, candidateCount: 0, customerName: null, poNumber: null } },
{ ...common, workItemNo: 'OT-2', sourceType: 'direct_pdf', sourceSummary: { emailSubject: null, filename: 'b.pdf', documentCount: 1, parsedDocumentCount: 0, candidateCount: 0, customerName: null, poNumber: null } },
]);
expect(projection?.processing).toHaveLength(2);
});
it('prefers work_items task lists over embedded conversation_processing when both exist', () => {
const workItems: ShippingProcessingProjection[] = [
{
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: [],
},
];
const embedded = {
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 projection = resolveConversationProcessingFromUnified(workItems, embedded);
// 关键断言:兄弟 OT 仅出现在 work_items;embedded 缺 sibling 时不得覆盖任务列表。
expect(projection?.needs_action.map((t) => t.user_task_no)).toEqual(['OT-ROOT']);
expect(projection?.processing).toEqual([]);
expect(projection?.needs_action[0]?.aggregateSummary).toEqual(expect.objectContaining({
intakeNo: 'SNI-1', total: 2, completed: 0, processing: 1, needsAction: 1,
}));
expect(projection?.focused_task_no).toBe('OT-ROOT');
expect(projection?.recent_task_no).toBe('OT-SIBLING');
});
it('uses backend status_groups instead of rebuilding a file list from work_items', () => {
const workItems: ShippingProcessingProjection[] = [{
workItemType: 'order_task', workItemNo: 'OT-LIVE', sourceType: 'direct_pdf',
rootOrderTaskNo: 'OT-LIVE', shippingNoticeNo: null, conversationId: 'conv-live',
submissionNo: 'SOS-LIVE', intakeNo: 'SNI-LIVE', status: 'waiting_review',
stage: 'order_review', progressVersion: 9, lastActivityAt: '2026-08-16T00:00:00Z',
currentGate: null, availableActions: ['open_order_review'], childOrderTasks: [],
sourceSummary: { emailSubject: null, filename: 'live.pdf', documentCount: 1,
parsedDocumentCount: 1, candidateCount: 1, customerName: null, poNumber: 'PO-LIVE' },
}];
const backendProjection = {
summary: { total_tasks: 1, total_files: 1, processing: 1, needs_action: 0, completed: 0, history: 0 },
status_groups: {
failed: [], waiting_human: [{
user_task_no: 'OT-LIVE', group: 'needs_action', status_label: 'waiting_human',
file_count: 1, can_append: false,
}], processing: [], completed: [], cancelled: [], archived: [],
},
needs_action: [], processing: [{ user_task_no: 'OT-HISTORY', status_label: 'extracting' }],
completed: [], history: [], focused_task_no: null, recent_task_no: null,
};
const projection = resolveConversationProcessingFromUnified(workItems, backendProjection);
// 后端已排除的历史条目不允许被前端 work_items 重建回页面。
expect(projection?.needs_action.map((task) => task.user_task_no)).toEqual(['OT-LIVE']);
expect(projection?.processing).toEqual([]);
});
it('merges focus metadata from embedded onto work_items-derived projection', () => {
const derived = projectConversationProcessingFromWorkItems([{
workItemType: 'order_task',
workItemNo: 'OT-1',
sourceType: 'direct_pdf',
rootOrderTaskNo: 'OT-1',
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: 'a.pdf',
documentCount: 1,
parsedDocumentCount: 1,
candidateCount: 0,
customerName: null,
poNumber: null,
},
childOrderTasks: [],
}]);
const merged = mergeConversationProcessingFocusMetadata(derived, {
summary: derived!.summary,
focused_task_no: 'OT-FOCUS',
recent_task_no: 'OT-RECENT',
needs_action: [{ user_task_no: 'OT-STALE', group: 'needs_action', can_append: false }],
processing: [],
history: [],
});
expect(merged?.processing[0]?.user_task_no).toBe('OT-1');
expect(merged?.focused_task_no).toBe('OT-FOCUS');
expect(merged?.recent_task_no).toBe('OT-RECENT');
});
});
/**
* 方案 1~4 的防御链单元测试:
* normalize → semanticKey → stabilize;任何一环击穿都会导致轮询按钮闪烁。
* 对应验收:动作顺序变化按钮不变 / updated_at 变化按钮不变 / 轮询相同数据按钮 DOM 不变。
*/
describe('conversationProcessingProjection — normalize & semantic & stabilize', () => {
it('normalizeActionCodes: 去空白、小写、去重、字典序排序', () => {
expect(normalizeActionCodes([' View_Details ', 'Confirm_Customer', 'view_details', ' confirm_customer ']))
.toEqual(['confirm_customer', 'view_details']);
expect(normalizeActionCodes([null, undefined, '', ' ', 'cancel', '0']))
.toEqual(['0', 'cancel']);
expect(normalizeActionCodes([])).toEqual([]);
expect(normalizeActionCodes([undefined, null])).toEqual([]);
});
it('buildTaskSemanticKey: available_actions 乱序 → 同一签名(不影响按钮顺序)', () => {
const base: Parameters<typeof projectConversationProcessingFromWorkItems>[0][number] = {
workItemType: 'order_task',
workItemNo: 'OT-1',
sourceType: 'direct_pdf',
rootOrderTaskNo: 'OT-1',
shippingNoticeNo: null,
conversationId: 'conv-1',
submissionNo: 'SOS-1',
intakeNo: 'SNI-1',
status: 'waiting_review',
stage: 'waiting_review',
progressVersion: 1,
lastActivityAt: '2026-08-10T00:00:00Z',
currentGate: {
gateCode: 'order_freeze_readiness',
status: 'blocked',
nextActionCode: 'open_order_review',
blockingReasonCode: 'review_case_draft',
attemptNo: 0,
},
availableActions: ['open_order_review', 'view_details'],
sourceSummary: {
emailSubject: null,
filename: 'a.pdf',
documentCount: 1,
parsedDocumentCount: 1,
candidateCount: 0,
customerName: null,
poNumber: 'PO-1',
},
childOrderTasks: [],
};
const p1 = projectConversationProcessingFromWorkItems([{ ...base }]);
const p2 = projectConversationProcessingFromWorkItems([
{ ...base, availableActions: ['view_details', 'open_order_review'], lastActivityAt: '2099-01-01T00:00:00Z' },
]);
const t1 = p1!.needs_action[0]!;
const t2 = p2!.needs_action[0]!;
// 相同语义字段 -> 同签名;即使 available_actions 顺序不同、lastActivityAt 不同。
expect(buildTaskSemanticKey(t1)).toBe(buildTaskSemanticKey(t2));
// available_actions 内永远是 normalized 排序后的数组,不是原始后端乱序。
expect(t1.available_actions).toEqual(['open_order_review', 'view_details']);
expect(t2.available_actions).toEqual(['open_order_review', 'view_details']);
});
it('buildTaskSemanticKey: ui_state 动作变化必须改变签名', () => {
const shared = {
user_task_no: 'INTAKE:SNI-UI', group: 'needs_action' as const,
status_label: 'waiting_human', file_count: 1, can_append: false,
available_actions: ['retry_parse'],
};
const before = {
...shared,
uiState: {
status: 'waiting_human', stage: 'order_review', blocking_reason: null,
primary_action: { code: 'open_order_review', i18nKey: 'action.open_order_review', parameters: {} },
secondary_actions: [],
},
};
const after = {
...before,
uiState: {
...before.uiState,
primary_action: { code: 'retry_parse', i18nKey: 'action.retry_parse', parameters: {} },
},
};
expect(buildTaskSemanticKey(before)).not.toBe(buildTaskSemanticKey(after));
});
it('buildTaskSemanticKey: 后端撤销生命周期入口时必须改变签名', () => {
const shared = {
user_task_no: 'INTAKE:SNI-LIFECYCLE', group: 'needs_action' as const,
status_label: 'waiting_human', file_count: 1, can_append: false,
uiState: {
status: 'waiting_human', stage: 'waiting_review', blocking_reason: null,
primary_action: null, secondary_actions: [],
lifecycleEntries: [{ code: 'order_review' as const, state: 'current' as const, targetSurface: 'order_lifecycle_workbench' as const }],
},
};
const revoked = {
...shared,
uiState: { ...shared.uiState, lifecycleEntries: [] },
};
expect(buildTaskSemanticKey(shared)).not.toBe(buildTaskSemanticKey(revoked));
});
it('buildTaskSemanticKey: EML 子文件入口被撤销时必须替换聚合卡', () => {
const child = {
workItemNo: 'OT-LEAF-1',
intakeNo: 'SNI-LEAF',
status: 'waiting_human',
stage: 'order_review',
sourceSummary: { filename: 'leaf.pdf', documentId: 801 },
uiState: {
status: 'waiting_human', stage: 'order_review', blocking_reason: null,
primary_action: null, secondary_actions: [],
lifecycleEntries: [{
code: 'order_review' as const, state: 'current' as const,
targetSurface: 'order_lifecycle_workbench' as const,
}],
},
} as any;
const task = {
user_task_no: 'INTAKE:SNI-LEAF', group: 'needs_action' as const,
status_label: 'waiting_human', file_count: 1, can_append: false,
uiState: { status: 'waiting_human', stage: 'order_review', blocking_reason: null, primary_action: null, secondary_actions: [] },
aggregateChildren: [child],
} as any;
const revoked = {
...task,
aggregateChildren: [{
...child,
uiState: { ...child.uiState, lifecycleEntries: [] },
}],
};
expect(buildTaskSemanticKey(task)).not.toBe(buildTaskSemanticKey(revoked));
});
it('buildTaskSemanticKey: authoritative ui_state without a primary action ignores stale legacy action', () => {
const shared = {
user_task_no: 'INTAKE:SNI-NO-ACTION', group: 'processing' as const,
status_label: 'processing', file_count: 1, can_append: false,
primary_action: 'retry_parse', available_actions: ['retry_parse'],
uiState: { status: 'processing', stage: 'document_parsing', blocking_reason: null, primary_action: null, secondary_actions: [] },
};
const withoutLegacy = { ...shared, primary_action: null, available_actions: [] };
// 后端 ui_state 已明确“无动作”时,旧字段变动不能让状态卡语义闪烁或伪造 CTA。
expect(buildTaskSemanticKey(shared)).toBe(buildTaskSemanticKey(withoutLegacy));
});
it('stabilizeTaskObjects: 同一 user_task_no 且语义相同,优先复用旧对象引用(避免 DOM 重建)', () => {
const baseTask = (no: string, updatedAt: string) => ({
user_task_no: no,
group: 'processing' as const,
status_label: 'document_parsing',
run_no: 'RUN-1',
title: '订单识别任务',
primary_action: 'view_details',
display_kind: 'single_document_task',
file_count: 1,
can_append: false,
updated_at: updatedAt,
last_activity_at: updatedAt,
available_actions: ['view_details'],
current_gate: null,
user_task_authoritative: true,
documents: [],
});
const oldOne = baseTask('OT-1', '2026-08-10T00:00:00Z');
const nextOne = baseTask('OT-1', '2026-08-10T00:00:02Z');
const oldTasks = [oldOne];
const nextRawTasks = [nextOne];
const stabilized = stabilizeTaskObjects(oldTasks, nextRawTasks);
// updated_at/last_activity_at 不参与 semanticKey 比较 -> 复用旧引用。
expect(stabilized[0]).toBe(oldOne);
expect(stabilized[0].updated_at).toBe('2026-08-10T00:00:00Z');
});
it('buildProcessingSemanticKey: 只基于语义字段,忽略 updated_at/last_activity_at 扰动', () => {
function makeProjection() {
return projectConversationProcessingFromWorkItems([{
workItemType: 'order_task',
workItemNo: 'OT-A',
sourceType: 'direct_pdf',
rootOrderTaskNo: 'OT-A',
shippingNoticeNo: null,
conversationId: 'conv-1',
submissionNo: 'SOS-1',
intakeNo: 'SNI-1',
status: 'processing',
stage: 'document_parsing',
progressVersion: 1,
lastActivityAt: '2026-08-10T00:00:00Z',
currentGate: null,
availableActions: ['view_details'],
sourceSummary: {
emailSubject: null, filename: 'a.pdf',
documentCount: 1, parsedDocumentCount: 1, candidateCount: 0,
customerName: null, poNumber: null,
},
childOrderTasks: [],
}])!;
}
const pA = makeProjection();
const pB = makeProjection();
// 模拟轮询差异:updated_at / last_activity_at / created_at 等辅助字段都变。
pA.processing[0]!.updated_at = '2026-08-10T00:00:00Z';
pA.processing[0]!.last_activity_at = '2026-08-10T00:00:00Z';
pB.processing[0]!.updated_at = '2026-08-10T00:00:02Z';
pB.processing[0]!.last_activity_at = '2026-08-10T00:00:02Z';
expect(buildProcessingSemanticKey(pA)).toBe(buildProcessingSemanticKey(pB));
});
it('stabilizeTaskObjects: 语义变化时(status 改变)必须返回新对象,不能错误冻结旧状态', () => {
const oldTask = {
user_task_no: 'OT-1',
group: 'processing' as const,
status_label: 'document_parsing',
run_no: 'RUN-1',
title: '订单识别任务',
primary_action: 'view_details',
display_kind: 'single_document_task',
file_count: 1,
can_append: false,
updated_at: '2026-08-10T00:00:00Z',
last_activity_at: '2026-08-10T00:00:00Z',
available_actions: ['view_details'],
current_gate: null,
user_task_authoritative: true,
documents: [],
};
const nextTask = {
...oldTask,
group: 'needs_action' as const,
status_label: 'waiting_review',
primary_action: 'open_order_review',
available_actions: ['open_order_review', 'view_details'],
updated_at: '2026-08-10T00:00:10Z',
last_activity_at: '2026-08-10T00:00:10Z',
current_gate: {
blockingReasonCode: 'review_case_draft',
nextActionCode: 'open_order_review',
},
};
const stabilized = stabilizeTaskObjects([oldTask], [nextTask]);
// 状态从 processing→needs_action 语义已变,必须替换成新引用。
expect(stabilized[0]).not.toBe(oldTask);
expect(stabilized[0].status_label).toBe('waiting_review');
expect(stabilized[0].available_actions).toEqual(['open_order_review', 'view_details']);
});
it('normalizeLifecycleStatus: waiting_human / pending_review / review_required 一律归并为 waiting_review', () => {
expect(normalizeLifecycleStatus('waiting_human')).toBe('waiting_review');
expect(normalizeLifecycleStatus('WAITING_HUMAN ')).toBe('waiting_review');
expect(normalizeLifecycleStatus('pending_review')).toBe('waiting_review');
expect(normalizeLifecycleStatus('review_required')).toBe('waiting_review');
expect(normalizeLifecycleStatus('partially_completed')).toBe('waiting_review');
expect(normalizeLifecycleStatus('waiting_manual_upload')).toBe('manual_upload_pending');
expect(normalizeLifecycleStatus('retryable')).toBe('failed');
expect(normalizeLifecycleStatus('completed')).toBe('completed');
expect(normalizeLifecycleStatus('')).toBe('');
expect(normalizeLifecycleStatus(null)).toBe('');
});
it('buildTaskSemanticKey: waiting_human 与 waiting_review 语义相同 → 同签名(不闪烁)', () => {
const shared = {
user_task_no: 'OT-SAME',
group: 'needs_action' as const,
run_no: 'RUN-1',
display_kind: 'single_document_task' as const,
file_count: 1,
title: 'a.pdf',
primary_action: 'open_order_review',
available_actions: ['open_order_review', 'view_details'],
can_append: false,
user_task_authoritative: true,
objects: [],
};
const t1 = { ...shared, status_label: 'waiting_human' };
const t2 = { ...shared, status_label: 'waiting_review' };
expect(buildTaskSemanticKey(t1)).toBe(buildTaskSemanticKey(t2));
// updated_at 不影响,这里再确认 userStatus 为 waiting_human 也一致。
const t3 = { ...shared, status_label: 'queued', userStatus: 'waiting_human' } as typeof t1 & { userStatus: string };
const t4 = { ...shared, status_label: 'queued', userStatus: 'waiting_review' } as typeof t1 & { userStatus: string };
expect(buildTaskSemanticKey(t3)).toBe(buildTaskSemanticKey(t4));
});
it('normalizeConversationProcessingProjection: embedded waiting_human → waiting_review / needs_action', () => {
const embedded: ConversationProcessingProjection = {
summary: { total_tasks: 1, total_files: 1, processing: 0, needs_action: 0, completed: 0, history: 0 },
focused_task_no: null,
recent_task_no: null,
needs_action: [],
processing: [
{
user_task_no: 'OT-LEGACY',
user_task_authoritative: false,
title: 'a.pdf',
display_kind: 'single_document_task',
document_names: ['a.pdf'],
// 旧投影错误地把 waiting_human 放进了 processing 组
group: 'processing',
status_label: 'waiting_human',
file_count: 1,
run_no: 'RUN-LEG',
can_append: false,
available_actions: ['enter_manual_review', 'view_details'],
primary_action: 'enter_manual_review',
},
],
completed: [],
history: [],
};
const normalized = normalizeConversationProcessingProjection(embedded);
const task = normalized.needs_action[0];
expect(task).toBeDefined();
expect(task!.status_label).toBe('waiting_review');
// waiting_human → waiting_review → 必须迁入 needs_action
expect(task!.group).toBe('needs_action');
expect(normalized.processing.length).toBe(0);
});
it('normalizes backend status-group task UI state and EML children without recalculating batch facts', () => {
const backendProjection = {
// 统计是后端按完整批次裁决的事实,不能由当前返回的局部 EML/附件数组替代。
summary: { total_tasks: 1, total_files: 7, processing: 0, needs_action: 1, completed: 0, history: 0 },
focused_task_no: 'INTAKE:SNI-API',
recent_task_no: 'INTAKE:SNI-API',
needs_action: [], processing: [], completed: [], history: [],
status_groups: {
failed: [{
user_task_no: 'INTAKE:SNI-API', title: 'source.eml', display_kind: 'multi_document_task',
document_names: ['a.pdf', 'b.pdf'], group: 'needs_action', status_label: 'failed', file_count: 2,
can_append: false, available_actions: [], primary_action: null,
ui_state: {
status: 'failed', stage: 'document_parsing',
blocking_reason: { code: 'PARSE_FAILED', i18n_key: 'shipping.parse_failed', details: {} },
primary_action: { code: 'retry', i18n_key: 'shipping.retry', parameters: {} }, secondary_actions: [],
},
aggregate_children: [{
work_item_type: 'order_task', work_item_no: 'OT-API-1', source_type: 'direct_pdf',
root_order_task_no: 'OT-API-1', shipping_notice_no: null, conversation_id: 'conv-api',
submission_no: 'SUB-1', intake_no: 'SNI-API', status: 'failed', stage: 'document_parsing',
progress_version: 1, last_activity_at: '2026-08-14T00:00:00Z', current_gate: null, available_actions: [],
source_summary: { email_subject: 'Subject', filename: 'a.pdf', document_count: 1, parsed_document_count: 0, candidate_count: 0 },
child_order_tasks: [], ui_state: {
status: 'failed', stage: 'document_parsing', blocking_reason: { code: 'PARSE_FAILED', details: {} },
primary_action: { code: 'retry', parameters: {} }, secondary_actions: [],
},
}],
}],
waiting_human: [], processing: [], completed: [], cancelled: [], archived: [],
},
four_stage_nodes: [{ code: 'intake_parse', label_key: 'shipping.stage.intake', status: 'blocked' }],
output_artifacts: [{ order_task_no: 'OT-API-1', filename: 'shipping.xlsx', type: 'excel', status: 'ready', action: { code: 'download_excel', enabled: true } }],
} as unknown as ConversationProcessingProjection;
const normalized = normalizeConversationProcessingProjection(backendProjection);
const eml = normalized.status_groups!.failed[0]!;
// 后端裁决的状态/按钮必须在 EML 与附件层均可直接消费,前端不重新推导。
expect(eml.uiState?.primary_action?.code).toBe('retry');
expect(eml.uiState?.primary_action?.i18nKey).toBe('shipping.retry');
expect(eml.aggregateChildren?.[0]?.uiState?.primary_action?.code).toBe('retry');
expect(eml.aggregateChildren?.[0]?.sourceSummary.filename).toBe('a.pdf');
// 批次统计、四阶段与产物均是后端事实,适配时不得从附件重算或丢失。
expect(normalized.summary.total_files).toBe(7);
expect(normalized.four_stage_nodes).toEqual([{ code: 'intake_parse', label_key: 'shipping.stage.intake', status: 'blocked' }]);
expect(normalized.output_artifacts?.[0]?.action.enabled).toBe(true);
});
it('normalizes backend lifecycle_entries in status groups without recreating entries', () => {
const backendProjection = {
summary: { total_tasks: 1, total_files: 1, processing: 0, needs_action: 1, completed: 0, history: 0 },
focused_task_no: null,
recent_task_no: null,
needs_action: [], processing: [], completed: [], history: [],
status_groups: {
failed: [],
waiting_human: [{
user_task_no: 'OT-LIFECYCLE-SNAKE', title: 'order.pdf', display_kind: 'single_document_task',
document_names: ['order.pdf'], group: 'needs_action', status_label: 'waiting_human', file_count: 1,
can_append: false, available_actions: [],
ui_state: {
status: 'waiting_human', stage: 'field_completeness', lifecycle_stage: 'order_review',
lifecycle_entries: [{ code: 'intake_parse', state: 'available', target_surface: 'order_lifecycle_workbench' }, {
code: 'order_review', state: 'current', target_surface: 'order_lifecycle_workbench',
}],
blocking_reason: null, primary_action: null, secondary_actions: [],
},
}],
processing: [], completed: [], cancelled: [], archived: [],
},
} as unknown as ConversationProcessingProjection;
const normalized = normalizeConversationProcessingProjection(backendProjection);
const task = normalized.status_groups!.waiting_human[0]!;
expect(task.uiState?.lifecycleStage).toBe('order_review');
expect(task.uiState?.lifecycleEntries).toEqual([
{ code: 'intake_parse', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'order_review', state: 'current', targetSurface: 'order_lifecycle_workbench' },
]);
});
it('normalizes embedded primary-action lifecycle navigation fields from backend snake_case', () => {
const embedded = {
summary: { total_tasks: 1, total_files: 1, processing: 0, needs_action: 1, completed: 0, history: 0 },
focused_task_no: null, recent_task_no: null,
needs_action: [], processing: [], completed: [], history: [],
status_groups: {
failed: [],
waiting_human: [{
user_task_no: 'OT-FULFILLMENT-NAV', title: 'order.pdf', display_kind: 'single_document_task',
document_names: ['order.pdf'], group: 'needs_action', status_label: 'waiting_human', file_count: 1,
can_append: false, available_actions: [],
ui_state: {
status: 'waiting_human', stage: 'inventory_matching', lifecycle_stage: 'fulfillment_prep',
lifecycle_entries: [], blocking_reason: null,
primary_action: {
code: 'open_inventory_match_review', execution_mode: 'navigate',
target_surface: 'order_lifecycle_workbench', target_lifecycle_stage: 'fulfillment_prep',
}, secondary_actions: [],
},
}],
processing: [], completed: [], cancelled: [], archived: [],
},
} as unknown as ConversationProcessingProjection;
const action = normalizeConversationProcessingProjection(embedded)
.status_groups!.waiting_human[0]!.uiState!.primary_action!;
expect(action.executionMode).toBe('navigate');
expect(action.targetSurface).toBe('order_lifecycle_workbench');
expect(action.targetLifecycleStage).toBe('fulfillment_prep');
});
it('normalizes embedded secondary-action lifecycle navigation fields from backend snake_case', () => {
const embedded = {
summary: { total_tasks: 1, total_files: 1, processing: 0, needs_action: 1, completed: 0, history: 0 },
focused_task_no: null, recent_task_no: null,
needs_action: [], processing: [], completed: [], history: [],
status_groups: {
failed: [],
waiting_human: [{
user_task_no: 'OT-VIEW-NAV', title: 'order.pdf', display_kind: 'single_document_task',
document_names: ['order.pdf'], group: 'needs_action', status_label: 'waiting_human', file_count: 1,
can_append: false, available_actions: [],
ui_state: {
status: 'waiting_human', stage: 'inventory_matching', lifecycle_stage: 'fulfillment_prep',
lifecycle_entries: [], blocking_reason: null, primary_action: null,
secondary_actions: [{
code: 'view_result', enabled: true, execution_mode: 'navigate',
target_surface: 'order_lifecycle_workbench', target_lifecycle_stage: 'fulfillment_prep',
}],
},
}],
processing: [], completed: [], cancelled: [], archived: [],
},
} as unknown as ConversationProcessingProjection;
const action = normalizeConversationProcessingProjection(embedded)
.status_groups!.waiting_human[0]!.uiState!.secondary_actions[0]!;
// 次动作与主动作一样来自后端授权;缺失导航字段会使文件级查看结果静默失效。
expect(action.executionMode).toBe('navigate');
expect(action.targetSurface).toBe('order_lifecycle_workbench');
expect(action.targetLifecycleStage).toBe('fulfillment_prep');
});
it('fails closed for unsupported embedded primary-action navigation targets', () => {
const embedded = {
summary: { total_tasks: 1, total_files: 1, processing: 0, needs_action: 1, completed: 0, history: 0 },
focused_task_no: null, recent_task_no: null,
needs_action: [], processing: [], completed: [], history: [],
status_groups: {
failed: [],
waiting_human: [{
user_task_no: 'OT-INVALID-NAV', title: 'order.pdf', display_kind: 'single_document_task',
document_names: ['order.pdf'], group: 'needs_action', status_label: 'waiting_human', file_count: 1,
can_append: false, available_actions: [],
ui_state: {
status: 'waiting_human', stage: 'inventory_matching', lifecycle_stage: 'fulfillment_prep',
lifecycle_entries: [], blocking_reason: null,
primary_action: {
code: 'open_inventory_match_review', execution_mode: 'unknown',
target_surface: 'unsupported_surface', target_lifecycle_stage: 'unsupported_stage',
}, secondary_actions: [],
},
}],
processing: [], completed: [], cancelled: [], archived: [],
},
} as unknown as ConversationProcessingProjection;
const action = normalizeConversationProcessingProjection(embedded)
.status_groups!.waiting_human[0]!.uiState!.primary_action!;
expect(action.executionMode).toBeUndefined();
expect(action.targetSurface).toBeNull();
expect(action.targetLifecycleStage).toBeNull();
});
it('keeps backend intake_parse primary-action target instead of dropping it', () => {
const normalized = normalizeShippingProcessingProjection({
work_item_no: 'OT-INTAKE-ACTION', source_type: 'direct_pdf', status: 'waiting_human',
stage: 'intake_parse', progress_version: 1, last_activity_at: '2026-08-16T00:00:00Z',
source_summary: {}, available_actions: [], child_order_tasks: [],
ui_state: {
status: 'waiting_human', stage: 'intake_parse', lifecycle_stage: 'intake_parse',
lifecycle_entries: [{ code: 'intake_parse', state: 'current', target_surface: 'order_lifecycle_workbench' }],
blocking_reason: null,
primary_action: {
code: 'open_intake_parse', parameters: {}, execution_mode: 'navigate',
target_surface: 'order_lifecycle_workbench', target_lifecycle_stage: 'intake_parse',
},
secondary_actions: [],
},
});
// 后端指定接收解析时,前端仅透传该目标,不得由现有三阶段白名单裁决或改写。
expect(normalized?.uiState?.primary_action?.targetLifecycleStage).toBe('intake_parse');
expect(normalized?.uiState?.lifecycleEntries).toEqual([
{ code: 'intake_parse', state: 'current', targetSurface: 'order_lifecycle_workbench', disabledReasonKey: null },
]);
});
it('resolveConversationProcessingFromUnified: work_items 为空时,embedded waiting_human 任务迁入 needs_action 且统一文案', () => {
const embedded: ConversationProcessingProjection = {
summary: { total_tasks: 1, total_files: 1, processing: 1, needs_action: 0, completed: 0, history: 0 },
focused_task_no: null,
recent_task_no: null,
needs_action: [],
processing: [
{
user_task_no: 'OT-LEG2',
user_task_authoritative: false,
title: 'b.pdf',
display_kind: 'single_document_task',
document_names: ['b.pdf'],
group: 'processing',
status_label: 'waiting_human',
file_count: 1,
run_no: 'RUN-LEG2',
can_append: false,
available_actions: [],
primary_action: 'view_details',
},
],
completed: [],
history: [],
};
const result = resolveConversationProcessingFromUnified([], embedded);
expect(result).not.toBeNull();
// waiting_human 任务从 processing 组迁入 needs_action
expect(result!.processing.length).toBe(0);
expect(result!.needs_action.length).toBe(1);
expect(result!.needs_action[0]!.status_label).toBe('waiting_review');
expect(result!.needs_action[0]!.title).toBe('b.pdf');
});
it('resolveConversationProcessingFromUnified: 仅含 EML order_intake 时,派生统一 processing 投影而非回退 embedded', () => {
const embedded: ConversationProcessingProjection = {
summary: { total_tasks: 1, total_files: 1, processing: 1, needs_action: 0, completed: 0, history: 0 },
focused_task_no: 'OT-LEG3',
recent_task_no: 'OT-LEG3',
needs_action: [],
processing: [
{
user_task_no: 'OT-LEG3',
user_task_authoritative: false,
title: 'c.pdf',
display_kind: 'single_document_task',
document_names: ['c.pdf'],
group: 'processing',
status_label: 'waiting_human',
file_count: 1,
run_no: 'RUN-LEG3',
can_append: false,
available_actions: ['enter_manual_review'],
primary_action: 'enter_manual_review',
},
],
completed: [],
history: [],
};
const workItems: ShippingProcessingProjection[] = [
{
workItemType: 'order_intake',
workItemNo: 'SNI-1',
sourceType: 'eml',
rootOrderTaskNo: null,
shippingNoticeNo: null,
conversationId: 'conv-1',
submissionNo: 'SOS-1',
intakeNo: 'SNI-1',
status: 'processing',
stage: 'building_order',
progressVersion: 1,
lastActivityAt: '2026-08-06T00:00:00Z',
currentGate: null,
availableActions: [],
sourceSummary: {
emailSubject: null,
filename: 'c.pdf',
documentCount: 1,
parsedDocumentCount: 0,
candidateCount: 0,
customerName: null,
poNumber: null,
},
childOrderTasks: [],
},
];
const result = resolveConversationProcessingFromUnified(workItems, embedded);
expect(result).not.toBeNull();
// EML 尚未创建 OT 时,也必须作为一张 EML 卡进入统一“系统处理中”区。
expect(result!.focused_task_no).toBe('OT-LEG3');
expect(result!.needs_action).toHaveLength(0);
expect(result!.processing).toHaveLength(1);
expect(result!.processing[0]).toMatchObject({
user_task_no: 'SNI-1',
title: 'c.pdf',
group: 'processing',
status_label: 'processing',
});
});
it('resolveConversationProcessingFromUnified + IntakeOtStabilizer: 看到 order_task 后 2s 内暂缺 OT 保持 previousProjection(避免轮询抖动)', () => {
const stabilizer = createIntakeOtStabilizer();
const embedded: ConversationProcessingProjection = {
summary: { total_tasks: 1, total_files: 1, processing: 0, needs_action: 1, completed: 0, history: 0 },
focused_task_no: null,
recent_task_no: null,
needs_action: [
{
user_task_no: 'OT-LG',
user_task_authoritative: false,
title: 'fallback.pdf',
display_kind: 'single_document_task',
document_names: ['fallback.pdf'],
group: 'needs_action',
status_label: 'waiting_human',
file_count: 1,
run_no: 'RUN-LG',
can_append: false,
available_actions: [],
primary_action: 'enter_manual_review',
},
],
processing: [],
completed: [],
history: [],
};
const intakeOnly: ShippingProcessingProjection[] = [
{
workItemType: 'order_intake',
workItemNo: 'SNI-1',
sourceType: 'direct_pdf',
rootOrderTaskNo: null,
shippingNoticeNo: null,
conversationId: 'conv-1',
submissionNo: 'SOS-1',
intakeNo: 'SNI-1',
status: 'processing',
stage: 'building_order',
progressVersion: 1,
lastActivityAt: '2026-08-06T00:00:00Z',
currentGate: null,
availableActions: [],
sourceSummary: { filename: 'a.pdf', documentCount: 1 },
childOrderTasks: [],
},
];
const withOrderTask: ShippingProcessingProjection[] = [
{
workItemType: 'order_task',
workItemNo: 'OT-NEW',
sourceType: 'direct_pdf',
rootOrderTaskNo: 'OT-NEW',
shippingNoticeNo: null,
conversationId: 'conv-1',
runNo: 'RUN-NEW',
caseNo: 'CASE-NEW',
submissionNo: 'SOS-1',
intakeNo: 'SNI-1',
userStatus: 'waiting_review',
status: 'waiting_review',
stage: 'waiting_human_review',
progressVersion: 1,
lastActivityAt: '2026-08-06T00:00:01Z',
primaryAction: { code: 'open_order_review', i18nKey: 'chat.shippingProcessing.action.open_order_review' },
currentGate: null,
availableActions: ['open_order_review', 'cancel_task'],
sourceSummary: { filename: 'a.pdf', documentCount: 1 },
},
];
// Step 1: 初始只有 intake,还没见过 OT → 走 embedded normalize
const step1 = resolveConversationProcessingFromUnified(
intakeOnly,
embedded,
null,
{ conversationId: 'conv-1', ...stabilizer },
);
expect(step1!.needs_action[0]!.title).toBe('fallback.pdf');
expect(step1!.needs_action[0]!.status_label).toBe('waiting_review');
// Step 2: 第一轮看到 OT → derived 生成,同时 markSeen
const step2 = resolveConversationProcessingFromUnified(
withOrderTask,
embedded,
step1,
{ conversationId: 'conv-1', ...stabilizer },
);
expect(step2!.needs_action[0]!.user_task_no).toBe('OT-NEW');
expect(step2!.needs_action[0]!.status_label).toBe('waiting_review');
// Step 3: 下一次轮询只有 intake(本次响应暂缺 OT)→ 保持 previousProjection,不抖回 embedded
const step3 = resolveConversationProcessingFromUnified(
intakeOnly,
embedded,
step2,
{ conversationId: 'conv-1', ...stabilizer },
);
expect(step3).toBe(step2);
// Step 4: 用户点刷新 reset 后,允许走 embedded(业务认为需要重新建立稳定态)
stabilizer.reset('conv-1');
const step4 = resolveConversationProcessingFromUnified(
intakeOnly,
embedded,
step2,
{ conversationId: 'conv-1', ...stabilizer },
);
expect(step4!.needs_action[0]!.title).toBe('fallback.pdf');
expect(step4!.needs_action[0]!.status_label).toBe('waiting_review');
});
});