246 lines
10 KiB
TypeScript
246 lines
10 KiB
TypeScript
/**
|
||
* 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 };
|
||
}
|