Files
syops/frontend/src/features/chat/composables/useChatShipping.ts
T
hugo 8846ce159f refactor(agent-runtime, shipping-notice, frontend): 重构上下文体系,修复重试RPA无响应问题
- 替换原有的hxops_context模块为全新的代理运行时上下文平台协议,统一跨业务上下文注入逻辑
- 新增多语言操作繁忙提示文案(覆盖中、繁、英、泰四语),前端绑定页面繁忙状态实现操作阻断
- 调整RPA库存导出重试策略:移除可配置的最大自动重试次数,改为固定单次自动重试,手动重试需用户显式触发
- 优化任务用户态状态展示逻辑,优先展示具体的pending原因而非通用状态文案
- 重构任务焦点切换逻辑,统一事件日志与处理流程,复用switch_batch_focus工具函数
- 修复clearAllHistory函数残留UI问题,确保清空会话后完全复位发货通知相关视图
- 更新OpenAPI文档与静态快照,补充工具使用约束说明
- 新增调试打点日志与问题排查文档,完善全套单元测试与快照校验用例
- 更新RPA脚本的README文档,调整登录方式说明与浏览器 profile 路径配置
- 删除废弃的hxops_context模块,迁移所有相关调用到新的上下文体系
2026-07-03 17:01:42 +08:00

