feat(shipping-notice): 添加订单抽取功能,支持异步运行和管理,优化相关数据模型和处理逻辑

This commit is contained in:
hugo committed 2026-07-21 09:02:42 +08:00
1 parent 34d489a2d1
commit ce26d6d0c4
144 files changed
+12241 -4233

No files matched your search

@@ -23,6 +23,8 @@ import type {
ShippingTaskPage,
ShippingTaskSummary,
ShippingCustomerOption,
ShippingOrderExtractionRun,
ShippingOrderExtractionRunCreateResponse,
ShippingTaskUiState,
} from '../types/shipping.api.types';
@@ -152,6 +154,40 @@ export const deleteWorkspaceShippingTasks = (taskNos: string[], reason: string)
'/api/workspace/shipping-tasks/batch-delete', jsonPost({ task_nos: taskNos, reason }),
);
/** 创建或幂等复用订单抽取 Run;新聊天可不传 conversation_id,由服务端创建本地会话。 */
export const createWorkspaceShippingOrderExtractionRun = (payload: {
agent_id: number;
conversation_id?: string | null;
intake_nos: string[];
}) => requestJson<ShippingOrderExtractionRunCreateResponse>(
'/api/workspace/shipping-notice/order-extraction-runs',
jsonPost(payload),
);
/**
* 查询单个订单抽取 Run,供聊天页短轮询。
* @param runNo - Run 业务编号。
* @param signal - 切会话或超时时取消当前 GET,不取消后台 Run。
*/
export const getWorkspaceShippingOrderExtractionRun = (runNo: string, signal?: AbortSignal) =>
requestJson<ShippingOrderExtractionRun>(
`/api/workspace/shipping-notice/order-extraction-runs/${encodeURIComponent(runNo)}`,
{ signal },
);
/** 按会话恢复订单抽取 Run,刷新页面后不依赖聊天 SSE 历史。 */
export const listWorkspaceShippingOrderExtractionRuns = (
conversationId: string,
limit = 50,
signal?: AbortSignal,
) => {
const params = new URLSearchParams({ conversation_id: conversationId, limit: String(limit) });
return requestJson<{ items: ShippingOrderExtractionRun[] }>(
`/api/workspace/shipping-notice/order-extraction-runs?${params.toString()}`,
{ signal },
);
};
/** 批量归档任务,适用于外部上传中或已上传而禁止平台单方作废的任务。 */
export const archiveWorkspaceShippingTasks = (taskNos: string[]) =>
requestJson<ShippingTaskBatchDispositionResponse>(
@@ -1,17 +1,15 @@
/**
* features/chat/composables/useChat.spec.ts
* 用途:验证聊天流的附件快照、货代 UI State 与终态事件过滤。
* 用途:验证聊天流对发货通知 UI State 与订单识别生命周期 SSE 的消息级回写行为。
* 依赖:vitest、useChat/chat.api 导出的纯函数、chat.types。
* 逻辑:覆盖任务状态投影、terminal 后 UI State 放行及用户附件快照。
* 逻辑:覆盖任务状态投影、订单识别终态保护、terminal 后事件放行及历史 payload 恢复。
*/
import { describe, expect, it } from 'vitest';
import {
applyShippingOrderExtractionStateToMessage,
applyShippingUiStateToMessage,
createUserChatMessage,
isAllowedAfterStreamTerminal,
} from './useChat';
import { hydrateShippingOrderExtractionState } from '../api/chat.api';
import type { ChatMessage } from '../types/chat.types';
describe('useChat user attachment snapshots', () => {
@@ -128,113 +126,11 @@ describe('useChat shipping_ui_state SSE', () => {
});
});
describe('useChat shipping_order_extraction_state SSE', () => {
it('replaces extracting with persisted facts without overwriting Dify content', () => {
const message: ChatMessage = {
role: 'assistant',
content: 'Dify 最终正文保持不变',
payload: { existing_key: 'kept' },
};
applyShippingOrderExtractionStateToMessage(message, {
event: 'shipping_order_extraction_state',
status: 'extracting',
phase: 'llm_extraction',
message: '正在识别邮件及附件中的订单',
created_count: -1,
terminal: false,
});
expect(message.shipping_order_extraction_state?.status).toBe('extracting');
expect(message.shipping_order_extraction_state?.created_count).toBe(0);
applyShippingOrderExtractionStateToMessage(message, {
event: 'shipping_order_extraction_state',
status: 'completed',
phase: 'result_persisted',
message: '已创建 1 个发货任务',
created_count: 1,
opened_existing_count: 2,
pending_count: 0,
non_shipping_count: 3,
created_with_missing_fields_count: 1,
batch_no: 'SB-STATE-001',
terminal: true,
});
expect(message.content).toBe('Dify 最终正文保持不变');
expect(message.shipping_order_extraction_state).toMatchObject({
status: 'completed',
created_count: 1,
opened_existing_count: 2,
non_shipping_count: 3,
batch_no: 'SB-STATE-001',
terminal: true,
});
expect((message.payload as Record<string, unknown>).existing_key).toBe('kept');
expect((message.payload as { shipping_order_extraction_state?: { created_count?: number } })
.shipping_order_extraction_state?.created_count).toBe(1);
// 关键断言:网络重排导致的迟到进行态不能覆盖已经展示的终态。
applyShippingOrderExtractionStateToMessage(message, {
status: 'extracting',
phase: 'llm_extraction',
message: '迟到事件',
terminal: false,
});
expect(message.shipping_order_extraction_state?.status).toBe('completed');
});
it('allows HXOPS domain states after the upstream terminal event', () => {
expect(isAllowedAfterStreamTerminal('shipping_order_extraction_state')).toBe(true);
describe('useChat terminal event filtering', () => {
it('allows only shipping UI state after the upstream terminal event', () => {
expect(isAllowedAfterStreamTerminal('shipping_ui_state')).toBe(true);
expect(isAllowedAfterStreamTerminal('shipping_order_extraction_state')).toBe(false);
expect(isAllowedAfterStreamTerminal('agent_message')).toBe(false);
});
it('clears a generic stream failure after persisted partial completion', () => {
const message: ChatMessage = {
role: 'assistant',
content: '请求失败,请稍后重试。',
stream_error: true,
};
applyShippingOrderExtractionStateToMessage(message, {
status: 'partially_completed',
phase: 'result_persisted',
message: '仍有 1 个订单需要补充信息',
pending_count: 1,
terminal: true,
});
// 关键断言:已保存的订单部分完成结果不得被通用 SSE 断流提示覆盖。
expect(message.content).toBe('');
expect(message.stream_error).toBe(false);
expect(message.shipping_order_extraction_state?.status).toBe('partially_completed');
});
it('hydrates persisted terminal state from ChatLog payload', () => {
const message: ChatMessage = {
role: 'assistant',
content: '订单识别完成',
payload: {
shipping_order_extraction_state: {
status: 'partially_completed',
phase: 'result_persisted',
message: '仍有 1 个订单需要补充信息',
created_count: 1,
opened_existing_count: 0,
pending_count: 1,
non_shipping_count: 0,
created_with_missing_fields_count: 0,
batch_no: 'SB-HISTORY-001',
terminal: true,
},
},
};
hydrateShippingOrderExtractionState(message);
expect(message.shipping_order_extraction_state?.status).toBe('partially_completed');
expect(message.shipping_order_extraction_state?.pending_count).toBe(1);
expect(message.shipping_order_extraction_state?.batch_no).toBe('SB-HISTORY-001');
});
});
@@ -1,8 +1,8 @@
/**
* features/chat/composables/useChat.ts
* 用途:维护聊天消息、并行 run 与 legacy SSE 流式收发,并投影货代领域状态。
* 用途:维护聊天消息、并行 run 与 legacy SSE 流式收发,并投影普通货代 UI 状态。
* 依赖:Vue、vue-i18n、useChatTurn、streamErrorMessage、chat/shipping 类型。
* 逻辑:页面调用 useChat 发起消息;Dify/HXOPS SSE 被归并到当前助手消息,领域终态可继续在上游终止事件后写入。
* 逻辑:页面调用 useChat 发起消息;Dify/HXOPS SSE 被归并到当前助手消息,订单抽取状态由独立 Run API 维护。
*/
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
@@ -13,8 +13,6 @@ import type {
ChatMessageAttachment,
ChatRun,
RetrieverResource,
ShippingOrderExtractionState,
ShippingOrderExtractionStatus,
} from '../types/chat.types';
import type { ShippingBatchUiState, ShippingTaskUiState } from '../types/shipping.api.types';
import type { ChatMessageSendResult } from '../types/chat-turn.types';
@@ -167,85 +165,8 @@ export const applyShippingUiStateToMessage = (msg: ChatMessage, data: Record<str
};
};
const SHIPPING_ORDER_EXTRACTION_STATUSES = new Set<ShippingOrderExtractionStatus>([
'extracting',
'completed',
'partially_completed',
'failed',
]);
const STREAM_ERROR_FALLBACK_SUFFIXES = [
'请求失败,请稍后重试。',
'請求失敗,請稍後重試。',
'The request failed. Please try again.',
'คำขอล้มเหลว โปรดลองใหม่อีกครั้ง',
];
/**
* 将未知 SSE payload 规范为订单识别状态。
* 核心逻辑:只接受固定状态枚举;计数字段统一约束为非负整数,避免异常上游值破坏卡片布局。
* @param data - shipping_order_extraction_state 事件对象。
* @returns 合法状态;协议不匹配时返回 undefined。
*/
const resolveShippingOrderExtractionState = (
data: Record<string, unknown>,
): ShippingOrderExtractionState | undefined => {
const status = String(data.status || '') as ShippingOrderExtractionStatus;
if (!SHIPPING_ORDER_EXTRACTION_STATUSES.has(status)) return undefined;
const phase = String(data.phase || '');
if (!['llm_extraction', 'result_persisted', 'failed'].includes(phase)) return undefined;
const count = (value: unknown) => {
const parsed = Number(value);
return Number.isFinite(parsed) ? Math.max(Math.trunc(parsed), 0) : 0;
};
return {
status,
phase: phase as ShippingOrderExtractionState['phase'],
message: String(data.message || '').trim(),
created_count: count(data.created_count),
opened_existing_count: count(data.opened_existing_count),
pending_count: count(data.pending_count),
non_shipping_count: count(data.non_shipping_count),
created_with_missing_fields_count: count(data.created_with_missing_fields_count),
batch_no: typeof data.batch_no === 'string' && data.batch_no.trim() ? data.batch_no.trim() : null,
terminal: data.terminal === true || status !== 'extracting',
};
};
/**
* 将订单识别领域事件同步到当前助手消息及可持久化 payload。
* 核心逻辑:终态不得被迟到的 extracting 覆盖;正文由 Dify 独立维护,本函数只更新结构化状态。
* @param msg - 当前助手消息。
* @param data - shipping_order_extraction_state SSE 事件。
*/
export const applyShippingOrderExtractionStateToMessage = (
msg: ChatMessage,
data: Record<string, unknown>,
): void => {
const state = resolveShippingOrderExtractionState(data);
if (!state) return;
if (msg.shipping_order_extraction_state?.terminal && !state.terminal) return;
msg.shipping_order_extraction_state = state;
if (msg.stream_error && (state.status === 'completed' || state.status === 'partially_completed')) {
// 已持久化的订单事实优先于连接层通用断流提示,避免业务成功仍向用户误报失败。
const fallbackSuffix = STREAM_ERROR_FALLBACK_SUFFIXES.find((suffix) => msg.content.endsWith(suffix));
if (fallbackSuffix) msg.content = msg.content.slice(0, -fallbackSuffix.length).trimEnd();
msg.stream_error = false;
}
msg.payload = {
...(msg.payload && typeof msg.payload === 'object' ? msg.payload as Record<string, unknown> : {}),
shipping_order_extraction_state: state,
};
};
/**
* 判断上游终态之后仍允许写入当前消息的领域事件。
* 核心逻辑:普通 Dify 文本在 terminal 后丢弃,但 HXOPS 的抽取终态和任务 UI State 由 Handler 在 terminal 后生成。
* @param eventName - SSE event 字段。
* @returns 是否允许继续消费。
*/
export const isAllowedAfterStreamTerminal = (eventName: string): boolean => (
eventName === 'shipping_ui_state' || eventName === 'shipping_order_extraction_state'
eventName === 'shipping_ui_state'
);
/**
@@ -545,7 +466,7 @@ export function useChat() {
| { type: 'image' | 'document' | 'audio' | 'video' | 'custom'; transfer_method: 'local_file'; upload_file_id: string }
| { type: 'image' | 'document' | 'audio' | 'video' | 'custom'; transfer_method: 'remote_url'; url: string }
>,
context?: { task_id?: string; batch_no?: string; shipping_intake_nos?: string[]; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string },
context?: { task_id?: string; batch_no?: string; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string },
hooks?: SendMessageLifecycleHooks,
): Promise<ChatMessageSendResult> => {
const displayQuery = String(
@@ -613,7 +534,6 @@ export function useChat() {
files: files && files.length > 0 ? files : undefined,
task_id: context?.task_id || undefined,
batch_no: context?.batch_no || undefined,
shipping_intake_nos: context?.shipping_intake_nos?.length ? context.shipping_intake_nos : undefined,
shipping_temporary_inventory_asset_no: context?.shipping_temporary_inventory_asset_no || undefined,
shipping_temporary_inventory_session_no: context?.shipping_temporary_inventory_session_no || undefined,
display_query: context && Object.prototype.hasOwnProperty.call(context, 'display_query')
@@ -685,10 +605,7 @@ export function useChat() {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
applyShippingUiStateToMessage(botMsg, data);
} else if (eventName === 'shipping_order_extraction_state') {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
applyShippingOrderExtractionStateToMessage(botMsg, data);
} else if (eventName === 'message' || eventName === 'agent_message') {
if (typeof data.answer === 'string' && data.answer.length > 0) {
const botMsg = ensureBotMessage();
@@ -28,6 +28,7 @@ import {
createShippingParseReviewHandlers,
createShippingSendHandlers,
createShippingUploadHandlers,
useShippingOrderExtractionRuns,
onNoticeBatchConversationChanging,
findLatestShippingTaskId,
getShippingMatchResultPayload,
@@ -83,7 +84,7 @@ export interface UseChatShippingOptions {
isUploadingAttachments: Ref<boolean>;
attachmentPolicy: ComputedRef<{ anyEnabled: boolean }>;
presetQuestion: ComputedRef<string>;
saveLocalMessageToBackend: (msg: ChatMessage, userQuery?: string) => Promise<void>;
saveLocalMessageToBackend: (msg: ChatMessage, userQuery?: string) => Promise<boolean>;
newLocalMessageId: (prefix: string) => string;
stripReasoningPrelude: (text: string) => string;
sendMessage: (
@@ -91,7 +92,7 @@ export interface UseChatShippingOptions {
agentId: number,
kb: string,
files: ChatUploadFileSpec[],
context?: { task_id?: string; batch_no?: string; shipping_intake_nos?: string[]; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string },
context?: { task_id?: string; batch_no?: string; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string },
hooks?: SendMessageLifecycleHooks,
) => Promise<ChatMessageSendResult>;
startChatTurn: (options: import('../types/chat-turn.types').StartChatTurnOptions) => Promise<boolean>;
@@ -639,7 +640,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
const getCurrentShippingChatContext = () => ({
task_id: getActiveBatchTaskId() || getActiveShippingTaskId(),
batch_no: getActiveShippingBatchNo(),
shipping_intake_nos: shippingIntakes.getParsedIntakeNos(),
});
const getCurrentShippingChatContextWithDisplay = (displayQuery: string) => ({
@@ -862,6 +862,27 @@ export function useChatShipping(options: UseChatShippingOptions) {
msg,
t,
});
const shippingOrderExtractionRuns = useShippingOrderExtractionRuns({
messages,
conversationId,
currentAgentId,
newLocalMessageId,
saveLocalMessageToBackend,
refreshNoticeIntakeStatuses: shippingIntakes.refreshStatuses,
clearConsumedNoticeAttachments: shippingIntakes.clearConsumedAttachments,
syncShippingConversationWorkspace,
refreshShippingActions,
loadHistory,
onConversationResolved: async (resolvedConversationId) => {
const currentRouteId = typeof route.query.conversation_id === 'string' ? route.query.conversation_id : '';
if (currentRouteId === resolvedConversationId) return;
await router.replace({
path: route.path,
query: { ...route.query, conversation_id: resolvedConversationId },
});
},
t,
});
const showShippingDuplicateDialog = ref(false);
const showShippingCustomerDialog = ref(false);
@@ -1119,10 +1140,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
hasSelectedNoticeCandidates: () => shippingIntakes.getSelectedCandidateNos().length > 0,
openShippingDuplicateDialog,
getParsedIntakeNos: shippingIntakes.getParsedIntakeNos,
markOrderExtractionStarted: shippingIntakes.markOrderExtractionStarted,
rollbackOrderExtractionStarted: shippingIntakes.rollbackOrderExtractionStarted,
refreshNoticeIntakeStatuses: shippingIntakes.refreshStatuses,
clearConsumedNoticeAttachments: shippingIntakes.clearConsumedAttachments,
startOrderExtractionRun: shippingOrderExtractionRuns.startRun,
applyShippingMessageRecovery,
applyShippingBatchSnapshot,
syncShippingConversationWorkspace,
@@ -1169,8 +1187,10 @@ export function useChatShipping(options: UseChatShippingOptions) {
const onConversationIdChanging = (nextId: string, prevId: string | null | undefined) => {
onNoticeBatchConversationChanging(nextId, prevId);
shippingIntakes.stopPolling();
shippingOrderExtractionRuns.stopPolling();
if (nextId && nextId !== prevId) {
void shippingIntakes.restoreForConversation(nextId);
void shippingOrderExtractionRuns.restoreForConversation(nextId);
}
if (prevId !== nextId) {
resolvedShippingTaskId.value = '';
@@ -9,10 +9,7 @@ import { getAuthHeaders } from '@/shared/utils/auth';
import { applyStreamErrorToMessage, type StreamErrorLabels } from '../utils/streamErrorMessage';
import type { StartChatTurnOptions } from '../types/chat-turn.types';
import type { ChatMessage, ChatRun } from '../types/chat.types';
import {
applyShippingOrderExtractionStateToMessage,
applyShippingUiStateToMessage,
} from './useChat';
import { applyShippingUiStateToMessage } from './useChat';
export interface CreateStartChatTurnOptions {
messages: Ref<ChatMessage[]>;
@@ -172,9 +169,7 @@ export function createStartChatTurn(options: CreateStartChatTurnOptions) {
if (eventName === 'shipping_ui_state' || eventName === 'ui_state.updated') {
const botMsg = ensureBotMessage();
if (botMsg) applyShippingUiStateToMessage(botMsg, data);
} else if (eventName === 'shipping_order_extraction_state') {
const botMsg = ensureBotMessage();
if (botMsg) applyShippingOrderExtractionStateToMessage(botMsg, data);
} else if (
eventName === 'message'
|| eventName === 'agent_message'
@@ -0,0 +1,30 @@
/**
* features/chat/page/useChatPageLocalMessage.spec.ts
* 用途:验证非 SSE 本地消息的 ID 和持久化结果契约。
* 依赖:Vitest、useChatPageLocalMessage、chat.api mock。
* 逻辑:成功回写会话/日志并返回 true,且工厂始终返回可调用 helpers。
*/
import { computed, ref } from 'vue';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { ChatMessage } from '../types/chat.types';
const api = vi.hoisted(() => ({ saveLocalChatMessage: vi.fn() }));
vi.mock('../api/chat.api', () => ({ saveLocalChatMessage: api.saveLocalChatMessage }));
import { createChatPageLocalMessageApi } from './useChatPageLocalMessage';
describe('createChatPageLocalMessageApi', () => {
beforeEach(() => api.saveLocalChatMessage.mockReset());
it('returns helpers and reports a successful persisted message', async () => {
const conversationId = ref<string | null>(null);
api.saveLocalChatMessage.mockResolvedValue({ conversation_id: 'conv-local', chat_log_id: 42 });
const helpers = createChatPageLocalMessageApi({ conversationId, currentAgentId: computed(() => 7) });
const message: ChatMessage = { role: 'assistant', type: 'text', content: 'done' };
expect(helpers.newLocalMessageId('local')).toContain('local-');
expect(await helpers.saveLocalMessageToBackend(message)).toBe(true);
expect(conversationId.value).toBe('conv-local');
expect(message.chat_log_id).toBe(42);
});
});
@@ -1,5 +1,8 @@
/**
* 对话页:本地消息落库(请假/出货等不经过 SSE 的消息)。
* features/chat/page/useChatPageLocalMessage.ts
* 用途:持久化请假、出货等不经过 SSE 的本地聊天消息。
* 依赖:chat.api.saveLocalChatMessage、ChatMessage、Vue refs。
* 逻辑:各业务 composable 传入本地消息;本模块绑定当前会话并返回明确保存结果。
*/
import { saveLocalChatMessage } from '../api/chat.api';
import type { ChatMessage } from '../types/chat.types';
@@ -13,12 +16,19 @@ export interface ChatPageLocalMessageContext {
export function createChatPageLocalMessageApi(ctx: ChatPageLocalMessageContext) {
let localMessageCounter = 0;
const newLocalMessageId = (prefix: string) => {
/** 生成组件实例内唯一的本地消息 ID,用于前端渲染和提交前关联。 */
const newLocalMessageId = (prefix: string): string => {
localMessageCounter += 1;
return `${prefix}-${Date.now()}-${localMessageCounter}`;
};
const saveLocalMessageToBackend = async (localMsg: ChatMessage, userQuery: string = '') => {
/**
* 保存一条本地消息,并把服务端会话与日志主键回写到前端对象。
* @param localMsg - 待保存的用户或助手消息。
* @param userQuery - 用户消息展示文本;助手消息必须为空。
* @returns 服务端确认提交时为 true;网络或业务失败时为 false。
*/
const saveLocalMessageToBackend = async (localMsg: ChatMessage, userQuery: string = ''): Promise<boolean> => {
try {
const data = await saveLocalChatMessage({
conversation_id: ctx.conversationId.value,
@@ -35,8 +45,9 @@ export function createChatPageLocalMessageApi(ctx: ChatPageLocalMessageContext)
if (data.chat_log_id) {
localMsg.chat_log_id = data.chat_log_id;
}
} catch (e) {
console.error('Failed to save local message', e);
return true;
} catch {
return false;
}
};
@@ -54,7 +54,7 @@ export interface ChatPageSendContext {
agentId: number,
kb: string,
files: ChatUploadFileSpec[],
context?: { task_id?: string; batch_no?: string; shipping_intake_nos?: string[]; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string },
context?: { task_id?: string; batch_no?: string; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string },
hooks?: SendMessageLifecycleHooks,
) => Promise<ChatMessageSendResult>;
refreshHistoryAfterSend: () => Promise<void>;
@@ -75,7 +75,7 @@ export interface ChatPageSendContext {
msg: { warning: (text: string) => void; info: (text: string) => void };
t: (key: string) => string;
copiedIndex: Ref<number | null>;
getChatContext?: () => { task_id?: string; batch_no?: string; shipping_intake_nos?: string[]; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string };
getChatContext?: () => { task_id?: string; batch_no?: string; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string };
onAssistantMessageFinished?: (message: ChatMessage, runMessages: ChatMessage[]) => void | Promise<void>;
}
@@ -22,4 +22,5 @@ export * from './useChatShippingDecision';
export * from './useChatShippingMenuHandler';
export * from './useChatShippingUploadHandler';
export * from './useChatShippingSendHandler';
export * from './useShippingOrderExtractionRuns';
export * from './shippingTurnActions';
@@ -13,7 +13,7 @@ import type { Ref } from 'vue';
export interface ShippingLocalMessageContext {
messages: Ref<ChatMessage[]>;
newLocalMessageId: (prefix: string) => string;
saveLocalMessageToBackend: (msg: ChatMessage, userQuery?: string) => Promise<void>;
saveLocalMessageToBackend: (msg: ChatMessage, userQuery?: string) => Promise<boolean>;
}
/** @deprecated 使用 startChatTurn 替代 */
@@ -260,7 +260,6 @@ export function sanitizeShippingConversationText(text: string, enabled: boolean)
result = result
.replace(/\bcreate_task\b/gi, '新建任务')
.replace(/\bget_task_status\b/gi, '查询任务状态')
.replace(/\bsubmit_order_extraction\b/gi, '提交订单抽取')
.replace(/\bsubmit_decision\b/gi, '提交处理结果')
.replace(/\bmatch_inventory\b/gi, '匹配库存')
.replace(/\bgenerate_excel\b/gi, '生成发货 Excel')
@@ -21,7 +21,7 @@ export interface ShippingParseReviewContext {
messages: Ref<ChatMessage[]>;
resolvedShippingTaskId: Ref<string>;
newLocalMessageId: (prefix: string) => string;
saveLocalMessageToBackend: (msg: ChatMessage, userQuery?: string) => Promise<void>;
saveLocalMessageToBackend: (msg: ChatMessage, userQuery?: string) => Promise<boolean>;
refreshShippingActions: () => Promise<void>;
msg: { warning: (text: string) => void };
}
@@ -51,8 +51,7 @@ const createContext = (
handleShippingAutoUploadFile: vi.fn(async () => undefined),
handleShippingAutoUploadNoticeBatch: vi.fn(async () => undefined),
isShippingNoticeBatchSubmitting: () => isShippingNoticeBatchSubmitting(),
markOrderExtractionStarted: vi.fn(),
rollbackOrderExtractionStarted: vi.fn(),
startOrderExtractionRun: vi.fn(async () => true),
syncShippingConversationWorkspace: vi.fn(async () => true),
refreshShippingActions: vi.fn(async () => undefined),
shippingSuggestedPrompt: computed(() => ''),
@@ -116,8 +115,7 @@ describe('useChatShippingSendHandler', () => {
expect(ctx.handleShippingAutoUploadNoticeBatch).not.toHaveBeenCalled();
});
it('sends parsed intakes to the existing Chatflow without requiring upload-time candidates', async () => {
const completionOrder: string[] = [];
it('creates a background Run for parsed intakes without calling the Chatflow', async () => {
const attachment = {
id: 'notice-1',
kind: 'shipping_notice' as const,
@@ -134,11 +132,6 @@ describe('useChatShippingSendHandler', () => {
hasCandidateReviewIssues: () => true,
hasSelectedNoticeCandidates: () => true,
getParsedIntakeNos: () => ['SNI-1'],
applyShippingMessageRecovery: vi.fn(async () => { completionOrder.push('recovery'); 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);
@@ -146,35 +139,20 @@ describe('useChatShippingSendHandler', () => {
expect(consumed).toBe(true);
expect(ctx.handleShippingAutoUploadNoticeBatch).not.toHaveBeenCalled();
expect(ctx.sendMessage).toHaveBeenCalledWith(
expect(ctx.startOrderExtractionRun).toHaveBeenCalledWith(
'chat.shippingOrderExtractionDefaultPrompt',
1,
'',
[],
{
shipping_intake_nos: ['SNI-1'],
display_query: 'chat.shippingOrderExtractionDefaultPrompt',
},
expect.objectContaining({
userAttachments: [{
['SNI-1'],
[{
id: 'notice-1',
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.applyShippingMessageRecovery).toHaveBeenCalledWith(assistantMessage);
expect(completionOrder).toEqual(['recovery', 'intakes', 'workspace', 'clear', 'actions']);
expect(ctx.syncShippingConversationWorkspace).toHaveBeenCalledWith({ preferLatest: true });
expect(ctx.sendMessage).not.toHaveBeenCalled();
expect(ctx.attachments.value).toEqual([]);
});
it('uses the user query for full extraction even when no candidate exists before send', async () => {
@@ -201,33 +179,21 @@ describe('useChatShippingSendHandler', () => {
expect(consumed).toBe(true);
expect(ctx.handleShippingAutoUploadNoticeBatch).not.toHaveBeenCalled();
expect(ctx.sendMessage).toHaveBeenCalledWith(
expect(ctx.startOrderExtractionRun).toHaveBeenCalledWith(
'请解析这些附件',
1,
'',
[],
{
shipping_intake_nos: ['SNI-1'],
display_query: '请解析这些附件',
},
expect.objectContaining({
userAttachments: [{
['SNI-1'],
[{
id: 'notice-1',
name: 'orders.eml',
size: 100,
extension: 'eml',
type: 'document',
source: 'shipping_notice',
}],
onAssistantMessageFinished: expect.any(Function),
}),
}],
);
});
it('retries the conversation workspace once when the first refresh fails', async () => {
const syncWorkspace = vi.fn()
.mockResolvedValueOnce(false)
.mockResolvedValueOnce(true);
it('keeps attachments when Run creation reports not started', async () => {
const ctx = createContext({
attachments: ref([{
id: 'notice-retry',
@@ -241,22 +207,15 @@ describe('useChatShippingSendHandler', () => {
intakeNo: 'SNI-RETRY',
}]),
getParsedIntakeNos: () => ['SNI-RETRY'],
syncShippingConversationWorkspace: syncWorkspace,
startOrderExtractionRun: vi.fn(async () => false),
});
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);
expect(ctx.attachments.value).toHaveLength(1);
});
it('rolls back the local extracting state when the chat request fails', async () => {
const rollback = vi.fn();
it('keeps attachments and reports the error when Run creation fails', async () => {
const ctx = createContext({
attachments: ref([{
id: 'notice-failed-send',
@@ -270,20 +229,18 @@ describe('useChatShippingSendHandler', () => {
intakeNo: 'SNI-FAILED-SEND',
}]),
getParsedIntakeNos: () => ['SNI-FAILED-SEND'],
sendMessage: vi.fn(async () => { throw new Error('network failed'); }),
rollbackOrderExtractionStarted: rollback,
startOrderExtractionRun: vi.fn(async () => { throw new Error('network 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');
expect(ctx.attachments.value).toHaveLength(1);
});
it('rolls back extraction state when sendMessage reports a handled stream failure', async () => {
const rollback = vi.fn();
it('does not call the Chatflow when Run creation is handled as unavailable', async () => {
const ctx = createContext({
attachments: ref([{
id: 'notice-handled-failure',
@@ -297,19 +254,18 @@ describe('useChatShippingSendHandler', () => {
intakeNo: 'SNI-HANDLED-FAILURE',
}]),
getParsedIntakeNos: () => ['SNI-HANDLED-FAILURE'],
sendMessage: vi.fn(async () => ({ accepted: false, completed: false })),
rollbackOrderExtractionStarted: rollback,
startOrderExtractionRun: vi.fn(async () => false),
});
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(ctx.sendMessage).not.toHaveBeenCalled();
expect(ctx.attachments.value).toHaveLength(1);
});
it('removes submitted notice attachments after acceptance even when the assistant stream fails', async () => {
it('removes only the Intake set accepted by the background Run', async () => {
const submitted = {
id: 'notice-accepted-error',
kind: 'shipping_notice' as const,
@@ -330,15 +286,14 @@ describe('useChatShippingSendHandler', () => {
const ctx = createContext({
attachments: ref([submitted, retained]),
getParsedIntakeNos: () => ['SNI-ACCEPTED-ERROR'],
sendMessage: vi.fn(async () => ({ accepted: true, completed: false, chatLogId: 42 })),
startOrderExtractionRun: vi.fn(async () => true),
});
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
expect(consumed).toBe(true);
expect(ctx.rollbackOrderExtractionStarted).not.toHaveBeenCalled();
expect(ctx.attachments.value).toEqual([retained]);
expect(ctx.loadHistory).toHaveBeenCalledOnce();
expect(ctx.sendMessage).not.toHaveBeenCalled();
});
});
@@ -2,7 +2,7 @@
* features/chat/shipping/useChatShippingSendHandler.ts
* 用途:在聊天发送前拦截发货通知专属意图,如订单抽取、切票、决策文本和附件自动流程。
* 依赖:shipping.api、shippingIntents、shippingMenu、shippingDownload、chat.types。
* 逻辑:已预处理 Intake 通过普通聊天接口进入现有 Dify Chatflow;其他业务动作经 Chat Turn / handleShippingMenuAction。
* 逻辑:已预处理 Intake 创建独立订单抽取 Run;其他业务动作经 Chat Turn / handleShippingMenuAction。
*/
import {
getWorkspaceShippingBatch,
@@ -51,7 +51,7 @@ export interface ShippingSendHandlerContext {
agentId: number,
kb: string,
files: ChatUploadFileSpec[],
context?: { task_id?: string; batch_no?: string; shipping_intake_nos?: string[]; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string },
context?: { task_id?: string; batch_no?: string; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string },
hooks?: SendMessageLifecycleHooks,
) => Promise<ChatMessageSendResult>;
buildFileSpecsForSend: () => Promise<ChatUploadFileSpec[]>;
@@ -72,10 +72,7 @@ export interface ShippingSendHandlerContext {
hasSelectedNoticeCandidates?: () => boolean;
openShippingDuplicateDialog?: (attachmentId?: string) => void;
getParsedIntakeNos?: () => string[];
markOrderExtractionStarted?: (intakeNos: string[]) => void;
rollbackOrderExtractionStarted?: (intakeNos: string[]) => void;
refreshNoticeIntakeStatuses?: () => Promise<void>;
clearConsumedNoticeAttachments?: () => void;
startOrderExtractionRun?: (query: string, intakeNos: string[], attachments: ReturnType<typeof createChatMessageAttachmentSnapshots>) => Promise<boolean>;
applyShippingMessageRecovery?: (message: ChatMessage) => Promise<boolean>;
applyShippingBatchSnapshot?: (message: ChatMessage) => boolean;
syncShippingConversationWorkspace: (options?: { preferLatest?: boolean }) => Promise<boolean>;
@@ -90,7 +87,7 @@ export interface ShippingSendHandlerContext {
/**
* 创建发货通知发送拦截器。
*
* 核心逻辑:已预处理邮件固定 Intake 上下文后调用普通聊天;其余识别切换任务、数字菜单、决策文本、映射文本、上传/导出意图。
* 核心逻辑:已预处理邮件固定 Intake 后创建后台 Run;其余识别切换任务、数字菜单、决策文本、映射文本、上传/导出意图。
* @param ctx - 发送拦截上下文
* @returns 发送前文本与附件自动流程处理函数;返回 true 表示已消费本次发送
*/
@@ -221,48 +218,16 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
const query = trimmed || ctx.t('chat.shippingOrderExtractionDefaultPrompt');
ctx.shippingAutoFlowRequested.value = false;
if (typeof textOrEvent !== 'string') ctx.input.value = '';
ctx.markOrderExtractionStarted?.(intakeNos);
try {
const sent = await ctx.sendMessage(
query,
ctx.currentAgentId.value,
ctx.selectedKb.value,
[],
{
shipping_intake_nos: intakeNos,
display_query: query,
},
{
userAttachments,
onAssistantMessageFinished: async (assistantMessage) => {
if (ctx.applyShippingMessageRecovery) {
await ctx.applyShippingMessageRecovery(assistantMessage);
} else {
ctx.applyShippingBatchSnapshot?.(assistantMessage);
}
await ctx.refreshNoticeIntakeStatuses?.();
if (!(await ctx.syncShippingConversationWorkspace({ preferLatest: true }))) {
await new Promise((resolve) => setTimeout(resolve, 300));
await ctx.syncShippingConversationWorkspace({ preferLatest: true });
}
ctx.clearConsumedNoticeAttachments?.();
await ctx.refreshShippingActions();
},
},
);
if (!sent.accepted) {
ctx.rollbackOrderExtractionStarted?.(intakeNos);
return true;
}
const started = 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
|| !submittedIntakes.has(item.intakeNo.trim().toUpperCase()),
);
await ctx.loadHistory();
} catch (e: unknown) {
ctx.rollbackOrderExtractionStarted?.(intakeNos);
const errorMessage = e instanceof Error ? e.message : '文件处理失败';
ctx.msg.warning(errorMessage);
}
@@ -21,6 +21,18 @@ describe('shipping notice order extraction state', () => {
})).toBe(false);
});
it('does not resubmit persisted or active order extraction results', () => {
const base = {
intakeNo: 'SNI-PERSISTED',
parseStatus: 'parsed' as const,
parseSummary: undefined,
};
expect(isOrderExtractionEligibleIntake({ ...base, orderExtractionStatus: 'extracting' })).toBe(false);
expect(isOrderExtractionEligibleIntake({ ...base, orderExtractionStatus: 'partially_completed' })).toBe(false);
expect(isOrderExtractionEligibleIntake({ ...base, orderExtractionStatus: 'completed' })).toBe(false);
expect(isOrderExtractionEligibleIntake({ ...base, orderExtractionStatus: 'failed' })).toBe(true);
});
it('keeps polling after preprocessing is parsed while order extraction is active', () => {
expect(shouldPollShippingNoticeIntake({
parseStatus: 'parsed',
@@ -47,6 +59,7 @@ 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', 'failed', 0)).toBe(true);
expect(shouldRestoreShippingNoticeIntake('parsed', 'partially_completed', 2)).toBe(true);
// 已完成且没有待审核 Candidate 的文件仅保留在用户消息气泡中。
@@ -53,6 +53,7 @@ export function shouldRestoreShippingNoticeIntake(
const extractionStatus = String(orderExtractionStatus || '').trim().toLowerCase();
return ACTIVE_PARSE.has(status)
|| status === 'parse_failed'
|| extractionStatus === 'failed'
|| (extractionStatus === 'partially_completed' && candidateCount > 0);
}
@@ -66,10 +67,12 @@ export function shouldPollShippingNoticeIntake(
/** 判断附件是否仍可作为新一轮完整订单抽取的输入。 */
export function isOrderExtractionEligibleIntake(
item: Pick<ShippingNoticePendingAttachment, 'intakeNo' | 'parseStatus' | 'parseSummary'>,
item: Pick<ShippingNoticePendingAttachment, 'intakeNo' | 'parseStatus' | 'parseSummary' | 'orderExtractionStatus'>,
): boolean {
const extractionStatus = String(item.orderExtractionStatus || 'not_started').trim().toLowerCase();
return item.parseStatus === 'parsed'
&& Boolean(item.intakeNo)
&& (extractionStatus === 'not_started' || extractionStatus === 'failed')
&& !isShippingNoticeAttachmentParseIncomplete(item.parseSummary);
}
@@ -0,0 +1,157 @@
/**
* 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(() => ({
createRun: vi.fn(),
getRun: vi.fn(),
listRuns: vi.fn(),
}));
vi.mock('../api/shipping.api', () => ({
createWorkspaceShippingOrderExtractionRun: api.createRun,
getWorkspaceShippingOrderExtractionRun: api.getRun,
listWorkspaceShippingOrderExtractionRuns: api.listRuns,
}));
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,
...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),
clearConsumedNoticeAttachments: vi.fn(),
syncShippingConversationWorkspace: vi.fn(async () => true),
refreshShippingActions: vi.fn(async () => undefined),
loadHistory: vi.fn(async () => undefined),
onConversationResolved: vi.fn(async () => undefined),
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 stable user and assistant formIds and does not write unchanged polling state again', async () => {
const queued = run({ run_no: 'SNER-START', conversation_id: 'conv-created' });
api.createRun.mockResolvedValue({ run: queued, reused: false });
api.getRun.mockResolvedValue(queued);
const harness = createHarness();
await harness.runs.startRun('解析附件', ['SNI-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([
'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('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' })] })
.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('extracting');
});
it('aborts a hanging Run query after ten seconds and keeps polling as a transport failure', async () => {
api.createRun.mockResolvedValue({ run: run({ run_no: 'SNER-TIMEOUT', conversation_id: 'conv-timeout' }), reused: false });
api.getRun.mockImplementation((_runNo: string, signal: AbortSignal) => 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');
expect(harness.messages.value[1]?.shipping_order_extraction_state?.status).toBe('extracting');
harness.runs.stopPolling();
});
});
describe('mapOrderExtractionRunToMessageState', () => {
it('maps queued/running to indeterminate extracting state', () => {
expect(mapOrderExtractionRunToMessageState(run({ status: 'running', phase: 'calling_provider' }))).toMatchObject({
status: 'extracting', terminal: false, phase: 'llm_extraction',
});
});
it('maps completed result counters without guessing from text', () => {
expect(mapOrderExtractionRunToMessageState(run({
status: 'completed',
result: { batch_no: 'SB-1', created_count: 2, opened_existing_count: 1, pending_count: 0 },
}))).toMatchObject({
status: 'completed', terminal: true, batch_no: 'SB-1', created_count: 2, opened_existing_count: 1,
});
});
it('maps needs_review 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 });
expect(mapOrderExtractionRunToMessageState(run({
status: 'failed', error: { code: 'X', message: 'provider failed' },
}))).toMatchObject({ status: 'failed', message: 'provider failed', terminal: true });
});
});
@@ -0,0 +1,245 @@
/**
* features/chat/shipping/useShippingOrderExtractionRuns.ts
* 用途:把货代订单抽取作为独立 Run 启动、轮询并投影到聊天状态消息。
* 依赖:shipping.api Run 接口、chat.types、Vue refs。
* 逻辑:发送处理器调用 startRun;本模块持久化本地消息并轮询 Run,终态后刷新 Intake、批次工作台与动作。
*/
import { onBeforeUnmount, type ComputedRef, type Ref } from 'vue';
import {
createWorkspaceShippingOrderExtractionRun,
getWorkspaceShippingOrderExtractionRun,
listWorkspaceShippingOrderExtractionRuns,
} from '../api/shipping.api';
import type { ChatMessage, ChatMessageAttachment, ShippingOrderExtractionState } from '../types/chat.types';
import type { ShippingOrderExtractionRun } from '../types/shipping.api.types';
interface UseShippingOrderExtractionRunsOptions {
messages: Ref<ChatMessage[]>;
conversationId: Ref<string | null>;
currentAgentId: ComputedRef<number>;
newLocalMessageId: (prefix: string) => string;
saveLocalMessageToBackend: (message: ChatMessage, userQuery?: string) => Promise<boolean>;
refreshNoticeIntakeStatuses: () => Promise<void>;
clearConsumedNoticeAttachments: () => void;
syncShippingConversationWorkspace: (options?: { preferLatest?: boolean }) => Promise<boolean>;
refreshShippingActions: () => Promise<void>;
loadHistory: () => Promise<void>;
onConversationResolved: (conversationId: string) => Promise<void> | void;
t: (key: string, params?: Record<string, unknown>) => string;
}
const ACTIVE_RUN_STATUSES = new Set(['queued', 'running', 'result_persisted']);
/** 把领域 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',
message: failed ? String(run.error?.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,
};
}
export function useShippingOrderExtractionRuns(options: UseShippingOrderExtractionRunsOptions) {
let pollTimer: ReturnType<typeof setTimeout> | null = null;
let requestController: AbortController | null = null;
let activeRunNo = '';
let pollFailureCount = 0;
let pollGeneration = 0;
const persistedSignatures = new Map<string, string>();
/** 停止当前 Run 短轮询;终态、切会话和组件卸载都会调用。 */
const stopPolling = () => {
if (pollTimer) clearTimeout(pollTimer);
requestController?.abort();
requestController = null;
pollTimer = null;
activeRunNo = '';
pollFailureCount = 0;
pollGeneration += 1;
};
/**
* 查找或创建当前 Run 的助手状态消息,仅在业务状态真正变化时持久化。
* @param run - 用户态 Run 摘要,不包含 Provider 快照或原始文档。
* @returns 当前会话内原位更新后的助手状态消息。
*/
const upsertRunMessage = async (run: ShippingOrderExtractionRun): Promise<ChatMessage> => {
const formId = `shipping-order-extraction-run:${run.run_no}`;
const state = mapOrderExtractionRunToMessageState(run);
let message = options.messages.value.find((item) => {
const payload = item.payload && typeof item.payload === 'object' ? item.payload as Record<string, unknown> : {};
return payload.formId === formId;
});
if (!message) {
message = {
role: 'assistant',
type: 'text',
content: '',
local_id: options.newLocalMessageId('shipping-order-extraction'),
local_only: true,
};
options.messages.value.push(message);
}
message.shipping_order_extraction_state = state;
message.payload = {
formId,
order_extraction_run_no: run.run_no,
shipping_order_extraction_state: state,
};
const signature = JSON.stringify({ status: run.status, phase: run.phase, result: run.result, error: run.error });
if (persistedSignatures.get(run.run_no) !== signature) {
const persisted = await options.saveLocalMessageToBackend(message);
if (persisted) persistedSignatures.set(run.run_no, signature);
}
return message;
};
/**
* Run 终态后容错刷新领域事实;单个视图失败不得阻断其他事实和聊天历史恢复。
* @returns 所有可独立执行的刷新均已尝试完成。
*/
const refreshTerminalFacts = async () => {
await Promise.allSettled([
options.refreshNoticeIntakeStatuses(),
options.refreshShippingActions(),
]);
options.clearConsumedNoticeAttachments();
try {
if (!(await options.syncShippingConversationWorkspace({ preferLatest: true }))) {
await new Promise((resolve) => setTimeout(resolve, 300));
await options.syncShippingConversationWorkspace({ preferLatest: true });
}
} catch {
// Run 状态卡已持久化;工作台可由页面下一次刷新继续恢复。
}
await Promise.allSettled([options.loadHistory()]);
};
/** 创建带 10 秒上限的 Run GET 控制器;超时只中止本次查询,不改变后台业务状态。 */
const createRequestController = (generation: number) => {
requestController?.abort();
const controller = new AbortController();
requestController = controller;
const timeout = setTimeout(() => controller.abort(), 10000);
return {
signal: controller.signal,
release: () => { clearTimeout(timeout); if (generation === pollGeneration) requestController = null; },
};
};
/**
* 轮询指定 Run;generation 隔离切会话后的迟到响应,网络失败按上限退避。
* @param runNo - 当前会话唯一活动 Run 编号。
* @param generation - 启动本轮轮询时的生命周期版本。
*/
const pollRun = async (runNo: string, generation: number): Promise<void> => {
if (generation !== pollGeneration || activeRunNo !== runNo) return;
try {
const request = createRequestController(generation);
const run = await getWorkspaceShippingOrderExtractionRun(runNo, request.signal).finally(request.release);
if (generation !== pollGeneration || activeRunNo !== runNo) return;
pollFailureCount = 0;
await upsertRunMessage(run);
if (generation !== pollGeneration || activeRunNo !== runNo) return;
if (!ACTIVE_RUN_STATUSES.has(run.status)) {
stopPolling();
await refreshTerminalFacts();
return;
}
pollTimer = setTimeout(() => void pollRun(run.run_no, generation), 2000);
} catch {
if (generation !== pollGeneration || activeRunNo !== runNo) return;
pollFailureCount += 1;
const delayMs = Math.min(15000, 2000 * (2 ** Math.min(pollFailureCount, 3)));
pollTimer = setTimeout(() => void pollRun(runNo, generation), delayMs);
}
};
/** 为活动 Run 建立新的轮询生命周期,确保同一组件实例仅跟踪一个 Run。 */
const beginPolling = (runNo: string, delayMs: number) => {
stopPolling();
activeRunNo = runNo;
const generation = pollGeneration;
pollTimer = setTimeout(() => void pollRun(runNo, generation), delayMs);
};
/**
* 启动订单抽取后台 Run,并把用户操作和状态卡持久化到本地会话。
* @param query - 用户本次展示文本;不发送给 Dify Chatflow。
* @param intakeNos - 本次冻结的 Intake 编号。
* @param attachments - 用户消息中的安全附件快照。
* @returns Run 已成功创建或幂等复用时为 true。
*/
const startRun = async (
query: string,
intakeNos: string[],
attachments: ChatMessageAttachment[],
): Promise<boolean> => {
stopPolling();
const response = await createWorkspaceShippingOrderExtractionRun({
agent_id: options.currentAgentId.value,
conversation_id: options.conversationId.value || undefined,
intake_nos: intakeNos,
});
const run = response.run;
if (!options.conversationId.value) options.conversationId.value = run.conversation_id;
const userMessage: ChatMessage = {
role: 'user',
type: 'text',
content: query,
attachments,
local_id: options.newLocalMessageId('shipping-order-extraction-user'),
local_only: true,
payload: {
formId: `shipping-order-extraction-user:${run.run_no}`,
order_extraction_run_no: run.run_no,
},
};
options.messages.value.push(userMessage);
await options.saveLocalMessageToBackend(userMessage, query);
await upsertRunMessage(run);
await options.onConversationResolved(run.conversation_id);
if (ACTIVE_RUN_STATUSES.has(run.status)) {
beginPolling(run.run_no, 1000);
} else {
await refreshTerminalFacts();
}
return true;
};
/** 刷新或进入既有会话时恢复最新 Run;活动 Run 继续轮询,终态只恢复状态卡。 */
const restoreForConversation = async (conversationId: string): Promise<void> => {
stopPolling();
try {
const generation = pollGeneration;
const request = createRequestController(generation);
const { items } = await listWorkspaceShippingOrderExtractionRuns(conversationId, 20, request.signal).finally(request.release);
if (options.conversationId.value !== conversationId) return;
const latest = items[0];
if (!latest) return;
await upsertRunMessage(latest);
if (options.conversationId.value !== conversationId) return;
if (ACTIVE_RUN_STATUSES.has(latest.status)) {
beginPolling(latest.run_no, 1000);
}
} catch {
// 会话历史仍可正常使用;下一次进入会话或手动刷新时重新恢复 Run。
}
};
onBeforeUnmount(stopPolling);
return { startRun, restoreForConversation, stopPolling, getActiveRunNo: () => activeRunNo };
}
@@ -540,6 +540,46 @@ export interface ShippingNoticeIntakeResponse {
candidate_count?: number;
}
export type ShippingOrderExtractionRunStatus =
| 'queued'
| 'running'
| 'result_persisted'
| 'completed'
| 'needs_review'
| 'failed'
| 'cancelled';
export interface ShippingOrderExtractionRun {
run_no: string;
agent_id: number;
conversation_id: string;
status: ShippingOrderExtractionRunStatus;
phase: string;
intake_nos: string[];
schema_version_id: number;
schema_version?: number | null;
schema_checksum?: string | null;
attempt_count: number;
result?: {
batch_no?: string | null;
created_count?: number;
opened_existing_count?: number;
pending_count?: number;
non_shipping_count?: number;
created_with_missing_fields_count?: number;
} | null;
error?: { code?: string | null; message?: string | null } | null;
created_at?: string | null;
updated_at?: string | null;
started_at?: string | null;
finished_at?: string | null;
}
export interface ShippingOrderExtractionRunCreateResponse {
run: ShippingOrderExtractionRun;
reused: boolean;
}
export interface ShippingNoticeDocumentResponse {
id: number;
document_type: string;