feat(chat): 优化发货相关消息处理逻辑

- 在列出聊天消息时,过滤掉类型为'shipping-parse-review'的消息
- 移除不再使用的shippingConversationTaskIdCache
- 更新发货决策处理逻辑,简化保存消息的参数
- 添加发货动作按钮刷新时的任务定位优先级逻辑
- 移除解析复核消息的展示逻辑,统一处理到轻量工作台
- 增加单元测试,验证发货动作按钮刷新时的任务定位优先级
This commit is contained in:
hugo committed 2026-07-01 08:57:36 +08:00
1 parent 9f5493185d
commit 6a0a51313f
18 files changed
+1230 -199

No files matched your search

+6 -2
View File
@@ -26,8 +26,12 @@ export const deleteAllChatSessions = (agentId: number) =>
export const deleteChatSession = (conversationId: string, agentId: number) =>
requestJson(`/api/chat/sessions/${conversationId}?agent_id=${agentId}`, { method: 'DELETE', ...auth() });
export const listChatMessages = (conversationId: string, agentId: number) =>
requestJson<ChatMessage[]>(`/api/chat/messages?conversation_id=${conversationId}&agent_id=${agentId}`, auth());
export const listChatMessages = async (conversationId: string, agentId: number) => {
const messages = await requestJson<ChatMessage[]>(`/api/chat/messages?conversation_id=${conversationId}&agent_id=${agentId}`, auth());
return Array.isArray(messages)
? messages.filter((message) => message?.type !== 'shipping-parse-review')
: messages;
};
export const saveLocalChatMessage = (payload: Record<string, unknown>) =>
requestJson<{ conversation_id?: string; chat_log_id?: number }>('/api/chat/messages/local', {
@@ -166,7 +166,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
const retryingShippingPendingTasks = ref(false);
const activeShippingTaskDetail = ref<ShippingTaskDetail | null>(null);
const shippingFocusReason = ref('');
const shippingConversationTaskIdCache = ref<Record<string, string>>({});
const shippingInventorySchemaPreviewCache = ref<Record<string, unknown>>({});
const autoResumedShippingTasks = ref<Record<string, boolean>>({});
const lastConversationSyncKey = ref('');
@@ -320,7 +319,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
shippingWorkspaceOpen.value = false;
retryingShippingPendingTasks.value = false;
activeShippingTaskDetail.value = null;
shippingConversationTaskIdCache.value = {};
shippingInventorySchemaPreviewCache.value = {};
lastConversationSyncKey.value = '';
};
@@ -443,7 +441,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
history,
resolvedShippingTaskId,
shippingTaskIdFromQuery,
shippingConversationTaskIdCache,
getActiveBatchTaskId,
});
const { pushShippingLocalUserMessage, pushShippingLocalAssistantMessage } = createShippingLocalMessages({
@@ -181,6 +181,7 @@ function downloadInlineFile(file: InlineDownloadFile): void {
export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
const shouldRenderMessage = (msgItem: ChatMessage): boolean => {
if (msgItem?.role === 'user') return true;
if (msgItem?.type === 'shipping-parse-review') return false;
if (msgItem?.type === 'leave-form' || msgItem?.type === 'leave-confirmation' || msgItem?.type === 'leave-result') return true;
const content = (msgItem?.content || '').trim();
if (content) return true;
@@ -47,4 +47,22 @@ describe('shippingText', () => {
expect(result).toContain('1. SKU A001');
expect(result).toContain('2. SKU B002');
});
it('removes plain action menus generated in assistant text', () => {
// 关键断言:即使 Dify 没有用 1/2/3 编号,只要正文手写按钮菜单,也不能露给用户。
const result = sanitizeShippingConversationText(
[
'请使用下方按钮进行确认操作:',
'确认 — 解析无误,进入下一步库存上传与匹配',
'驳回 — 解析有误,终止当前任务',
'重新解析 — 重新解析发货通知原始文件',
].join('\n'),
true,
);
expect(result).not.toContain('请使用下方按钮');
expect(result).not.toContain('确认 —');
expect(result).not.toContain('驳回 —');
expect(result).not.toContain('重新解析 —');
});
});
@@ -28,7 +28,10 @@ const isShippingActionListContextLine = (line: string) =>
/(?:请选择操作|选择操作|操作选项|下方按钮|按钮继续操作|以下.*方式|任一方式|库存上传|提供当前库存|提供.*库存数据)/.test(line);
const isShippingActionChoiceLine = (line: string) =>
/(?:选择库存文件|上传库存|粘贴库存|重试\s*RPA|修改映射|确认字段|继续处理|查看卡点|返回修订|重新匹配|重试当前步骤|切换为当前任务)/i.test(line);
/(?:选择库存文件|上传库存|粘贴库存|重试\s*RPA|修改映射|确认字段|继续处理|查看卡点|返回修订|重新匹配|重试当前步骤|切换为当前任务|确认|驳回|重新解析)/i.test(line);
const isPlainActionMenuLine = (line: string) =>
/^\s*(?:[-*]\s*)?(?:\*\*)?(?:确认|驳回|重新解析|更正映射|重新匹配|继续处理|重试当前步骤|选择库存文件|上传库存|粘贴库存)(?:\*\*)?\s*(?:[-—-::]|$)/.test(line);
/**
* 移除 Agent 正文里重复描述按钮的 1/2/3 编号动作列表。
@@ -95,6 +98,39 @@ export function stripShippingRedundantNumberedActionList(text: string): string {
.trim();
}
/**
* 移除 Agent 正文中手写的操作菜单段落。
*
* 核心逻辑:结构化按钮已经由系统渲染,正文里再写“请使用下方按钮/确认/驳回/重新解析”
* 会形成两套入口。只删除明确处在按钮/操作上下文附近的菜单行,避免误删普通业务说明。
*/
export function stripShippingPlainActionMenu(text: string): string {
const lines = String(text || '').split('\n');
const remove = new Set<number>();
lines.forEach((line, index) => {
if (!isPlainActionMenuLine(line)) return;
const nearby = lines.slice(Math.max(0, index - 4), Math.min(lines.length, index + 4));
const hasContext = nearby.some((item) => isShippingActionListContextLine(item) || /(?:按钮|确认操作|进行确认操作|操作$)/.test(item));
if (!hasContext) return;
remove.add(index);
for (let before = index - 1; before >= 0 && before >= index - 4; before -= 1) {
const prev = lines[before] || '';
if (!prev.trim() || isShippingActionListContextLine(prev) || /(?:按钮|确认操作|进行确认操作|操作$)/.test(prev)) {
remove.add(before);
continue;
}
break;
}
});
return lines
.filter((_, index) => !remove.has(index))
.join('\n')
.replace(/\n{3,}/g, '\n\n')
.trim();
}
/**
* 根据后端 action_buttons 移除 Agent 正文中重复生成的编号操作列表。
*
@@ -213,7 +249,7 @@ export function sanitizeShippingConversationText(text: string, enabled: boolean)
result = result.replace(quoted, '');
result = result.replace(new RegExp(`\`${token}\``, 'gi'), '');
}
return stripShippingRedundantNumberedActionList(result.replace(/\n{3,}/g, '\n\n').trim());
return stripShippingPlainActionMenu(stripShippingRedundantNumberedActionList(result.replace(/\n{3,}/g, '\n\n').trim()));
}
/**
@@ -92,7 +92,7 @@ export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
};
ctx.messages.value.push(userMsg, assistantMsg);
await ctx.saveLocalMessageToBackend(userMsg, userText);
await ctx.saveLocalMessageToBackend(assistantMsg, userText);
await ctx.saveLocalMessageToBackend(assistantMsg);
if (result.message && !ctx.isShippingNoticeAgent.value) {
ctx.msg.success(result.message);
}
@@ -149,7 +149,7 @@ export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
if (shouldAppendUser) {
await ctx.saveLocalMessageToBackend(userMsg, userText);
}
await ctx.saveLocalMessageToBackend(assistantMsg, userText);
await ctx.saveLocalMessageToBackend(assistantMsg);
void ctx.refreshShippingActions();
return true;
} catch (e: unknown) {
@@ -166,7 +166,7 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
};
ctx.messages.value.push(userMsg, assistantMsg);
await ctx.saveLocalMessageToBackend(userMsg, action.message || '生成发货 Excel');
await ctx.saveLocalMessageToBackend(assistantMsg, action.message || '生成发货 Excel');
await ctx.saveLocalMessageToBackend(assistantMsg);
void ctx.refreshShippingActions();
} catch (e: unknown) {
const errorMessage = e instanceof Error ? e.message : '生成发货 Excel 失败';
@@ -201,7 +201,7 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
};
ctx.messages.value.push(userMsg, assistantMsg);
await ctx.saveLocalMessageToBackend(userMsg, userText);
await ctx.saveLocalMessageToBackend(assistantMsg, userText);
await ctx.saveLocalMessageToBackend(assistantMsg);
void ctx.refreshShippingActions();
} catch (e: unknown) {
const errorMessage = e instanceof Error ? e.message : ctx.t('chat.shippingNoticeRetryUploadFailed');
@@ -246,7 +246,7 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
};
ctx.messages.value.push(userMsg, assistantMsg);
await ctx.saveLocalMessageToBackend(userMsg, userText);
await ctx.saveLocalMessageToBackend(assistantMsg, userText);
await ctx.saveLocalMessageToBackend(assistantMsg);
void ctx.refreshShippingActions();
} catch (e: unknown) {
const errorMessage = e instanceof Error ? e.message : '确认库存源失败';
@@ -304,7 +304,7 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
};
ctx.messages.value.push(userMsg, assistantMsg);
await ctx.saveLocalMessageToBackend(userMsg, action.message || '匹配库存');
await ctx.saveLocalMessageToBackend(assistantMsg, action.message || '匹配库存');
await ctx.saveLocalMessageToBackend(assistantMsg);
void ctx.refreshShippingActions();
} catch (e: unknown) {
const errorMessage = e instanceof Error ? e.message : '匹配库存失败';
@@ -6,8 +6,6 @@
*/
import {
addWorkspaceShippingNoticeLine,
getShippingChatActions,
getWorkspaceShippingTask,
removeWorkspaceShippingNoticeLine,
updateWorkspaceShippingNoticeFields,
updateWorkspaceShippingNoticeLine,
@@ -16,7 +14,6 @@ import {
} from '@/features/chat/api/shipping.api';
import { getShippingParseReviewPayload } from './shippingParseReview';
import type { ChatMessage } from '../types/chat.types';
import type { ShippingParseReviewPayload } from '../types/shipping.types';
import type { Ref } from 'vue';
export interface ShippingParseReviewContext {
@@ -28,27 +25,6 @@ export interface ShippingParseReviewContext {
msg: { warning: (text: string) => void };
}
/** 由任务详情与 checkpoint 构建 parse_review 卡片 payload。 */
function buildParseReviewPayload(
taskId: string,
detail: Awaited<ReturnType<typeof getWorkspaceShippingTask>>,
checkpoint: string,
): ShippingParseReviewPayload {
return {
taskId,
checkpoint,
header: {
customer_name: detail.customer_name ?? null,
customer_code: detail.customer_code ?? null,
ship_to: detail.ship_to ?? null,
po_number: detail.po_number ?? null,
required_date: detail.required_date ?? null,
},
lines: Array.isArray(detail.lines) ? detail.lines : [],
saving: false,
};
}
/**
* 创建发货通知 parse review 卡片处理器。
*
@@ -70,48 +46,12 @@ export function createShippingParseReviewHandlers(ctx: ShippingParseReviewContex
}
};
const upsertParseReviewMessage = async (payload: ShippingParseReviewPayload) => {
const normalized = String(payload.taskId || '').trim().toUpperCase();
const existing = ctx.messages.value.find((msg) => {
const current = getShippingParseReviewPayload(msg);
return current?.taskId?.trim().toUpperCase() === normalized;
});
if (existing) {
existing.content = `请确认或修订以下解析结果。\n任务编号:${normalized}`;
existing.payload = payload;
existing.local_only = true;
return;
}
const reviewMsg: ChatMessage = {
role: 'assistant',
type: 'shipping-parse-review',
content: `请确认或修订以下解析结果。\n任务编号:${normalized}`,
payload,
local_id: ctx.newLocalMessageId('shipping-parse-review'),
local_only: true,
};
ctx.messages.value.push(reviewMsg);
await ctx.saveLocalMessageToBackend(reviewMsg);
};
const syncShippingParseReviewCard = async (taskId?: string): Promise<boolean> => {
const normalized = String(taskId || ctx.resolvedShippingTaskId.value || '').trim().toUpperCase();
if (!normalized) return false;
try {
const [detail, actions] = await Promise.all([
getWorkspaceShippingTask(normalized),
getShippingChatActions(normalized),
]);
const checkpoint = String(actions.checkpoint || '').trim();
if (checkpoint !== 'parse_review') {
removeParseReviewMessageForTask(normalized);
return false;
}
await upsertParseReviewMessage(buildParseReviewPayload(normalized, detail, checkpoint));
return true;
} catch {
return false;
}
// 解析复核表单不再作为聊天历史消息展示;当前步骤操作统一放到轻量工作台/动作按钮中。
removeParseReviewMessageForTask(normalized);
return false;
};
const updateShippingParseReviewHeader = async (
@@ -0,0 +1,30 @@
/**
* useChatShippingRefresh.spec.ts
* 用途:验证发货动作按钮刷新时的任务定位优先级,避免按 conversation 猜任务导致按钮绑错票。
* 依赖:vitest、useChatShippingRefresh 纯函数导出。
* 逻辑:只覆盖任务编号解析优先级,不触碰 Vue 组件或网络请求。
*/
import { describe, expect, it } from 'vitest';
import { resolvePreferredShippingTaskId } from './useChatShippingRefresh';
describe('useChatShippingRefresh', () => {
it('prefers current batch focus task over message and history fallbacks', () => {
expect(resolvePreferredShippingTaskId({
batchTaskId: 'sn-batch-001',
messageTaskId: 'sn-message-001',
resolvedTaskId: 'sn-resolved-001',
queryTaskId: 'sn-query-001',
historyTaskId: 'sn-history-001',
})).toBe('SN-BATCH-001');
});
it('returns empty string when no explicit task anchor is available', () => {
expect(resolvePreferredShippingTaskId({
batchTaskId: '',
messageTaskId: '',
resolvedTaskId: '',
queryTaskId: '',
historyTaskId: '',
})).toBe('');
});
});
@@ -4,14 +4,12 @@
* 依赖:shipping.api、shippingMenu、shippingTaskId、shippingNoticeActions 常量、chat.types。
* 逻辑:由 useChatShipping 调用本文件;本文件根据当前 taskId 拉取动作配置并回写到 messages[].shipping_actions。
*/
import {
getShippingChatActions,
listWorkspaceShippingTasks,
} from '@/features/chat/api/shipping.api';
import { getShippingChatActions } from '@/features/chat/api/shipping.api';
import { SHIPPING_TERMINAL_CHECKPOINTS } from '@/constants/shippingNoticeActions';
import { SHIPPING_TASK_ID_RE } from '../constants/shipping';
import { findLatestShippingTaskId } from './shippingTaskId';
import { resolveShippingActionButtons } from './shippingMenu';
import { stripShippingPlainActionMenu } from './shippingText';
import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
import type { ShippingActionButton } from '../types/shipping.types';
import type { ComputedRef, Ref } from 'vue';
@@ -24,7 +22,32 @@ export interface ShippingRefreshContext {
history: Ref<ChatSessionItem[]>;
resolvedShippingTaskId: Ref<string>;
shippingTaskIdFromQuery: ComputedRef<string>;
shippingConversationTaskIdCache: Ref<Record<string, string>>;
getActiveBatchTaskId: () => string;
}
/**
* 解析当前聊天页最可靠的发货任务编号。
*
* 核心逻辑:优先使用批次当前焦点任务,其次才回退到消息内嵌任务号、已解析状态和路由参数;
* 禁止再按 conversation 扫任务列表“猜”一票,避免多票会话把动作按钮挂错任务。
* @param params - 当前聊天页中可用的任务定位线索
* @returns 可信的任务编号;无法明确定位时返回空字符串
*/
export function resolvePreferredShippingTaskId(params: {
batchTaskId?: string | null;
messageTaskId?: string | null;
resolvedTaskId?: string | null;
queryTaskId?: string | null;
historyTaskId?: string | null;
}) {
return String(
params.batchTaskId
|| params.messageTaskId
|| params.resolvedTaskId
|| params.queryTaskId
|| params.historyTaskId
|| '',
).trim().toUpperCase();
}
/**
@@ -59,28 +82,13 @@ export function createShippingActionsRefresher(ctx: ShippingRefreshContext) {
const match = title.match(SHIPPING_TASK_ID_RE);
return match?.[0] ? match[0].toUpperCase() : '';
})();
let taskId = findLatestShippingTaskId(msgs)
|| ctx.resolvedShippingTaskId.value
|| ctx.shippingTaskIdFromQuery.value
|| historyTaskId;
if (!taskId && cid && !ctx.isThinking.value) {
const cached = ctx.shippingConversationTaskIdCache.value[cid];
if (cached) {
taskId = cached;
} else {
try {
const rows = await listWorkspaceShippingTasks({ limit: 500 });
const hit = rows.find((row) => String(row.conversation_id || '') === cid);
const taskNo = hit?.task_no ? String(hit.task_no).trim().toUpperCase() : '';
if (taskNo) {
ctx.shippingConversationTaskIdCache.value = { ...ctx.shippingConversationTaskIdCache.value, [cid]: taskNo };
taskId = taskNo;
}
} catch {
// fall back to structured directive buttons embedded in the message
}
}
}
const taskId = resolvePreferredShippingTaskId({
batchTaskId: ctx.getActiveBatchTaskId(),
messageTaskId: findLatestShippingTaskId(msgs),
resolvedTaskId: ctx.resolvedShippingTaskId.value,
queryTaskId: ctx.shippingTaskIdFromQuery.value,
historyTaskId,
});
if (taskId) ctx.resolvedShippingTaskId.value = taskId;
let lastOpenAssistantIndex = -1;
for (let i = msgs.length - 1; i >= 0; i -= 1) {
@@ -102,11 +110,9 @@ export function createShippingActionsRefresher(ctx: ShippingRefreshContext) {
if (targetAssistantIndex >= 0) {
const target = msgs[targetAssistantIndex] as ChatMessage & { shipping_actions?: ShippingActionButton[] };
const resolved = resolveShippingActionButtons(String(target.content || ''), null);
if (resolved.cleanedText !== String(target.content || '').trim()) {
target.content = resolved.cleanedText;
}
if (resolved.buttons.length && !target.shipping_actions?.length) {
target.shipping_actions = resolved.buttons;
const cleanedText = stripShippingPlainActionMenu(resolved.cleanedText);
if (cleanedText !== String(target.content || '').trim()) {
target.content = cleanedText;
}
}
@@ -158,16 +164,20 @@ export function createShippingActionsRefresher(ctx: ShippingRefreshContext) {
apiResolved ? (apiButtons ?? []) : null,
{ apiResolved },
);
if (resolved.fromDirective || resolved.cleanedText !== String(chatMsg.content || '').trim()) {
chatMsg.content = resolved.cleanedText;
const cleanedText = stripShippingPlainActionMenu(resolved.cleanedText);
if (resolved.fromDirective || cleanedText !== String(chatMsg.content || '').trim()) {
chatMsg.content = cleanedText;
}
buttons = resolved.buttons;
} else if (!apiResolved) {
const resolved = resolveShippingActionButtons(String(chatMsg.content || ''), null);
if (resolved.fromDirective) {
chatMsg.content = resolved.cleanedText;
const cleanedText = stripShippingPlainActionMenu(resolved.cleanedText);
if (resolved.fromDirective || cleanedText !== String(chatMsg.content || '').trim()) {
chatMsg.content = cleanedText;
}
buttons = resolved.buttons;
} else {
chatMsg.content = stripShippingPlainActionMenu(String(chatMsg.content || ''));
}
if (chatMsg.type === 'shipping-match-result' && chatMsg.payload && typeof chatMsg.payload === 'object') {
(chatMsg.payload as { action_buttons?: ShippingActionButton[] }).action_buttons = buttons;