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:
1 parent
60dd0c0f58
commit
8846ce159f
102 files changed
+18289
-9072
No files matched your search
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* features/chat/shipping/shippingActionBusy.spec.ts
|
||||
* 用途:验证发货工作台动作忙碌态只在真实活跃 run 存在时才阻塞。
|
||||
* 依赖:vitest、shippingActionBusy 纯函数。
|
||||
* 逻辑:覆盖正常运行中、残留 isThinking、缺失 activeRunId 回退扫描三类路径,避免 retry_rpa 被误锁死。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { hasActiveRunningChatRun } from './shippingActionBusy';
|
||||
|
||||
describe('shippingActionBusy', () => {
|
||||
it('returns true when active run is still running', () => {
|
||||
expect(hasActiveRunningChatRun(true, 12, [
|
||||
{
|
||||
runId: 12,
|
||||
agentId: 1,
|
||||
viewId: 1,
|
||||
query: '继续处理',
|
||||
messages: [],
|
||||
conversationId: 'conv-1',
|
||||
status: 'running',
|
||||
createdAt: '2026-07-02T00:00:00.000Z',
|
||||
},
|
||||
])).toBe(true);
|
||||
});
|
||||
|
||||
it('returns false when isThinking is stale and no run is running', () => {
|
||||
expect(hasActiveRunningChatRun(true, 12, [
|
||||
{
|
||||
runId: 12,
|
||||
agentId: 1,
|
||||
viewId: 1,
|
||||
query: '继续处理',
|
||||
messages: [],
|
||||
conversationId: 'conv-1',
|
||||
status: 'done',
|
||||
createdAt: '2026-07-02T00:00:00.000Z',
|
||||
},
|
||||
])).toBe(false);
|
||||
});
|
||||
|
||||
it('falls back to scanning all runs when activeRunId is missing', () => {
|
||||
expect(hasActiveRunningChatRun(true, null, [
|
||||
{
|
||||
runId: 21,
|
||||
agentId: 1,
|
||||
viewId: 2,
|
||||
query: '查询库存',
|
||||
messages: [],
|
||||
conversationId: 'conv-2',
|
||||
status: 'running',
|
||||
createdAt: '2026-07-02T00:00:00.000Z',
|
||||
},
|
||||
])).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* features/chat/shipping/shippingActionBusy.ts
|
||||
* 用途:判定发货工作台动作是否应被聊天流忙碌态阻塞。
|
||||
* 依赖:chat.types 中的 ChatRunStatus 约定;由 useChatPage 与 useChatShipping 共同复用。
|
||||
* 逻辑:上游先维护全局 isThinking / runs / activeRunId;本文件再过滤出“当前确实存在运行中的 chat run”这一更可信的忙碌态,避免残留 isThinking 误锁工作台。
|
||||
*/
|
||||
import type { ChatRun } from '../types/chat.types';
|
||||
|
||||
/**
|
||||
* 判断当前聊天页是否真的存在活跃中的流式问答。
|
||||
*
|
||||
* 核心逻辑:仅当 `isThinking=true` 且 runs 中仍存在 `status=running` 的记录时才返回 busy;
|
||||
* 如果只是历史残留的 thinking 标记,但没有任何运行中的 run,则允许 shipping 工作台继续触发人工动作。
|
||||
* @param isThinking - 聊天页当前暴露的全局思考态
|
||||
* @param activeRunId - 当前激活 run 编号;缺失时会回退扫描全部 runs
|
||||
* @param runs - 当前页面维护的 run 列表
|
||||
* @returns `true` 表示应继续阻塞工作台动作;`false` 表示可视为残留锁定并允许继续操作
|
||||
*/
|
||||
export function hasActiveRunningChatRun(
|
||||
isThinking: boolean,
|
||||
activeRunId: number | null | undefined,
|
||||
runs: ChatRun[] | null | undefined,
|
||||
): boolean {
|
||||
if (!isThinking) return false;
|
||||
const list = Array.isArray(runs) ? runs : [];
|
||||
if (!list.length) return false;
|
||||
|
||||
const normalizedActiveRunId = Number(activeRunId);
|
||||
if (Number.isFinite(normalizedActiveRunId) && normalizedActiveRunId > 0) {
|
||||
return list.some((run) => run.runId === normalizedActiveRunId && run.status === 'running');
|
||||
}
|
||||
|
||||
return list.some((run) => run.status === 'running');
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* features/chat/shipping/shippingDebugReporter.ts
|
||||
* 用途:集中封装发货通知前端的临时调试上报,避免生产路径直接裸调本地 7778 调试端口。
|
||||
* 依赖:Vite `import.meta.env.DEV` 与浏览器 fetch。
|
||||
* 逻辑:由 shipping 相关 composable / API 在开发环境按需调用;生产环境直接 no-op。
|
||||
*/
|
||||
|
||||
/**
|
||||
* 在开发环境把指定调试事件上报到本地调试服务。
|
||||
* 核心逻辑:仅当 `import.meta.env.DEV` 为 true 时发送 fetch,请求失败静默吞掉,避免影响业务链路。
|
||||
* @param location - 调试事件来源文件
|
||||
* @param hypothesisId - 本轮假设/链路标识
|
||||
* @param msg - 简短调试消息
|
||||
* @param data - 需要附带的上下文数据
|
||||
*/
|
||||
export const reportShippingDebugEvent = (
|
||||
location: string,
|
||||
hypothesisId: string,
|
||||
msg: string,
|
||||
data: Record<string, unknown>,
|
||||
) => {
|
||||
if (!import.meta.env.DEV) return;
|
||||
void fetch('http://127.0.0.1:7778/event', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
sessionId: 'retry-rpa-no-request',
|
||||
runId: 'pre',
|
||||
hypothesisId,
|
||||
location,
|
||||
msg: `[DEBUG] ${msg}`,
|
||||
data,
|
||||
ts: Date.now(),
|
||||
}),
|
||||
}).catch(() => {});
|
||||
};
|
||||
@@ -5,7 +5,7 @@
|
||||
* 逻辑:输入典型 Agent 回复,断言冗余 1/2/3 操作列表被移除,同时普通业务编号列表不受影响。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { sanitizeShippingConversationText } from './shippingText';
|
||||
import { sanitizeShippingConversationText, sanitizeShippingRuntimeStatusText, stripShippingActionListByButtons } from './shippingText';
|
||||
|
||||
describe('shippingText', () => {
|
||||
it('removes numbered action lists that duplicate structured shipping buttons', () => {
|
||||
@@ -65,4 +65,37 @@ describe('shippingText', () => {
|
||||
expect(result).not.toContain('驳回 —');
|
||||
expect(result).not.toContain('重新解析 —');
|
||||
});
|
||||
|
||||
it('removes inline retry/upload hints when matching structured buttons exist', () => {
|
||||
const result = stripShippingActionListByButtons(
|
||||
'已手动重新触发 RPA 库存导出,等待结果。若 6 分内无回调/无落盘文件,可手动重试,或上传库存 Excel。\n任务编号:SN-001',
|
||||
[
|
||||
{ label: '重试 RPA', message: '重试 RPA 导出库存' },
|
||||
{ label: '选择库存文件', message: '我要上传库存 Excel' },
|
||||
],
|
||||
);
|
||||
|
||||
expect(result).toContain('已手动重新触发 RPA 库存导出');
|
||||
expect(result).toContain('任务编号:SN-001');
|
||||
expect(result).not.toContain('可手动重试');
|
||||
expect(result).not.toContain('上传库存 Excel');
|
||||
});
|
||||
|
||||
it('hides manual retry count in user-facing runtime copy', () => {
|
||||
// 关键断言:前台状态文案不暴露“第几次重试”,只保留当前状态本身。
|
||||
const result = sanitizeShippingConversationText(
|
||||
'已手动重新触发 RPA 库存导出(手动第 2 次)。\n任务编号:SN-002',
|
||||
true,
|
||||
);
|
||||
|
||||
expect(result).toContain('已重新触发 RPA 库存导出。');
|
||||
expect(result).not.toContain('手动第 2 次');
|
||||
expect(result).not.toContain('第 2 次');
|
||||
});
|
||||
|
||||
it('hides automatic retry count in runtime status text', () => {
|
||||
const result = sanitizeShippingRuntimeStatusText('RPA 库存导出进行中(第 2/3 次)。');
|
||||
|
||||
expect(result).toBe('RPA 库存导出进行中。');
|
||||
});
|
||||
});
|
||||
@@ -33,6 +33,34 @@ const isShippingActionChoiceLine = (line: string) =>
|
||||
const isPlainActionMenuLine = (line: string) =>
|
||||
/^\s*(?:[-*]\s*)?(?:\*\*)?(?:确认|驳回|重新解析|更正映射|重新匹配|继续处理|重试当前步骤|选择库存文件|上传库存|粘贴库存)(?:\*\*)?\s*(?:[-—-::]|$)/.test(line);
|
||||
|
||||
/**
|
||||
* 规范化运行态提示文案,隐藏“第几次重试/尝试”这类面对业务用户价值较低的过程指标。
|
||||
*
|
||||
* 核心逻辑:仅收敛库存 RPA 相关状态短语,保留“已触发 / 已重新触发 / 进行中”这些对下一步决策有帮助的状态,
|
||||
* 不在前台暴露机械性的第 N 次计数。
|
||||
*/
|
||||
export function sanitizeShippingRuntimeStatusText(text: string): string {
|
||||
return String(text || '')
|
||||
.replace(
|
||||
/已手动重新触发\s*RPA\s*库存导出\s*[((]\s*(?:手动第\s*\d+\s*次(?:尝试)?|第\s*\d+(?:\s*\/\s*\d+)?\s*次(?:尝试)?)\s*[))]\s*[。.]?/gi,
|
||||
'已重新触发 RPA 库存导出。',
|
||||
)
|
||||
.replace(
|
||||
/已触发\s*RPA\s*库存导出\s*[((]\s*第\s*\d+(?:\s*\/\s*\d+)?\s*次(?:尝试)?\s*[))]\s*[。.]?/gi,
|
||||
'已触发 RPA 库存导出。',
|
||||
)
|
||||
.replace(
|
||||
/RPA\s*库存导出进行中\s*[((]\s*第\s*\d+(?:\s*\/\s*\d+)?\s*次(?:尝试)?\s*[))]\s*[。.]?/gi,
|
||||
'RPA 库存导出进行中。',
|
||||
)
|
||||
.replace(
|
||||
/手动第\s*\d+\s*次尝试/gi,
|
||||
'手动重试',
|
||||
)
|
||||
.replace(/\s+([。!?,])/g, '$1')
|
||||
.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除 Agent 正文里重复描述按钮的 1/2/3 编号动作列表。
|
||||
*
|
||||
@@ -141,12 +169,21 @@ export function stripShippingActionListByButtons(
|
||||
text: string,
|
||||
buttons: Array<Pick<ShippingActionButton, 'label' | 'message'>> | null | undefined,
|
||||
): string {
|
||||
const source = String(text || '');
|
||||
let source = String(text || '');
|
||||
const normalizedActions = (buttons || [])
|
||||
.flatMap((button) => [button.label, button.message])
|
||||
.map((item) => normalizeActionComparableText(String(item || '')))
|
||||
.filter((item) => item.length >= 2);
|
||||
if (!normalizedActions.length) return source;
|
||||
const hasRetryRpaAction = normalizedActions.some((action) => /重试.*rpa|rpa.*重试|重试库存抓取|重试库存导出/.test(action));
|
||||
const hasInventoryUploadAction = normalizedActions.some((action) => /选择库存文件|上传库存|库存excel|库存文件/.test(action));
|
||||
if (hasRetryRpaAction && hasInventoryUploadAction) {
|
||||
source = source
|
||||
.replace(/若[^。.\n]*(?:无回调|没有回调|未回调|无落盘|没有落盘|无落盘文件)[^。.\n]*(?:手动)?(?:重试|重试\s*RPA)[^。.\n]*(?:上传库存|库存\s*Excel|库存文件)[^。.\n]*[。.]?/gi, '')
|
||||
.replace(/可(?:手动)?(?:重试|重试\s*RPA)[^。.\n]*(?:上传库存|库存\s*Excel|库存文件)[^。.\n]*[。.]?/gi, '')
|
||||
.replace(/\n{3,}/g, '\n\n')
|
||||
.trim();
|
||||
}
|
||||
|
||||
const lines = source.split('\n');
|
||||
const remove = new Set<number>();
|
||||
@@ -199,7 +236,7 @@ export function stripShippingActionListByButtons(
|
||||
*/
|
||||
export function sanitizeShippingConversationText(text: string, enabled: boolean): string {
|
||||
if (!enabled) return text;
|
||||
let result = String(text || '')
|
||||
let result = sanitizeShippingRuntimeStatusText(String(text || ''))
|
||||
.replace(
|
||||
/已回到列映射步骤。?请根据\s*schema_preview\s*提供新的\s*map_json\s*[,,]\s*再调用\s*(?:应用库存字段映射|apply_inventory_mapping)[^。.\n]*[。.]?/gi,
|
||||
'已回到库存字段确认步骤。请检查系统识别的库存列名,确认无误后继续;如有问题请修改映射。',
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
/**
|
||||
* features/chat/shipping/shippingWorkspaceActions.spec.ts
|
||||
* 用途:锁定聊天页右侧批次工作台的业务按钮解析契约。
|
||||
* 依赖:vitest、shippingWorkspaceActions、shipping.api.types。
|
||||
* 逻辑:验证终态任务不渲染业务按钮,且非终态任务只消费后端 `ui_state.action_buttons`。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type { ShippingTaskSummary } from '../types/shipping.api.types';
|
||||
import {
|
||||
isShippingWorkspaceTerminalTask,
|
||||
resolveShippingWorkspaceActionButtons,
|
||||
} from './shippingWorkspaceActions';
|
||||
|
||||
const createTask = (overrides: Partial<ShippingTaskSummary> = {}): ShippingTaskSummary => ({
|
||||
id: 1,
|
||||
task_no: 'SN-UNIT-001',
|
||||
source_type: 'manual',
|
||||
process_status: 'matched',
|
||||
ui_state: {
|
||||
task_no: 'SN-UNIT-001',
|
||||
process_status: 'matched',
|
||||
steps: [],
|
||||
summary: {},
|
||||
action_buttons: [],
|
||||
},
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe('shippingWorkspaceActions', () => {
|
||||
it('treats uploaded/completed/closed/rejected tasks as terminal workspace tasks', () => {
|
||||
expect(isShippingWorkspaceTerminalTask(createTask({ process_status: 'uploaded' }))).toBe(true);
|
||||
expect(isShippingWorkspaceTerminalTask(createTask({ process_status: 'completed' }))).toBe(true);
|
||||
expect(isShippingWorkspaceTerminalTask(createTask({ process_status: 'closed' }))).toBe(true);
|
||||
expect(isShippingWorkspaceTerminalTask(createTask({ process_status: 'rejected' }))).toBe(true);
|
||||
expect(isShippingWorkspaceTerminalTask(createTask({ process_status: 'matched' }))).toBe(false);
|
||||
});
|
||||
|
||||
it('hides business buttons for completed tasks even if ui_state.action_buttons exists', () => {
|
||||
const task = createTask({
|
||||
process_status: 'completed',
|
||||
ui_state: {
|
||||
task_no: 'SN-UNIT-001',
|
||||
process_status: 'completed',
|
||||
steps: [],
|
||||
summary: {},
|
||||
action_buttons: [
|
||||
{
|
||||
id: 'retry_rpa',
|
||||
label: '重试 RPA',
|
||||
message: '重试 RPA',
|
||||
variant: 'primary',
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
expect(resolveShippingWorkspaceActionButtons(task)).toEqual([]);
|
||||
});
|
||||
|
||||
it('hides business buttons for rejected tasks even if ui_state.action_buttons exists', () => {
|
||||
const task = createTask({
|
||||
process_status: 'rejected',
|
||||
ui_state: {
|
||||
task_no: 'SN-UNIT-001',
|
||||
process_status: 'rejected',
|
||||
steps: [],
|
||||
summary: {},
|
||||
action_buttons: [
|
||||
{
|
||||
id: 'retry_upload',
|
||||
label: '重试上传',
|
||||
message: '重试上传',
|
||||
variant: 'danger',
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
expect(resolveShippingWorkspaceActionButtons(task)).toEqual([]);
|
||||
});
|
||||
|
||||
it('uses backend ui_state.action_buttons as the only business button source for non-completed tasks', () => {
|
||||
const task = createTask({
|
||||
process_status: 'waiting_inventory',
|
||||
pending_human_reason: 'rpa_exhausted',
|
||||
ui_state: {
|
||||
task_no: 'SN-UNIT-001',
|
||||
process_status: 'waiting_inventory',
|
||||
steps: [],
|
||||
summary: {},
|
||||
action_buttons: [
|
||||
{
|
||||
id: 'upload_inventory_file',
|
||||
label: '上传库存文件',
|
||||
message: '请上传库存文件',
|
||||
variant: 'primary',
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
expect(resolveShippingWorkspaceActionButtons(task)).toEqual([
|
||||
{
|
||||
id: 'upload_inventory_file',
|
||||
label: '上传库存文件',
|
||||
message: '请上传库存文件',
|
||||
variant: 'primary',
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('returns empty array when non-completed task has no backend action_buttons', () => {
|
||||
const task = createTask({
|
||||
process_status: 'waiting_inventory',
|
||||
pending_human_reason: 'rpa_exhausted',
|
||||
ui_state: {
|
||||
task_no: 'SN-UNIT-001',
|
||||
process_status: 'waiting_inventory',
|
||||
steps: [],
|
||||
summary: {},
|
||||
action_buttons: [],
|
||||
},
|
||||
});
|
||||
|
||||
expect(resolveShippingWorkspaceActionButtons(task)).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* features/chat/shipping/shippingWorkspaceActions.ts
|
||||
* 用途:集中封装聊天页右侧批次工作台的业务按钮解析规则。
|
||||
* 依赖:shipping.api.types 任务 DTO 类型。
|
||||
* 逻辑:由 ShippingBatchWorkspaceDrawer 调用;统一约束终态任务不渲染业务按钮,且非终态任务只消费后端 `ui_state.action_buttons`。
|
||||
*/
|
||||
import type { ShippingChatAction, ShippingTaskDetail, ShippingTaskSummary } from '../api/shipping.api';
|
||||
|
||||
const TERMINAL_PROCESS_STATUSES = new Set(['uploaded', 'completed', 'closed', 'rejected']);
|
||||
|
||||
/**
|
||||
* 判断工作台任务是否已进入终态。
|
||||
* 核心逻辑:终态任务只允许查看/切换,不再暴露任何后端业务动作按钮。
|
||||
* @param task - 工作台任务摘要或详情
|
||||
* @returns 是否属于终态任务
|
||||
*/
|
||||
export const isShippingWorkspaceTerminalTask = (task: ShippingTaskSummary | ShippingTaskDetail) =>
|
||||
TERMINAL_PROCESS_STATUSES.has(String(task.process_status || '').trim());
|
||||
|
||||
/**
|
||||
* 解析工作台应渲染的业务按钮列表。
|
||||
* 核心逻辑:终态任务直接返回空数组;其他任务只信任后端 `ui_state.action_buttons`,
|
||||
* 不再根据 `process_status / pending_human_reason` 在前端二次推导。
|
||||
* @param task - 工作台任务摘要或详情
|
||||
* @returns 可渲染的业务动作按钮列表
|
||||
*/
|
||||
export const resolveShippingWorkspaceActionButtons = (
|
||||
task: ShippingTaskSummary | ShippingTaskDetail,
|
||||
): ShippingChatAction[] => {
|
||||
if (isShippingWorkspaceTerminalTask(task)) return [];
|
||||
return Array.isArray(task.ui_state?.action_buttons) ? task.ui_state.action_buttons : [];
|
||||
};
|
||||
@@ -81,4 +81,37 @@ describe('useChatShippingDecision', () => {
|
||||
expect(ctx.saveLocalMessageToBackend).toHaveBeenCalledTimes(2);
|
||||
expect(ctx.refreshShippingActions).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does not show success toast for retry_rpa inside shipping agent workspace', async () => {
|
||||
submitWorkspaceShippingDecision.mockResolvedValue({
|
||||
message: '已加入 RPA 队列',
|
||||
data: {},
|
||||
});
|
||||
const ctx = createContext();
|
||||
const { executeShippingDecision } = createShippingDecisionHandlers(ctx);
|
||||
|
||||
const ok = await executeShippingDecision('retry_rpa', '重试 RPA');
|
||||
|
||||
expect(ok).toBe(true);
|
||||
expect(submitWorkspaceShippingDecision).toHaveBeenCalledWith('SN-FOCUS-001', 'retry_rpa');
|
||||
expect(ctx.msg.success).not.toHaveBeenCalled();
|
||||
expect(ctx.refreshShippingActions).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('prefers explicit taskId for workspace retry decisions', async () => {
|
||||
submitWorkspaceShippingDecision.mockResolvedValue({
|
||||
message: '已加入 RPA 队列',
|
||||
data: {},
|
||||
});
|
||||
const ctx = createContext({
|
||||
getActiveShippingTaskId: () => '',
|
||||
});
|
||||
const { executeShippingDecision } = createShippingDecisionHandlers(ctx);
|
||||
|
||||
const ok = await executeShippingDecision('retry_rpa', '重试 RPA', { taskId: 'sn-target-009' });
|
||||
|
||||
expect(ok).toBe(true);
|
||||
expect(submitWorkspaceShippingDecision).toHaveBeenCalledWith('SN-TARGET-009', 'retry_rpa');
|
||||
expect(ctx.msg.warning).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
submitWorkspaceShippingDecision,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import { formatShippingDecisionAssistantMessage } from './shippingDecisionFormat';
|
||||
import { reportShippingDebugEvent } from './shippingDebugReporter';
|
||||
import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
|
||||
import type { ComputedRef, Ref } from 'vue';
|
||||
|
||||
@@ -31,6 +32,7 @@ export interface ShippingDecisionContext {
|
||||
|
||||
export interface ExecuteShippingDecisionOptions {
|
||||
silent?: boolean;
|
||||
taskId?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -43,6 +45,11 @@ export interface ExecuteShippingDecisionOptions {
|
||||
export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
|
||||
const manualUploadInFlightTaskIds = new Set<string>();
|
||||
|
||||
// #region debug-point D:decision-submit
|
||||
const reportRetryRpaDebug = (hypothesisId: string, msg: string, data: Record<string, unknown>) =>
|
||||
reportShippingDebugEvent('useChatShippingDecision.ts', hypothesisId, msg, data);
|
||||
// #endregion
|
||||
|
||||
const syncHistoryIfNeeded = async () => {
|
||||
if (!ctx.conversationId.value && ctx.history.value.length === 0) {
|
||||
await ctx.loadHistory();
|
||||
@@ -54,10 +61,12 @@ export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
|
||||
|
||||
/**
|
||||
* 提交发货人工决策,并按需把结果落为本地聊天消息。
|
||||
* 核心逻辑:先基于 taskId 调后端决策接口,再根据 silent 选项决定是否写入本地 user/assistant 气泡。
|
||||
* 核心逻辑:优先使用 options.taskId 提交指定任务的决策;未显式传入时再回退到当前激活任务。
|
||||
* 这样可避免工作台多任务场景在焦点刷新抖动时,把 retry_rpa 错投到空任务或直接中断。
|
||||
* @param decision - 决策动作 ID,如 confirm、reparse_inventory
|
||||
* @param displayText - 用户侧展示文案;未传时回退为 decision
|
||||
* @param options.silent - 为 true 时只更新状态与按钮,不追加本地聊天消息
|
||||
* @param options.taskId - 显式指定要提交决策的任务编号;工作台多票动作优先传入
|
||||
* @returns 是否成功提交决策
|
||||
*/
|
||||
const executeShippingDecision = async (
|
||||
@@ -65,16 +74,44 @@ export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
|
||||
displayText?: string,
|
||||
options?: ExecuteShippingDecisionOptions,
|
||||
) => {
|
||||
const taskId = ctx.getActiveShippingTaskId();
|
||||
const taskId = String(options?.taskId || ctx.getActiveShippingTaskId() || '').trim().toUpperCase();
|
||||
// #region debug-point D:decision-entry
|
||||
void reportRetryRpaDebug('D', 'executeShippingDecision entry', {
|
||||
decision,
|
||||
taskId,
|
||||
conversationId: ctx.conversationId.value,
|
||||
isShippingNoticeAgent: ctx.isShippingNoticeAgent.value,
|
||||
silent: Boolean(options?.silent),
|
||||
});
|
||||
// #endregion
|
||||
if (!taskId) {
|
||||
// #region debug-point D:decision-missing-task
|
||||
void reportRetryRpaDebug('D', 'executeShippingDecision missing taskId', {
|
||||
decision,
|
||||
conversationId: ctx.conversationId.value,
|
||||
});
|
||||
// #endregion
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
// #region debug-point D:decision-before-submit
|
||||
void reportRetryRpaDebug('D', 'executeShippingDecision before submit', {
|
||||
decision,
|
||||
taskId,
|
||||
});
|
||||
// #endregion
|
||||
const result =
|
||||
decision === 'confirm_inventory_mapping'
|
||||
? await autoProgressWorkspaceShippingTask(taskId)
|
||||
: await submitWorkspaceShippingDecision(taskId, decision);
|
||||
// #region debug-point D:decision-after-submit
|
||||
void reportRetryRpaDebug('D', 'executeShippingDecision after submit', {
|
||||
decision,
|
||||
taskId,
|
||||
message: String(result?.message || ''),
|
||||
});
|
||||
// #endregion
|
||||
if (decision === 'correct_inventory_mapping') {
|
||||
const preview = result?.data?.schema_preview;
|
||||
const key = String(taskId || '').trim().toUpperCase();
|
||||
@@ -108,10 +145,20 @@ export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
|
||||
local_only: true,
|
||||
};
|
||||
ctx.messages.value.push(userMsg, assistantMsg);
|
||||
// #region debug-point D:decision-messages-appended
|
||||
void reportRetryRpaDebug('D', 'executeShippingDecision appended local messages', {
|
||||
decision,
|
||||
taskId,
|
||||
totalMessages: ctx.messages.value.length,
|
||||
lastUserPreview: String(userMsg.content || '').slice(0, 80),
|
||||
lastAssistantPreview: String(assistantContent || '').slice(0, 120),
|
||||
});
|
||||
// #endregion
|
||||
await ctx.saveLocalMessageToBackend(userMsg, userText);
|
||||
await ctx.saveLocalMessageToBackend(assistantMsg);
|
||||
await syncHistoryIfNeeded();
|
||||
}
|
||||
// 工作台内的 shipping agent 决策以聊天气泡和任务卡刷新为主,避免 retry_rpa 再弹成功 toast 打断操作流。
|
||||
if (result.message && !ctx.isShippingNoticeAgent.value) {
|
||||
ctx.msg.success(result.message);
|
||||
}
|
||||
@@ -121,6 +168,13 @@ export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
|
||||
}
|
||||
return true;
|
||||
} catch (e: unknown) {
|
||||
// #region debug-point D:decision-catch
|
||||
void reportRetryRpaDebug('D', 'executeShippingDecision caught error', {
|
||||
decision,
|
||||
taskId,
|
||||
errorMessage: e instanceof Error ? e.message : String(e),
|
||||
});
|
||||
// #endregion
|
||||
const errorMessage = e instanceof Error ? e.message : ctx.t('chat.shippingNoticeUploadFailed');
|
||||
ctx.msg.warning(errorMessage);
|
||||
return false;
|
||||
|
||||
@@ -1,26 +1,55 @@
|
||||
/**
|
||||
* features/chat/shipping/useChatShippingMenuHandler.spec.ts
|
||||
* 用途:验证发货通知聊天菜单动作分流,避免 UI 按钮误走普通对话链路。
|
||||
* 依赖:vitest、vue refs、useChatShippingMenuHandler。
|
||||
* 逻辑:直接调用 createShippingMenuHandlers,覆盖 reparse_inventory 的 silent 决策提交、缺少 task 提示与上传器打开条件。
|
||||
* 用途:验证发货聊天动作菜单在工作台显式 taskId 场景下会命中指定任务,而不是误用当前激活任务。
|
||||
* 依赖:vitest、vue refs、shipping.api、useChatShippingMenuHandler。
|
||||
* 逻辑:覆盖工作台点击 `retry_rpa` 与 `generate_excel` 两类动作,锁死统一按钮分发时的任务归属。
|
||||
*/
|
||||
import { ref } from 'vue';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { createShippingMenuHandlers, type ShippingMenuHandlerContext } from './useChatShippingMenuHandler';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
|
||||
const {
|
||||
confirmWorkspaceShippingInventorySource,
|
||||
generateWorkspaceShippingExcel,
|
||||
getWorkspaceShippingTask,
|
||||
matchWorkspaceShippingInventory,
|
||||
retryWorkspaceShippingUpload,
|
||||
} = vi.hoisted(() => ({
|
||||
confirmWorkspaceShippingInventorySource: vi.fn(),
|
||||
generateWorkspaceShippingExcel: vi.fn(),
|
||||
getWorkspaceShippingTask: vi.fn(),
|
||||
matchWorkspaceShippingInventory: vi.fn(),
|
||||
retryWorkspaceShippingUpload: vi.fn(),
|
||||
}));
|
||||
|
||||
const { downloadWorkspaceShippingExcelFile } = vi.hoisted(() => ({
|
||||
downloadWorkspaceShippingExcelFile: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/chat/api/shipping.api', () => ({
|
||||
confirmWorkspaceShippingInventorySource,
|
||||
generateWorkspaceShippingExcel,
|
||||
getWorkspaceShippingTask,
|
||||
matchWorkspaceShippingInventory,
|
||||
retryWorkspaceShippingUpload,
|
||||
}));
|
||||
|
||||
vi.mock('./shippingDownload', () => ({
|
||||
downloadWorkspaceShippingExcelFile,
|
||||
}));
|
||||
|
||||
const createContext = (
|
||||
overrides: Partial<ShippingMenuHandlerContext> = {},
|
||||
): ShippingMenuHandlerContext => ({
|
||||
isThinking: ref(false),
|
||||
getActiveShippingTaskId: () => 'SN-FOCUS-001',
|
||||
getActiveShippingTaskId: () => 'SN-ACTIVE-001',
|
||||
messages: ref([]),
|
||||
newLocalMessageId: vi.fn(() => 'local-id'),
|
||||
newLocalMessageId: vi.fn((prefix: string) => `${prefix}-local-id`),
|
||||
saveLocalMessageToBackend: vi.fn(async () => undefined),
|
||||
sendShippingMenuMessage: vi.fn(async () => undefined),
|
||||
openShippingInventoryMappingFormForTask: vi.fn(async () => true),
|
||||
openShippingInventoryPicker: vi.fn(() => true),
|
||||
openShippingNoticePicker: vi.fn(() => true),
|
||||
openShippingInventoryPicker: vi.fn((_taskId?: string) => true),
|
||||
openShippingNoticePicker: vi.fn((_taskId?: string) => true),
|
||||
executeShippingDecision: vi.fn(async () => true),
|
||||
executeShippingManualUpload: vi.fn(async () => true),
|
||||
refreshShippingActions: vi.fn(async () => undefined),
|
||||
@@ -33,61 +62,79 @@ const createContext = (
|
||||
});
|
||||
|
||||
describe('useChatShippingMenuHandler', () => {
|
||||
it('clears inventory state and opens picker for reparse_inventory without sending chat text', async () => {
|
||||
beforeEach(() => {
|
||||
confirmWorkspaceShippingInventorySource.mockReset();
|
||||
generateWorkspaceShippingExcel.mockReset();
|
||||
getWorkspaceShippingTask.mockReset();
|
||||
matchWorkspaceShippingInventory.mockReset();
|
||||
retryWorkspaceShippingUpload.mockReset();
|
||||
downloadWorkspaceShippingExcelFile.mockReset();
|
||||
});
|
||||
|
||||
it('uses explicit taskId for retry_rpa workspace actions', async () => {
|
||||
const ctx = createContext();
|
||||
const { handleShippingMenuAction } = createShippingMenuHandlers(ctx);
|
||||
const chatMsg = { role: 'assistant', content: '请重新上传库存' } as ChatMessage & { shipping_actions_used?: boolean };
|
||||
|
||||
await handleShippingMenuAction(
|
||||
{ id: 'reparse_inventory', message: '重新上传库存' },
|
||||
chatMsg,
|
||||
{ id: 'retry_rpa', label: '重试 RPA', message: '重试 RPA' },
|
||||
undefined,
|
||||
{ taskId: 'sn-target-009' },
|
||||
);
|
||||
|
||||
expect(chatMsg.shipping_actions_used).toBe(true);
|
||||
expect(ctx.executeShippingDecision).toHaveBeenCalledTimes(1);
|
||||
expect(ctx.executeShippingDecision).toHaveBeenCalledWith('reparse_inventory', '重新上传库存', { silent: true });
|
||||
expect(ctx.openShippingInventoryPicker).toHaveBeenCalledTimes(1);
|
||||
expect(ctx.sendShippingMenuMessage).not.toHaveBeenCalled();
|
||||
expect(ctx.executeShippingDecision).toHaveBeenCalledWith(
|
||||
'retry_rpa',
|
||||
'重试 RPA',
|
||||
{ taskId: 'SN-TARGET-009' },
|
||||
);
|
||||
expect(ctx.executeShippingDecision).not.toHaveBeenCalledWith(
|
||||
'retry_rpa',
|
||||
'重试 RPA',
|
||||
{ taskId: 'SN-ACTIVE-001' },
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps existing missing task warning when reparse_inventory has no active task', async () => {
|
||||
const ctx = createContext({
|
||||
getActiveShippingTaskId: () => '',
|
||||
it('uses explicit taskId for generate_excel workspace actions', async () => {
|
||||
generateWorkspaceShippingExcel.mockResolvedValue({
|
||||
message: '发货文件已生成',
|
||||
data: {},
|
||||
});
|
||||
const ctx = createContext();
|
||||
const { handleShippingMenuAction } = createShippingMenuHandlers(ctx);
|
||||
|
||||
await handleShippingMenuAction({ id: 'reparse_inventory', message: '重新上传库存' });
|
||||
await handleShippingMenuAction(
|
||||
{ id: 'generate_excel', label: '生成发货文件', message: '请生成发货文件' },
|
||||
undefined,
|
||||
{ taskId: 'sn-target-777' },
|
||||
);
|
||||
|
||||
expect(ctx.msg.warning).toHaveBeenCalledWith('chat.shippingNoticeMissingTaskId');
|
||||
expect(ctx.executeShippingDecision).not.toHaveBeenCalled();
|
||||
expect(ctx.openShippingInventoryPicker).not.toHaveBeenCalled();
|
||||
expect(ctx.sendShippingMenuMessage).not.toHaveBeenCalled();
|
||||
expect(generateWorkspaceShippingExcel).toHaveBeenCalledWith('SN-TARGET-777');
|
||||
expect(ctx.messages.value[0]?.content).toContain('SN-TARGET-777');
|
||||
expect(ctx.messages.value[1]?.content).toContain('SN-TARGET-777');
|
||||
});
|
||||
|
||||
it('does not open picker when reparse_inventory decision fails', async () => {
|
||||
const ctx = createContext({
|
||||
executeShippingDecision: vi.fn(async () => false),
|
||||
});
|
||||
it('passes explicit taskId into inventory picker actions', async () => {
|
||||
const ctx = createContext();
|
||||
const { handleShippingMenuAction } = createShippingMenuHandlers(ctx);
|
||||
|
||||
await handleShippingMenuAction({ id: 'reparse_inventory', message: '重新上传库存' });
|
||||
await handleShippingMenuAction(
|
||||
{ id: 'upload_inventory_file', label: '上传库存文件', message: '请上传库存文件' },
|
||||
undefined,
|
||||
{ taskId: 'sn-picker-123' },
|
||||
);
|
||||
|
||||
expect(ctx.executeShippingDecision).toHaveBeenCalledWith('reparse_inventory', '重新上传库存', { silent: true });
|
||||
expect(ctx.openShippingInventoryPicker).not.toHaveBeenCalled();
|
||||
expect(ctx.sendShippingMenuMessage).not.toHaveBeenCalled();
|
||||
expect(ctx.openShippingInventoryPicker).toHaveBeenCalledWith('SN-PICKER-123');
|
||||
});
|
||||
|
||||
it('does not mark button used when reparse_inventory has no active task', async () => {
|
||||
const ctx = createContext({
|
||||
getActiveShippingTaskId: () => '',
|
||||
});
|
||||
it('passes explicit taskId into notice picker actions', async () => {
|
||||
const ctx = createContext();
|
||||
const { handleShippingMenuAction } = createShippingMenuHandlers(ctx);
|
||||
const chatMsg = { role: 'assistant', content: '请重新上传库存' } as ChatMessage & { shipping_actions_used?: boolean };
|
||||
|
||||
await handleShippingMenuAction({ id: 'reparse_inventory', message: '重新上传库存' }, chatMsg);
|
||||
await handleShippingMenuAction(
|
||||
{ id: 'replace_notice_file', label: '重新上传通知', message: '请重新上传通知' },
|
||||
undefined,
|
||||
{ taskId: 'sn-notice-123' },
|
||||
);
|
||||
|
||||
expect(chatMsg.shipping_actions_used).toBeUndefined();
|
||||
expect(ctx.executeShippingDecision).not.toHaveBeenCalled();
|
||||
expect(ctx.openShippingInventoryPicker).not.toHaveBeenCalled();
|
||||
expect(ctx.openShippingNoticePicker).toHaveBeenCalledWith('SN-NOTICE-123');
|
||||
});
|
||||
});
|
||||
@@ -27,12 +27,12 @@ export interface ShippingMenuHandlerContext {
|
||||
saveLocalMessageToBackend: (msg: ChatMessage, userQuery?: string) => Promise<void>;
|
||||
sendShippingMenuMessage: (message: string) => Promise<void>;
|
||||
openShippingInventoryMappingFormForTask: (taskId: string) => Promise<boolean>;
|
||||
openShippingInventoryPicker: () => boolean;
|
||||
openShippingNoticePicker: () => boolean;
|
||||
openShippingInventoryPicker: (taskId?: string) => boolean;
|
||||
openShippingNoticePicker: (taskId?: string) => boolean;
|
||||
executeShippingDecision: (
|
||||
decision: string,
|
||||
displayText?: string,
|
||||
options?: { silent?: boolean },
|
||||
options?: { silent?: boolean; taskId?: string },
|
||||
) => Promise<boolean>;
|
||||
executeShippingManualUpload: (taskId: string, displayText?: string) => Promise<boolean>;
|
||||
refreshShippingActions: () => Promise<void>;
|
||||
@@ -40,6 +40,10 @@ export interface ShippingMenuHandlerContext {
|
||||
t: (key: string) => string;
|
||||
}
|
||||
|
||||
export interface HandleShippingMenuActionOptions {
|
||||
taskId?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建发货通知动作菜单处理器。
|
||||
*
|
||||
@@ -120,7 +124,10 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
|
||||
const handleShippingMenuAction = async (
|
||||
action: ShippingActionButton | { id?: string; message: string },
|
||||
chatMsg?: ChatMessage & { shipping_actions_used?: boolean },
|
||||
options?: HandleShippingMenuActionOptions,
|
||||
) => {
|
||||
const explicitTaskId = String(options?.taskId || '').trim().toUpperCase();
|
||||
const resolveTaskId = () => explicitTaskId || ctx.getActiveShippingTaskId();
|
||||
if (ctx.isThinking.value) return;
|
||||
if (action.id === 'refresh') {
|
||||
await ctx.refreshShippingActions();
|
||||
@@ -128,7 +135,7 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
|
||||
return;
|
||||
}
|
||||
if (action.id === 'download_excel') {
|
||||
const taskId = ctx.getActiveShippingTaskId();
|
||||
const taskId = resolveTaskId();
|
||||
if (!taskId) {
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
|
||||
return;
|
||||
@@ -144,7 +151,7 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
|
||||
if (action.id === 'generate_excel') {
|
||||
if (chatMsg?.shipping_actions_used) return;
|
||||
if (chatMsg) chatMsg.shipping_actions_used = true;
|
||||
const taskId = ctx.getActiveShippingTaskId();
|
||||
const taskId = resolveTaskId();
|
||||
if (!taskId) {
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
|
||||
return;
|
||||
@@ -181,7 +188,7 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
|
||||
if (action.id === 'retry_upload') {
|
||||
if (chatMsg?.shipping_actions_used) return;
|
||||
if (chatMsg) chatMsg.shipping_actions_used = true;
|
||||
const taskId = ctx.getActiveShippingTaskId();
|
||||
const taskId = resolveTaskId();
|
||||
if (!taskId) {
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
|
||||
return;
|
||||
@@ -216,7 +223,7 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
|
||||
if (action.id === 'confirm_inventory_source') {
|
||||
if (chatMsg?.shipping_actions_used) return;
|
||||
if (chatMsg) chatMsg.shipping_actions_used = true;
|
||||
const taskId = ctx.getActiveShippingTaskId();
|
||||
const taskId = resolveTaskId();
|
||||
if (!taskId) {
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
|
||||
return;
|
||||
@@ -265,7 +272,7 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
|
||||
return;
|
||||
}
|
||||
if (action.id === 'edit_inventory_mapping') {
|
||||
const taskId = ctx.getActiveShippingTaskId();
|
||||
const taskId = resolveTaskId();
|
||||
if (!taskId) {
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
|
||||
return;
|
||||
@@ -274,17 +281,17 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
|
||||
return;
|
||||
}
|
||||
if (action.id === 'upload_inventory_file') {
|
||||
ctx.openShippingInventoryPicker();
|
||||
ctx.openShippingInventoryPicker(resolveTaskId());
|
||||
return;
|
||||
}
|
||||
if (action.id === 'replace_notice_file') {
|
||||
ctx.openShippingNoticePicker();
|
||||
ctx.openShippingNoticePicker(resolveTaskId());
|
||||
return;
|
||||
}
|
||||
if (action.id === 'match_inventory') {
|
||||
if (chatMsg?.shipping_actions_used) return;
|
||||
if (chatMsg) chatMsg.shipping_actions_used = true;
|
||||
const taskId = ctx.getActiveShippingTaskId();
|
||||
const taskId = resolveTaskId();
|
||||
if (!taskId) {
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
|
||||
return;
|
||||
@@ -322,7 +329,7 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
|
||||
chatMsg.shipping_actions_used = true;
|
||||
chatMsg.shipping_actions = undefined;
|
||||
}
|
||||
const taskId = ctx.getActiveShippingTaskId();
|
||||
const taskId = resolveTaskId();
|
||||
if (!taskId) {
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
|
||||
return;
|
||||
@@ -336,20 +343,20 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
|
||||
}
|
||||
if (action.id === 'reparse_inventory') {
|
||||
if (chatMsg?.shipping_actions_used) return;
|
||||
const taskId = ctx.getActiveShippingTaskId();
|
||||
const taskId = resolveTaskId();
|
||||
if (!taskId) {
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
|
||||
return;
|
||||
}
|
||||
if (chatMsg) chatMsg.shipping_actions_used = true;
|
||||
const ok = await ctx.executeShippingDecision('reparse_inventory', action.message, { silent: true });
|
||||
if (ok) ctx.openShippingInventoryPicker();
|
||||
const ok = await ctx.executeShippingDecision('reparse_inventory', action.message, { silent: true, taskId });
|
||||
if (ok) ctx.openShippingInventoryPicker(taskId);
|
||||
return;
|
||||
}
|
||||
if (action.id && SHIPPING_DECISION_ACTIONS.has(action.id)) {
|
||||
if (chatMsg?.shipping_actions_used) return;
|
||||
if (chatMsg) chatMsg.shipping_actions_used = true;
|
||||
await ctx.executeShippingDecision(action.id, action.message);
|
||||
await ctx.executeShippingDecision(action.id, action.message, { taskId: resolveTaskId() });
|
||||
return;
|
||||
}
|
||||
if (chatMsg?.shipping_actions_used) return;
|
||||
|
||||
@@ -102,4 +102,72 @@ describe('useChatShippingRefresh', () => {
|
||||
expect(messages.value[0].shipping_ui_state?.task_no).toBe('SN-FOCUS-B');
|
||||
expect(messages.value[0].shipping_actions?.map((item) => item.id)).toEqual(['generate_excel']);
|
||||
});
|
||||
|
||||
it('treats backend ui_state.action_buttons as the only button source when api refresh succeeds', async () => {
|
||||
getWorkspaceShippingTaskUiState.mockResolvedValue({
|
||||
task_no: 'SN-SOURCE-001',
|
||||
batch_no: 'SB-SOURCE-001',
|
||||
checkpoint: 'ready_export',
|
||||
process_status: 'matched',
|
||||
review_status: null,
|
||||
pending_human_reason: null,
|
||||
match_status: 'fulfillable',
|
||||
current_step: null,
|
||||
steps: [],
|
||||
summary: {
|
||||
title: '可生成发货文件',
|
||||
message: '库存匹配已满足发货条件,可以生成发货文件。',
|
||||
error_message: null,
|
||||
},
|
||||
action_buttons: [
|
||||
{
|
||||
id: 'download_excel',
|
||||
label: '下载发货文件',
|
||||
message: '请下载发货文件',
|
||||
variant: 'primary',
|
||||
},
|
||||
],
|
||||
updated_at: '2026-07-03T10:00:00+08:00',
|
||||
});
|
||||
|
||||
const messages = ref([
|
||||
{
|
||||
role: 'assistant' as const,
|
||||
content: '请使用下方按钮继续。',
|
||||
shipping_actions: [
|
||||
{
|
||||
id: 'legacy-local-action',
|
||||
label: '旧按钮',
|
||||
message: '旧按钮',
|
||||
variant: 'secondary' as const,
|
||||
},
|
||||
],
|
||||
shipping_ui_state: {
|
||||
action_buttons: [
|
||||
{
|
||||
id: 'legacy-ui-state-action',
|
||||
label: '旧状态按钮',
|
||||
message: '旧状态按钮',
|
||||
variant: 'secondary' as const,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
]);
|
||||
const { refreshShippingActions } = createShippingActionsRefresher({
|
||||
isShippingNoticeAgent: computed(() => true),
|
||||
messages,
|
||||
conversationId: ref('conv-source'),
|
||||
isThinking: ref(false),
|
||||
history: ref([]),
|
||||
resolvedShippingTaskId: ref('SN-SOURCE-001'),
|
||||
shippingTaskIdFromQuery: computed(() => ''),
|
||||
getActiveBatchTaskId: () => 'SN-SOURCE-001',
|
||||
});
|
||||
|
||||
await refreshShippingActions();
|
||||
|
||||
expect(messages.value[0].shipping_actions?.map((item) => item.id)).toEqual(['download_excel']);
|
||||
expect(messages.value[0].shipping_ui_state?.action_buttons?.map((item) => item.id)).toEqual(['download_excel']);
|
||||
});
|
||||
});
|
||||
@@ -8,7 +8,7 @@ import { getWorkspaceShippingTaskUiState } from '@/features/chat/api/shipping.ap
|
||||
import { SHIPPING_TERMINAL_CHECKPOINTS } from '@/constants/shippingNoticeActions';
|
||||
import { SHIPPING_TASK_ID_RE } from '../constants/shipping';
|
||||
import { findLatestShippingTaskId } from './shippingTaskId';
|
||||
import { stripShippingPlainActionMenu } from './shippingText';
|
||||
import { stripShippingActionListByButtons, stripShippingPlainActionMenu } from './shippingText';
|
||||
import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
|
||||
import type { ShippingActionButton } from '../types/shipping.types';
|
||||
import type { ShippingTaskUiState } from '../types/shipping.api.types';
|
||||
@@ -157,19 +157,22 @@ export function createShippingActionsRefresher(ctx: ShippingRefreshContext) {
|
||||
return;
|
||||
}
|
||||
let buttons: ShippingActionButton[] = [];
|
||||
let cleanedText = stripShippingPlainActionMenu(String(chatMsg.content || ''));
|
||||
if (index === targetAssistantIndex) {
|
||||
const cleanedText = stripShippingPlainActionMenu(String(chatMsg.content || ''));
|
||||
if (cleanedText !== String(chatMsg.content || '').trim()) {
|
||||
chatMsg.content = cleanedText;
|
||||
}
|
||||
if (apiState?.action_buttons?.length) {
|
||||
buttons = apiState.action_buttons;
|
||||
chatMsg.shipping_ui_state = apiState;
|
||||
} else if (!apiResolved && chatMsg.shipping_ui_state?.action_buttons?.length) {
|
||||
buttons = chatMsg.shipping_ui_state.action_buttons;
|
||||
}
|
||||
if (buttons.length) {
|
||||
cleanedText = stripShippingActionListByButtons(cleanedText, buttons);
|
||||
}
|
||||
} else {
|
||||
chatMsg.content = stripShippingPlainActionMenu(String(chatMsg.content || ''));
|
||||
cleanedText = stripShippingPlainActionMenu(String(chatMsg.content || ''));
|
||||
}
|
||||
if (cleanedText !== String(chatMsg.content || '').trim()) {
|
||||
chatMsg.content = cleanedText;
|
||||
}
|
||||
if (chatMsg.type === 'shipping-match-result' && chatMsg.payload && typeof chatMsg.payload === 'object') {
|
||||
(chatMsg.payload as { action_buttons?: ShippingActionButton[] }).action_buttons = buttons;
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
/**
|
||||
* features/chat/shipping/useChatShippingUploadHandler.spec.ts
|
||||
* 用途:验证发货通知上传 handler 在显式 taskId 场景下不会把库存/通知文件错投到当前激活任务。
|
||||
* 依赖:vitest、vue refs、shipping.api、useChatShippingUploadHandler。
|
||||
* 逻辑:覆盖库存/通知 picker 的任务锁定,以及 notice replace 在 pending task 锁定下命中指定任务。
|
||||
*/
|
||||
import { ref } from 'vue';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
createShippingUploadHandlers,
|
||||
type ShippingUploadHandlerContext,
|
||||
} from './useChatShippingUploadHandler';
|
||||
|
||||
const {
|
||||
createWorkspaceShippingBatchFromNotices,
|
||||
createWorkspaceShippingTask,
|
||||
replaceWorkspaceShippingTaskNotice,
|
||||
uploadWorkspaceShippingInventory,
|
||||
} = vi.hoisted(() => ({
|
||||
createWorkspaceShippingBatchFromNotices: vi.fn(),
|
||||
createWorkspaceShippingTask: vi.fn(),
|
||||
replaceWorkspaceShippingTaskNotice: vi.fn(),
|
||||
uploadWorkspaceShippingInventory: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/chat/api/shipping.api', () => ({
|
||||
createWorkspaceShippingBatchFromNotices,
|
||||
createWorkspaceShippingTask,
|
||||
replaceWorkspaceShippingTaskNotice,
|
||||
uploadWorkspaceShippingInventory,
|
||||
}));
|
||||
|
||||
const createContext = (
|
||||
overrides: Partial<ShippingUploadHandlerContext> = {},
|
||||
): ShippingUploadHandlerContext => ({
|
||||
conversationId: ref('conv-upload'),
|
||||
attachments: ref([]),
|
||||
input: ref(''),
|
||||
shippingAutoFlowRequested: ref(false),
|
||||
shippingInventoryPickerRef: ref({ click: vi.fn() } as unknown as HTMLInputElement),
|
||||
shippingNoticePickerRef: ref({ click: vi.fn() } as unknown as HTMLInputElement),
|
||||
pendingShippingUploadTaskId: ref(''),
|
||||
pendingShippingNoticeTaskId: ref(''),
|
||||
pendingShippingInventoryFile: ref(null),
|
||||
resolvedShippingTaskId: ref(''),
|
||||
resolvedShippingBatchNo: ref(''),
|
||||
shippingBatchSummary: ref(null),
|
||||
shippingBatchTasks: ref([]),
|
||||
shippingInventorySelectionActive: ref(false),
|
||||
shippingInventorySelectionTaskId: ref(''),
|
||||
shippingInventorySchemaPreviewCache: ref({}),
|
||||
getActiveShippingTaskId: () => 'SN-ACTIVE-001',
|
||||
sendShippingMenuMessage: vi.fn(async () => undefined),
|
||||
pushShippingLocalUserMessage: vi.fn(async () => undefined),
|
||||
pushShippingLocalAssistantMessage: vi.fn(async () => undefined),
|
||||
refreshShippingActions: vi.fn(async () => undefined),
|
||||
msg: { warning: vi.fn() },
|
||||
t: (key: string, params?: Record<string, unknown>) => {
|
||||
if (key === 'chat.shippingNoticeInventoryUploadStarted') {
|
||||
return `开始上传库存:${String(params?.fileName || '')}`;
|
||||
}
|
||||
if (key === 'chat.shippingNoticeMissingTaskId') return '缺少任务编号';
|
||||
if (key === 'chat.shippingNoticeUploadFailed') return '上传失败';
|
||||
return key;
|
||||
},
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe('useChatShippingUploadHandler', () => {
|
||||
beforeEach(() => {
|
||||
createWorkspaceShippingBatchFromNotices.mockReset();
|
||||
createWorkspaceShippingTask.mockReset();
|
||||
replaceWorkspaceShippingTaskNotice.mockReset();
|
||||
uploadWorkspaceShippingInventory.mockReset();
|
||||
});
|
||||
|
||||
it('opens inventory picker for explicit taskId instead of current active task', () => {
|
||||
const inventoryClick = vi.fn();
|
||||
const ctx = createContext({
|
||||
shippingInventoryPickerRef: ref({ click: inventoryClick } as unknown as HTMLInputElement),
|
||||
});
|
||||
const { openShippingInventoryPicker } = createShippingUploadHandlers(ctx);
|
||||
|
||||
const ok = openShippingInventoryPicker('sn-target-100');
|
||||
|
||||
expect(ok).toBe(true);
|
||||
expect(ctx.pendingShippingUploadTaskId.value).toBe('SN-TARGET-100');
|
||||
expect(inventoryClick).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('replaces notice on locked pending task instead of current active task', async () => {
|
||||
replaceWorkspaceShippingTaskNotice.mockResolvedValue({
|
||||
message: '已覆盖通知',
|
||||
data: { orchestrator_started: true },
|
||||
});
|
||||
const ctx = createContext({
|
||||
pendingShippingNoticeTaskId: ref('SN-TARGET-200'),
|
||||
});
|
||||
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
|
||||
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
|
||||
|
||||
await handleShippingAutoUploadNoticeBatch([file]);
|
||||
|
||||
expect(replaceWorkspaceShippingTaskNotice).toHaveBeenCalledWith('SN-TARGET-200', file);
|
||||
expect(replaceWorkspaceShippingTaskNotice).not.toHaveBeenCalledWith('SN-ACTIVE-001', file);
|
||||
expect(ctx.pendingShippingNoticeTaskId.value).toBe('');
|
||||
});
|
||||
|
||||
it('does not open notice picker when both explicit taskId and active task are missing', () => {
|
||||
const noticeClick = vi.fn();
|
||||
const warning = vi.fn();
|
||||
const ctx = createContext({
|
||||
shippingNoticePickerRef: ref({ click: noticeClick } as unknown as HTMLInputElement),
|
||||
getActiveShippingTaskId: () => '',
|
||||
msg: { warning },
|
||||
});
|
||||
const { openShippingNoticePicker } = createShippingUploadHandlers(ctx);
|
||||
|
||||
const ok = openShippingNoticePicker();
|
||||
|
||||
expect(ok).toBe(false);
|
||||
expect(noticeClick).not.toHaveBeenCalled();
|
||||
expect(warning).toHaveBeenCalledWith('缺少任务编号');
|
||||
expect(ctx.pendingShippingNoticeTaskId.value).toBe('');
|
||||
});
|
||||
});
|
||||
@@ -23,7 +23,9 @@ export interface ShippingUploadHandlerContext {
|
||||
input: Ref<string>;
|
||||
shippingAutoFlowRequested: Ref<boolean>;
|
||||
shippingInventoryPickerRef: Ref<HTMLInputElement | null>;
|
||||
shippingNoticePickerRef: Ref<HTMLInputElement | null>;
|
||||
pendingShippingUploadTaskId: Ref<string>;
|
||||
pendingShippingNoticeTaskId: Ref<string>;
|
||||
pendingShippingInventoryFile: Ref<File | null>;
|
||||
resolvedShippingTaskId: Ref<string>;
|
||||
resolvedShippingBatchNo: Ref<string>;
|
||||
@@ -175,9 +177,11 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
|
||||
await uploadInventoryForTask(taskId, file);
|
||||
return;
|
||||
}
|
||||
const activeTaskId = String(ctx.getActiveShippingTaskId() || '').trim().toUpperCase();
|
||||
if (activeTaskId) {
|
||||
await handleReplaceNoticeForCurrentTask(activeTaskId, file);
|
||||
const pendingNoticeTaskId = String(ctx.pendingShippingNoticeTaskId.value || '').trim().toUpperCase();
|
||||
ctx.pendingShippingNoticeTaskId.value = '';
|
||||
const targetTaskId = pendingNoticeTaskId || String(ctx.getActiveShippingTaskId() || '').trim().toUpperCase();
|
||||
if (targetTaskId) {
|
||||
await handleReplaceNoticeForCurrentTask(targetTaskId, file);
|
||||
return;
|
||||
}
|
||||
const result = await createWorkspaceShippingBatchFromNotices(
|
||||
@@ -216,7 +220,9 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
|
||||
const handleShippingAutoUploadNoticeBatch = async (files: File[]) => {
|
||||
const noticeFiles = files.filter(Boolean);
|
||||
if (!noticeFiles.length) return;
|
||||
const activeTaskId = String(ctx.getActiveShippingTaskId() || '').trim().toUpperCase();
|
||||
const pendingNoticeTaskId = String(ctx.pendingShippingNoticeTaskId.value || '').trim().toUpperCase();
|
||||
ctx.pendingShippingNoticeTaskId.value = '';
|
||||
const activeTaskId = pendingNoticeTaskId || String(ctx.getActiveShippingTaskId() || '').trim().toUpperCase();
|
||||
const singleNoticeFile = noticeFiles[0];
|
||||
if (noticeFiles.length === 1 && activeTaskId && singleNoticeFile) {
|
||||
await handleReplaceNoticeForCurrentTask(activeTaskId, singleNoticeFile);
|
||||
@@ -268,13 +274,30 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
|
||||
void ctx.refreshShippingActions();
|
||||
};
|
||||
|
||||
const openShippingInventoryPicker = (): boolean => {
|
||||
const taskId = ctx.getActiveShippingTaskId();
|
||||
if (!taskId) {
|
||||
const openShippingInventoryPicker = (taskId?: string): boolean => {
|
||||
const resolvedTaskId = String(taskId || ctx.getActiveShippingTaskId() || '').trim().toUpperCase();
|
||||
if (!resolvedTaskId) {
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
|
||||
return false;
|
||||
}
|
||||
return selectShippingInventoryUploadTask(taskId);
|
||||
return selectShippingInventoryUploadTask(resolvedTaskId);
|
||||
};
|
||||
|
||||
/**
|
||||
* 打开发货通知文件选择器,并在需要覆盖既有任务时锁定目标任务。
|
||||
* 核心逻辑:优先使用显式 taskId 记录待覆盖任务;后续用户选中文件后,自动上传流程会消费该锁定任务而不是回退到最近聊天上下文。
|
||||
* @param taskId - 可选任务编号;工作台/动作按钮重传时必须显式传入
|
||||
* @returns 是否成功打开文件选择器
|
||||
*/
|
||||
const openShippingNoticePicker = (taskId?: string): boolean => {
|
||||
const resolvedTaskId = String(taskId || ctx.getActiveShippingTaskId() || '').trim().toUpperCase();
|
||||
if (!resolvedTaskId) {
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
|
||||
return false;
|
||||
}
|
||||
ctx.pendingShippingNoticeTaskId.value = resolvedTaskId;
|
||||
ctx.shippingNoticePickerRef.value?.click();
|
||||
return true;
|
||||
};
|
||||
|
||||
const handleShippingInventorySelected = async (event: Event) => {
|
||||
@@ -318,6 +341,7 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
|
||||
handleShippingAutoUploadFile,
|
||||
handleShippingAutoUploadNoticeBatch,
|
||||
openShippingInventoryPicker,
|
||||
openShippingNoticePicker,
|
||||
selectShippingInventoryUploadTask,
|
||||
cancelShippingInventoryTaskSelection,
|
||||
handleShippingInventorySelected,
|
||||
|
||||
Reference in new issue
Block a user