1005 lines
37 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* features/chat/composables/useChatShipping.ts
* 用途:发货通知聊天编排入口,组合 shipping/* 子模块并对 ChatView 暴露统一交互能力。
* 依赖:shipping.api、shipping/ 下各 handler 工厂、chat.deps、chat.types、Vue refs/computed/watch。
* 逻辑:上游由 ChatView/ChatPage 调用本 composable;本文件再把任务状态、动作刷新、文件上传、决策与发送拦截分发给 shipping 子模块。
*/
import {
computed,
onBeforeUnmount,
ref,
watch,
type ComputedRef,
type Ref,
} from 'vue';
import { SHIPPING_NOTICE_AGENT_NAME } from '@/features/chat/api/shipping.api';
import { hasActiveRunningChatRun } from '../shipping/shippingActionBusy';
import {
createShippingActionsRefresher,
createShippingConversationHelpers,
createShippingDecisionHandlers,
createShippingLocalMessages,
createShippingMappingFormHandlers,
createShippingMenuHandlers,
createShippingParseReviewHandlers,
createShippingSendHandlers,
createShippingUploadHandlers,
findHistorySessionForShippingTask,
findLatestShippingTaskId,
getShippingInventoryMappingPayload,
getShippingMatchResultPayload,
getShippingParseReviewPayload,
getShippingInventorySampleRowText,
hasShippingInventorySampleRows,
normalizeShippingHeaderForDisplay,
sanitizeShippingConversationText,
shippingActionButtonClass,
} from '../shipping';
import { reportShippingDebugEvent } from '../shipping/shippingDebugReporter';
import {
getWorkspaceShippingConversationBatches,
getWorkspaceShippingBatch,
getWorkspaceShippingTask,
switchWorkspaceShippingBatchFocusTask,
type ShippingBatchUiState,
type ShippingBatchSummary,
type ShippingConversationWorkspace,
type ShippingTaskDetail,
type ShippingTaskSummary,
} from '@/features/chat/api/shipping.api';
import {
buildShortageDetailsMessage,
hasShortageLines,
isShippingShortageQueryIntent,
} from '../shipping/shippingShortageDetails';
import type { ChatMessage, ChatRun, ChatSessionItem } from '../types/chat.types';
import type { ChatUploadFileSpec, PendingAttachment, ShippingActionButton } from '../types/shipping.types';
import type { ChatDeps } from './chat.deps';
import { listChatMessages } from '../api/chat.api';
export interface UseChatShippingOptions {
deps: ChatDeps;
currentAgent: Ref<{ name?: string } | null>;
currentAgentId: ComputedRef<number>;
messages: Ref<ChatMessage[]>;
conversationId: Ref<string | null>;
isThinking: Ref<boolean>;
shippingActionBusy: ComputedRef<boolean>;
activeRunId: Ref<number | null>;
runs: Ref<ChatRun[]>;
history: Ref<ChatSessionItem[]>;
loadHistory: () => Promise<void>;
input: Ref<string>;
chatScrollContainer: Ref<HTMLElement | null>;
attachments: Ref<PendingAttachment[]>;
selectedKb: Ref<string>;
isUploadingAttachments: Ref<boolean>;
attachmentPolicy: ComputedRef<{ anyEnabled: boolean }>;
presetQuestion: ComputedRef<string>;
saveLocalMessageToBackend: (msg: ChatMessage, userQuery?: string) => Promise<void>;
newLocalMessageId: (prefix: string) => string;
stripReasoningPrelude: (text: string) => string;
sendMessage: (
content: string,
agentId: number,
kb: string,
files: ChatUploadFileSpec[],
context?: { task_id?: string; batch_no?: string; display_query?: string },
hooks?: { onAssistantMessageFinished?: (message: ChatMessage, runMessages: ChatMessage[]) => void | Promise<void> },
) => Promise<void>;
buildFileSpecsForSend: () => Promise<ChatUploadFileSpec[]>;
loadConversation: (id: string, options?: { force?: boolean }) => Promise<void>;
createNewChatView: () => void;
}
/**
* 解析批次切换后的默认焦点状态。
* 核心逻辑:优先取状态机记录的 current focus,其次回退到 process summary 当前任务,再回退到任务列表首票;只有拿到 task_no 才回填默认聚焦原因。
* @param batchSummary - 当前批次摘要
* @param batchTasks - 当前批次任务列表
* @param defaultReason - 批次切换后写入输入栏提示的默认焦点原因
* @returns 供步骤条、按钮与右侧工作台共用的 focus 状态;取不到 task 时返回空焦点
*/
export const resolveShippingBatchFocusState = (
batchSummary: {
current_focus_task_no?: string | null;
process_summary?: { current_task_no?: string | null } | null;
} | null | undefined,
batchTasks: Array<{ task_no?: string | null }> | null | undefined,
defaultReason: string,
) => {
const taskNo = String(
batchSummary?.current_focus_task_no
|| batchSummary?.process_summary?.current_task_no
|| batchTasks?.[0]?.task_no
|| '',
).trim();
return {
taskNo,
focusReason: taskNo ? defaultReason : '',
};
};
/**
* 组装发货通知聊天所需的状态、动作处理器与发送拦截逻辑。
*
* 核心逻辑:统一管理当前任务/批次上下文,组合上传、映射、决策、动作刷新等子模块,并对 ChatView 暴露稳定 API。
* @param options - 聊天页依赖与响应式状态集合
* @returns 发货通知聊天场景所需的状态、事件处理器和工具函数
*/
export function useChatShipping(options: UseChatShippingOptions) {
const {
deps: { t, msg, router, route },
currentAgent,
currentAgentId,
messages,
conversationId,
isThinking,
shippingActionBusy,
activeRunId,
runs,
history,
loadHistory,
input,
chatScrollContainer,
attachments,
selectedKb,
isUploadingAttachments,
attachmentPolicy,
presetQuestion,
saveLocalMessageToBackend,
newLocalMessageId,
stripReasoningPrelude,
sendMessage,
buildFileSpecsForSend,
loadConversation,
createNewChatView,
} = options;
const shippingBindSend = (_fn: () => Promise<void>) => {
void _fn;
// 保留旧绑定入口,续办链路已改为直接调用 sendMessage 以支持 display_query 上下文。
};
// ── 功能开关与 UI refs ────────────────────────────────────
const isShippingNoticeAgent = computed(() => currentAgent.value?.name === SHIPPING_NOTICE_AGENT_NAME);
const isShippingActionBusy = computed(() => {
if (shippingActionBusy.value) return true;
return hasActiveRunningChatRun(isThinking.value, activeRunId.value, runs.value);
});
const allowsSendWithAttachmentsOnly = computed(
() => isShippingNoticeAgent.value && attachments.value.length > 0,
);
const shippingAutoFlowRequested = ref(false);
const shippingInventoryPickerRef = ref<HTMLInputElement | null>(null);
const shippingNoticePickerRef = ref<HTMLInputElement | null>(null);
const pendingShippingUploadTaskId = ref('');
const pendingShippingNoticeTaskId = ref('');
const pendingShippingInventoryFile = ref<File | null>(null);
const shippingInventorySelectionActive = ref(false);
const shippingInventorySelectionTaskId = ref('');
const prepareMarkdownDisplayText = (text: string) => {
return sanitizeShippingConversationText(stripReasoningPrelude(text), isShippingNoticeAgent.value);
};
// ── 任务编号状态 ──────────────────────────────────────────
const shippingTaskIdFromQuery = computed(() => {
const value = route.query.task_id;
return typeof value === 'string' ? value.trim() : '';
});
const shippingBatchNoFromQuery = computed(() => {
const value = route.query.batch_no;
return typeof value === 'string' ? value.trim() : '';
});
const resolvedShippingTaskId = ref('');
const resolvedShippingBatchNo = ref('');
const activeShippingBatchNo = ref('');
const focusedShippingTaskNo = ref('');
const shippingConversationWorkspace = ref<ShippingConversationWorkspace | null>(null);
const shippingBatchSummary = ref<ShippingBatchSummary | null>(null);
const shippingBatchTasks = ref<ShippingTaskSummary[]>([]);
const shippingWorkspaceOpen = ref(false);
const retryingShippingPendingTasks = ref(false);
const activeShippingTaskDetail = ref<ShippingTaskDetail | null>(null);
const shippingFocusReason = ref('');
const shippingInventorySchemaPreviewCache = ref<Record<string, unknown>>({});
const autoResumedShippingTasks = ref<Record<string, boolean>>({});
const lastConversationSyncKey = ref('');
let shippingStatusPollTimer: ReturnType<typeof setInterval> | null = null;
// #region debug-point B:shipping-retry-chain
const reportRetryRpaDebug = (hypothesisId: string, msg: string, data: Record<string, unknown>) =>
reportShippingDebugEvent('useChatShipping.ts', hypothesisId, msg, data);
// #endregion
const applyShippingBatchDetail = (
detail: ShippingBatchUiState,
fallbackBatchNo: string,
) => {
const normalizedBatchNo = detail.batch_no || fallbackBatchNo;
resolvedShippingBatchNo.value = normalizedBatchNo;
if (!activeShippingBatchNo.value || activeShippingBatchNo.value === fallbackBatchNo) {
activeShippingBatchNo.value = normalizedBatchNo;
}
shippingBatchTasks.value = Array.isArray(detail.tasks) ? detail.tasks : [];
shippingBatchSummary.value = {
id: detail.id,
batch_no: detail.batch_no,
conversation_id: detail.conversation_id,
current_focus_task_no: detail.focus_task?.task_no || detail.current_focus_task_no || null,
file_count: detail.file_count,
process_summary: detail.process_summary || null,
created_at: detail.created_at,
updated_at: detail.updated_at,
};
const preferredTaskNo = String(
detail.focus_task?.task_no
|| detail.process_summary?.current_task_no
|| detail.current_focus_task_no
|| '',
).trim();
if (preferredTaskNo) {
resolvedShippingTaskId.value = preferredTaskNo;
}
if (detail.focus_task && detail.focus_task_ui_state) {
activeShippingTaskDetail.value = {
...(activeShippingTaskDetail.value || {}),
...detail.focus_task,
lines: activeShippingTaskDetail.value?.lines || [],
events: activeShippingTaskDetail.value?.events || [],
ui_state: detail.focus_task_ui_state,
} as ShippingTaskDetail;
}
};
const syncShippingBatchSummary = async (batchNo: string) => {
const normalized = String(batchNo || '').trim();
if (!normalized) {
shippingBatchSummary.value = null;
shippingBatchTasks.value = [];
return;
}
try {
const detail = await getWorkspaceShippingBatch(normalized);
applyShippingBatchDetail(detail, normalized);
} catch {
// ignore summary refresh failure in chat flow
}
};
const applyConversationWorkspaceFocus = (workspace: ShippingConversationWorkspace) => {
const batches = Array.isArray(workspace.batches) ? workspace.batches : [];
if (!batches.length) return;
const queryBatchNo = String(shippingBatchNoFromQuery.value || '').trim();
const currentBatchNo = String(activeShippingBatchNo.value || resolvedShippingBatchNo.value || queryBatchNo || '').trim();
const selectedBatch = batches.find((item) => item.batch_no === currentBatchNo)
|| (queryBatchNo ? batches.find((item) => item.batch_no === queryBatchNo) : null)
|| batches.find((item) => item.focus_task?.task_no)
|| batches[0];
if (!selectedBatch) return;
applyShippingBatchDetail(selectedBatch, selectedBatch.batch_no);
};
const syncShippingConversationWorkspace = async () => {
const localConversationId = String(conversationId.value || '').trim();
if (!localConversationId || !isShippingNoticeAgent.value) {
shippingConversationWorkspace.value = null;
return;
}
try {
const workspace = await getWorkspaceShippingConversationBatches(localConversationId);
shippingConversationWorkspace.value = workspace;
applyConversationWorkspaceFocus(workspace);
} catch {
shippingConversationWorkspace.value = null;
}
};
const switchShippingFocusTask = async (taskNo: string) => {
const batchNo = getActiveShippingBatchNo();
const normalizedTaskNo = String(taskNo || '').trim().toUpperCase();
// #region debug-point C:switch-focus-entry
void reportRetryRpaDebug('C', 'switchShippingFocusTask entry', {
batchNo,
normalizedTaskNo,
activeBatchNo: activeShippingBatchNo.value,
resolvedBatchNo: resolvedShippingBatchNo.value,
routeBatchNo: shippingBatchNoFromQuery.value,
});
// #endregion
if (!batchNo || !normalizedTaskNo) {
// #region debug-point C:switch-focus-guard
void reportRetryRpaDebug('C', 'switchShippingFocusTask guard returned false', {
batchNo,
normalizedTaskNo,
});
// #endregion
return false;
}
await switchWorkspaceShippingBatchFocusTask(batchNo, normalizedTaskNo);
resolvedShippingTaskId.value = normalizedTaskNo;
focusedShippingTaskNo.value = normalizedTaskNo;
shippingFocusReason.value = t('chat.shippingNoticeUi.currentFocusDefaultReason');
if (shippingBatchSummary.value) {
shippingBatchSummary.value = {
...shippingBatchSummary.value,
current_focus_task_no: normalizedTaskNo,
};
}
await syncShippingBatchSummary(batchNo);
await syncShippingConversationWorkspace();
await syncActiveShippingTaskDetail(normalizedTaskNo);
await refreshShippingActions();
// #region debug-point C:switch-focus-success
void reportRetryRpaDebug('C', 'switchShippingFocusTask success', {
batchNo,
normalizedTaskNo,
resolvedTaskId: resolvedShippingTaskId.value,
});
// #endregion
return true;
};
const clearShippingFocus = () => {
focusedShippingTaskNo.value = '';
shippingFocusReason.value = '';
};
const switchShippingBatch = async (batchNo: string) => {
const normalizedBatchNo = String(batchNo || '').trim();
if (!normalizedBatchNo) return false;
activeShippingBatchNo.value = normalizedBatchNo;
resolvedShippingBatchNo.value = normalizedBatchNo;
const workspaceBatch = shippingConversationWorkspace.value?.batches.find((item) => item.batch_no === normalizedBatchNo);
if (workspaceBatch) {
applyShippingBatchDetail(workspaceBatch, normalizedBatchNo);
} else {
await syncShippingBatchSummary(normalizedBatchNo);
}
const nextFocusState = resolveShippingBatchFocusState(
shippingBatchSummary.value,
shippingBatchTasks.value,
t('chat.shippingNoticeUi.currentFocusDefaultReason'),
);
const nextTaskNo = nextFocusState.taskNo;
focusedShippingTaskNo.value = nextFocusState.taskNo;
shippingFocusReason.value = nextFocusState.focusReason;
if (nextTaskNo) {
resolvedShippingTaskId.value = nextTaskNo;
await syncActiveShippingTaskDetail(nextTaskNo);
}
await refreshShippingActions();
return true;
};
/**
* 清空当前聊天页绑定的发货任务上下文。
*
* 核心逻辑:在新建对话、切换 Agent 或离开发货任务场景时,主动清掉批次/任务/上传缓存,
* 避免顶部 Stepper、列表展开态和待上传库存文件残留到下一次新会话。
*/
const resetShippingConversationState = () => {
shippingAutoFlowRequested.value = false;
pendingShippingUploadTaskId.value = '';
pendingShippingNoticeTaskId.value = '';
pendingShippingInventoryFile.value = null;
shippingInventorySelectionActive.value = false;
shippingInventorySelectionTaskId.value = '';
resolvedShippingTaskId.value = '';
resolvedShippingBatchNo.value = '';
activeShippingBatchNo.value = '';
focusedShippingTaskNo.value = '';
shippingFocusReason.value = '';
shippingConversationWorkspace.value = null;
shippingBatchSummary.value = null;
shippingBatchTasks.value = [];
shippingWorkspaceOpen.value = false;
retryingShippingPendingTasks.value = false;
activeShippingTaskDetail.value = null;
shippingInventorySchemaPreviewCache.value = {};
lastConversationSyncKey.value = '';
};
const getActiveShippingTaskId = () =>
findLatestShippingTaskId(messages.value)
|| resolvedShippingTaskId.value
|| shippingTaskIdFromQuery.value
|| '';
const getActiveShippingBatchNo = () =>
activeShippingBatchNo.value
|| resolvedShippingBatchNo.value
|| shippingBatchNoFromQuery.value
|| String(shippingBatchSummary.value?.batch_no || '').trim()
|| '';
const getCurrentShippingChatContext = () => ({
task_id: getActiveBatchTaskId() || getActiveShippingTaskId(),
batch_no: getActiveShippingBatchNo(),
});
const getCurrentShippingChatContextWithDisplay = (displayQuery: string) => ({
...getCurrentShippingChatContext(),
display_query: displayQuery,
});
const getActiveBatchTaskId = () => String(
shippingBatchSummary.value?.current_focus_task_no
|| shippingBatchSummary.value?.process_summary?.current_task_no
|| shippingBatchTasks.value[0]?.task_no
|| focusedShippingTaskNo.value
|| resolvedShippingTaskId.value
|| '',
).trim();
const hasRunningShippingBatchTasks = () =>
shippingBatchTasks.value.some(
(task) => !['uploaded', 'completed', 'closed', 'rejected'].includes(String(task.process_status || '').trim()),
);
/**
* 同步当前焦点任务详情,并在仅恢复 `task_no` 的场景下补齐 `batch_no` 上下文。
*
* 核心逻辑:先拉取任务详情,再把详情里的批次号回填到聊天状态,确保会话恢复后仍能继续按批次模式加载 2 票/多票摘要。
* @param taskId - 可选任务编号;未传时回退到当前激活任务
*/
const syncActiveShippingTaskDetail = async (taskId?: string) => {
const normalized = String(taskId || getActiveShippingTaskId() || '').trim().toUpperCase();
if (!normalized) {
activeShippingTaskDetail.value = null;
return;
}
try {
const detail = await getWorkspaceShippingTask(normalized);
const detailBatchNo = String(detail.batch_no || '').trim();
const activeBatchNo = String(activeShippingBatchNo.value || '').trim();
if (activeBatchNo && detailBatchNo && detailBatchNo !== activeBatchNo) {
return;
}
activeShippingTaskDetail.value = detail;
if (detailBatchNo && resolvedShippingBatchNo.value !== detailBatchNo) {
resolvedShippingBatchNo.value = detailBatchNo;
activeShippingBatchNo.value = activeShippingBatchNo.value || detailBatchNo;
}
} catch {
activeShippingTaskDetail.value = null;
}
};
const syncConversationMessagesIfNeeded = async (taskId?: string) => {
const conversationKey = String(conversationId.value || '').trim();
const normalizedTaskId = String(taskId || getActiveShippingTaskId() || '').trim().toUpperCase();
if (!conversationKey || !normalizedTaskId || !isShippingNoticeAgent.value || isShippingActionBusy.value) return;
const detail = activeShippingTaskDetail.value;
// 任务详情接口当前不返回顶层 checkpoint,parse_review 需从详情状态字段回推。
const checkpoint = String(
(detail?.step_payload as Record<string, unknown> | undefined)?.checkpoint
|| detail?.review_status
|| '',
).trim();
if (checkpoint !== 'parse_review') return;
const exists = messages.value.some((msg) => {
if (msg.type !== 'shipping-parse-review' || !msg.payload || typeof msg.payload !== 'object') return false;
return String((msg.payload as { taskId?: string }).taskId || '').trim().toUpperCase() === normalizedTaskId;
});
if (exists) return;
const syncKey = `${conversationKey}|${normalizedTaskId}|parse_review`;
if (lastConversationSyncKey.value === syncKey) return;
const loaded = await listChatMessages(conversationKey, currentAgentId.value);
if (Array.isArray(loaded) && loaded.length > 0) {
messages.value = loaded;
lastConversationSyncKey.value = syncKey;
}
};
const lastAssistantMessageContent = () => {
for (let i = messages.value.length - 1; i >= 0; i -= 1) {
const item = messages.value[i];
if (item?.role === 'assistant') return String(item.content || '');
}
return '';
};
const lastAssistantShippingActions = () => {
for (let i = messages.value.length - 1; i >= 0; i -= 1) {
const item = messages.value[i];
if (item?.role === 'assistant' && Array.isArray(item.shipping_actions)) {
return item.shipping_actions;
}
}
return [];
};
const { refreshShippingActions } = createShippingActionsRefresher({
isShippingNoticeAgent,
messages,
conversationId,
isThinking,
history,
resolvedShippingTaskId,
shippingTaskIdFromQuery,
getActiveBatchTaskId,
});
const { pushShippingLocalUserMessage, pushShippingLocalAssistantMessage } = createShippingLocalMessages({
messages,
newLocalMessageId,
saveLocalMessageToBackend,
});
/**
* Dify SSE 完成后立即净化最后一条回复,并同步后端动作按钮。
*
* 核心逻辑:流式过程中只做展示层净化;终态事件到达后消息对象已经完整,
* 此时调用统一 refreshShippingActions,把 action_buttons 回写到当前 assistant 气泡。
*/
const finalizeShippingAssistantMessage = async () => {
if (!isShippingNoticeAgent.value) return;
await refreshShippingActions();
};
/**
* 为“查询缺口明细”定位任务事实来源。
*
* 核心逻辑:优先使用显式任务号或当前聚焦任务,再从批次摘要/当前详情中读取;
* 摘要缺少逐行缺口时补拉既有任务详情接口,确保聊天回复只基于后端事实数据。
*/
const resolveShippingTaskForShortageQuery = async (taskNo?: string) => {
const normalizedTaskNo = String(
taskNo
|| focusedShippingTaskNo.value
|| getActiveBatchTaskId()
|| getActiveShippingTaskId()
|| '',
).trim().toUpperCase();
if (!normalizedTaskNo) return null;
const summaryTask = shippingBatchTasks.value.find(
(item) => String(item.task_no || '').trim().toUpperCase() === normalizedTaskNo,
);
if (summaryTask && hasShortageLines(summaryTask)) return summaryTask;
const detail = activeShippingTaskDetail.value;
if (String(detail?.task_no || '').trim().toUpperCase() === normalizedTaskNo && hasShortageLines(detail)) {
return detail;
}
try {
return await getWorkspaceShippingTask(normalizedTaskNo);
} catch {
return summaryTask || null;
}
};
/**
* 在聊天流中输出确定性的缺口明细。
*
* 核心逻辑:追加一条本地用户意图消息和一条本地助手事实回复,不转发给 Dify,
* 避免大模型复述或重新计算预订单、料号与缺口数量。
*/
const queryShippingShortageDetails = async (taskNo?: string, displayText?: string) => {
const task = await resolveShippingTaskForShortageQuery(taskNo);
if (!task) {
msg.warning(t('chat.shippingNoticeMissingTaskId'));
return true;
}
await pushShippingLocalUserMessage(displayText || t('chat.shippingNoticeUi.queryShortageDetails'));
await pushShippingLocalAssistantMessage(buildShortageDetailsMessage(task, t));
return true;
};
const { sendShippingMenuMessage } = createShippingConversationHelpers({
conversationId,
history,
loadHistory,
getActiveShippingTaskId,
currentAgentId,
selectedKb,
sendMessage,
});
const {
openShippingInventoryMappingFormForTask,
applyShippingInventoryMappingForm,
reuploadShippingInventoryFromMappingForm,
} = createShippingMappingFormHandlers({
messages,
chatScrollContainer,
shippingInventorySchemaPreviewCache,
shippingInventoryPickerRef,
pendingShippingUploadTaskId,
resolvedShippingTaskId,
newLocalMessageId,
saveLocalMessageToBackend,
pushShippingLocalAssistantMessage,
refreshShippingActions,
msg,
});
const { executeShippingDecision, executeShippingManualUpload } = createShippingDecisionHandlers({
messages,
conversationId,
history,
isShippingNoticeAgent,
shippingInventorySchemaPreviewCache,
getActiveShippingTaskId,
newLocalMessageId,
saveLocalMessageToBackend,
loadHistory,
openShippingInventoryMappingFormForTask,
refreshShippingActions,
msg,
t,
});
const {
syncShippingParseReviewCard,
updateShippingParseReviewHeader,
updateShippingParseReviewLine,
addShippingParseReviewLine,
removeShippingParseReviewLine,
} = createShippingParseReviewHandlers({
messages,
resolvedShippingTaskId,
newLocalMessageId,
saveLocalMessageToBackend,
refreshShippingActions,
msg,
});
const {
handleShippingAutoUploadFile,
handleShippingAutoUploadNoticeBatch,
openShippingInventoryPicker,
openShippingNoticePicker,
selectShippingInventoryUploadTask,
cancelShippingInventoryTaskSelection,
handleShippingInventorySelected,
shippingSuggestedPrompt,
useShippingSuggestedPrompt,
} = createShippingUploadHandlers({
conversationId,
attachments,
input,
shippingAutoFlowRequested,
shippingInventoryPickerRef,
shippingNoticePickerRef,
pendingShippingUploadTaskId,
pendingShippingNoticeTaskId,
pendingShippingInventoryFile,
resolvedShippingTaskId,
resolvedShippingBatchNo,
shippingBatchSummary,
shippingBatchTasks,
shippingInventorySelectionActive,
shippingInventorySelectionTaskId,
shippingInventorySchemaPreviewCache,
getActiveShippingTaskId,
sendShippingMenuMessage,
pushShippingLocalUserMessage,
pushShippingLocalAssistantMessage,
refreshShippingActions,
msg,
t,
});
const { handleShippingMenuAction, handleShippingActionClick } = createShippingMenuHandlers({
isThinking,
getActiveShippingTaskId,
messages,
newLocalMessageId,
saveLocalMessageToBackend,
sendShippingMenuMessage,
openShippingInventoryMappingFormForTask,
openShippingInventoryPicker,
openShippingNoticePicker,
executeShippingDecision,
executeShippingManualUpload,
refreshShippingActions,
msg,
t,
});
const { tryHandleShippingSend, tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers({
isShippingNoticeAgent,
isThinking,
isUploadingAttachments,
messages,
conversationId,
history,
input,
attachments,
shippingAutoFlowRequested,
resolvedShippingTaskId,
getActiveShippingBatchNo,
currentAgentId,
selectedKb,
attachmentPolicy,
getActiveShippingTaskId,
lastAssistantMessageContent,
lastAssistantShippingActions,
sendMessage,
buildFileSpecsForSend,
loadHistory,
sendShippingMenuMessage,
pushShippingLocalUserMessage,
pushShippingLocalAssistantMessage,
openShippingInventoryPicker,
executeShippingDecision,
executeShippingManualUpload,
handleShippingMenuAction,
handleShippingAutoUploadFile,
handleShippingAutoUploadNoticeBatch,
refreshShippingActions,
shippingSuggestedPrompt,
isShippingShortageQueryIntent,
queryShippingShortageDetails,
msg,
t,
});
// ── 路由 / 会话生命周期 ───────────────────────────────────
const resumeShippingTaskFromQuery = async () => {
const batchNo = shippingBatchNoFromQuery.value;
if (batchNo && isShippingNoticeAgent.value) {
await syncShippingBatchSummary(batchNo);
if (!shippingTaskIdFromQuery.value && resolvedShippingTaskId.value) {
return;
}
}
const taskId = shippingTaskIdFromQuery.value;
if (!taskId || !isShippingNoticeAgent.value) return;
if (route.query.conversation_id) return;
if (presetQuestion.value) return;
if (autoResumedShippingTasks.value[taskId]) return;
const existing = findHistorySessionForShippingTask(history.value, taskId);
if (existing) {
await loadConversation(existing.conversation_id, { force: true });
return;
}
autoResumedShippingTasks.value[taskId] = true;
const displayText = t('chat.shippingNoticeUi.retrySingleTaskMessage', { taskId });
await sendMessage(
t('chat.shippingNoticeContinue', { taskId }),
currentAgentId.value,
selectedKb.value,
[],
getCurrentShippingChatContextWithDisplay(displayText),
);
await loadHistory();
};
const onConversationIdChanging = (nextId: string, prevId: string | null | undefined) => {
if (prevId !== nextId) {
resolvedShippingTaskId.value = '';
if (!shippingBatchNoFromQuery.value) {
resolvedShippingBatchNo.value = '';
shippingBatchSummary.value = null;
shippingBatchTasks.value = [];
}
}
};
const WORKSPACE_DIRECT_PICKER_ACTION_IDS = new Set(['upload_inventory_file', 'replace_notice_file']);
/**
* 从右侧批次工作台触发指定任务的后端状态机动作。
*
* 核心逻辑:普通动作先把 batch focus 切到目标 task,再复用聊天气泡的统一 action.id 分发器;
* 文件选择类动作必须先同步打开 picker,再异步切焦点,避免浏览器丢失用户点击手势。
* @param taskNo - 被点击按钮所属的任务编号
* @param action - 后端 `ui_state.action_buttons` 返回的动作按钮
* @returns 是否成功进入统一动作处理链
*/
const handleShippingWorkspaceAction = async (taskNo: string, action: ShippingActionButton) => {
const normalizedTaskNo = String(taskNo || '').trim().toUpperCase();
if (!normalizedTaskNo || !action?.id || !isShippingNoticeAgent.value) return false;
if (isShippingActionBusy.value) {
msg.warning(t('chat.shippingNoticeUi.actionBusyHint'));
return false;
}
if (WORKSPACE_DIRECT_PICKER_ACTION_IDS.has(String(action.id || ''))) {
await handleShippingMenuAction(action, undefined, { taskId: normalizedTaskNo });
void switchShippingFocusTask(normalizedTaskNo);
return true;
}
const switched = await switchShippingFocusTask(normalizedTaskNo);
if (!switched) return false;
await handleShippingMenuAction(action, undefined, { taskId: normalizedTaskNo });
return true;
};
const retryCurrentShippingBatchPendingTasks = async () => {
const batchNo = getActiveShippingBatchNo();
if (!batchNo || retryingShippingPendingTasks.value) return false;
if (isShippingActionBusy.value) {
msg.warning(t('chat.shippingNoticeUi.actionBusyHint'));
return false;
}
retryingShippingPendingTasks.value = true;
try {
const { retryWorkspaceShippingBatchPending } = await import('@/features/chat/api/shipping.api');
const result = await retryWorkspaceShippingBatchPending(batchNo);
msg.success(result.message || t('chat.shippingNoticeUi.retryPendingDone'));
await syncShippingConversationWorkspace();
await syncShippingBatchSummary(batchNo);
await refreshShippingActions();
return true;
} catch (error) {
msg.error(error instanceof Error ? error.message : t('chat.shippingNoticeUi.retryFailed'));
return false;
} finally {
retryingShippingPendingTasks.value = false;
}
};
const onConversationLoadedEmpty = async () => {
if (!isShippingNoticeAgent.value || !shippingTaskIdFromQuery.value || isShippingActionBusy.value) return;
const nextQuery: Record<string, string> = { task_id: shippingTaskIdFromQuery.value };
if (shippingBatchNoFromQuery.value) nextQuery.batch_no = shippingBatchNoFromQuery.value;
await router.replace({ path: route.path, query: nextQuery });
};
const onConversationLoadFailed = async () => {
if (!isShippingNoticeAgent.value || !shippingTaskIdFromQuery.value || isShippingActionBusy.value) return;
createNewChatView();
const nextQuery: Record<string, string> = { task_id: shippingTaskIdFromQuery.value };
if (shippingBatchNoFromQuery.value) nextQuery.batch_no = shippingBatchNoFromQuery.value;
void router.replace({ path: route.path, query: nextQuery });
const displayText = t('chat.shippingNoticeUi.retrySingleTaskMessage', { taskId: shippingTaskIdFromQuery.value });
await sendMessage(
t('chat.shippingNoticeContinue', { taskId: shippingTaskIdFromQuery.value }),
currentAgentId.value,
selectedKb.value,
[],
getCurrentShippingChatContextWithDisplay(displayText),
);
await loadHistory();
};
/**
* 启停发货批次状态短轮询。
*
* 核心逻辑:聊天流当前没有 shipping 专属 SSE;因此在存在任务/批次上下文时每 3 秒补拉一次,
* 让顶部 Stepper、批次统计和动作按钮能在后端异步状态变化后自动更新。
*/
const restartShippingStatusPolling = () => {
if (shippingStatusPollTimer) {
clearInterval(shippingStatusPollTimer);
shippingStatusPollTimer = null;
}
if (!isShippingNoticeAgent.value) return;
const batchNo = getActiveShippingBatchNo();
const taskId = getActiveBatchTaskId();
if (!batchNo && !taskId) return;
shippingStatusPollTimer = setInterval(() => {
if (!isShippingNoticeAgent.value) return;
const nextBatchNo = getActiveShippingBatchNo();
const nextTaskId = getActiveBatchTaskId();
if (!nextBatchNo && !nextTaskId) return;
void (async () => {
await syncShippingConversationWorkspace();
if (nextBatchNo) await syncShippingBatchSummary(nextBatchNo);
if (nextTaskId) {
await syncActiveShippingTaskDetail(nextTaskId);
await syncConversationMessagesIfNeeded(nextTaskId);
}
await refreshShippingActions();
if (!hasRunningShippingBatchTasks() && !isShippingActionBusy.value && shippingStatusPollTimer) {
clearInterval(shippingStatusPollTimer);
shippingStatusPollTimer = null;
}
})();
}, 3000);
};
// ── 动作按钮 watch ────────────────────────────────────────
const shippingActionsWatchKey = computed(() => {
const msgs = messages.value;
const last = msgs.length ? msgs[msgs.length - 1] : null;
return [
String(conversationId.value || ''),
String(msgs.length),
String(last?.role || ''),
String(last?.content || '').slice(-120),
].join('|');
});
watch([shippingActionsWatchKey, isThinking, isShippingNoticeAgent, () => currentAgent.value?.name], () => {
void refreshShippingActions().then(async () => {
const taskId = getActiveBatchTaskId() || getActiveShippingTaskId();
await Promise.all([
syncShippingParseReviewCard(taskId),
syncActiveShippingTaskDetail(taskId),
]);
await syncConversationMessagesIfNeeded(taskId);
});
});
watch([activeShippingBatchNo, shippingBatchNoFromQuery, resolvedShippingBatchNo], ([activeBatchNo, queryBatchNo, batchNo]) => {
const nextBatchNo = String(activeBatchNo || queryBatchNo || batchNo || '').trim();
if (!nextBatchNo) {
shippingBatchSummary.value = null;
return;
}
void syncShippingBatchSummary(nextBatchNo);
}, { immediate: true });
watch([conversationId, isShippingNoticeAgent], () => {
void syncShippingConversationWorkspace();
}, { immediate: true });
watch(
[isShippingNoticeAgent, conversationId, resolvedShippingBatchNo, shippingBatchNoFromQuery, resolvedShippingTaskId, shippingTaskIdFromQuery, isThinking],
() => {
restartShippingStatusPolling();
},
{ immediate: true },
);
onBeforeUnmount(() => {
if (shippingStatusPollTimer) {
clearInterval(shippingStatusPollTimer);
shippingStatusPollTimer = null;
}
});
return {
shippingBindSend,
isShippingNoticeAgent,
prepareMarkdownDisplayText,
shippingAutoFlowRequested,
shippingInventoryPickerRef,
shippingNoticePickerRef,
pendingShippingUploadTaskId,
shippingInventorySelectionActive,
shippingInventorySelectionTaskId,
allowsSendWithAttachmentsOnly,
shippingTaskIdFromQuery,
shippingBatchNoFromQuery,
resolvedShippingBatchNo,
activeShippingBatchNo,
focusedShippingTaskNo,
shippingFocusReason,
shippingConversationWorkspace,
shippingBatchSummary,
shippingBatchTasks,
shippingWorkspaceOpen,
isShippingActionBusy,
retryingShippingPendingTasks,
activeShippingTaskDetail,
getCurrentShippingChatContext,
getActiveShippingBatchNo,
switchShippingBatch,
switchShippingFocusTask,
clearShippingFocus,
handleShippingWorkspaceAction,
retryCurrentShippingBatchPendingTasks,
queryShippingShortageDetails,
resetShippingConversationState,
resumeShippingTaskFromQuery,
normalizeShippingHeaderForDisplay,
getShippingInventoryMappingPayload,
getShippingMatchResultPayload,
getShippingParseReviewPayload,
hasShippingInventorySampleRows,
getShippingInventorySampleRowText,
applyShippingInventoryMappingForm,
reuploadShippingInventoryFromMappingForm,
updateShippingParseReviewHeader,
updateShippingParseReviewLine,
addShippingParseReviewLine,
removeShippingParseReviewLine,
handleShippingActionClick,
handleShippingInventorySelected,
finalizeShippingAssistantMessage,
selectShippingInventoryUploadTask,
cancelShippingInventoryTaskSelection,
shippingActionButtonClass,
shippingSuggestedPrompt,
useShippingSuggestedPrompt,
tryHandleShippingAttachmentAutoFlow,
tryHandleShippingSend,
onConversationIdChanging,
onConversationLoadedEmpty,
onConversationLoadFailed,
};
}