/** * features/chat/shipping/useShippingNoticeWorkflow.ts * 用途:会话级货代发货通知「本次处理」投影轮询(统一 ShippingProcessing)。 * 依赖:shipping.api getWorkspaceShippingProcessing / focus·viewed、Vue 响应式、BusinessError。 * 逻辑:由 ChatViewContent / ShippingWorkflowTimeline 消费;仅读 shipping-processing; * focus/viewed 写路径优先应用响应中的 work_items; * 前台 2s / 后台 8s;请求 10s AbortController 超时;失败指数退避至 8s;无活跃任务时停轮询。 */ import { computed, getCurrentInstance, onBeforeUnmount, ref, unref, watch, type InjectionKey, type MaybeRefOrGetter, type Ref, } from 'vue'; import { BusinessError } from '@/shared/api/client'; import { focusWorkspaceConversationTask, getWorkspaceShippingProcessing, markWorkspaceConversationTaskViewed, } from '../api/shipping.api'; import type { ConversationProcessingProjection, ShippingProcessingProjection, } from '../types/shipping.api.types'; import { resolveConversationProcessingFromUnified } from './conversationProcessingProjection'; const FOREGROUND_POLL_MS = 2000; const BACKGROUND_POLL_MS = 8000; const REQUEST_TIMEOUT_MS = 10000; const MAX_BACKOFF_MS = 8000; export type UseShippingNoticeWorkflowOptions = { /** 当前会话 ID;空则停轮询并清空。 */ conversationId: MaybeRefOrGetter; /** 父级递增以触发立即刷新(终态/重识别后)。 */ refreshTrigger?: MaybeRefOrGetter; }; export type UseShippingNoticeWorkflowReturn = { /** 后端 conversation_processing / 由 work_items 合成。 */ processing: Ref; /** 统一 ShippingProcessing work_items。 */ processingWorkItems: Ref; loading: Ref; error: Ref; refresh: () => Promise; focusConversationTask: (taskNo: string) => Promise; markConversationTaskViewed: (taskNo: string) => Promise; stop: () => void; }; /** ChatViewContent provide → Timeline / ExtractionCard inject。 */ export const SHIPPING_WORKFLOW_KEY: InjectionKey = Symbol( 'shippingNoticeWorkflow', ); /** * 解析 conversationId / refreshTrigger 的 MaybeRefOrGetter。 */ function readOption(source: MaybeRefOrGetter): T { return typeof source === 'function' ? (source as () => T)() : unref(source); } /** * 按页面可见性选择轮询间隔。 */ function resolvePollMs(): number { if (typeof document !== 'undefined' && document.visibilityState === 'hidden') { return BACKGROUND_POLL_MS; } return FOREGROUND_POLL_MS; } /** * 失败退避:2s → 4s → 8s(封顶)。 * @param failureCount - 连续失败次数(≥1) */ export function resolveProcessingPollBackoffMs(failureCount: number): number { const n = Math.max(1, Math.floor(failureCount)); return Math.min(FOREGROUND_POLL_MS * (2 ** (n - 1)), MAX_BACKOFF_MS); } /** * 判断是否应继续轮询统一 ShippingProcessing。 * 核心逻辑:processing / needs_action 有活跃项则继续。 */ export function shouldContinueProcessingPolling( processing?: ConversationProcessingProjection | null, ): boolean { const processingCount = Number(processing?.summary?.processing || processing?.processing?.length || 0); const needsActionCount = Number(processing?.summary?.needs_action || processing?.needs_action?.length || 0); return processingCount > 0 || needsActionCount > 0; } /** * 会话级 ShippingProcessing 轮询 composable。 * * @param options.conversationId - 会话 ID * @param options.refreshTrigger - 外部刷新触发器 * @returns processing / processingWorkItems / loading / error … */ export function useShippingNoticeWorkflow( options: UseShippingNoticeWorkflowOptions, ): UseShippingNoticeWorkflowReturn { const processing = ref(null); const processingWorkItems = ref([]); const loading = ref(false); const error = ref(null); let pollTimer: ReturnType | null = null; let pollGeneration = 0; let requestController: AbortController | null = null; let requestGeneration = 0; let inFlightRefresh: { conversationId: string; promise: Promise } | null = null; let failureCount = 0; let pollingStopped = false; const normalizedConversationId = computed(() => String(readOption(options.conversationId) || '').trim(), ); /** * 中止进行中的请求与定时器。 */ function stop() { pollingStopped = true; if (pollTimer) clearTimeout(pollTimer); pollTimer = null; requestController?.abort(); requestController = null; requestGeneration += 1; pollGeneration += 1; } /** * 创建带超时的 AbortController。 */ function createRequestController(): AbortController { requestController?.abort(); const controller = new AbortController(); requestController = controller; const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS); controller.signal.addEventListener('abort', () => clearTimeout(timeout), { once: true }); return controller; } /** * 仅拉取统一 shipping-processing 投影。 * 核心逻辑:work_items 非空时始终由 order_task 合成任务列表;embedded 仅补焦点元数据; * 同会话在途请求合并;跨会话请求中止,且只有最新一代可回写页面数据。 * @returns Promise;可恢复网络失败写入 error,不向页面抛出。 */ async function executeRefresh(conversationId: string): Promise { const generation = ++requestGeneration; loading.value = true; const controller = createRequestController(); try { // [STEP 1] 统一投影为唯一读源。 const unified = await getWorkspaceShippingProcessing(conversationId, controller.signal); if ( controller.signal.aborted || generation !== requestGeneration || conversationId !== normalizedConversationId.value ) return; const workItems = Array.isArray(unified?.work_items) ? unified.work_items : []; const embedded = unified?.conversation_processing as ConversationProcessingProjection | null | undefined; processingWorkItems.value = workItems; processing.value = resolveConversationProcessingFromUnified(workItems, embedded); error.value = null; failureCount = 0; } catch (reason) { if ( controller.signal.aborted || generation !== requestGeneration || conversationId !== normalizedConversationId.value ) return; failureCount += 1; error.value = reason instanceof BusinessError ? reason.message : 'network_recoverable'; } finally { if (requestController === controller) requestController = null; if (generation === requestGeneration) loading.value = false; } } /** * 拉取统一进度;同一会话已有请求时复用该 Promise,避免首屏触发源互相取消重发。 */ function refresh(): Promise { const conversationId = normalizedConversationId.value; if (!conversationId) { processing.value = null; processingWorkItems.value = []; error.value = null; return Promise.resolve(); } if (inFlightRefresh?.conversationId === conversationId) { return inFlightRefresh.promise; } const promise = executeRefresh(conversationId).finally(() => { if (inFlightRefresh?.promise === promise) inFlightRefresh = null; }); inFlightRefresh = { conversationId, promise }; return promise; } /** * 将 focus/viewed/submit 写路径响应应用到本地 processing 与 work_items。 * 核心逻辑:有 work_items 时用统一合成;否则仅回写 processing 兼容块。 */ function applyMutationProcessingResponse(response: { processing?: ConversationProcessingProjection | null; work_items?: unknown[]; }): void { const workItems = Array.isArray(response.work_items) ? response.work_items : []; if (workItems.length > 0) { processingWorkItems.value = workItems as typeof processingWorkItems.value; processing.value = resolveConversationProcessingFromUnified( workItems as typeof processingWorkItems.value, response.processing ?? null, ); return; } if (response.processing) processing.value = response.processing; } /** * 标记用户可见任务为焦点(写审计并刷新 processing)。 */ async function focusConversationTask(taskNo: string): Promise { const normalized = String(taskNo || '').trim(); const conversationId = normalizedConversationId.value; if (!normalized || !conversationId) return; const response = await focusWorkspaceConversationTask(normalized, { conversation_id: conversationId, }); applyMutationProcessingResponse(response); } /** * 标记用户可见任务已查看(不等于业务已处理)。 */ async function markConversationTaskViewed(taskNo: string): Promise { const normalized = String(taskNo || '').trim(); const conversationId = normalizedConversationId.value; if (!normalized || !conversationId) return; const response = await markWorkspaceConversationTaskViewed(normalized, { conversation_id: conversationId, }); applyMutationProcessingResponse(response); } /** * 调度下一次轮询;失败时按退避间隔。 */ function schedulePoll(generation: number, delayMs: number) { if (pollTimer) clearTimeout(pollTimer); pollTimer = setTimeout(async () => { if (generation !== pollGeneration || pollingStopped) return; await refresh(); if (generation !== pollGeneration || pollingStopped) return; if (!normalizedConversationId.value) return; if (error.value) { schedulePoll(generation, resolveProcessingPollBackoffMs(failureCount)); return; } if (!shouldContinueProcessingPolling(processing.value)) { return; } const nextDelay = failureCount > 0 ? resolveProcessingPollBackoffMs(failureCount) : resolvePollMs(); schedulePoll(generation, nextDelay); }, delayMs); } /** * 重启轮询生命周期。 */ function restartPolling() { stop(); pollingStopped = false; const conversationId = normalizedConversationId.value; if (!conversationId) { error.value = null; return; } const generation = pollGeneration; void refresh().then(() => { if (generation !== pollGeneration || pollingStopped) return; if (error.value) { schedulePoll(generation, resolveProcessingPollBackoffMs(failureCount)); return; } if (!shouldContinueProcessingPolling(processing.value)) return; schedulePoll(generation, resolvePollMs()); }); } function onVisibilityChange() { if (typeof document === 'undefined' || document.visibilityState !== 'visible') return; if (!normalizedConversationId.value || pollingStopped) return; schedulePoll(pollGeneration, 0); } watch(normalizedConversationId, (nextConversationId, previousConversationId) => { if (nextConversationId !== previousConversationId) { processing.value = null; processingWorkItems.value = []; error.value = null; } restartPolling(); }, { immediate: true }); watch( () => readOption(options.refreshTrigger ?? 0), () => { if (!normalizedConversationId.value) return; pollingStopped = false; schedulePoll(pollGeneration, 0); }, ); if (typeof document !== 'undefined') { document.addEventListener('visibilitychange', onVisibilityChange); } if (getCurrentInstance()) { onBeforeUnmount(() => { if (typeof document !== 'undefined') { document.removeEventListener('visibilitychange', onVisibilityChange); } stop(); }); } return { processing, processingWorkItems, loading, error, refresh, focusConversationTask, markConversationTaskViewed, stop, }; }