657 lines
25 KiB
TypeScript
657 lines
25 KiB
TypeScript
/**
|
|
* features/chat/shipping/useShippingOrderExtractionRuns.spec.ts
|
|
* 用途:验证订单抽取 Run 的状态映射、单状态卡消息持久化与轮询生命周期。
|
|
* 依赖:Vitest、Vue refs、shipping.api mock、useShippingOrderExtractionRuns。
|
|
* 逻辑:覆盖新建/追加提交不生成重复反馈气泡、状态契约、无变化轮询及恢复隔离。
|
|
*/
|
|
import { computed, ref } from 'vue';
|
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
import { mapOrderExtractionRunToMessageState, useShippingOrderExtractionRuns } from './useShippingOrderExtractionRuns';
|
|
import type { ShippingOrderExtractionRun } from '../types/shipping.api.types';
|
|
import type { ChatMessage } from '../types/chat.types';
|
|
|
|
const api = vi.hoisted(() => ({
|
|
createSubmission: vi.fn(),
|
|
getRun: vi.fn(),
|
|
listRuns: vi.fn(),
|
|
markSeen: vi.fn(),
|
|
retryRun: vi.fn(),
|
|
reparseRun: vi.fn(),
|
|
cancelRun: vi.fn(),
|
|
cancelDocument: vi.fn(),
|
|
}));
|
|
|
|
vi.mock('../api/shipping.api', () => ({
|
|
createWorkspaceOrderExtractionSubmission: api.createSubmission,
|
|
getWorkspaceShippingOrderExtractionRun: api.getRun,
|
|
listWorkspaceShippingOrderExtractionRuns: api.listRuns,
|
|
markWorkspaceShippingOrderExtractionRunSeen: api.markSeen,
|
|
retryWorkspaceShippingOrderExtractionRun: api.retryRun,
|
|
reparseWorkspaceShippingOrderExtractionRun: api.reparseRun,
|
|
cancelWorkspaceShippingOrderExtractionRun: api.cancelRun,
|
|
cancelWorkspaceShippingOrderExtractionDocument: api.cancelDocument,
|
|
}));
|
|
|
|
const run = (patch: Partial<ShippingOrderExtractionRun>): ShippingOrderExtractionRun => ({
|
|
run_no: 'SNER-1',
|
|
agent_id: 1,
|
|
conversation_id: 'conv-1',
|
|
status: 'queued',
|
|
phase: 'queued',
|
|
intake_nos: ['SNI-1'],
|
|
schema_version_id: 1,
|
|
attempt_count: 0,
|
|
summary: {
|
|
total_documents: 1,
|
|
pending_documents: 1,
|
|
processing_documents: 0,
|
|
completed_documents: 0,
|
|
review_required_documents: 0,
|
|
failed_documents: 0,
|
|
candidate_count: 0,
|
|
},
|
|
current_activity: null,
|
|
available_actions: ['view_details'],
|
|
...patch,
|
|
});
|
|
|
|
const createHarness = () => {
|
|
const messages = ref<ChatMessage[]>([]);
|
|
const conversationId = ref<string | null>(null);
|
|
let localId = 0;
|
|
const options = {
|
|
messages,
|
|
conversationId,
|
|
currentAgentId: computed(() => 1),
|
|
newLocalMessageId: vi.fn((prefix: string) => `${prefix}-${++localId}`),
|
|
saveLocalMessageToBackend: vi.fn(async () => true),
|
|
refreshNoticeIntakeStatuses: vi.fn(async () => undefined),
|
|
getOrderExtractionReview: vi.fn(() => []),
|
|
clearConsumedNoticeAttachments: vi.fn(),
|
|
syncShippingConversationWorkspace: vi.fn(async () => true),
|
|
refreshShippingActions: vi.fn(async () => undefined),
|
|
loadHistory: vi.fn(async () => undefined),
|
|
onConversationResolved: vi.fn(async () => undefined),
|
|
onRetryError: vi.fn(),
|
|
onWorkflowRefresh: vi.fn(),
|
|
getFocusedUserTaskNo: vi.fn(() => null),
|
|
setFocusedUserTaskNo: vi.fn(),
|
|
t: (key: string) => key,
|
|
};
|
|
return { messages, conversationId, options, runs: useShippingOrderExtractionRuns(options) };
|
|
};
|
|
|
|
/** 创建可手工完成的 Promise,用于验证切会话后的迟到响应。 */
|
|
const deferred = <T>() => {
|
|
let resolve!: (value: T) => void;
|
|
const promise = new Promise<T>((done) => { resolve = done; });
|
|
return { promise, resolve };
|
|
};
|
|
|
|
describe('useShippingOrderExtractionRuns lifecycle', () => {
|
|
beforeEach(() => {
|
|
vi.useFakeTimers();
|
|
vi.clearAllMocks();
|
|
});
|
|
|
|
afterEach(() => {
|
|
vi.useRealTimers();
|
|
});
|
|
|
|
it('persists one user message and one Run state card without duplicate submission feedback', async () => {
|
|
const queued = run({
|
|
run_no: 'SNER-START',
|
|
conversation_id: 'conv-created',
|
|
user_task_no: 'OT-SNER-START',
|
|
});
|
|
api.createSubmission.mockResolvedValue({
|
|
decision: 'created',
|
|
user_task_no: 'OT-SNER-START',
|
|
run_no: 'SNER-START',
|
|
created_new: true,
|
|
operation_id: 'op-1',
|
|
});
|
|
api.getRun.mockResolvedValue(queued);
|
|
const harness = createHarness();
|
|
|
|
await harness.runs.startRun('解析附件', ['SNI-1'], [], 'batch-1');
|
|
expect(api.createSubmission).toHaveBeenCalledWith(expect.objectContaining({
|
|
upload_batch_id: 'batch-1',
|
|
intake_nos: ['SNI-1'],
|
|
composer_context_id: expect.stringMatching(/^CMP-/),
|
|
submission_id: expect.stringMatching(/^SUB-/),
|
|
}));
|
|
expect(harness.options.setFocusedUserTaskNo).toHaveBeenCalledWith('OT-SNER-START');
|
|
expect(harness.conversationId.value).toBe('conv-created');
|
|
expect(harness.options.onConversationResolved).toHaveBeenCalledWith('conv-created');
|
|
expect(harness.messages.value.map((item) => item.payload?.formId)).toEqual([
|
|
'shipping-order-extraction-user:SNER-START',
|
|
'shipping-order-extraction-run:SNER-START',
|
|
]);
|
|
expect(harness.options.saveLocalMessageToBackend).toHaveBeenCalledTimes(2);
|
|
|
|
await vi.advanceTimersByTimeAsync(1000);
|
|
expect(api.getRun).toHaveBeenCalledWith('SNER-START', expect.any(AbortSignal));
|
|
expect(harness.options.saveLocalMessageToBackend).toHaveBeenCalledTimes(2);
|
|
harness.runs.stopPolling();
|
|
});
|
|
|
|
it('merges sibling Runs from one upload batch into one chat status card', async () => {
|
|
const first = Object.assign(run({
|
|
run_no: 'SNER-BATCH-1',
|
|
conversation_id: 'conv-batch',
|
|
intake_nos: ['SNI-BATCH-1'],
|
|
summary: {
|
|
total_documents: 1,
|
|
pending_documents: 1,
|
|
processing_documents: 0,
|
|
completed_documents: 0,
|
|
review_required_documents: 0,
|
|
failed_documents: 0,
|
|
candidate_count: 0,
|
|
},
|
|
documents: [{
|
|
unit_id: 1,
|
|
document_id: 101,
|
|
file_name: 'notice-a.pdf',
|
|
status: 'queued',
|
|
line_count: 0,
|
|
email_supplement: { status: 'none', relation_codes: [] },
|
|
available_actions: [],
|
|
}],
|
|
}), { upload_batch_id: 'upload-batch-1' });
|
|
const second = Object.assign(run({
|
|
run_no: 'SNER-BATCH-2',
|
|
conversation_id: 'conv-batch',
|
|
intake_nos: ['SNI-BATCH-2'],
|
|
summary: {
|
|
total_documents: 1,
|
|
pending_documents: 0,
|
|
processing_documents: 1,
|
|
completed_documents: 0,
|
|
review_required_documents: 0,
|
|
failed_documents: 0,
|
|
candidate_count: 0,
|
|
},
|
|
documents: [{
|
|
unit_id: 2,
|
|
document_id: 102,
|
|
file_name: 'notice-b.pdf',
|
|
status: 'processing',
|
|
line_count: 0,
|
|
email_supplement: { status: 'none', relation_codes: [] },
|
|
available_actions: [],
|
|
}],
|
|
}), { upload_batch_id: 'upload-batch-1' });
|
|
api.createSubmission.mockResolvedValue({
|
|
decision: 'created',
|
|
user_task_no: null,
|
|
run_no: first.run_no,
|
|
created_new: true,
|
|
operation_id: 'op-batch',
|
|
});
|
|
api.getRun.mockResolvedValue(first);
|
|
api.listRuns.mockResolvedValue({ items: [first, second] });
|
|
const harness = createHarness();
|
|
|
|
await harness.runs.startRun('', ['SNI-BATCH-1', 'SNI-BATCH-2'], [], 'upload-batch-1');
|
|
|
|
const cards = harness.messages.value.filter((message) => message.shipping_order_extraction_state);
|
|
expect(cards).toHaveLength(1);
|
|
expect(cards[0]?.shipping_order_extraction_state?.summary).toMatchObject({
|
|
totalDocuments: 2,
|
|
pendingDocuments: 1,
|
|
processingDocuments: 1,
|
|
});
|
|
expect(cards[0]?.shipping_order_extraction_state?.documents?.map((item) => item.fileName)).toEqual([
|
|
'notice-a.pdf',
|
|
'notice-b.pdf',
|
|
]);
|
|
harness.runs.stopPolling();
|
|
});
|
|
|
|
it('keeps an appended submission in the user message and the existing Run state card only', async () => {
|
|
const queued = run({
|
|
run_no: 'SNER-APPENDED',
|
|
conversation_id: 'conv-existing',
|
|
user_task_no: 'OT-EXISTING',
|
|
});
|
|
api.createSubmission.mockResolvedValue({
|
|
decision: 'appended',
|
|
user_task_no: 'OT-EXISTING',
|
|
run_no: 'SNER-APPENDED',
|
|
created_new: false,
|
|
operation_id: 'op-appended',
|
|
});
|
|
api.getRun.mockResolvedValue(queued);
|
|
const harness = createHarness();
|
|
harness.conversationId.value = 'conv-existing';
|
|
|
|
await harness.runs.startRun('追加附件', ['SNI-1'], []);
|
|
|
|
expect(harness.messages.value.map((item) => item.payload?.formId)).toEqual([
|
|
'shipping-order-extraction-user:SNER-APPENDED',
|
|
'shipping-order-extraction-run:SNER-APPENDED',
|
|
]);
|
|
expect(harness.messages.value[0]?.payload?.submission_decision).toBe('appended');
|
|
expect(harness.options.saveLocalMessageToBackend).toHaveBeenCalledTimes(2);
|
|
harness.runs.stopPolling();
|
|
});
|
|
|
|
it('persists an attachment-only user message when the run starts without a text note', async () => {
|
|
const queued = run({
|
|
run_no: 'SNER-EMPTY-NOTE',
|
|
conversation_id: 'conv-empty-note',
|
|
user_task_no: 'OT-SNER-EMPTY-NOTE',
|
|
});
|
|
api.createSubmission.mockResolvedValue({
|
|
decision: 'created',
|
|
user_task_no: 'OT-SNER-EMPTY-NOTE',
|
|
run_no: 'SNER-EMPTY-NOTE',
|
|
created_new: true,
|
|
operation_id: 'op-empty',
|
|
});
|
|
api.getRun.mockResolvedValue(queued);
|
|
const harness = createHarness();
|
|
|
|
await harness.runs.startRun('', ['SNI-1'], [{
|
|
name: 'orders.eml',
|
|
size: 128,
|
|
extension: 'eml',
|
|
type: 'document',
|
|
source: 'shipping_notice',
|
|
}]);
|
|
|
|
expect(harness.messages.value[0]).toMatchObject({
|
|
role: 'user',
|
|
content: '',
|
|
attachments: [{
|
|
name: 'orders.eml',
|
|
size: 128,
|
|
extension: 'eml',
|
|
type: 'document',
|
|
source: 'shipping_notice',
|
|
}],
|
|
});
|
|
expect(harness.options.saveLocalMessageToBackend).toHaveBeenNthCalledWith(
|
|
1,
|
|
expect.objectContaining({ content: '' }),
|
|
undefined,
|
|
);
|
|
expect(harness.messages.value).toHaveLength(2);
|
|
harness.runs.stopPolling();
|
|
});
|
|
|
|
it('absorbs restore failures and ignores an old conversation late response', async () => {
|
|
const pending = deferred<ShippingOrderExtractionRun>();
|
|
api.listRuns
|
|
.mockResolvedValueOnce({ items: [run({ run_no: 'SNER-OLD', conversation_id: 'conv-old', status: 'processing' })] })
|
|
.mockRejectedValueOnce(new Error('offline'));
|
|
api.getRun.mockReturnValueOnce(pending.promise);
|
|
const harness = createHarness();
|
|
harness.conversationId.value = 'conv-old';
|
|
await harness.runs.restoreForConversation('conv-old');
|
|
await vi.advanceTimersByTimeAsync(1000);
|
|
|
|
harness.conversationId.value = 'conv-new';
|
|
await expect(harness.runs.restoreForConversation('conv-new')).resolves.toBeUndefined();
|
|
pending.resolve(run({ run_no: 'SNER-OLD', conversation_id: 'conv-old', status: 'completed' }));
|
|
await Promise.resolve();
|
|
expect(harness.runs.getActiveRunNo()).toBe('');
|
|
expect(harness.messages.value).toHaveLength(1);
|
|
expect(harness.messages.value[0]?.shipping_order_extraction_state?.status).toBe('processing');
|
|
});
|
|
|
|
it('notifies session work items refresh after restoring a terminal run', async () => {
|
|
api.listRuns.mockResolvedValue({
|
|
items: [run({ run_no: 'SNER-DONE', status: 'completed', phase: 'completed' })],
|
|
});
|
|
const harness = createHarness();
|
|
harness.conversationId.value = 'conv-1';
|
|
await harness.runs.restoreForConversation('conv-1');
|
|
expect(harness.options.onWorkflowRefresh).toHaveBeenCalled();
|
|
});
|
|
|
|
it('aborts a hanging Run query after ten seconds and keeps polling as a transport failure', async () => {
|
|
api.createSubmission.mockResolvedValue({
|
|
decision: 'created',
|
|
user_task_no: 'OT-SNER-TIMEOUT',
|
|
run_no: 'SNER-TIMEOUT',
|
|
created_new: true,
|
|
operation_id: 'op-timeout',
|
|
});
|
|
api.getRun.mockResolvedValue(run({ run_no: 'SNER-TIMEOUT', conversation_id: 'conv-timeout' }));
|
|
// 首次 GET(提交后投影)已返回;后续轮询挂起直至 Abort。
|
|
let pollCalls = 0;
|
|
api.getRun.mockImplementation((_runNo: string, signal?: AbortSignal) => {
|
|
pollCalls += 1;
|
|
if (pollCalls === 1) {
|
|
return Promise.resolve(run({ run_no: 'SNER-TIMEOUT', conversation_id: 'conv-timeout' }));
|
|
}
|
|
return new Promise((_resolve, reject) => {
|
|
signal?.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError')), { once: true });
|
|
});
|
|
});
|
|
const harness = createHarness();
|
|
await harness.runs.startRun('解析附件', ['SNI-1'], []);
|
|
|
|
await vi.advanceTimersByTimeAsync(11000);
|
|
expect(api.getRun).toHaveBeenCalledWith('SNER-TIMEOUT', expect.any(AbortSignal));
|
|
expect(harness.runs.getActiveRunNo()).toBe('SNER-TIMEOUT');
|
|
const runMessage = harness.messages.value.find((item) => item.shipping_order_extraction_state);
|
|
expect(runMessage?.shipping_order_extraction_state?.status).toBe('queued');
|
|
harness.runs.stopPolling();
|
|
});
|
|
|
|
it('retries a failed Run in place and resumes polling without creating a new user message', async () => {
|
|
const failed = run({ run_no: 'SNER-RETRY', status: 'failed', phase: 'failed', error: { code: 'SHIPPING_NOTICE.ORDER_EXTRACTION_FAILED' } });
|
|
const queued = run({ run_no: 'SNER-RETRY', status: 'queued', phase: 'manual_retry_queued', error: null });
|
|
api.listRuns.mockResolvedValue({ items: [failed] });
|
|
api.retryRun.mockResolvedValue({ run: queued, reused: false });
|
|
api.getRun.mockResolvedValue(queued);
|
|
const harness = createHarness();
|
|
harness.conversationId.value = 'conv-1';
|
|
await harness.runs.restoreForConversation('conv-1');
|
|
|
|
await expect(harness.runs.retryRun('SNER-RETRY')).resolves.toBe(true);
|
|
|
|
expect(api.retryRun).toHaveBeenCalledWith('SNER-RETRY');
|
|
expect(harness.options.refreshNoticeIntakeStatuses).toHaveBeenCalledTimes(2);
|
|
expect(harness.messages.value).toHaveLength(1);
|
|
expect(harness.messages.value[0]?.shipping_order_extraction_state?.status).toBe('queued');
|
|
expect(harness.runs.getActiveRunNo()).toBe('SNER-RETRY');
|
|
harness.runs.stopPolling();
|
|
});
|
|
|
|
it('reports a retry API error and leaves the failed state available for another retry', async () => {
|
|
api.retryRun.mockRejectedValue(new Error('retry unavailable'));
|
|
const harness = createHarness();
|
|
|
|
await expect(harness.runs.retryRun('SNER-FAILED')).resolves.toBe(false);
|
|
|
|
expect(harness.options.onRetryError).toHaveBeenCalledWith('retry unavailable');
|
|
expect(harness.runs.getActiveRunNo()).toBe('');
|
|
});
|
|
|
|
it('creates a new Run for reidentification and switches polling to the new version', async () => {
|
|
const source = run({ run_no: 'SNER-SOURCE', status: 'review_required' });
|
|
const replacement = run({
|
|
run_no: 'SNER-REPLACEMENT', status: 'queued',
|
|
reparse: { source_run_no: 'SNER-SOURCE', reason: 'field_mapping_error' },
|
|
});
|
|
api.listRuns.mockResolvedValue({ items: [source] });
|
|
api.reparseRun.mockResolvedValue({ run: replacement, reused: false });
|
|
api.getRun.mockResolvedValue(replacement);
|
|
const harness = createHarness();
|
|
harness.conversationId.value = 'conv-1';
|
|
await harness.runs.restoreForConversation('conv-1');
|
|
|
|
await expect(harness.runs.reparseRun('SNER-SOURCE', 'field_mapping_error')).resolves.toBe(true);
|
|
|
|
expect(api.reparseRun).toHaveBeenCalledWith('SNER-SOURCE', { reason: 'field_mapping_error' });
|
|
expect(harness.runs.getActiveRunNo()).toBe('SNER-REPLACEMENT');
|
|
expect(harness.messages.value).toHaveLength(2);
|
|
harness.runs.stopPolling();
|
|
});
|
|
});
|
|
|
|
|
|
describe('mapOrderExtractionRunToMessageState', () => {
|
|
it('maps queued and processing to the new Run summary state', () => {
|
|
expect(mapOrderExtractionRunToMessageState(run({
|
|
status: 'processing',
|
|
selection_plan: {
|
|
max_initial_attachments: 2,
|
|
max_initial_concurrency: 2,
|
|
expansion_batch_size: 2,
|
|
max_total_attachments: 6,
|
|
total_attachment_count: 5,
|
|
eligible_attachment_count: 4,
|
|
selected_attachment_count: 2,
|
|
planned_attachment_count: 4,
|
|
pending_expansion_attachment_count: 2,
|
|
pending_expansion_batches: { '2': 2 },
|
|
skipped_attachment_count: 1,
|
|
duplicate_attachment_count: 1,
|
|
budget_limited_attachment_count: 0,
|
|
group_count: 2,
|
|
},
|
|
current_activity: { unit_id: 7, file_name: 'PO-1.pdf', event_code: 'profile_matching' },
|
|
summary: {
|
|
total_documents: 3,
|
|
pending_documents: 0,
|
|
processing_documents: 1,
|
|
completed_documents: 2,
|
|
review_required_documents: 0,
|
|
failed_documents: 0,
|
|
candidate_count: 2,
|
|
},
|
|
}))).toMatchObject({
|
|
status: 'processing',
|
|
terminal: false,
|
|
summary: {
|
|
totalDocuments: 3,
|
|
processingDocuments: 1,
|
|
completedDocuments: 2,
|
|
candidateCount: 2,
|
|
},
|
|
selectionPlan: {
|
|
expansionBatchSize: 2,
|
|
maxTotalAttachments: 6,
|
|
plannedAttachmentCount: 4,
|
|
pendingExpansionAttachmentCount: 2,
|
|
pendingExpansionBatches: { '2': 2 },
|
|
},
|
|
currentActivity: { unitId: 7, fileName: 'PO-1.pdf', eventCode: 'profile_matching' },
|
|
});
|
|
});
|
|
|
|
it('persists a changed summary projection even when Run status is unchanged', async () => {
|
|
vi.useFakeTimers();
|
|
const first = run({
|
|
run_no: 'SNER-PROGRESS',
|
|
status: 'processing',
|
|
current_activity: { unit_id: 1, file_name: 'PO-A.pdf', event_code: 'document_queued' },
|
|
});
|
|
const second = run({
|
|
run_no: 'SNER-PROGRESS',
|
|
status: 'processing',
|
|
current_activity: { unit_id: 1, file_name: 'PO-A.pdf', event_code: 'profile_matching' },
|
|
summary: {
|
|
total_documents: 2,
|
|
pending_documents: 0,
|
|
processing_documents: 1,
|
|
completed_documents: 1,
|
|
review_required_documents: 0,
|
|
failed_documents: 0,
|
|
candidate_count: 1,
|
|
},
|
|
});
|
|
api.listRuns.mockResolvedValue({ items: [first] });
|
|
api.getRun.mockResolvedValueOnce(second);
|
|
const harness = createHarness();
|
|
harness.conversationId.value = 'conv-1';
|
|
|
|
await harness.runs.restoreForConversation('conv-1');
|
|
expect(harness.options.saveLocalMessageToBackend).toHaveBeenCalledTimes(1);
|
|
await vi.advanceTimersByTimeAsync(1000);
|
|
|
|
expect(harness.options.saveLocalMessageToBackend).toHaveBeenCalledTimes(2);
|
|
expect(harness.messages.value[0]?.shipping_order_extraction_state?.currentActivity?.eventCode).toBe('profile_matching');
|
|
expect(harness.messages.value[0]?.shipping_order_extraction_state?.summary.completedDocuments).toBe(1);
|
|
harness.runs.stopPolling();
|
|
vi.useRealTimers();
|
|
});
|
|
|
|
it('persists again when only handling_items or primary_notice change', async () => {
|
|
vi.useFakeTimers();
|
|
const first = run({
|
|
run_no: 'SNER-HANDLING',
|
|
status: 'processing',
|
|
primary_notice: 'candidate_conflict',
|
|
handling_items: [{
|
|
category: 'candidate_conflict',
|
|
count: 1,
|
|
reason_codes: ['email_supplement_conflict'],
|
|
affected_refs: [{ type: 'candidate', candidate_no: 'C-1' }],
|
|
primary_action: 'review_candidate',
|
|
}],
|
|
});
|
|
const second = run({
|
|
run_no: 'SNER-HANDLING',
|
|
status: 'processing',
|
|
primary_notice: 'auto_freeze_blocked',
|
|
handling_items: [{
|
|
category: 'auto_freeze_blocked',
|
|
count: 1,
|
|
reason_codes: ['profile_not_auto_freeze_approved'],
|
|
affected_refs: [{ type: 'task', task_no: 'ST-9', candidate_no: 'C-2' }],
|
|
primary_action: 'view_details',
|
|
}],
|
|
});
|
|
api.listRuns.mockResolvedValue({ items: [first] });
|
|
api.getRun.mockResolvedValueOnce(second);
|
|
const harness = createHarness();
|
|
harness.conversationId.value = 'conv-1';
|
|
|
|
await harness.runs.restoreForConversation('conv-1');
|
|
expect(harness.options.saveLocalMessageToBackend).toHaveBeenCalledTimes(1);
|
|
await vi.advanceTimersByTimeAsync(1000);
|
|
|
|
// 关键断言:处理说明独立变化也必须重新持久化,历史会话才能恢复最新原因与影响对象。
|
|
expect(harness.options.saveLocalMessageToBackend).toHaveBeenCalledTimes(2);
|
|
expect(harness.messages.value[0]?.shipping_order_extraction_state?.primaryNotice).toBe('auto_freeze_blocked');
|
|
expect(harness.messages.value[0]?.shipping_order_extraction_state?.handlingItems?.[0]?.affectedRefs?.[0]).toMatchObject({
|
|
type: 'task',
|
|
task_no: 'ST-9',
|
|
});
|
|
harness.runs.stopPolling();
|
|
vi.useRealTimers();
|
|
});
|
|
|
|
it('merges duplicate local cards for one Run when a terminal update arrives', async () => {
|
|
vi.useFakeTimers();
|
|
const active = run({ run_no: 'SNER-DUPLICATE', status: 'processing' });
|
|
const failed = run({
|
|
run_no: 'SNER-DUPLICATE', status: 'failed', phase: 'failed', error: { code: 'SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_FAILED' },
|
|
});
|
|
api.listRuns.mockResolvedValue({ items: [active] });
|
|
api.getRun.mockResolvedValue(failed);
|
|
const harness = createHarness();
|
|
harness.conversationId.value = 'conv-1';
|
|
harness.messages.value.push({
|
|
role: 'assistant', type: 'text', content: '', local_id: 'legacy-duplicate', local_only: true,
|
|
shipping_order_extraction_state: mapOrderExtractionRunToMessageState(active),
|
|
payload: { formId: 'legacy-state-card', order_extraction_run_no: 'SNER-DUPLICATE' },
|
|
});
|
|
|
|
await harness.runs.restoreForConversation('conv-1');
|
|
await vi.advanceTimersByTimeAsync(1000);
|
|
|
|
const cards = harness.messages.value.filter((item) => item.shipping_order_extraction_state);
|
|
expect(cards).toHaveLength(1);
|
|
expect(cards[0]?.shipping_order_extraction_state?.status).toBe('failed');
|
|
harness.runs.stopPolling();
|
|
vi.useRealTimers();
|
|
});
|
|
|
|
it('refreshes Intake candidates and persists them on the terminal Run card without page reload', async () => {
|
|
vi.useFakeTimers();
|
|
const active = run({ run_no: 'SNER-REVIEW', status: 'processing' });
|
|
const terminal = run({
|
|
run_no: 'SNER-REVIEW',
|
|
status: 'review_required',
|
|
summary: {
|
|
total_documents: 1,
|
|
pending_documents: 0,
|
|
processing_documents: 0,
|
|
completed_documents: 0,
|
|
review_required_documents: 1,
|
|
failed_documents: 0,
|
|
candidate_count: 0,
|
|
},
|
|
result: { pending_count: 1 },
|
|
available_actions: ['view_details', 'enter_manual_review'],
|
|
});
|
|
api.listRuns.mockResolvedValue({ items: [active] });
|
|
api.getRun.mockResolvedValue(terminal);
|
|
const harness = createHarness();
|
|
harness.options.getOrderExtractionReview.mockReturnValue([{
|
|
intakeNo: 'SNI-1',
|
|
originalFilename: 'notice.eml',
|
|
candidates: [{
|
|
candidateNo: 'SNC-1', validationStatus: 'needs_review', selected: true,
|
|
conflicts: [], businessSummary: { po_number: 'PO-1', lines: [] },
|
|
}],
|
|
}]);
|
|
harness.conversationId.value = 'conv-1';
|
|
|
|
await harness.runs.restoreForConversation('conv-1');
|
|
await vi.advanceTimersByTimeAsync(1000);
|
|
|
|
expect(harness.options.refreshNoticeIntakeStatuses).toHaveBeenCalled();
|
|
expect(harness.messages.value[0]?.payload).toMatchObject({
|
|
shipping_order_extraction_review: [{ intakeNo: 'SNI-1', candidates: [{ candidateNo: 'SNC-1' }] }],
|
|
});
|
|
harness.runs.stopPolling();
|
|
});
|
|
|
|
it('maps completed summaries without guessing from text', () => {
|
|
expect(mapOrderExtractionRunToMessageState(run({
|
|
status: 'completed',
|
|
summary: {
|
|
total_documents: 3,
|
|
pending_documents: 0,
|
|
processing_documents: 0,
|
|
completed_documents: 3,
|
|
review_required_documents: 0,
|
|
failed_documents: 0,
|
|
candidate_count: 3,
|
|
},
|
|
available_actions: ['view_details'],
|
|
}))).toMatchObject({
|
|
status: 'completed',
|
|
terminal: true,
|
|
summary: { completedDocuments: 3, candidateCount: 3 },
|
|
availableActions: ['view_details'],
|
|
});
|
|
});
|
|
|
|
it('maps review_required and failed to distinct terminal states', () => {
|
|
expect(mapOrderExtractionRunToMessageState(run({
|
|
status: 'review_required',
|
|
summary: {
|
|
total_documents: 3,
|
|
pending_documents: 0,
|
|
processing_documents: 0,
|
|
completed_documents: 0,
|
|
review_required_documents: 3,
|
|
failed_documents: 0,
|
|
candidate_count: 0,
|
|
},
|
|
available_actions: ['view_details', 'enter_manual_review'],
|
|
}))).toMatchObject({
|
|
status: 'review_required',
|
|
terminal: true,
|
|
summary: { reviewRequiredDocuments: 3 },
|
|
availableActions: ['view_details', 'enter_manual_review'],
|
|
});
|
|
expect(mapOrderExtractionRunToMessageState(run({
|
|
status: 'failed', error: { code: 'X' },
|
|
}))).toMatchObject({ status: 'failed', errorCode: 'X', terminal: true });
|
|
});
|
|
|
|
it('acknowledges a terminal Run only after it is restored into the active conversation', async () => {
|
|
const terminal = run({ run_no: 'SNER-SEEN', status: 'completed' });
|
|
api.listRuns.mockResolvedValue({ items: [terminal] });
|
|
api.markSeen.mockResolvedValue({ seen: true });
|
|
const harness = createHarness();
|
|
harness.conversationId.value = 'conv-1';
|
|
|
|
await harness.runs.restoreForConversation('conv-1');
|
|
|
|
expect(api.markSeen).toHaveBeenCalledWith('SNER-SEEN');
|
|
expect(harness.options.loadHistory).toHaveBeenCalledTimes(2);
|
|
});
|
|
});
|