/** * features/chat/shipping/useShippingNoticeWorkflow.ts * 用途:会话级货代发货通知「本次处理」投影轮询(统一 ShippingProcessing)。 * 依赖:shipping.api getWorkspaceShippingProcessing / focus·viewed、Vue 响应式、BusinessError。 * 逻辑:由 ChatViewContent / ShippingWorkflowTimeline 消费;仅读 shipping-processing; * focus/viewed 写路径优先应用响应中的 work_items; * 前台 2s / 后台 8s;共享请求的超时由 API 层统一管理;会话切换/卸载才取消当前消费者;失败指数退避至 8s; * 分层轮询:仅系统处理中 2s 轮询;外部 Run 轮询不会在待人工处理时反复唤醒本读接口; * 区分 initialLoading / manualRefreshing / polling 三种 loading 态; * 语义签名比较:业务状态未变化时不替换投影对象,防止按钮闪烁与 DOM 重建。 */ 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 { buildProcessingSemanticKey, createIntakeOtStabilizer, resolveConversationProcessingFromUnified, } from './conversationProcessingProjection'; const FIRST_ACTIVE_POLL_MS = 2000; const MID_ACTIVE_POLL_MS = 5000; const LONG_ACTIVE_POLL_MS = 10000; const BACKGROUND_POLL_MS = 30000; const MAX_BACKOFF_MS = 30000; const SNAPSHOT_CACHE_LIMIT = 20; type ProjectionSnapshot = { conversationId: string; processing: ConversationProcessingProjection; workItems: ShippingProcessingProjection[]; semanticKey: string; receivedAt: number; lastAccessedAt: number; processingStartedAt: number | null; }; export type ProcessingPollContext = { elapsedMs: number; visibility: DocumentVisibilityState | 'visible' | 'hidden'; hasProcessing: boolean; failureCount: number; }; export type UseShippingNoticeWorkflowOptions = { /** 当前会话 ID;空则停轮询并清空。 */ conversationId: MaybeRefOrGetter; /** 父级递增以触发立即刷新(终态/重识别后)。 */ refreshTrigger?: MaybeRefOrGetter; }; export type UseShippingNoticeWorkflowReturn = { /** 后端 conversation_processing;仅旧接口缺状态组时由 work_items 兼容合成。 */ processing: Ref; /** 统一 ShippingProcessing work_items。 */ processingWorkItems: Ref; /** 兼容旧消费者:任何加载状态均为 true。 */ loading: Ref; /** 首次打开会话加载中(投影仍为空)。 */ initialLoading: Ref; /** 用户主动点击刷新或执行重试/重解析/取消等写操作后加载。 */ manualRefreshing: Ref; /** 后台静默轮询中(不显示 loading,不禁用按钮)。 */ polling: Ref; /** 当前会话任意 Projection GET 在途;不得作为整卡遮罩条件。 */ isFetching: Ref; /** 当前会话已有成功 Projection 时的刷新状态。 */ isRefreshing: Ref; /** 当前会话最后一次成功 Projection 接收时间。 */ snapshotUpdatedAt: 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); } /** * 按页面可见性 + 业务状态选择轮询间隔。 * 分层策略:系统处理中 2s;待人工复核 30s;后台标签页 8s(若仍需轮询)。 */ export function resolveProcessingPollIntervalMs(context: ProcessingPollContext): number | null { if (!context.hasProcessing) return null; if (context.failureCount > 0) return resolveProcessingPollBackoffMs(context.failureCount); if (context.visibility === 'hidden') return BACKGROUND_POLL_MS; if (context.elapsedMs < 15000) return FIRST_ACTIVE_POLL_MS; if (context.elapsedMs < 60000) return MID_ACTIVE_POLL_MS; return LONG_ACTIVE_POLL_MS; } /** * 失败退避:10s → 20s → 30s(封顶)。 * @param failureCount - 连续失败次数(≥1) */ export function resolveProcessingPollBackoffMs(failureCount: number): number { const n = Math.max(1, Math.floor(failureCount)); return Math.min(LONG_ACTIVE_POLL_MS * (2 ** (n - 1)), MAX_BACKOFF_MS); } /** * 判断是否应继续轮询统一 ShippingProcessing。 * 核心逻辑:仅系统处理中(processing>0)时持续 2s 轮询; * 待人工复核不触发后台轮询;全部完成/取消/历史时停止轮询。 */ export function shouldContinueProcessingPolling( processing?: ConversationProcessingProjection | null, ): boolean { const processingCount = Number( processing?.summary?.processing ?? processing?.status_groups?.processing.length ?? 0, ); return processingCount > 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 initialLoading = ref(false); const manualRefreshing = ref(false); const polling = ref(false); const error = ref(null); const snapshotUpdatedAt = ref(null); const isFetching = ref(false); const snapshots = new Map(); const loading = computed(() => ( initialLoading.value || manualRefreshing.value || polling.value )); const isRefreshing = computed(() => isFetching.value && processing.value !== null); let pollTimer: ReturnType | null = null; let pollGeneration = 0; let requestController: AbortController | null = null; let requestGeneration = 0; const requestGenerations = new Map(); let inFlightRefresh: { conversationId: string; promise: Promise } | null = null; let failureCount = 0; let pollingStopped = false; let lastSemanticKey = ''; const intakeOtStabilizer = createIntakeOtStabilizer(); function touchSnapshot(snapshot: ProjectionSnapshot): ProjectionSnapshot { snapshot.lastAccessedAt = Date.now(); return snapshot; } function readSnapshot(conversationId: string): ProjectionSnapshot | null { const snapshot = snapshots.get(conversationId); return snapshot ? touchSnapshot(snapshot) : null; } function pruneSnapshots(): void { while (snapshots.size > SNAPSHOT_CACHE_LIMIT) { const oldest = [...snapshots.values()] .sort((left, right) => left.lastAccessedAt - right.lastAccessedAt)[0]; if (!oldest) return; snapshots.delete(oldest.conversationId); } } function workItemsSemanticKey(items: ShippingProcessingProjection[]): string { return JSON.stringify(items.map((item) => ({ no: item.workItemNo, type: item.workItemType, status: item.uiState?.status ?? null, stage: item.uiState?.stage ?? null, runNo: item.runNo ?? null, caseNo: item.caseNo ?? null, gate: item.uiState?.blocking_reason?.code ?? null, action: (() => { const action = item.uiState?.primary_action ?? null; return action ? { code: action.code, executionMode: action.executionMode ?? null, targetSurface: action.targetSurface ?? null, targetLifecycleStage: action.targetLifecycleStage ?? null, } : null; })(), lifecycleEntries: item.uiState?.lifecycleEntries?.map((entry) => ({ code: entry.code, state: entry.state, targetSurface: entry.targetSurface, disabledReasonKey: entry.disabledReasonKey ?? null, })) ?? [], version: item.progressVersion, files: (item.aggregateChildren || []).map((child) => ({ no: child.workItemNo, status: child.uiState?.status ?? child.userStatus ?? child.status, stage: child.uiState?.stage ?? child.userStage ?? child.stage, runNo: child.runNo ?? null, caseNo: child.caseNo ?? null, primaryAction: child.uiState?.primary_action ? { code: child.uiState.primary_action.code, executionMode: child.uiState.primary_action.executionMode ?? null, targetSurface: child.uiState.primary_action.targetSurface ?? null, targetLifecycleStage: child.uiState.primary_action.targetLifecycleStage ?? null, } : null, lifecycleEntries: child.uiState?.lifecycleEntries?.map((entry) => ({ code: entry.code, state: entry.state, targetSurface: entry.targetSurface, disabledReasonKey: entry.disabledReasonKey ?? null, })) ?? [], file: child.sourceSummary?.filename ?? null, })), }))); } function applySnapshot(snapshot: ProjectionSnapshot | null): void { processing.value = snapshot?.processing ?? null; processingWorkItems.value = snapshot?.workItems ?? []; snapshotUpdatedAt.value = snapshot?.receivedAt ?? null; } function currentPollElapsedMs(): number { const snapshot = readSnapshot(normalizedConversationId.value); return snapshot?.processingStartedAt === null || snapshot?.processingStartedAt === undefined ? 0 : Math.max(0, Date.now() - snapshot.processingStartedAt); } function resolveCurrentPollInterval(): number | null { return resolveProcessingPollIntervalMs({ elapsedMs: currentPollElapsedMs(), visibility: typeof document === 'undefined' ? 'visible' : document.visibilityState, hasProcessing: shouldContinueProcessingPolling(processing.value), failureCount, }); } /** * 在 Intake→OT 过渡窗里,若 projection 被稳定器保留为上一轮 OT 视图, * 则 work_items 也必须同步保留上一轮 order_task;否则卡片正文与侧边进度条 * 会来自两轮不同响应,导致右侧布局在“带进度条/只剩按钮”之间来回切换。 */ function resolveStableWorkItems( nextWorkItems: ShippingProcessingProjection[], previousProjection: ConversationProcessingProjection | null, nextProjection: ConversationProcessingProjection | null, ): ShippingProcessingProjection[] { const hasNextOrderTask = nextWorkItems.some((item) => item.workItemType === 'order_task'); if (hasNextOrderTask) return nextWorkItems; if (!previousProjection || nextProjection !== previousProjection) return nextWorkItems; const currentWorkItems = Array.isArray(processingWorkItems.value) ? processingWorkItems.value : []; const hasCurrentOrderTask = currentWorkItems.some((item) => item.workItemType === 'order_task'); return hasCurrentOrderTask ? currentWorkItems : nextWorkItems; } const normalizedConversationId = computed(() => String(readOption(options.conversationId) || '').trim(), ); /** * 中止进行中的请求与定时器。 */ function stop() { pollingStopped = true; if (pollTimer) clearTimeout(pollTimer); pollTimer = null; requestController?.abort(); requestController = null; // 请求属于上一会话代际时 finally 会因 generation 不匹配而跳过清理; // 必须在此同步清空,才能让新会话首个 GET 固定进入 initialLoading。 initialLoading.value = false; manualRefreshing.value = false; polling.value = false; isFetching.value = false; requestGeneration += 1; pollGeneration += 1; } /** * 创建当前会话代际的 AbortController。 * * 共享 API 请求自行持有 30 秒超时,不能在此再设更短的消费者超时: * 否则底层请求虽仍可成功返回,当前代际会因 signal 已 aborted 而丢弃响应, * 导致首屏永久停留在权威投影骨架。这里仅用于会话切换或组件卸载的真实取消。 */ function createRequestController(): AbortController { requestController?.abort(); const controller = new AbortController(); requestController = controller; return controller; } /** * 仅拉取统一 shipping-processing 投影。 * 核心逻辑:只消费后端 status_groups; * 同会话在途请求合并;跨会话请求中止,且只有最新一代可回写页面数据; * 语义签名相同则不替换 projection 对象,避免 DOM 重建与按钮闪烁。 * * @param conversationId - 会话 ID * @param mode - 请求模式:initial=首次加载 / manual=用户主动触发 / poll=后台轮询 * @returns Promise;可恢复网络失败写入 error,不向页面抛出。 */ async function executeRefresh( conversationId: string, mode: 'initial' | 'manual' | 'poll', ): Promise { const generation = ++requestGeneration; requestGenerations.set(conversationId, generation); const existingSnapshot = readSnapshot(conversationId); if (mode === 'initial' && !existingSnapshot) initialLoading.value = true; else if (mode === 'manual') manualRefreshing.value = true; else polling.value = true; isFetching.value = true; const controller = createRequestController(); try { // [STEP 1] 统一投影为唯一读源。 const unified = await getWorkspaceShippingProcessing(conversationId, controller.signal); if ( controller.signal.aborted || requestGenerations.get(conversationId) !== generation || conversationId !== normalizedConversationId.value || String(unified?.conversation_id || '').trim() !== conversationId ) return; const workItems = Array.isArray(unified?.work_items) ? unified.work_items : []; // 记录该会话已见过 OT,供下一轮 Intake 稀疏响应在稳定窗口内保留上一投影。 if (workItems.some((item) => item.workItemType === 'order_task')) { intakeOtStabilizer.markSeen(conversationId); } const embedded = unified?.conversation_processing as ConversationProcessingProjection | null | undefined; const previousSnapshot = readSnapshot(conversationId); const prevProjection = previousSnapshot?.processing ?? null; const nextProjection = resolveConversationProcessingFromUnified( workItems, embedded, prevProjection, { conversationId, hasSeenOrderTaskBefore: (cId) => intakeOtStabilizer.hasSeenOrderTaskBefore(cId), markSeen: (cId) => intakeOtStabilizer.markSeen(cId), reset: (cId) => intakeOtStabilizer.reset(cId), }, ); if (!nextProjection) { // 空投影同样是本次后端裁决,但不作为“成功 Projection”缓存; // 保留已有 Snapshot 可避免短暂稀疏响应把业务卡卸载。 if (!previousSnapshot) applySnapshot(null); error.value = null; failureCount = 0; return; } const nextSemanticKey = `${buildProcessingSemanticKey(nextProjection)}:${workItemsSemanticKey(workItems)}`; const nextWorkItems = resolveStableWorkItems( workItems, prevProjection, nextProjection, ); // Intake→OT 的短暂稀疏响应由稳定器明确裁决为上一版 Projection; // 此时 work_items 也必须维持同一 Snapshot,不能因原始项差异替换。 const keepPreviousSnapshot = Boolean( previousSnapshot && !workItems.some((item) => item.workItemType === 'order_task') && intakeOtStabilizer.hasSeenOrderTaskBefore(conversationId), ); if (!previousSnapshot || (!keepPreviousSnapshot && nextSemanticKey !== previousSnapshot.semanticKey)) { const now = Date.now(); const processingStartedAt = shouldContinueProcessingPolling(nextProjection) ? (previousSnapshot?.processingStartedAt ?? now) : null; const snapshot: ProjectionSnapshot = { conversationId, processing: nextProjection, workItems: nextWorkItems, semanticKey: nextSemanticKey, receivedAt: now, lastAccessedAt: now, processingStartedAt, }; snapshots.set(conversationId, snapshot); pruneSnapshots(); applySnapshot(snapshot); lastSemanticKey = nextSemanticKey; } else { touchSnapshot(previousSnapshot); applySnapshot(previousSnapshot); } error.value = null; failureCount = 0; } catch (reason) { if ( controller.signal.aborted || requestGenerations.get(conversationId) !== generation || conversationId !== normalizedConversationId.value ) return; failureCount += 1; error.value = reason instanceof BusinessError ? reason.message : 'network_recoverable'; } finally { if (requestController === controller) requestController = null; if ( requestGenerations.get(conversationId) === generation && requestGeneration === generation ) { if (mode === 'initial') initialLoading.value = false; else if (mode === 'manual') manualRefreshing.value = false; else polling.value = false; isFetching.value = false; } } } /** * 拉取统一进度(用户主动刷新模式:显示刷新图标旋转,不轮询)。 * 同一会话已有请求时复用该 Promise,避免首屏触发源互相取消重发。 */ function refresh(): Promise { const conversationId = normalizedConversationId.value; if (!conversationId) { applySnapshot(null); error.value = null; lastSemanticKey = ''; return Promise.resolve(); } intakeOtStabilizer.reset(conversationId); if (inFlightRefresh?.conversationId === conversationId) { return inFlightRefresh.promise; } const isFirstLoad = !readSnapshot(conversationId) && !initialLoading.value && !manualRefreshing.value && !polling.value; const mode: 'initial' | 'manual' = isFirstLoad ? 'initial' : 'manual'; const promise = executeRefresh(conversationId, mode).finally(() => { if (inFlightRefresh?.promise === promise) inFlightRefresh = null; }); inFlightRefresh = { conversationId, promise }; return promise; } /** * 将 focus/viewed/submit 写路径响应应用到本地 processing 与 work_items。 * 核心逻辑:只回写后端返回的 status_groups;work_items 仅提供最小附件叶子。 * 每次回写后更新语义签名,避免下一轮轮询误判为「无变化」。 */ function applyMutationProcessingResponse(response: { processing?: ConversationProcessingProjection | null; work_items?: unknown[]; }): void { const workItems = Array.isArray(response.work_items) ? response.work_items : []; const nextProjection = resolveConversationProcessingFromUnified( workItems as typeof processingWorkItems.value, response.processing ?? null, processing.value, ); if (nextProjection) { processingWorkItems.value = resolveStableWorkItems( workItems as typeof processingWorkItems.value, processing.value, nextProjection, ); const nextKey = buildProcessingSemanticKey(nextProjection); if (nextKey !== lastSemanticKey) { processing.value = nextProjection; lastSemanticKey = nextKey; } return; } } /** * 标记用户可见任务为焦点(写审计并刷新 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); } /** * 执行后台静默轮询:不设置 manualRefreshing,使用 polling 态。 * 失败时复用 executeRefresh 的 failureCount 统计。 */ async function runBackgroundPoll(conversationId: string): Promise { const existing = inFlightRefresh; if (existing?.conversationId === conversationId) { await existing.promise; return; } const promise = executeRefresh(conversationId, 'poll').finally(() => { if (inFlightRefresh?.promise === promise) inFlightRefresh = null; }); inFlightRefresh = { conversationId, promise }; await promise; } /** * 调度下一次轮询;失败时按退避间隔。 */ function schedulePoll(generation: number, delayMs: number) { if (pollTimer) clearTimeout(pollTimer); pollTimer = setTimeout(async () => { if (generation !== pollGeneration || pollingStopped) return; const conversationId = normalizedConversationId.value; if (conversationId) { await runBackgroundPoll(conversationId); } if (generation !== pollGeneration || pollingStopped) return; if (!normalizedConversationId.value) return; if (error.value) { schedulePoll(generation, resolveProcessingPollBackoffMs(failureCount)); return; } if (!shouldContinueProcessingPolling(processing.value)) { return; } const nextDelay = resolveCurrentPollInterval(); if (nextDelay !== null) 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; const nextDelay = resolveCurrentPollInterval(); if (nextDelay !== null) schedulePoll(generation, nextDelay); }); } 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) { applySnapshot(readSnapshot(nextConversationId)); error.value = null; lastSemanticKey = readSnapshot(nextConversationId)?.semanticKey || ''; } restartPolling(); }, { immediate: true }); watch( () => readOption(options.refreshTrigger ?? 0), () => { if (!normalizedConversationId.value) return; // [STEP] Run 轮询也会递增 refreshTrigger。右侧已进入人工 Gate 时状态不会 // 自动变化,禁止每次 Run 轮询都重拉同一会话投影;首次尚无投影时仍允许恢复。 if (processing.value && !shouldContinueProcessingPolling(processing.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, initialLoading, manualRefreshing, polling, isFetching, isRefreshing, snapshotUpdatedAt, error, refresh, focusConversationTask, markConversationTaskViewed, stop, }; }