185 lines
7.2 KiB
TypeScript
185 lines
7.2 KiB
TypeScript
/**
|
||
* features/chat/shipping/useChatShippingRefresh.ts
|
||
* 用途:刷新聊天区发货通知 UI State,同步后端 summary/checkpoint 到消息,供通知展示。
|
||
* 依赖:shipping.api、shippingTaskId、shippingNoticeActions 常量、chat.types。
|
||
* 逻辑:由 useChatShipping 调用本文件;只读取后端 /ui-state 并净化正文中的动作菜单文案,不再把 action_buttons 映射为消息按钮。
|
||
*/
|
||
import { getWorkspaceShippingTaskUiState } from '@/features/chat/api/shipping.api';
|
||
import { SHIPPING_TERMINAL_CHECKPOINTS } from '@/constants/shippingNoticeActions';
|
||
import { findLatestShippingTaskId } from './shippingTaskId';
|
||
import { stripShippingActionListByButtons, stripShippingPlainActionMenu } from './shippingText';
|
||
import type { ChatMessage } from '../types/chat.types';
|
||
import type { ShippingTaskUiState } from '../types/shipping.api.types';
|
||
import type { ComputedRef, Ref } from 'vue';
|
||
|
||
export interface ShippingRefreshContext {
|
||
isShippingNoticeAgent: ComputedRef<boolean>;
|
||
messages: Ref<ChatMessage[]>;
|
||
conversationId: Ref<string | null>;
|
||
isThinking: Ref<boolean>;
|
||
resolvedShippingTaskId: Ref<string>;
|
||
shippingTaskIdFromQuery: ComputedRef<string>;
|
||
getActiveShippingTaskId: () => string;
|
||
}
|
||
|
||
/**
|
||
* 解析当前聊天页最可靠的发货任务编号。
|
||
*
|
||
* 核心逻辑:优先使用消息内嵌任务号,再回退到已解析状态和路由参数;
|
||
* 禁止再按 conversation 标题“猜”一票,避免多票会话把状态挂错任务。
|
||
* @param params - 当前聊天页中可用的任务定位线索
|
||
* @returns 可信的任务编号;无法明确定位时返回空字符串
|
||
*/
|
||
export function resolvePreferredShippingTaskId(params: {
|
||
activeTaskId?: string | null;
|
||
batchTaskId?: string | null;
|
||
messageTaskId?: string | null;
|
||
resolvedTaskId?: string | null;
|
||
queryTaskId?: string | null;
|
||
}) {
|
||
return String(
|
||
params.activeTaskId
|
||
|| params.batchTaskId
|
||
|| params.messageTaskId
|
||
|| params.resolvedTaskId
|
||
|| params.queryTaskId
|
||
|| '',
|
||
).trim().toUpperCase();
|
||
}
|
||
|
||
/**
|
||
* 判断某条助手消息后面是否已经出现新的用户回复。
|
||
* @param msgs - 当前消息列表
|
||
* @param index - 目标助手消息索引
|
||
* @returns `true` 表示该消息已被后续用户输入“盖住”
|
||
*/
|
||
export function assistantMessageHasLaterUserReply(msgs: Array<{ role?: string }>, index: number): boolean {
|
||
return msgs.slice(index + 1).some((item) => item.role === 'user');
|
||
}
|
||
|
||
/**
|
||
* 创建发货通知 UI State 刷新器。
|
||
*
|
||
* 核心逻辑:按 taskId 拉取后端 ui_state,写回 `shipping_ui_state` 供摘要/通知展示,
|
||
* 并清空消息上的 `shipping_actions`(Chat 不再渲染履约写按钮)。
|
||
* @param ctx - 发货通知聊天上下文
|
||
* @returns 状态刷新函数
|
||
*/
|
||
export function createShippingActionsRefresher(ctx: ShippingRefreshContext) {
|
||
let shippingActionsRequestSeq = 0;
|
||
|
||
const refreshShippingActions = async () => {
|
||
if (!ctx.isShippingNoticeAgent.value) return;
|
||
const msgs = ctx.messages.value;
|
||
if (!msgs.length) return;
|
||
const taskId = resolvePreferredShippingTaskId({
|
||
activeTaskId: ctx.getActiveShippingTaskId(),
|
||
messageTaskId: findLatestShippingTaskId(msgs),
|
||
resolvedTaskId: ctx.resolvedShippingTaskId.value,
|
||
queryTaskId: ctx.shippingTaskIdFromQuery.value,
|
||
});
|
||
if (taskId) ctx.resolvedShippingTaskId.value = taskId;
|
||
let lastOpenAssistantIndex = -1;
|
||
for (let i = msgs.length - 1; i >= 0; i -= 1) {
|
||
const item = msgs[i];
|
||
if (item?.role !== 'assistant') continue;
|
||
if (assistantMessageHasLaterUserReply(msgs, i)) continue;
|
||
lastOpenAssistantIndex = i;
|
||
break;
|
||
}
|
||
let lastAssistantIndex = -1;
|
||
for (let i = msgs.length - 1; i >= 0; i -= 1) {
|
||
const item = msgs[i];
|
||
if (item?.role === 'assistant') {
|
||
lastAssistantIndex = i;
|
||
break;
|
||
}
|
||
}
|
||
const targetAssistantIndex = lastOpenAssistantIndex >= 0 ? lastOpenAssistantIndex : lastAssistantIndex;
|
||
if (targetAssistantIndex >= 0) {
|
||
const target = msgs[targetAssistantIndex] as ChatMessage;
|
||
const cleanedText = stripShippingPlainActionMenu(String(target.content || ''));
|
||
if (cleanedText !== String(target.content || '').trim()) {
|
||
target.content = cleanedText;
|
||
}
|
||
}
|
||
|
||
let apiState: ShippingTaskUiState | null = null;
|
||
let apiResolved = false;
|
||
if (taskId) {
|
||
const seq = ++shippingActionsRequestSeq;
|
||
try {
|
||
const data = await getWorkspaceShippingTaskUiState(taskId);
|
||
if (seq === shippingActionsRequestSeq) {
|
||
apiResolved = true;
|
||
apiState = data;
|
||
}
|
||
} catch {
|
||
// keep existing SSE-delivered ui_state if present
|
||
}
|
||
}
|
||
const apiCheckpoint = String(
|
||
apiState?.checkpoint?.code
|
||
|| apiState?.checkpoint_code
|
||
|| '',
|
||
).trim() || null;
|
||
if (apiResolved && apiCheckpoint && SHIPPING_TERMINAL_CHECKPOINTS.has(apiCheckpoint)) {
|
||
msgs.forEach((rawMsg) => {
|
||
const m = rawMsg as ChatMessage;
|
||
if (m.role === 'assistant') {
|
||
m.shipping_actions = undefined;
|
||
m.shipping_ui_state = apiState || undefined;
|
||
}
|
||
});
|
||
return;
|
||
}
|
||
msgs.forEach((rawMsg, index) => {
|
||
const chatMsg = rawMsg as ChatMessage;
|
||
if (chatMsg.role !== 'assistant') {
|
||
return;
|
||
}
|
||
// Chat 只保留通知态:始终清空履约按钮,仅同步最新 ui_state summary。
|
||
chatMsg.shipping_actions = undefined;
|
||
if (chatMsg.type && !['text', undefined, 'shipping-match-result'].includes(chatMsg.type)) {
|
||
return;
|
||
}
|
||
let cleanedText = stripShippingPlainActionMenu(String(chatMsg.content || ''));
|
||
if (index === targetAssistantIndex && apiState) {
|
||
chatMsg.shipping_ui_state = apiState;
|
||
const projectedActions = [apiState.actions?.primary, ...(apiState.actions?.secondary || [])]
|
||
.filter(Boolean)
|
||
.map((action) => ({
|
||
id: String(action?.code || ''),
|
||
label: String(action?.label || ''),
|
||
message: String(action?.disabled_reason || ''),
|
||
variant: action?.kind === 'terminate' ? 'danger' : 'primary',
|
||
}));
|
||
if (projectedActions.length) {
|
||
cleanedText = stripShippingActionListByButtons(cleanedText, projectedActions);
|
||
}
|
||
} else if (!apiResolved && chatMsg.shipping_ui_state?.actions) {
|
||
const projectedActions = [chatMsg.shipping_ui_state.actions.primary, ...(chatMsg.shipping_ui_state.actions.secondary || [])]
|
||
.filter(Boolean)
|
||
.map((action) => ({
|
||
id: String(action?.code || ''),
|
||
label: String(action?.label || ''),
|
||
message: String(action?.disabled_reason || ''),
|
||
variant: action?.kind === 'terminate' ? 'danger' : 'primary',
|
||
}));
|
||
cleanedText = stripShippingActionListByButtons(
|
||
cleanedText,
|
||
projectedActions,
|
||
);
|
||
}
|
||
if (cleanedText !== String(chatMsg.content || '').trim()) {
|
||
chatMsg.content = cleanedText;
|
||
}
|
||
if (chatMsg.type === 'shipping-match-result' && chatMsg.payload && typeof chatMsg.payload === 'object') {
|
||
delete (chatMsg.payload as { action_buttons?: unknown[] }).action_buttons;
|
||
}
|
||
});
|
||
};
|
||
|
||
return { refreshShippingActions };
|
||
}
|