refactor(agent-runtime, shipping-notice, frontend): 重构上下文体系,修复重试RPA无响应问题

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

No files matched your search

@@ -27,6 +27,7 @@ import { useChatShipping } from './useChatShipping';
import { useChatSourceFiles } from './useChatSourceFiles';
import { useChatStore } from '../stores/chat.store';
import { useTrainingWorkspace, matchesTrainingAgent } from './useTrainingWorkspace';
import { hasActiveRunningChatRun } from '../shipping/shippingActionBusy';
import {
createChatPageConversationApi,
createChatPageLocalMessageApi,
@@ -112,6 +113,11 @@ export function useChatPage() {
loadConversationState,
sendMessage,
} = useChat();
const shippingActionBusy = computed(() => hasActiveRunningChatRun(
isThinking.value,
activeRunId.value,
runs.value,
));
const browser = useChatBrowserPanel({
warn: (text) => msg.warning(text),
@@ -254,6 +260,9 @@ export function useChatPage() {
messages,
conversationId,
isThinking,
shippingActionBusy,
activeRunId,
runs,
history,
loadHistory,
input,
@@ -468,6 +477,7 @@ export function useChatPage() {
scrollToBottom: scroll.scrollToBottomSmooth,
messages,
isThinking,
shippingActionBusy,
conversationId,
input,
browser,
@@ -543,8 +553,7 @@ export function useChatPage() {
switchShippingBatch: shipping.switchShippingBatch,
switchShippingFocusTask: shipping.switchShippingFocusTask,
clearShippingFocus: shipping.clearShippingFocus,
resumeShippingTask: shipping.resumeShippingTask,
retryShippingInventoryRpa: shipping.retryShippingInventoryRpa,
handleShippingWorkspaceAction: shipping.handleShippingWorkspaceAction,
retryCurrentShippingBatchPendingTasks: shipping.retryCurrentShippingBatchPendingTasks,
queryShippingShortageDetails: shipping.queryShippingShortageDetails,
selectShippingInventoryUploadTask: shipping.selectShippingInventoryUploadTask,
@@ -0,0 +1,94 @@
/**
* features/chat/composables/useChatSessions.spec.ts
* 用途:验证侧栏会话清空后的本地状态回收与新会话视图复位行为。
* 依赖:vitest、vue refs/computed、useChatSessions、chat.api、chat.store。
* 逻辑:覆盖“无 conversationId 也要复位页面”的回归场景,避免发货通知顶部批次进度条残留。
*/
import { computed, ref } from 'vue';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { useChatSessions } from './useChatSessions';
const { deleteAllChatSessions, deleteChatSession, listChatSessions } = vi.hoisted(() => ({
deleteAllChatSessions: vi.fn(),
deleteChatSession: vi.fn(),
listChatSessions: vi.fn(),
}));
const {
getSessionHistory,
setSessionHistory,
patchSessionHistory,
} = vi.hoisted(() => ({
getSessionHistory: vi.fn(),
setSessionHistory: vi.fn(),
patchSessionHistory: vi.fn(),
}));
vi.mock('../api/chat.api', () => ({
deleteAllChatSessions,
deleteChatSession,
listChatSessions,
}));
vi.mock('../stores/chat.store', () => ({
useChatStore: () => ({
getSessionHistory,
setSessionHistory,
patchSessionHistory,
}),
}));
describe('useChatSessions', () => {
beforeEach(() => {
deleteAllChatSessions.mockReset();
deleteChatSession.mockReset();
listChatSessions.mockReset();
getSessionHistory.mockReset();
setSessionHistory.mockReset();
patchSessionHistory.mockReset();
getSessionHistory.mockReturnValue([]);
});
it('always resets to a fresh chat view after clearing history', async () => {
deleteAllChatSessions.mockResolvedValue(undefined);
const runs = ref([
{
runId: 101,
agentId: 7,
conversationId: null,
status: 'running',
messages: [],
query: '继续处理',
createdAt: '2026-07-02T09:00:00+08:00',
},
]);
const startNewChat = vi.fn();
const sessions = useChatSessions({
deps: {
t: (key: string) => key,
router: { replace: vi.fn() },
route: { query: {}, path: '/chat/7' },
} as never,
currentAgentId: computed(() => 7),
conversationId: ref(null),
activeRunId: ref(null),
runs,
activateRun: vi.fn(),
loadConversation: vi.fn(async () => {}),
isSidebarOpen: ref(false),
onConfirmDelete: (_message, action) => {
void action();
},
startNewChat,
});
await sessions.clearAllHistory();
expect(deleteAllChatSessions).toHaveBeenCalledWith(7);
expect(setSessionHistory).toHaveBeenCalledWith(7, []);
expect(runs.value).toEqual([]);
expect(startNewChat).toHaveBeenCalledTimes(1);
});
});
@@ -164,6 +164,12 @@ export function useChatSessions(options: UseChatSessionsOptions) {
);
// ── 删除单条 / 清空全部 ───────────────────────────────────
/**
* 清空当前 Agent 的全部会话历史,并回到干净的新会话视图。
*
* 核心逻辑:服务端删除成功后同步清空本地 history/run 缓存,并始终触发 `startNewChat`;
* 这样即使当前页面没有 `conversationId`,也能把发货通知顶部进度条等会话外残留 UI 一并复位。
*/
const clearAllHistory = async () => {
onConfirmDelete(t('chat.confirmClearHistory'), async () => {
try {
@@ -172,9 +178,7 @@ export function useChatSessions(options: UseChatSessionsOptions) {
history.value = [];
chatStore.setSessionHistory(agentId, []);
runs.value = [];
if (conversationId.value || activeRunId.value) {
startNewChat();
}
startNewChat();
} catch (e) {
console.error('Failed to clear history', e);
}
@@ -14,6 +14,7 @@ import {
type Ref,
} from 'vue';
import { SHIPPING_NOTICE_AGENT_NAME } from '@/features/chat/api/shipping.api';
import { hasActiveRunningChatRun } from '../shipping/shippingActionBusy';
import {
createShippingActionsRefresher,
@@ -36,6 +37,7 @@ import {
sanitizeShippingConversationText,
shippingActionButtonClass,
} from '../shipping';
import { reportShippingDebugEvent } from '../shipping/shippingDebugReporter';
import {
getWorkspaceShippingConversationBatches,
getWorkspaceShippingBatch,
@@ -53,8 +55,8 @@ import {
isShippingShortageQueryIntent,
} from '../shipping/shippingShortageDetails';
import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
import type { ChatUploadFileSpec, PendingAttachment } from '../types/shipping.types';
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';
@@ -65,6 +67,9 @@ export interface UseChatShippingOptions {
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>;
@@ -133,6 +138,9 @@ export function useChatShipping(options: UseChatShippingOptions) {
messages,
conversationId,
isThinking,
shippingActionBusy,
activeRunId,
runs,
history,
loadHistory,
input,
@@ -158,6 +166,10 @@ export function useChatShipping(options: UseChatShippingOptions) {
// ── 功能开关与 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,
);
@@ -165,6 +177,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
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('');
@@ -198,6 +211,11 @@ export function useChatShipping(options: UseChatShippingOptions) {
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,
@@ -284,7 +302,24 @@ export function useChatShipping(options: UseChatShippingOptions) {
const switchShippingFocusTask = async (taskNo: string) => {
const batchNo = getActiveShippingBatchNo();
const normalizedTaskNo = String(taskNo || '').trim().toUpperCase();
if (!batchNo || !normalizedTaskNo) return false;
// #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;
@@ -299,6 +334,13 @@ export function useChatShipping(options: UseChatShippingOptions) {
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;
};
@@ -343,6 +385,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
const resetShippingConversationState = () => {
shippingAutoFlowRequested.value = false;
pendingShippingUploadTaskId.value = '';
pendingShippingNoticeTaskId.value = '';
pendingShippingInventoryFile.value = null;
shippingInventorySelectionActive.value = false;
shippingInventorySelectionTaskId.value = '';
@@ -430,7 +473,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
const syncConversationMessagesIfNeeded = async (taskId?: string) => {
const conversationKey = String(conversationId.value || '').trim();
const normalizedTaskId = String(taskId || getActiveShippingTaskId() || '').trim().toUpperCase();
if (!conversationKey || !normalizedTaskId || !isShippingNoticeAgent.value || isThinking.value) return;
if (!conversationKey || !normalizedTaskId || !isShippingNoticeAgent.value || isShippingActionBusy.value) return;
const detail = activeShippingTaskDetail.value;
// 任务详情接口当前不返回顶层 checkpoint,parse_review 需从详情状态字段回推。
const checkpoint = String(
@@ -609,6 +652,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
handleShippingAutoUploadFile,
handleShippingAutoUploadNoticeBatch,
openShippingInventoryPicker,
openShippingNoticePicker,
selectShippingInventoryUploadTask,
cancelShippingInventoryTaskSelection,
handleShippingInventorySelected,
@@ -620,7 +664,9 @@ export function useChatShipping(options: UseChatShippingOptions) {
input,
shippingAutoFlowRequested,
shippingInventoryPickerRef,
shippingNoticePickerRef,
pendingShippingUploadTaskId,
pendingShippingNoticeTaskId,
pendingShippingInventoryFile,
resolvedShippingTaskId,
resolvedShippingBatchNo,
@@ -647,10 +693,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
sendShippingMenuMessage,
openShippingInventoryMappingFormForTask,
openShippingInventoryPicker,
openShippingNoticePicker: () => {
shippingNoticePickerRef.value?.click();
return true;
},
openShippingNoticePicker,
executeShippingDecision,
executeShippingManualUpload,
refreshShippingActions,
@@ -738,48 +781,42 @@ export function useChatShipping(options: UseChatShippingOptions) {
}
};
/**
* 续办指定任务,并把聊天上下文切到该任务继续推进。
*
* 核心逻辑:先切换批次焦点任务,再把内部续办指令发给 Agent;
* 前端和历史只展示业务端可理解的简短重试话术,避免暴露工具名。
* @param taskNo - 需要续办的任务编号
* @returns 是否已成功触发续办
*/
const resumeShippingTask = async (taskNo: string) => {
const normalizedTaskNo = String(taskNo || '').trim().toUpperCase();
if (!normalizedTaskNo || !isShippingNoticeAgent.value || isThinking.value) return false;
const switched = await switchShippingFocusTask(normalizedTaskNo);
if (!switched) return false;
const displayText = t('chat.shippingNoticeUi.retrySingleTaskMessage', { taskId: normalizedTaskNo });
await sendMessage(
t('chat.shippingNoticeContinue', { taskId: normalizedTaskNo }),
currentAgentId.value,
selectedKb.value,
[],
getCurrentShippingChatContextWithDisplay(displayText),
);
await loadHistory();
await refreshShippingActions();
return true;
};
const WORKSPACE_DIRECT_PICKER_ACTION_IDS = new Set(['upload_inventory_file', 'replace_notice_file']);
const retryShippingInventoryRpa = async (taskNo: string) => {
/**
* 从右侧批次工作台触发指定任务的后端状态机动作。
*
* 核心逻辑:普通动作先把 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 || !isShippingNoticeAgent.value || isThinking.value) return false;
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;
const ok = await executeShippingDecision('retry_rpa', t('chat.shippingNoticeUi.retryRpa'));
await syncShippingConversationWorkspace();
const batchNo = getActiveShippingBatchNo();
if (batchNo) await syncShippingBatchSummary(batchNo);
await refreshShippingActions();
return ok;
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');
@@ -798,14 +835,14 @@ export function useChatShipping(options: UseChatShippingOptions) {
};
const onConversationLoadedEmpty = async () => {
if (!isShippingNoticeAgent.value || !shippingTaskIdFromQuery.value || isThinking.value) return;
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 || isThinking.value) return;
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;
@@ -850,7 +887,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
await syncConversationMessagesIfNeeded(nextTaskId);
}
await refreshShippingActions();
if (!hasRunningShippingBatchTasks() && !isThinking.value && shippingStatusPollTimer) {
if (!hasRunningShippingBatchTasks() && !isShippingActionBusy.value && shippingStatusPollTimer) {
clearInterval(shippingStatusPollTimer);
shippingStatusPollTimer = null;
}
@@ -925,6 +962,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
shippingBatchSummary,
shippingBatchTasks,
shippingWorkspaceOpen,
isShippingActionBusy,
retryingShippingPendingTasks,
activeShippingTaskDetail,
getCurrentShippingChatContext,
@@ -932,8 +970,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
switchShippingBatch,
switchShippingFocusTask,
clearShippingFocus,
resumeShippingTask,
retryShippingInventoryRpa,
handleShippingWorkspaceAction,
retryCurrentShippingBatchPendingTasks,
queryShippingShortageDetails,
resetShippingConversationState,