refactor(agent, shipping): 简化代理模型并完善订单抽取业务

- 移除 Agent 的 exposure_mode 与 internal_executor 相关逻辑,清理关联的过滤、序列化代码
- 删除废弃的 AgentRuntimeBinding 模型及其依赖
- 新增订单抽取上传批次、请求快照等数据库迁移与业务逻辑
- 修复附件完整性检测、订单抽取状态映射问题
- 更新多语言错误文案与前端单元测试配置
- 清理平台配置中不再使用的暴露模式配置
This commit is contained in:
hugo committed 2026-07-28 20:25:48 +08:00
1 parent 1f3ecb87b7
commit 61ac6403c4
159 files changed
+12883 -5099

No files matched your search

@@ -0,0 +1,46 @@
/**
* features/chat/shipping/orderExtractionTimeline.spec.ts
* 用途:验证订单抽取 Run 时间线事件分类纯函数。
* 依赖:Vitest、progress-event DTO 类型、orderExtractionTimeline 纯函数。
* 逻辑:卡住业务复核、技术失败、预算停止和普通进度的最小分类契约。
*/
import { describe, expect, it } from 'vitest';
import type { ShippingOrderExtractionProgressEvent } from '../types/shipping.api.types';
import { classifyOrderExtractionTimelineEvent } from './orderExtractionTimeline';
const event = (patch: Partial<ShippingOrderExtractionProgressEvent> = {}): ShippingOrderExtractionProgressEvent => ({
event_code: 'initial_wave_started',
status: 'completed',
occurred_at: '2026-07-28T10:00:00Z',
...patch,
});
describe('classifyOrderExtractionTimelineEvent', () => {
it('classifies review and expansion reasons as business timeline items', () => {
expect(classifyOrderExtractionTimelineEvent(event({
event_code: 'expansion_wave_started',
summary: { reason_codes: ['required_field_missing'] },
}))).toBe('business');
});
it('classifies technical failure codes as technical timeline items', () => {
expect(classifyOrderExtractionTimelineEvent(event({
event_code: 'technical_failed',
reason_code: 'SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT',
}))).toBe('technical');
});
it('classifies budget stop reasons as budget timeline items', () => {
expect(classifyOrderExtractionTimelineEvent(event({
event_code: 'budget_stopped',
reason_code: 'budget_initial_limit',
}))).toBe('budget');
});
it('keeps neutral progress events in the progress bucket', () => {
expect(classifyOrderExtractionTimelineEvent(event({
event_code: 'plan_created',
summary: { selection_batch: 1 },
}))).toBe('progress');
});
});
@@ -0,0 +1,74 @@
/**
* features/chat/shipping/orderExtractionTimeline.ts
* 用途:归类订单抽取 Run 时间线事件,供卡片/抽屉统一展示标签。
* 依赖:订单抽取 progress-event DTO(纯函数,不依赖 Vue)。
* 逻辑:区分业务复核、技术失败、预算停止与普通进度,避免组件散落条件分支。
*/
import type { ShippingOrderExtractionProgressEvent } from '../types/shipping.api.types';
export type OrderExtractionTimelineCategory = 'business' | 'technical' | 'budget' | 'progress';
const TECHNICAL_EVENT_CODES = new Set([
'technical_retrying',
'technical_failed',
]);
const BUDGET_EVENT_CODES = new Set([
'budget_stopped',
]);
const BUSINESS_EVENT_CODES = new Set([
'review_required',
'expansion_wave_started',
]);
const BUDGET_REASON_CODES = new Set([
'budget_initial_limit',
'budget_total_limit',
]);
const TECHNICAL_REASON_PREFIXES = [
'SHIPPING_NOTICE.',
'SYSTEM.',
];
const collectEventReasonCodes = (event: ShippingOrderExtractionProgressEvent): string[] => {
const summary = event.summary && typeof event.summary === 'object'
? event.summary as Record<string, unknown>
: {};
const reasonCodes = [
String(event.reason_code || '').trim(),
...(Array.isArray(summary.reason_codes) ? summary.reason_codes.map((item) => String(item || '').trim()) : []),
].filter(Boolean);
return Array.from(new Set(reasonCodes));
};
export function classifyOrderExtractionTimelineEvent(
event: ShippingOrderExtractionProgressEvent,
): OrderExtractionTimelineCategory {
const eventCode = String(event.event_code || '').trim();
const reasonCodes = collectEventReasonCodes(event);
if (
TECHNICAL_EVENT_CODES.has(eventCode)
|| reasonCodes.some((code) => TECHNICAL_REASON_PREFIXES.some((prefix) => code.startsWith(prefix)))
) {
return 'technical';
}
if (
BUDGET_EVENT_CODES.has(eventCode)
|| reasonCodes.some((code) => BUDGET_REASON_CODES.has(code))
) {
return 'budget';
}
if (
BUSINESS_EVENT_CODES.has(eventCode)
|| reasonCodes.some((code) => !TECHNICAL_REASON_PREFIXES.some((prefix) => code.startsWith(prefix)))
) {
return 'business';
}
return 'progress';
}
@@ -38,6 +38,16 @@ export function isShippingNoticeAttachmentParseIncomplete(
summary?: ShippingNoticeParseSummary | null,
): boolean {
if (!summary) return false;
const previewStatus = String(summary.preview_status || '').trim().toLowerCase();
if (summary.technical_failure) {
return true;
}
if (previewStatus === 'technical_failed' || previewStatus === 'directory_incomplete') {
return true;
}
if (summary.attachment_directory_complete === false || summary.ready_for_extraction === false) {
return true;
}
const warnings = summary.warnings || [];
if (warnings.some((item) => isBlockingWarning(String(item || '')))) {
return true;
@@ -1,17 +1,11 @@
/**
* features/chat/shipping/useChatShippingSendHandler.spec.ts
* 用途:验证上传预处理与点击发送完整抽取链路,以及建批提交中的并发拦截。
* 用途:验证阶段 2 发送语义,只冻结当前输入框这批 Intake,并允许空备注启动识别。
*/
import { computed, ref } from 'vue';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { createShippingSendHandlers, type ShippingSendHandlerContext } from './useChatShippingSendHandler';
const isShippingNoticeBatchSubmitting = vi.hoisted(() => vi.fn(() => false));
vi.mock('./useChatShippingUploadHandler', () => ({
isShippingNoticeBatchSubmitting,
}));
const createContext = (
overrides: Partial<ShippingSendHandlerContext> = {},
): ShippingSendHandlerContext => ({
@@ -22,14 +16,7 @@ const createContext = (
conversationId: ref('conv-send'),
history: ref([]),
input: ref(''),
attachments: ref([{
id: 'local-notice',
kind: 'local',
file: new File(['notice'], 'notice.txt', { type: 'text/plain' }),
type: 'document',
uploadStatus: 'waiting',
uploadProgress: 0,
}]),
attachments: ref([]),
shippingAutoFlowRequested: ref(true),
resolvedShippingTaskId: ref(''),
getActiveShippingBatchNo: () => '',
@@ -39,7 +26,7 @@ const createContext = (
getActiveShippingTaskId: () => '',
lastAssistantMessageContent: () => '',
lastAssistantShippingActions: () => [],
sendMessage: vi.fn(async () => true),
sendMessage: vi.fn(async () => ({ ok: true } as never)),
buildFileSpecsForSend: vi.fn(async () => []),
loadHistory: vi.fn(async () => undefined),
sendShippingMenuMessage: vi.fn(async () => undefined),
@@ -50,9 +37,17 @@ const createContext = (
handleShippingMenuAction: vi.fn(async () => undefined),
handleShippingAutoUploadFile: vi.fn(async () => undefined),
handleShippingAutoUploadNoticeBatch: vi.fn(async () => undefined),
isShippingNoticeBatchSubmitting: () => isShippingNoticeBatchSubmitting(),
markOrderExtractionStarted: vi.fn(),
rollbackOrderExtractionStarted: vi.fn(),
isShippingNoticeBatchSubmitting: () => false,
hasBlockingNoticeIntake: () => false,
hasNoticeIntakeFailures: () => false,
hasBlockingNoticeDuplicates: () => false,
hasCandidateReviewIssues: () => false,
hasSelectedNoticeCandidates: () => false,
openShippingDuplicateDialog: vi.fn(),
getParsedIntakeNos: () => [],
startOrderExtractionRun: vi.fn(async () => true),
applyShippingMessageRecovery: vi.fn(async () => false),
applyShippingBatchSnapshot: vi.fn(() => false),
syncShippingConversationWorkspace: vi.fn(async () => true),
refreshShippingActions: vi.fn(async () => undefined),
shippingSuggestedPrompt: computed(() => ''),
@@ -65,211 +60,158 @@ const createContext = (
describe('useChatShippingSendHandler', () => {
beforeEach(() => {
isShippingNoticeBatchSubmitting.mockReset();
isShippingNoticeBatchSubmitting.mockReturnValue(false);
vi.clearAllMocks();
});
it('consumes send while notice batch is submitting and does not call sendMessage', async () => {
isShippingNoticeBatchSubmitting.mockReturnValue(true);
const ctx = createContext();
it('blocks send while current notice attachments are still previewing', async () => {
const ctx = createContext({
attachments: ref([{
id: 'notice-waiting',
kind: 'shipping_notice',
type: 'document',
uploadStatus: 'uploaded',
parseStatus: 'parsing',
uploadProgress: 100,
originalFilename: 'orders.eml',
fileSize: 100,
intakeNo: 'SNI-WAITING',
}]),
hasBlockingNoticeIntake: () => true,
});
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
expect(consumed).toBe(true);
expect(ctx.sendMessage).not.toHaveBeenCalled();
expect(ctx.handleShippingAutoUploadNoticeBatch).not.toHaveBeenCalled();
expect(ctx.msg.info).toHaveBeenCalledWith('chat.shippingNoticeBatchSubmitting');
expect(ctx.startOrderExtractionRun).not.toHaveBeenCalled();
expect(ctx.msg.info).toHaveBeenCalledWith('chat.shippingNoticeWaitingForParse');
});
it('sends parsed intakes to the existing Chatflow without requiring upload-time candidates', async () => {
const completionOrder: string[] = [];
const attachment = {
id: 'notice-1',
it('starts extraction only for the current parsed intake batch and removes only submitted notice attachments', async () => {
const currentNotice = {
id: 'notice-current',
kind: 'shipping_notice' as const,
type: 'document' as const,
uploadStatus: 'uploaded' as const,
parseStatus: 'parsed' as const,
orderExtractionStatus: 'not_started' as const,
uploadProgress: 100,
originalFilename: 'orders.eml',
originalFilename: 'orders-current.eml',
fileSize: 100,
intakeNo: 'SNI-1',
intakeNo: 'SNI-CURRENT',
uploadBatchId: 'batch-current',
};
const ctx = createContext({
attachments: ref([attachment]),
hasCandidateReviewIssues: () => true,
hasSelectedNoticeCandidates: () => true,
getParsedIntakeNos: () => ['SNI-1'],
applyShippingBatchSnapshot: vi.fn(() => { completionOrder.push('snapshot'); return true; }),
refreshNoticeIntakeStatuses: vi.fn(async () => { completionOrder.push('intakes'); }),
syncShippingConversationWorkspace: vi.fn(async () => { completionOrder.push('workspace'); return true; }),
clearConsumedNoticeAttachments: vi.fn(() => { completionOrder.push('clear'); }),
refreshShippingActions: vi.fn(async () => { completionOrder.push('actions'); }),
});
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
expect(consumed).toBe(true);
expect(ctx.handleShippingAutoUploadNoticeBatch).not.toHaveBeenCalled();
expect(ctx.sendMessage).toHaveBeenCalledWith(
'chat.shippingOrderExtractionDefaultPrompt',
1,
'',
[],
{
shipping_intake_nos: ['SNI-1'],
display_query: 'chat.shippingOrderExtractionDefaultPrompt',
},
expect.objectContaining({
userAttachments: [{
name: 'orders.eml',
size: 100,
extension: 'eml',
type: 'document',
source: 'shipping_notice',
}],
onAssistantMessageFinished: expect.any(Function),
}),
);
expect(ctx.markOrderExtractionStarted).toHaveBeenCalledWith(['SNI-1']);
const hooks = vi.mocked(ctx.sendMessage).mock.calls[0]?.[5];
const assistantMessage = { role: 'assistant', content: '已打开已有任务' } as const;
await hooks?.onAssistantMessageFinished?.(assistantMessage, []);
expect(ctx.applyShippingBatchSnapshot).toHaveBeenCalledWith(assistantMessage);
expect(completionOrder).toEqual(['snapshot', 'intakes', 'workspace', 'clear', 'actions']);
expect(ctx.syncShippingConversationWorkspace).toHaveBeenCalledWith({ preferLatest: true });
});
it('uses the user query for full extraction even when no candidate exists before send', async () => {
const attachment = {
id: 'notice-1',
const laterNotice = {
id: 'notice-later',
kind: 'shipping_notice' as const,
type: 'document' as const,
uploadStatus: 'uploaded' as const,
parseStatus: 'parsed' as const,
orderExtractionStatus: 'not_started' as const,
uploadProgress: 100,
originalFilename: 'orders.eml',
fileSize: 100,
intakeNo: 'SNI-1',
originalFilename: 'orders-later.eml',
fileSize: 120,
intakeNo: 'SNI-LATER',
uploadBatchId: 'batch-later',
};
const otherAttachment = {
id: 'local-note',
kind: 'local' as const,
file: new File(['inventory'], 'inventory.xlsx', { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }),
type: 'document' as const,
uploadStatus: 'waiting' as const,
uploadProgress: 0,
};
const attachments = ref([currentNotice, laterNotice, otherAttachment]);
const startOrderExtractionRun = vi.fn(async () => true);
const ctx = createContext({
attachments: ref([attachment]),
hasCandidateReviewIssues: () => false,
hasSelectedNoticeCandidates: () => false,
getParsedIntakeNos: () => ['SNI-1'],
attachments,
getParsedIntakeNos: () => ['SNI-CURRENT'],
startOrderExtractionRun,
});
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '请解析这些附件', '请解析这些附件');
const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '请优先处理当前批次', '请优先处理当前批次');
expect(consumed).toBe(true);
expect(ctx.handleShippingAutoUploadNoticeBatch).not.toHaveBeenCalled();
expect(ctx.sendMessage).toHaveBeenCalledWith(
'请解析这些附件',
1,
expect(startOrderExtractionRun).toHaveBeenCalledWith(
'请优先处理当前批次',
['SNI-CURRENT'],
[{
name: 'orders-current.eml',
size: 100,
extension: 'eml',
type: 'document',
source: 'shipping_notice',
}],
'batch-current',
);
expect(attachments.value).toEqual([laterNotice, otherAttachment]);
});
it('allows an empty note when the user only authorizes attachment analysis', async () => {
const startOrderExtractionRun = vi.fn(async () => true);
const ctx = createContext({
attachments: ref([{
id: 'notice-empty-note',
kind: 'shipping_notice',
type: 'document',
uploadStatus: 'uploaded',
parseStatus: 'parsed',
orderExtractionStatus: 'not_started',
uploadProgress: 100,
originalFilename: 'orders.eml',
fileSize: 100,
intakeNo: 'SNI-EMPTY-NOTE',
uploadBatchId: 'batch-empty-note',
}]),
getParsedIntakeNos: () => ['SNI-EMPTY-NOTE'],
startOrderExtractionRun,
});
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
expect(consumed).toBe(true);
expect(startOrderExtractionRun).toHaveBeenCalledWith(
'',
[],
{
shipping_intake_nos: ['SNI-1'],
display_query: '请解析这些附件',
},
expect.objectContaining({
userAttachments: [{
name: 'orders.eml',
size: 100,
extension: 'eml',
type: 'document',
source: 'shipping_notice',
}],
onAssistantMessageFinished: expect.any(Function),
}),
['SNI-EMPTY-NOTE'],
[{
name: 'orders.eml',
size: 100,
extension: 'eml',
type: 'document',
source: 'shipping_notice',
}],
'batch-empty-note',
);
});
it('retries the conversation workspace once when the first refresh fails', async () => {
const syncWorkspace = vi.fn()
.mockResolvedValueOnce(false)
.mockResolvedValueOnce(true);
it('keeps attachments in the input when starting the run fails', async () => {
const attachment = {
id: 'notice-start-failed',
kind: 'shipping_notice' as const,
type: 'document' as const,
uploadStatus: 'uploaded' as const,
parseStatus: 'parsed' as const,
orderExtractionStatus: 'not_started' as const,
uploadProgress: 100,
originalFilename: 'orders.eml',
fileSize: 100,
intakeNo: 'SNI-START-FAILED',
};
const attachments = ref([attachment]);
const ctx = createContext({
attachments: ref([{
id: 'notice-retry',
kind: 'shipping_notice' as const,
type: 'document' as const,
uploadStatus: 'uploaded' as const,
parseStatus: 'parsed' as const,
uploadProgress: 100,
originalFilename: 'orders.eml',
fileSize: 100,
intakeNo: 'SNI-RETRY',
}]),
getParsedIntakeNos: () => ['SNI-RETRY'],
syncShippingConversationWorkspace: syncWorkspace,
});
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
const hooks = vi.mocked(ctx.sendMessage).mock.calls[0]?.[5];
await hooks?.onAssistantMessageFinished?.({} as never, []);
expect(syncWorkspace).toHaveBeenCalledTimes(2);
expect(syncWorkspace).toHaveBeenNthCalledWith(1, { preferLatest: true });
expect(syncWorkspace).toHaveBeenNthCalledWith(2, { preferLatest: true });
expect(ctx.refreshShippingActions).toHaveBeenCalledTimes(1);
});
it('rolls back the local extracting state when the chat request fails', async () => {
const rollback = vi.fn();
const ctx = createContext({
attachments: ref([{
id: 'notice-failed-send',
kind: 'shipping_notice' as const,
type: 'document' as const,
uploadStatus: 'uploaded' as const,
parseStatus: 'parsed' as const,
uploadProgress: 100,
originalFilename: 'orders.eml',
fileSize: 100,
intakeNo: 'SNI-FAILED-SEND',
}]),
getParsedIntakeNos: () => ['SNI-FAILED-SEND'],
sendMessage: vi.fn(async () => { throw new Error('network failed'); }),
rollbackOrderExtractionStarted: rollback,
attachments,
getParsedIntakeNos: () => ['SNI-START-FAILED'],
startOrderExtractionRun: vi.fn(async () => { throw new Error('run create failed'); }),
});
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
expect(consumed).toBe(true);
expect(rollback).toHaveBeenCalledWith(['SNI-FAILED-SEND']);
expect(ctx.msg.warning).toHaveBeenCalledWith('network failed');
});
it('rolls back extraction state when sendMessage reports a handled stream failure', async () => {
const rollback = vi.fn();
const ctx = createContext({
attachments: ref([{
id: 'notice-handled-failure',
kind: 'shipping_notice' as const,
type: 'document' as const,
uploadStatus: 'uploaded' as const,
parseStatus: 'parsed' as const,
uploadProgress: 100,
originalFilename: 'orders.eml',
fileSize: 100,
intakeNo: 'SNI-HANDLED-FAILURE',
}]),
getParsedIntakeNos: () => ['SNI-HANDLED-FAILURE'],
sendMessage: vi.fn(async () => false),
rollbackOrderExtractionStarted: rollback,
});
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
expect(consumed).toBe(true);
expect(rollback).toHaveBeenCalledWith(['SNI-HANDLED-FAILURE']);
expect(ctx.loadHistory).not.toHaveBeenCalled();
expect(attachments.value).toEqual([attachment]);
expect(ctx.msg.warning).toHaveBeenCalledWith('run create failed');
});
});
@@ -72,7 +72,12 @@ export interface ShippingSendHandlerContext {
hasSelectedNoticeCandidates?: () => boolean;
openShippingDuplicateDialog?: (attachmentId?: string) => void;
getParsedIntakeNos?: () => string[];
startOrderExtractionRun?: (query: string, intakeNos: string[], attachments: ReturnType<typeof createChatMessageAttachmentSnapshots>) => Promise<boolean>;
startOrderExtractionRun?: (
query: string,
intakeNos: string[],
attachments: ReturnType<typeof createChatMessageAttachmentSnapshots>,
uploadBatchId?: string,
) => Promise<boolean>;
applyShippingMessageRecovery?: (message: ChatMessage) => Promise<boolean>;
applyShippingBatchSnapshot?: (message: ChatMessage) => boolean;
syncShippingConversationWorkspace: (options?: { preferLatest?: boolean }) => Promise<boolean>;
@@ -214,14 +219,33 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
}
const intakeNos = ctx.getParsedIntakeNos?.() || [];
if (intakeNos.length) {
const userAttachments = createChatMessageAttachmentSnapshots(noticeItems);
const query = trimmed || ctx.t('chat.shippingOrderExtractionDefaultPrompt');
const submittedIntakes = new Set(intakeNos.map((item) => item.trim().toUpperCase()));
const batchIds = new Set(
noticeItems
.filter((item) => item.intakeNo && submittedIntakes.has(item.intakeNo.trim().toUpperCase()))
.map((item) => String(item.uploadBatchId || '').trim())
.filter(Boolean),
);
if (batchIds.size > 1) {
ctx.msg.warning('当前发送批次不一致,请重新上传需要一起识别的文件');
return true;
}
const userAttachments = createChatMessageAttachmentSnapshots(
noticeItems.filter((item) =>
item.intakeNo
&& submittedIntakes.has(item.intakeNo.trim().toUpperCase()),
),
);
// 阶段 2:发送是“授权开始识别”,备注允许为空,不能再偷偷注入默认提示词。
const query = trimmed;
ctx.shippingAutoFlowRequested.value = false;
if (typeof textOrEvent !== 'string') ctx.input.value = '';
try {
const started = await ctx.startOrderExtractionRun?.(query, intakeNos, userAttachments);
const uploadBatchId = [...batchIds][0];
const started = uploadBatchId
? await ctx.startOrderExtractionRun?.(query, intakeNos, userAttachments, uploadBatchId)
: await ctx.startOrderExtractionRun?.(query, intakeNos, userAttachments);
if (!started) return true;
const submittedIntakes = new Set(intakeNos.map((item) => item.trim().toUpperCase()));
ctx.attachments.value = ctx.attachments.value.filter(
(item) => item.kind !== 'shipping_notice'
|| !item.intakeNo
@@ -31,8 +31,14 @@ describe('shipping notice order extraction state', () => {
expect(isOrderExtractionEligibleIntake({ ...base, orderExtractionStatus: 'partially_completed' })).toBe(false);
expect(isOrderExtractionEligibleIntake({ ...base, orderExtractionStatus: 'completed' })).toBe(false);
expect(isOrderExtractionEligibleIntake({ ...base, orderExtractionStatus: 'failed' })).toBe(true);
expect(isOrderExtractionEligibleIntake({ ...base, layoutStatus: 'processing' })).toBe(false);
expect(isOrderExtractionEligibleIntake({ ...base, layoutStatus: 'completed' })).toBe(true);
expect(isOrderExtractionEligibleIntake({
...base,
parseSummary: {
preview_status: 'directory_incomplete',
ready_for_extraction: false,
attachment_directory_complete: false,
},
})).toBe(false);
});
it('keeps polling after preprocessing is parsed while order extraction is active', () => {
@@ -52,7 +58,7 @@ describe('shipping notice order extraction state', () => {
parseStatus: 'parsed',
orderExtractionStatus: 'not_started',
layoutStatus: 'processing',
})).toBe(true);
})).toBe(false);
});
it('preserves the immediate extracting state until the backend leaves not_started', () => {
@@ -66,12 +72,21 @@ describe('shipping notice order extraction state', () => {
expect(shouldRestoreShippingNoticeIntake('queued')).toBe(true);
expect(shouldRestoreShippingNoticeIntake('parsing')).toBe(true);
expect(shouldRestoreShippingNoticeIntake('parse_failed')).toBe(true);
expect(shouldRestoreShippingNoticeIntake('parsed', 'not_started', 0, {
preview_status: 'ready_for_extraction',
ready_for_extraction: true,
attachment_directory_complete: true,
})).toBe(true);
expect(shouldRestoreShippingNoticeIntake('parsed', 'failed', 0)).toBe(true);
expect(shouldRestoreShippingNoticeIntake('parsed', 'partially_completed', 2)).toBe(true);
expect(shouldRestoreShippingNoticeIntake('parsed', 'not_started', 0, 'processing')).toBe(true);
expect(shouldRestoreShippingNoticeIntake('parsed', 'not_started', 0, {
preview_status: 'directory_incomplete',
ready_for_extraction: false,
attachment_directory_complete: false,
})).toBe(false);
// 已完成且没有待审核 Candidate 的文件仅保留在用户消息气泡中。
expect(shouldRestoreShippingNoticeIntake('parsed')).toBe(false);
expect(shouldRestoreShippingNoticeIntake('parsed', 'completed')).toBe(false);
expect(shouldRestoreShippingNoticeIntake('parsed', 'partially_completed', 0)).toBe(false);
expect(shouldRestoreShippingNoticeIntake('parsed', 'completed', 2)).toBe(false);
expect(shouldRestoreShippingNoticeIntake('consumed')).toBe(false);
@@ -40,8 +40,8 @@ const ACTIVE_ORDER_EXTRACTION = new Set(['extracting']);
/**
* 判断服务端 Intake 是否应恢复到输入栏。
* AI 触发时机:无;页面刷新或重新打开会话时调用。
* 已解析文件已作为用户消息附件固化在对话气泡中,不能再次显示在输入栏;但存在待审核
* Candidate 的部分完成 Intake 必须恢复,否则用户无法补充字段并继续建单。
* 上传快览与发送授权已拆分:未发送但已快览成功的附件,刷新后也必须恢复到输入栏;
* 已进入订单抽取终态的附件仅保留在消息气泡中,避免把旧批次误带回当前输入框。
* @param parseStatus - 服务端返回的预解析状态。
* @param orderExtractionStatus - 服务端返回的订单抽取状态。
* @param candidateCount - 当前仍可审核的订单 Candidate 数量。
@@ -51,13 +51,17 @@ export function shouldRestoreShippingNoticeIntake(
parseStatus: string | null | undefined,
orderExtractionStatus?: string | null,
candidateCount = 0,
layoutStatus?: ShippingNoticePendingAttachment['layoutStatus'],
parseSummary?: ShippingNoticePendingAttachment['parseSummary'],
): boolean {
const status = String(parseStatus || '').trim().toLowerCase();
const extractionStatus = String(orderExtractionStatus || '').trim().toLowerCase();
return ACTIVE_PARSE.has(status)
|| status === 'parse_failed'
|| layoutStatus === 'processing'
|| (
status === 'parsed'
&& (!extractionStatus || extractionStatus === 'not_started')
&& !isShippingNoticeAttachmentParseIncomplete(parseSummary)
)
|| extractionStatus === 'failed'
|| (extractionStatus === 'partially_completed' && candidateCount > 0);
}
@@ -67,8 +71,7 @@ export function shouldPollShippingNoticeIntake(
item: Pick<ShippingNoticePendingAttachment, 'parseStatus' | 'orderExtractionStatus' | 'layoutStatus'>,
): boolean {
return !TERMINAL_PARSE.has(item.parseStatus)
|| ACTIVE_ORDER_EXTRACTION.has(String(item.orderExtractionStatus || '').trim().toLowerCase())
|| item.layoutStatus === 'processing';
|| ACTIVE_ORDER_EXTRACTION.has(String(item.orderExtractionStatus || '').trim().toLowerCase());
}
/** 判断附件是否仍可作为新一轮完整订单抽取的输入。 */
@@ -79,7 +82,6 @@ export function isOrderExtractionEligibleIntake(
return item.parseStatus === 'parsed'
&& Boolean(item.intakeNo)
&& (extractionStatus === 'not_started' || extractionStatus === 'failed')
&& item.layoutStatus !== 'processing'
&& !isShippingNoticeAttachmentParseIncomplete(item.parseSummary);
}
@@ -222,7 +224,7 @@ export function mapServerCandidate(remote: ShippingNoticeCandidateResponse): Shi
};
}
function createPendingAttachment(file: File): ShippingNoticePendingAttachment {
function createPendingAttachment(file: File, uploadBatchId: string): ShippingNoticePendingAttachment {
return {
id: `${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
kind: 'shipping_notice',
@@ -233,6 +235,7 @@ function createPendingAttachment(file: File): ShippingNoticePendingAttachment {
uploadProgress: 0,
originalFilename: file.name,
fileSize: file.size,
uploadBatchId,
};
}
@@ -246,6 +249,8 @@ export interface UseShippingNoticeIntakesOptions {
export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOptions) {
const pollTimer = ref<ReturnType<typeof setTimeout> | null>(null);
const pollRound = ref(0);
// 新文件选择显式推进当前批次;恢复历史卡片不能覆盖它。
const currentUploadBatchId = ref<string | null>(null);
const noticeAttachments = computed(() =>
options.attachments.value.filter(
@@ -253,20 +258,26 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
),
);
const currentBatchAttachments = computed(() => {
const batchId = currentUploadBatchId.value;
return batchId
? noticeAttachments.value.filter((item) => item.uploadBatchId === batchId)
: noticeAttachments.value;
});
const hasBlockingUploadOrParse = computed(() =>
noticeAttachments.value.some((item) =>
currentBatchAttachments.value.some((item) =>
item.uploadStatus === 'uploading'
|| item.uploadStatus === 'waiting'
|| ACTIVE_PARSE.has(item.parseStatus)
|| item.parseStatus === 'queued'
|| item.parseStatus === 'parsing'
|| item.layoutStatus === 'processing'
|| ACTIVE_ORDER_EXTRACTION.has(String(item.orderExtractionStatus || '').trim().toLowerCase()),
),
);
const hasParseFailures = computed(() =>
noticeAttachments.value.some(
currentBatchAttachments.value.some(
(item) =>
item.parseStatus === 'failed'
|| isShippingNoticeAttachmentParseIncomplete(item.parseSummary),
@@ -274,8 +285,8 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
);
const allParsedReady = computed(() =>
noticeAttachments.value.length > 0
&& noticeAttachments.value.every(
currentBatchAttachments.value.length > 0
&& currentBatchAttachments.value.every(
(item) =>
item.parseStatus === 'parsed'
&& !isShippingNoticeAttachmentParseIncomplete(item.parseSummary),
@@ -283,7 +294,7 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
);
const hasBlockingDuplicates = computed(() =>
noticeAttachments.value.some(
currentBatchAttachments.value.some(
(item) => (item.candidates?.length
? item.candidates.some((candidate) =>
candidate.selected && candidate.duplicate?.blocking && !candidate.duplicateResolution?.action,
@@ -293,7 +304,7 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
);
const hasCandidateReviewIssues = computed(() =>
noticeAttachments.value.some((item) =>
currentBatchAttachments.value.some((item) =>
(item.candidates || []).some((candidate) =>
candidate.selected && candidate.validationStatus !== 'ready',
),
@@ -305,7 +316,7 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
&& !hasBlockingDuplicates.value
&& !hasCandidateReviewIssues.value
&& !hasParseFailures.value
&& noticeAttachments.value.some((item) => (item.candidates || []).some((candidate) => candidate.selected)),
&& currentBatchAttachments.value.some((item) => (item.candidates || []).some((candidate) => candidate.selected)),
);
const stopPolling = () => {
@@ -386,9 +397,11 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
const intake = await createShippingNoticeIntake(
asset.asset_no,
options.conversationId.value,
attachment.uploadBatchId,
);
patchAttachment(attachment.id, {
intakeNo: intake.intake_no,
uploadBatchId: intake.upload_batch_id || attachment.uploadBatchId,
parseStatus: mapServerParseStatus(intake.parse_status),
orderExtractionStatus: intake.order_extraction_status || undefined,
parseSummary: (intake.parse_summary || undefined) as ShippingNoticeParseSummary | undefined,
@@ -412,8 +425,12 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
};
const enqueueNoticeFiles = async (files: File[]) => {
// 同一次选择共享一个持久化批次;后续发送只会自动取这个最新批次。
const uploadBatchId = globalThis.crypto?.randomUUID?.()
|| `${Date.now()}-${Math.random().toString(36).slice(2, 12)}`;
currentUploadBatchId.value = uploadBatchId;
for (const file of files) {
const attachment = createPendingAttachment(file);
const attachment = createPendingAttachment(file, uploadBatchId);
options.attachments.value = [...options.attachments.value, attachment];
await processSingleFile(attachment);
}
@@ -452,10 +469,14 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
schedulePoll();
};
const getParsedIntakeNos = () =>
noticeAttachments.value
.filter(isOrderExtractionEligibleIntake)
const getParsedIntakeNos = () => {
const eligible = noticeAttachments.value.filter(isOrderExtractionEligibleIntake);
const currentBatchId = currentUploadBatchId.value
|| [...noticeAttachments.value].reverse().find((item) => item.uploadBatchId)?.uploadBatchId;
return eligible
.filter((item) => item.uploadBatchId === currentBatchId)
.map((item) => String(item.intakeNo));
};
/** 点击发送后立即展示订单识别阶段,并启动 Intake 状态轮询。 */
const markOrderExtractionStarted = (intakeNos: string[]) => {
@@ -497,7 +518,7 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
item.parse_status,
item.order_extraction_status,
item.candidates?.length || 0,
item.layout_status,
(item.parse_summary || undefined) as ShippingNoticeParseSummary | undefined,
))
.map((item) => ({
id: `restored_${item.intake_no}`,
@@ -505,6 +526,7 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
type: 'document' as const,
assetNo: item.asset_no || undefined,
intakeNo: item.intake_no,
uploadBatchId: item.upload_batch_id || undefined,
uploadStatus: 'uploaded' as const,
parseStatus: mapServerParseStatus(item.parse_status),
orderExtractionStatus: item.order_extraction_status || undefined,
@@ -37,6 +37,17 @@ const run = (patch: Partial<ShippingOrderExtractionRun>): ShippingOrderExtractio
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,
});
@@ -86,7 +97,8 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
api.getRun.mockResolvedValue(queued);
const harness = createHarness();
await harness.runs.startRun('解析附件', ['SNI-1'], []);
await harness.runs.startRun('解析附件', ['SNI-1'], [], 'batch-1');
expect(api.createRun).toHaveBeenCalledWith(expect.objectContaining({ upload_batch_id: 'batch-1' }));
expect(harness.conversationId.value).toBe('conv-created');
expect(harness.options.onConversationResolved).toHaveBeenCalledWith('conv-created');
expect(harness.messages.value.map((item) => item.payload?.formId)).toEqual([
@@ -101,10 +113,42 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
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' });
api.createRun.mockResolvedValue({ run: queued, reused: false });
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,
);
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: 'running' })] })
.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();
@@ -118,7 +162,7 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
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('extracting');
expect(harness.messages.value[0]?.shipping_order_extraction_state?.status).toBe('processing');
});
it('aborts a hanging Run query after ten seconds and keeps polling as a transport failure', async () => {
@@ -132,7 +176,7 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
await vi.advanceTimersByTimeAsync(11000);
expect(api.getRun).toHaveBeenCalledWith('SNER-TIMEOUT', expect.any(AbortSignal));
expect(harness.runs.getActiveRunNo()).toBe('SNER-TIMEOUT');
expect(harness.messages.value[1]?.shipping_order_extraction_state?.status).toBe('extracting');
expect(harness.messages.value[1]?.shipping_order_extraction_state?.status).toBe('queued');
harness.runs.stopPolling();
});
@@ -151,7 +195,7 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
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('extracting');
expect(harness.messages.value[0]?.shipping_order_extraction_state?.status).toBe('queued');
expect(harness.runs.getActiveRunNo()).toBe('SNER-RETRY');
harness.runs.stopPolling();
});
@@ -167,7 +211,7 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
});
it('creates a new Run for reidentification and switches polling to the new version', async () => {
const source = run({ run_no: 'SNER-SOURCE', status: 'needs_review' });
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' },
@@ -190,34 +234,75 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
describe('mapOrderExtractionRunToMessageState', () => {
it('maps queued/running to indeterminate extracting state', () => {
it('maps queued and processing to the new Run summary state', () => {
expect(mapOrderExtractionRunToMessageState(run({
status: 'running',
phase: 'calling_provider',
progress: {
version: 3,
current_stage_code: 'document_processing',
health: 'normal',
last_activity_at: '2026-07-21T03:24:51Z',
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: 'extracting', terminal: false, phase: 'llm_extraction',
current_stage_code: 'document_processing', health: 'normal',
last_activity_at: '2026-07-21T03:24:51Z',
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 progress projection even when Run status and result are unchanged', async () => {
it('persists a changed summary projection even when Run status is unchanged', async () => {
vi.useFakeTimers();
const first = run({
run_no: 'SNER-PROGRESS',
status: 'running',
progress: { version: 1, current_stage_code: 'workflow_accepted' },
status: 'processing',
current_activity: { unit_id: 1, file_name: 'PO-A.pdf', event_code: 'document_queued' },
});
const second = run({
run_no: 'SNER-PROGRESS',
status: 'running',
progress: { version: 2, current_stage_code: 'order_recognition' },
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);
@@ -229,14 +314,15 @@ describe('mapOrderExtractionRunToMessageState', () => {
await vi.advanceTimersByTimeAsync(1000);
expect(harness.options.saveLocalMessageToBackend).toHaveBeenCalledTimes(2);
expect(harness.messages.value[0]?.shipping_order_extraction_state?.current_stage_code).toBe('order_recognition');
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('merges duplicate local cards for one Run when a terminal update arrives', async () => {
vi.useFakeTimers();
const active = run({ run_no: 'SNER-DUPLICATE', status: 'running' });
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' },
});
@@ -262,8 +348,22 @@ describe('mapOrderExtractionRunToMessageState', () => {
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: 'running' });
const terminal = run({ run_no: 'SNER-REVIEW', status: 'needs_review', result: { pending_count: 1 } });
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();
@@ -287,22 +387,49 @@ describe('mapOrderExtractionRunToMessageState', () => {
harness.runs.stopPolling();
});
it('maps completed result counters without guessing from text', () => {
it('maps completed summaries without guessing from text', () => {
expect(mapOrderExtractionRunToMessageState(run({
status: 'completed',
result: { batch_no: 'SB-1', created_count: 2, opened_existing_count: 1, pending_count: 0 },
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, batch_no: 'SB-1', created_count: 2, opened_existing_count: 1,
status: 'completed',
terminal: true,
summary: { completedDocuments: 3, candidateCount: 3 },
availableActions: ['view_details'],
});
});
it('maps needs_review and failed to distinct terminal states', () => {
it('maps review_required and failed to distinct terminal states', () => {
expect(mapOrderExtractionRunToMessageState(run({
status: 'needs_review', result: { pending_count: 3 },
}))).toMatchObject({ status: 'partially_completed', pending_count: 3, terminal: true });
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', message: '', terminal: true });
}))).toMatchObject({ status: 'failed', errorCode: 'X', terminal: true });
});
it('acknowledges a terminal Run only after it is restored into the active conversation', async () => {
@@ -4,7 +4,7 @@
* 依赖:shipping.api Run 接口、chat.types、Vue refs。
* 逻辑:发送处理器调用 startRun;本模块持久化本地消息并轮询 Run,终态后刷新 Intake、批次工作台与动作。
*/
import { onBeforeUnmount, type ComputedRef, type Ref } from 'vue';
import { getCurrentInstance, onBeforeUnmount, type ComputedRef, type Ref } from 'vue';
import {
createWorkspaceShippingOrderExtractionRun,
getWorkspaceShippingOrderExtractionRun,
@@ -34,30 +34,80 @@ interface UseShippingOrderExtractionRunsOptions {
t: (key: string, params?: Record<string, unknown>) => string;
}
const ACTIVE_RUN_STATUSES = new Set(['queued', 'running', 'result_persisted']);
const ACTIVE_RUN_STATUSES = new Set(['queued', 'processing']);
/** 把领域 Run 转为聊天组件既有的订单抽取状态卡契约。 */
export function mapOrderExtractionRunToMessageState(run: ShippingOrderExtractionRun): ShippingOrderExtractionState {
const result = run.result || {};
const failed = run.status === 'failed' || run.status === 'cancelled';
const partial = run.status === 'needs_review';
const completed = run.status === 'completed';
return {
status: failed ? 'failed' : partial ? 'partially_completed' : completed ? 'completed' : 'extracting',
phase: failed ? 'failed' : run.status === 'result_persisted' ? 'result_persisted' : 'llm_extraction',
// Provider/网络错误正文仅供管理员诊断,用户卡片统一展示可操作的业务提示。
message: '',
created_count: Number(result.created_count || 0),
opened_existing_count: Number(result.opened_existing_count || 0),
pending_count: Number(result.pending_count || 0),
non_shipping_count: Number(result.non_shipping_count || 0),
created_with_missing_fields_count: Number(result.created_with_missing_fields_count || 0),
batch_no: result.batch_no || null,
terminal: failed || partial || completed,
current_stage_code: run.progress?.current_stage_code || null,
health: run.progress?.health || 'normal',
last_activity_at: run.progress?.last_activity_at || null,
started_at: run.started_at || run.created_at || null,
status: run.status,
summary: {
totalDocuments: Number(run.summary?.total_documents || 0),
pendingDocuments: Number(run.summary?.pending_documents || 0),
processingDocuments: Number(run.summary?.processing_documents || 0),
completedDocuments: Number(run.summary?.completed_documents || 0),
reviewRequiredDocuments: Number(run.summary?.review_required_documents || 0),
failedDocuments: Number(run.summary?.failed_documents || 0),
candidateCount: Number(run.summary?.candidate_count || 0),
},
currentActivity: run.current_activity
? {
unitId: Number(run.current_activity.unit_id || 0),
fileName: run.current_activity.file_name || null,
eventCode: String(run.current_activity.event_code || ''),
selectionBatch: run.current_activity.selection_batch != null
? Number(run.current_activity.selection_batch || 0) || null
: null,
reasonCodes: Array.isArray(run.current_activity.reason_codes)
? run.current_activity.reason_codes.map((item) => String(item || '').trim()).filter(Boolean)
: [],
}
: null,
selectionPlan: run.selection_plan
? {
selectionVersion: run.selection_plan.selection_version || null,
maxInitialAttachments: Number(run.selection_plan.max_initial_attachments || 0),
maxInitialConcurrency: Number(run.selection_plan.max_initial_concurrency || 0),
expansionBatchSize: Number(run.selection_plan.expansion_batch_size || 0),
maxTotalAttachments: Number(run.selection_plan.max_total_attachments || 0),
totalAttachmentCount: Number(run.selection_plan.total_attachment_count || 0),
eligibleAttachmentCount: Number(run.selection_plan.eligible_attachment_count || 0),
selectedAttachmentCount: Number(run.selection_plan.selected_attachment_count || 0),
plannedAttachmentCount: Number(run.selection_plan.planned_attachment_count || 0),
pendingExpansionAttachmentCount: Number(run.selection_plan.pending_expansion_attachment_count || 0),
pendingExpansionBatches: run.selection_plan.pending_expansion_batches || {},
skippedAttachmentCount: Number(run.selection_plan.skipped_attachment_count || 0),
duplicateAttachmentCount: Number(run.selection_plan.duplicate_attachment_count || 0),
budgetLimitedAttachmentCount: Number(run.selection_plan.budget_limited_attachment_count || 0),
groupCount: Number(run.selection_plan.group_count || 0),
}
: null,
unitSummary: run.unit_summary
? {
totalUnits: Number(run.unit_summary.total_units || 0),
selectedUnits: Number(run.unit_summary.selected_units || 0),
retryingUnits: Number(run.unit_summary.retrying_units || 0),
pendingRetryUnits: Number(run.unit_summary.pending_retry_units || 0),
failedUnits: Number(run.unit_summary.failed_units || 0),
reviewRequiredUnits: Number(run.unit_summary.review_required_units || 0),
succeededUnits: Number(run.unit_summary.succeeded_units || 0),
selectionBatches: run.unit_summary.selection_batches || {},
reviewRequiredReasonCodes: Array.isArray(run.unit_summary.review_required_reason_codes)
? [...run.unit_summary.review_required_reason_codes]
: [],
expansionTriggerReasonCodes: Array.isArray(run.unit_summary.expansion_trigger_reason_codes)
? [...run.unit_summary.expansion_trigger_reason_codes]
: [],
technicalFailureReasonCodes: Array.isArray(run.unit_summary.technical_failure_reason_codes)
? [...run.unit_summary.technical_failure_reason_codes]
: [],
}
: null,
availableActions: Array.isArray(run.available_actions) ? [...run.available_actions] : [],
terminal: !ACTIVE_RUN_STATUSES.has(run.status),
refreshFailed: false,
errorCode: run.error?.code || null,
startedAt: run.started_at || null,
finishedAt: run.finished_at || null,
};
}
@@ -80,6 +130,20 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
pollGeneration += 1;
};
/** 网络轮询失败只更新本地提示,不得把后台业务 Run 误判为失败。 */
const setRunRefreshFailed = (runNo: string, refreshFailed: boolean) => {
const normalizedRunNo = String(runNo || '').trim();
if (!normalizedRunNo) return;
for (const message of options.messages.value) {
const payload = message.payload && typeof message.payload === 'object' ? message.payload as Record<string, unknown> : {};
if (payload.order_extraction_run_no !== normalizedRunNo || !message.shipping_order_extraction_state) continue;
message.shipping_order_extraction_state = {
...message.shipping_order_extraction_state,
refreshFailed,
};
}
};
/**
* 查找或创建当前 Run 的助手状态消息,仅在业务状态真正变化时持久化。
* @param run - 用户态 Run 摘要,不包含 Provider 快照或原始文档。
@@ -122,7 +186,16 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
order_extraction_reparse: run.reparse || null,
shipping_order_extraction_review: reviewAttachments || [],
};
const signature = JSON.stringify({ status: run.status, phase: run.phase, result: run.result, error: run.error, progress: run.progress, reparse: run.reparse, reviewAttachments });
const signature = JSON.stringify({
status: run.status,
summary: run.summary,
current_activity: run.current_activity,
available_actions: run.available_actions,
result: run.result,
error: run.error,
reparse: run.reparse,
reviewAttachments,
});
if (persistedSignatures.get(run.run_no) !== signature) {
const persisted = await options.saveLocalMessageToBackend(message);
if (persisted) persistedSignatures.set(run.run_no, signature);
@@ -203,6 +276,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
const run = await getWorkspaceShippingOrderExtractionRun(runNo, request.signal).finally(request.release);
if (generation !== pollGeneration || activeRunNo !== runNo) return;
pollFailureCount = 0;
setRunRefreshFailed(run.run_no, false);
if (!ACTIVE_RUN_STATUSES.has(run.status)) {
const reviewAttachments = await refreshTerminalFacts(run);
if (generation !== pollGeneration || activeRunNo !== runNo) return;
@@ -218,6 +292,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
} catch {
if (generation !== pollGeneration || activeRunNo !== runNo) return;
pollFailureCount += 1;
setRunRefreshFailed(runNo, true);
const delayMs = Math.min(15000, 2000 * (2 ** Math.min(pollFailureCount, 3)));
pollTimer = setTimeout(() => void pollRun(runNo, generation), delayMs);
}
@@ -233,7 +308,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
/**
* 启动订单抽取后台 Run,并把用户操作和状态卡持久化到本地会话。
* @param query - 用户本次展示文本;不发送给 Dify Chatflow。
* @param query - 用户本次备注;允许为空,不发送给 Dify Chatflow。
* @param intakeNos - 本次冻结的 Intake 编号。
* @param attachments - 用户消息中的安全附件快照。
* @returns Run 已成功创建或幂等复用时为 true。
@@ -242,12 +317,14 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
query: string,
intakeNos: string[],
attachments: ChatMessageAttachment[],
uploadBatchId?: string,
): Promise<boolean> => {
stopPolling();
const response = await createWorkspaceShippingOrderExtractionRun({
agent_id: options.currentAgentId.value,
conversation_id: options.conversationId.value || undefined,
intake_nos: intakeNos,
upload_batch_id: uploadBatchId || '',
});
const run = response.run;
if (!options.conversationId.value) options.conversationId.value = run.conversation_id;
@@ -265,7 +342,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
},
};
options.messages.value.push(userMessage);
await options.saveLocalMessageToBackend(userMessage, query);
await options.saveLocalMessageToBackend(userMessage, query || undefined);
await upsertRunMessage(run);
await acknowledgeTerminalRunWhenVisible(run);
await options.onConversationResolved(run.conversation_id);
@@ -369,6 +446,6 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
}
};
onBeforeUnmount(stopPolling);
if (getCurrentInstance()) onBeforeUnmount(stopPolling);
return { startRun, retryRun, reparseRun, restoreForConversation, stopPolling, updateCandidateReviewSnapshot, getActiveRunNo: () => activeRunNo };
}