837 lines
32 KiB
TypeScript
837 lines
32 KiB
TypeScript
/**
|
||
* features/chat/composables/useChat.ts
|
||
* 用途:维护聊天消息、并行 run 与 legacy SSE 流式收发,并投影货代领域状态。
|
||
* 依赖:Vue、vue-i18n、useChatTurn、streamErrorMessage、chat/shipping 类型。
|
||
* 逻辑:页面调用 useChat 发起消息;Dify/HXOPS SSE 被归并到当前助手消息,领域终态可继续在上游终止事件后写入。
|
||
*/
|
||
import { ref } from 'vue';
|
||
import { useI18n } from 'vue-i18n';
|
||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||
import { applyStreamErrorToMessage, type StreamErrorLabels } from '../utils/streamErrorMessage';
|
||
import type {
|
||
ChatMessage,
|
||
ChatMessageAttachment,
|
||
ChatRun,
|
||
RetrieverResource,
|
||
ShippingOrderExtractionState,
|
||
ShippingOrderExtractionStatus,
|
||
} from '../types/chat.types';
|
||
import type { ShippingBatchUiState, ShippingTaskUiState } from '../types/shipping.api.types';
|
||
import type { ChatMessageSendResult } from '../types/chat-turn.types';
|
||
import { createStartChatTurn } from './useChatTurn';
|
||
|
||
export interface SendMessageLifecycleHooks {
|
||
/** 当前轮用户消息的已发送附件快照;仅用于界面展示与后续持久化。 */
|
||
userAttachments?: ChatMessageAttachment[];
|
||
onAssistantMessageFinished?: (message: ChatMessage, runMessages: ChatMessage[]) => void | Promise<void>;
|
||
}
|
||
|
||
/**
|
||
* 创建当前轮乐观用户消息,并复制附件快照避免调用方后续修改污染消息历史。
|
||
* @param content - 用户可见问题文本
|
||
* @param attachments - 已上传并固化的附件快照
|
||
* @returns 可直接推入消息列表的用户消息
|
||
*/
|
||
export function createUserChatMessage(
|
||
content: string,
|
||
attachments?: ChatMessageAttachment[],
|
||
): ChatMessage {
|
||
return {
|
||
role: 'user',
|
||
content,
|
||
...(attachments?.length
|
||
? { attachments: attachments.map((attachment) => ({ ...attachment })) }
|
||
: {}),
|
||
};
|
||
}
|
||
|
||
const normalizeResources = (resources: unknown) => {
|
||
if (!resources) return [];
|
||
if (Array.isArray(resources)) return resources;
|
||
if (typeof resources === 'object' && resources !== null && Array.isArray((resources as { data?: unknown }).data)) {
|
||
return (resources as { data: unknown[] }).data;
|
||
}
|
||
return [];
|
||
};
|
||
|
||
const addRetrieverResources = (msg: ChatMessage, resources: unknown) => {
|
||
const list = normalizeResources(resources);
|
||
if (list.length === 0) return;
|
||
if (!msg.retriever_resources) msg.retriever_resources = [];
|
||
for (const item of list) {
|
||
const r = item as Record<string, unknown>;
|
||
const key = `${r.document_name || ''}|${r.segment_id || ''}|${r.content || ''}`;
|
||
const existingIndex = msg.retriever_resources.findIndex(
|
||
(x) => `${x.document_name || ''}|${x.segment_id || ''}|${x.content || ''}` === key,
|
||
);
|
||
if (existingIndex < 0) {
|
||
msg.retriever_resources.push(item as RetrieverResource);
|
||
} else {
|
||
msg.retriever_resources[existingIndex] = {
|
||
...msg.retriever_resources[existingIndex],
|
||
...(item as object),
|
||
};
|
||
}
|
||
}
|
||
};
|
||
|
||
const addAttributionParts = (msg: ChatMessage, value: unknown) => {
|
||
if (!value) return;
|
||
if (!msg.attribution_parts) msg.attribution_parts = [];
|
||
|
||
const pushUnique = (text: string) => {
|
||
const v = text.trim();
|
||
if (!v) return;
|
||
if (!msg.attribution_parts!.includes(v)) {
|
||
msg.attribution_parts!.push(v);
|
||
}
|
||
};
|
||
|
||
if (typeof value === 'string') {
|
||
pushUnique(value);
|
||
return;
|
||
}
|
||
|
||
if (Array.isArray(value)) {
|
||
for (const item of value) {
|
||
if (typeof item === 'string') {
|
||
pushUnique(item);
|
||
} else if (item && typeof item === 'object') {
|
||
const o = item as Record<string, unknown>;
|
||
pushUnique(String(o.content || o.text || o.title || JSON.stringify(item)));
|
||
}
|
||
}
|
||
return;
|
||
}
|
||
|
||
if (typeof value === 'object' && value !== null) {
|
||
const o = value as Record<string, unknown>;
|
||
pushUnique(String(o.content || o.text || o.title || JSON.stringify(value)));
|
||
}
|
||
};
|
||
|
||
/**
|
||
* 解析发货通知 SSE 事件中的统一 UI State 载荷。
|
||
*
|
||
* 核心逻辑:优先读取单票 `ui_state`,批次事件则下钻 `batch_ui_state.focus_task_ui_state`;
|
||
* 同时保留批次态原文,供右侧工作台和后续兼容逻辑继续消费。
|
||
* @param data - SSE 事件 JSON
|
||
* @returns 提炼后的单票 UI State 与原始批次 UI State
|
||
*/
|
||
export const resolveShippingUiStatePayload = (data: Record<string, unknown>): {
|
||
uiState?: ShippingTaskUiState;
|
||
batchUiState?: ShippingBatchUiState;
|
||
} => {
|
||
const rawUiState = data.ui_state;
|
||
const uiState = rawUiState && typeof rawUiState === 'object'
|
||
? rawUiState as ShippingTaskUiState
|
||
: undefined;
|
||
const rawBatchUiState = data.batch_ui_state;
|
||
const batchUiState = rawBatchUiState && typeof rawBatchUiState === 'object'
|
||
? rawBatchUiState as ShippingBatchUiState
|
||
: undefined;
|
||
const focusTaskUiState = batchUiState?.focus_task_ui_state && typeof batchUiState.focus_task_ui_state === 'object'
|
||
? batchUiState.focus_task_ui_state
|
||
: undefined;
|
||
return {
|
||
uiState: uiState || focusTaskUiState,
|
||
batchUiState,
|
||
};
|
||
};
|
||
|
||
/**
|
||
* 将发货通知状态机事件同步到当前助手消息。
|
||
*
|
||
* 说明:shipping_ui_state 是 HXOPS 自有 SSE 事件,不依赖 Dify 正文;收到后立即挂按钮,
|
||
* 让用户无需等待 `message_end` 才拿到状态机结果。若该消息按钮已被消费,则只更新状态快照,
|
||
* 不重新挂出可点击按钮,避免首帧旧状态覆盖。
|
||
*/
|
||
export const applyShippingUiStateToMessage = (msg: ChatMessage, data: Record<string, unknown>) => {
|
||
const { uiState, batchUiState } = resolveShippingUiStatePayload(data);
|
||
if (!uiState) return;
|
||
const nextActions = Array.isArray(uiState.action_buttons) && uiState.action_buttons.length
|
||
? uiState.action_buttons
|
||
: undefined;
|
||
|
||
msg.shipping_ui_state = uiState;
|
||
if (!msg.shipping_actions_used) {
|
||
msg.shipping_actions = nextActions;
|
||
}
|
||
if (msg.type === 'shipping-match-result' && msg.payload && typeof msg.payload === 'object' && !msg.shipping_actions_used) {
|
||
(msg.payload as { action_buttons?: ChatMessage['shipping_actions'] }).action_buttons = nextActions;
|
||
}
|
||
msg.payload = {
|
||
...(msg.payload && typeof msg.payload === 'object' ? msg.payload as Record<string, unknown> : {}),
|
||
shipping_ui_state: uiState,
|
||
...(batchUiState ? { shipping_batch_ui_state: batchUiState } : {}),
|
||
};
|
||
};
|
||
|
||
const SHIPPING_ORDER_EXTRACTION_STATUSES = new Set<ShippingOrderExtractionStatus>([
|
||
'extracting',
|
||
'completed',
|
||
'partially_completed',
|
||
'failed',
|
||
]);
|
||
|
||
/**
|
||
* 将未知 SSE payload 规范为订单识别状态。
|
||
* 核心逻辑:只接受固定状态枚举;计数字段统一约束为非负整数,避免异常上游值破坏卡片布局。
|
||
* @param data - shipping_order_extraction_state 事件对象。
|
||
* @returns 合法状态;协议不匹配时返回 undefined。
|
||
*/
|
||
const resolveShippingOrderExtractionState = (
|
||
data: Record<string, unknown>,
|
||
): ShippingOrderExtractionState | undefined => {
|
||
const status = String(data.status || '') as ShippingOrderExtractionStatus;
|
||
if (!SHIPPING_ORDER_EXTRACTION_STATUSES.has(status)) return undefined;
|
||
const phase = String(data.phase || '');
|
||
if (!['llm_extraction', 'result_persisted', 'failed'].includes(phase)) return undefined;
|
||
const count = (value: unknown) => {
|
||
const parsed = Number(value);
|
||
return Number.isFinite(parsed) ? Math.max(Math.trunc(parsed), 0) : 0;
|
||
};
|
||
return {
|
||
status,
|
||
phase: phase as ShippingOrderExtractionState['phase'],
|
||
message: String(data.message || '').trim(),
|
||
created_count: count(data.created_count),
|
||
opened_existing_count: count(data.opened_existing_count),
|
||
pending_count: count(data.pending_count),
|
||
non_shipping_count: count(data.non_shipping_count),
|
||
created_with_missing_fields_count: count(data.created_with_missing_fields_count),
|
||
batch_no: typeof data.batch_no === 'string' && data.batch_no.trim() ? data.batch_no.trim() : null,
|
||
terminal: data.terminal === true || status !== 'extracting',
|
||
};
|
||
};
|
||
|
||
/**
|
||
* 将订单识别领域事件同步到当前助手消息及可持久化 payload。
|
||
* 核心逻辑:终态不得被迟到的 extracting 覆盖;正文由 Dify 独立维护,本函数只更新结构化状态。
|
||
* @param msg - 当前助手消息。
|
||
* @param data - shipping_order_extraction_state SSE 事件。
|
||
*/
|
||
export const applyShippingOrderExtractionStateToMessage = (
|
||
msg: ChatMessage,
|
||
data: Record<string, unknown>,
|
||
): void => {
|
||
const state = resolveShippingOrderExtractionState(data);
|
||
if (!state) return;
|
||
if (msg.shipping_order_extraction_state?.terminal && !state.terminal) return;
|
||
msg.shipping_order_extraction_state = state;
|
||
msg.payload = {
|
||
...(msg.payload && typeof msg.payload === 'object' ? msg.payload as Record<string, unknown> : {}),
|
||
shipping_order_extraction_state: state,
|
||
};
|
||
};
|
||
|
||
/**
|
||
* 判断上游终态之后仍允许写入当前消息的领域事件。
|
||
* 核心逻辑:普通 Dify 文本在 terminal 后丢弃,但 HXOPS 的抽取终态和任务 UI State 由 Handler 在 terminal 后生成。
|
||
* @param eventName - SSE event 字段。
|
||
* @returns 是否允许继续消费。
|
||
*/
|
||
export const isAllowedAfterStreamTerminal = (eventName: string): boolean => (
|
||
eventName === 'shipping_ui_state' || eventName === 'shipping_order_extraction_state'
|
||
);
|
||
|
||
/**
|
||
* 把 SSE 事件附带的元数据同步到当前消息对象。
|
||
*
|
||
* 说明:
|
||
* - Text2SQL 在 `message_end` 才会返回 `payload/chat_log_id`,若这里不合并,
|
||
* 当前页不会立刻出现“查看全部预览”按钮,只能刷新后从历史消息里重新读到。
|
||
*/
|
||
const applyEventMetadata = (msg: ChatMessage, data: Record<string, unknown>) => {
|
||
const metadata = (data?.metadata || {}) as Record<string, unknown>;
|
||
if (Number.isInteger(data.chat_log_id)) {
|
||
msg.chat_log_id = Number(data.chat_log_id);
|
||
}
|
||
const runId = Number(data.run_id);
|
||
if (Number.isFinite(runId) && runId > 0) {
|
||
msg.run_id = runId;
|
||
}
|
||
if (typeof data.type === 'string' && data.type.trim()) {
|
||
msg.type = data.type as ChatMessage['type'];
|
||
}
|
||
if (data.payload && typeof data.payload === 'object') {
|
||
msg.payload = {
|
||
...(msg.payload && typeof msg.payload === 'object' ? msg.payload as Record<string, unknown> : {}),
|
||
...(data.payload as Record<string, unknown>),
|
||
};
|
||
}
|
||
addRetrieverResources(msg, data?.retriever_resources);
|
||
addRetrieverResources(msg, metadata?.retriever_resources);
|
||
addRetrieverResources(msg, metadata?.retrieverResources);
|
||
|
||
addAttributionParts(msg, data?.annotations);
|
||
addAttributionParts(msg, data?.annotation_reply);
|
||
addAttributionParts(msg, metadata?.annotations);
|
||
addAttributionParts(msg, metadata?.annotation_reply);
|
||
addAttributionParts(msg, data?.citation);
|
||
addAttributionParts(msg, metadata?.citation);
|
||
|
||
const messagePayload = data?.message_payload;
|
||
if (messagePayload && typeof messagePayload === 'object') {
|
||
msg.payload = messagePayload;
|
||
}
|
||
};
|
||
|
||
export function useChat() {
|
||
const { t } = useI18n();
|
||
const messages = ref<ChatMessage[]>([]);
|
||
const isThinking = ref(false);
|
||
const viewId = ref(0);
|
||
const runs = ref<ChatRun[]>([]);
|
||
const activeRunId = ref<number | null>(null);
|
||
let runSeq = 0;
|
||
const conversationId = ref<string | null>(null);
|
||
const activeStreamController = ref<AbortController | null>(null);
|
||
let likelyCompletedStreamTimer: ReturnType<typeof setTimeout> | null = null;
|
||
|
||
/**
|
||
* 取消当前仍在进行的流式请求。
|
||
*
|
||
* 说明:
|
||
* - 固资管理这类长文本/文件回答有时会在答案已经完整展示后,SSE 连接迟迟不结束;
|
||
* - 若不主动取消,`isThinking` 可能持续为 true,导致输入栏、重新提问和切换 Agent 都像“卡死”。
|
||
*/
|
||
const cancelActiveStream = () => {
|
||
if (!activeStreamController.value) return;
|
||
activeStreamController.value.abort();
|
||
activeStreamController.value = null;
|
||
};
|
||
|
||
/**
|
||
* 将当前流式请求从可见视图脱离,但不主动中止网络连接。
|
||
*
|
||
* 说明:
|
||
* - 用户切换历史会话时,旧会话回答往往已经接近完成,只是上游 SSE 还没来得及收尾;
|
||
* - 若这里直接 abort,浏览器会把 `/api/chat/completions` 记成 `ERR_ABORTED`;
|
||
* - 改为“脱离当前视图”后,旧流可以在后台自然结束,当前页面也能立即切到目标历史会话。
|
||
*/
|
||
const detachActiveStreamFromView = () => {
|
||
activeStreamController.value = null;
|
||
};
|
||
|
||
/**
|
||
* 清理“疑似已完成回答”的静默定时器。
|
||
* 说明:固资管理的完整报告有时已经展示出来,但上游流连接没有及时结束,
|
||
* 这里需要在收到新帧或完成收尾时把旧定时器清掉,避免重复收尾。
|
||
*/
|
||
const clearLikelyCompletedStreamTimer = () => {
|
||
if (!likelyCompletedStreamTimer) return;
|
||
clearTimeout(likelyCompletedStreamTimer);
|
||
likelyCompletedStreamTimer = null;
|
||
};
|
||
|
||
/**
|
||
* 判断当前助手内容是否已经像一份完整报告。
|
||
*
|
||
* 说明:
|
||
* - 固资管理 / ERP 问数最终答案通常会携带 `<details>`、结果表格或导出文件块;
|
||
* - 若这些终态标记已经出现,而连接仍未结束,说明前端可以在短暂静默后主动解锁输入区。
|
||
*/
|
||
const looksLikeCompletedAssistantReply = (content: string) => {
|
||
if (!content) return false;
|
||
return (
|
||
content.includes('<details>')
|
||
|| content.includes('**查询结果如下:**')
|
||
|| content.includes('**错误详情**')
|
||
|| content.includes('[FILE_START]')
|
||
|| content.includes('【💡 数据概述】')
|
||
|| content.includes('【📊 数据预览】')
|
||
|| content.includes('【📈 数据分析汇总报告】')
|
||
|| content.includes('系统为您从数据库中检索到共计')
|
||
);
|
||
};
|
||
|
||
/**
|
||
* 判断当前消息列表里是否已经出现“用户可感知为完成态”的上一轮回答。
|
||
*
|
||
* 说明:
|
||
* - 固资管理的第一轮大结果常常已经把完整表格和分析展示出来,但 SSE 终态还会晚 1~2 秒;
|
||
* - 若这时用户继续提问,不应再把发送动作死锁在 `isThinking=true` 上。
|
||
*/
|
||
const hasVisibleCompletedAssistantReply = (items: ChatMessage[]) => {
|
||
for (let i = items.length - 1; i >= 0; i -= 1) {
|
||
const message = items[i];
|
||
if (message?.role !== 'assistant') continue;
|
||
return looksLikeCompletedAssistantReply(String(message.content || ''));
|
||
}
|
||
return false;
|
||
};
|
||
|
||
/**
|
||
* 对“已看到完整报告但流未结束”的情况做兜底收尾。
|
||
*
|
||
* 核心逻辑:
|
||
* - 仅当当前回答内容已具备终态标记时才启动;
|
||
* - 若短时间内没有任何新帧到来,则主动将 run 标记为 done 并中止挂起连接;
|
||
* - 这样可以修复固资管理首轮问答后输入框一直被锁住的问题。
|
||
*/
|
||
const armLikelyCompletedStreamTimer = (
|
||
controller: AbortController,
|
||
run: ChatRun,
|
||
runMessages: ChatMessage[],
|
||
currentAssistantContent: string,
|
||
onUnlock: () => void,
|
||
) => {
|
||
clearLikelyCompletedStreamTimer();
|
||
if (!looksLikeCompletedAssistantReply(currentAssistantContent)) return;
|
||
likelyCompletedStreamTimer = setTimeout(() => {
|
||
likelyCompletedStreamTimer = null;
|
||
if (activeStreamController.value !== controller) return;
|
||
if (run.status !== 'running') return;
|
||
run.status = 'done';
|
||
if (messages.value === runMessages) {
|
||
isThinking.value = false;
|
||
}
|
||
onUnlock();
|
||
}, 600);
|
||
};
|
||
|
||
const activateRun = (runId: number) => {
|
||
const run = runs.value.find((r) => r.runId === runId);
|
||
if (!run) return;
|
||
messages.value = run.messages;
|
||
conversationId.value = run.conversationId;
|
||
isThinking.value = run.status === 'running';
|
||
activeRunId.value = runId;
|
||
};
|
||
|
||
/**
|
||
* 打开空白新会话视图:仅脱离当前流与视图绑定,不 abort 后台 SSE。
|
||
*
|
||
* 核心逻辑:与 loadConversationState 一致;旧 run 继续在 runs 中更新,并在侧栏显示为「生成中」。
|
||
*/
|
||
const createNewChatView = () => {
|
||
clearLikelyCompletedStreamTimer();
|
||
detachActiveStreamFromView();
|
||
viewId.value += 1;
|
||
messages.value = [];
|
||
conversationId.value = null;
|
||
isThinking.value = false;
|
||
activeRunId.value = null;
|
||
};
|
||
|
||
/**
|
||
* 用户显式点击「停止生成」时中止当前可见 run 的流式请求。
|
||
*
|
||
* 核心逻辑:优先 abort 活动视图绑定的 controller;若已 detach,则回退到 run 上保存的 controller。
|
||
*/
|
||
const stopActiveGeneration = () => {
|
||
clearLikelyCompletedStreamTimer();
|
||
const run = activeRunId.value != null
|
||
? runs.value.find((r) => r.runId === activeRunId.value)
|
||
: undefined;
|
||
const controller = activeStreamController.value ?? run?.abortController ?? null;
|
||
if (!controller) return;
|
||
controller.abort();
|
||
activeStreamController.value = null;
|
||
if (run && messages.value === run.messages) {
|
||
isThinking.value = false;
|
||
}
|
||
};
|
||
|
||
const loadConversationState = (id: string, nextMessages: ChatMessage[]) => {
|
||
clearLikelyCompletedStreamTimer();
|
||
detachActiveStreamFromView();
|
||
viewId.value += 1;
|
||
activeRunId.value = null;
|
||
isThinking.value = false;
|
||
messages.value = nextMessages;
|
||
conversationId.value = id;
|
||
};
|
||
|
||
const normalizeStreamText = (text: string) => {
|
||
if (!text) return '';
|
||
return text.replace(/\\n/g, '\n');
|
||
};
|
||
|
||
const formatStreamError = (message: unknown) => {
|
||
if (typeof message === 'string') return message;
|
||
if (message && typeof message === 'object') {
|
||
const record = message as Record<string, unknown>;
|
||
const nested = record.error;
|
||
if (typeof nested === 'string') return nested;
|
||
if (nested && typeof nested === 'object') {
|
||
const nestedRecord = nested as Record<string, unknown>;
|
||
if (typeof nestedRecord.message === 'string') return nestedRecord.message;
|
||
}
|
||
if (typeof record.message === 'string') return record.message;
|
||
if (typeof record.code === 'string') return record.code;
|
||
try {
|
||
return JSON.stringify(message);
|
||
} catch {
|
||
return 'Unknown error';
|
||
}
|
||
}
|
||
return String(message ?? 'Unknown error');
|
||
};
|
||
|
||
/**
|
||
* 从 workflow_finished 失败事件中提取用户可读错误。
|
||
*
|
||
* 说明:
|
||
* - Dify Chatflow 失败时常以 `workflow_finished + data.status=failed` 返回,HTTP 仍是 200;
|
||
* - 若这里只按“终态成功”处理,页面会出现“没有任何响应”;
|
||
* - 因此需要优先从 top-level / nested data / error 对象里抽取失败文案。
|
||
*/
|
||
const extractWorkflowFailureMessage = (data: Record<string, unknown>) => {
|
||
if (String(data.event || '') !== 'workflow_finished') return '';
|
||
const workflowData = data.data && typeof data.data === 'object'
|
||
? data.data as Record<string, unknown>
|
||
: {};
|
||
const isFailed = String(workflowData.status || '').toLowerCase() === 'failed';
|
||
if (!isFailed) return '';
|
||
const candidates = [
|
||
data.message,
|
||
data.description,
|
||
data.error,
|
||
workflowData.message,
|
||
workflowData.description,
|
||
workflowData.error,
|
||
workflowData.errmsg,
|
||
];
|
||
for (const candidate of candidates) {
|
||
const normalized = formatStreamError(candidate).trim();
|
||
if (!normalized || normalized === 'Unknown error') continue;
|
||
if (/maximum context length|input_tokens/i.test(normalized)) {
|
||
return '当前会话上下文过长,模型无法继续回答。请新建对话后重新查询该资产编号。';
|
||
}
|
||
return normalized;
|
||
}
|
||
return '工作流执行失败,请稍后重试';
|
||
};
|
||
|
||
const streamErrorLabels = (): StreamErrorLabels => ({
|
||
networkDisconnectedEmpty: t('chat.streamError.networkDisconnectedEmpty'),
|
||
partialInterrupted: t('chat.streamError.partialInterrupted'),
|
||
upstreamDisconnected: t('chat.streamError.upstreamDisconnected'),
|
||
generic: t('chat.streamError.generic'),
|
||
});
|
||
|
||
const { startChatTurn } = createStartChatTurn({
|
||
messages,
|
||
isThinking,
|
||
conversationId,
|
||
viewId,
|
||
runs,
|
||
activeRunId,
|
||
activeStreamController,
|
||
streamErrorLabels,
|
||
formatStreamError,
|
||
});
|
||
|
||
const sendMessage = async (
|
||
query: string,
|
||
agentId: number,
|
||
kbType = '企业知识库',
|
||
files?: Array<
|
||
| { type: 'image' | 'document' | 'audio' | 'video' | 'custom'; transfer_method: 'local_file'; upload_file_id: string }
|
||
| { type: 'image' | 'document' | 'audio' | 'video' | 'custom'; transfer_method: 'remote_url'; url: string }
|
||
>,
|
||
context?: { task_id?: string; batch_no?: string; shipping_intake_nos?: string[]; display_query?: string },
|
||
hooks?: SendMessageLifecycleHooks,
|
||
): Promise<ChatMessageSendResult> => {
|
||
const displayQuery = String(
|
||
context && Object.prototype.hasOwnProperty.call(context, 'display_query')
|
||
? context.display_query ?? ''
|
||
: query || '',
|
||
).trim();
|
||
clearLikelyCompletedStreamTimer();
|
||
const shouldDetachPreviousStream = Boolean(activeStreamController.value) && hasVisibleCompletedAssistantReply(messages.value);
|
||
if (shouldDetachPreviousStream) {
|
||
detachActiveStreamFromView();
|
||
} else {
|
||
cancelActiveStream();
|
||
}
|
||
const controller = new AbortController();
|
||
activeStreamController.value = controller;
|
||
const runViewId = viewId.value;
|
||
const runMessages = messages.value;
|
||
const run: ChatRun = {
|
||
runId: ++runSeq,
|
||
agentId,
|
||
viewId: runViewId,
|
||
query: displayQuery,
|
||
messages: runMessages,
|
||
conversationId: conversationId.value,
|
||
status: 'running',
|
||
createdAt: new Date().toISOString(),
|
||
abortController: controller,
|
||
};
|
||
runs.value.unshift(run);
|
||
if (runs.value.length > 30) runs.value = runs.value.slice(0, 30);
|
||
activeRunId.value = run.runId;
|
||
|
||
const userMessageIndex = runMessages.push(createUserChatMessage(displayQuery, hooks?.userAttachments)) - 1;
|
||
let botMsgIndex: number | null = null;
|
||
let hasAssistantContent = false;
|
||
let hasTerminalEvent = false;
|
||
let requestAccepted = false;
|
||
let chatLogId: number | undefined;
|
||
let ignoreFurtherStreamEvents = false;
|
||
const ensureBotMessage = () => {
|
||
if (botMsgIndex === null) {
|
||
botMsgIndex = runMessages.push({
|
||
role: 'assistant',
|
||
content: '',
|
||
retriever_resources: [],
|
||
attribution_parts: [],
|
||
}) - 1;
|
||
}
|
||
return runMessages[botMsgIndex] || null;
|
||
};
|
||
|
||
isThinking.value = true;
|
||
|
||
try {
|
||
const response = await fetch('/api/chat/completions', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||
signal: controller.signal,
|
||
body: JSON.stringify({
|
||
query,
|
||
agent_id: agentId,
|
||
conversation_id: conversationId.value,
|
||
kb_type: kbType,
|
||
files: files && files.length > 0 ? files : undefined,
|
||
task_id: context?.task_id || undefined,
|
||
batch_no: context?.batch_no || undefined,
|
||
shipping_intake_nos: context?.shipping_intake_nos?.length ? context.shipping_intake_nos : undefined,
|
||
display_query: context && Object.prototype.hasOwnProperty.call(context, 'display_query')
|
||
? context.display_query
|
||
: undefined,
|
||
user_attachments: hooks?.userAttachments?.length ? hooks.userAttachments : undefined,
|
||
}),
|
||
});
|
||
|
||
if (!response.ok) {
|
||
const err = await response.json().catch(() => ({}));
|
||
throw new Error((err as { error?: string }).error || `Request failed with status ${response.status}`);
|
||
}
|
||
requestAccepted = true;
|
||
|
||
const reader = response.body?.getReader();
|
||
const decoder = new TextDecoder();
|
||
if (!reader) throw new Error('No reader');
|
||
|
||
let buffer = '';
|
||
while (true) {
|
||
const { done, value } = await reader.read();
|
||
if (done) break;
|
||
clearLikelyCompletedStreamTimer();
|
||
|
||
buffer += decoder.decode(value, { stream: true });
|
||
buffer = buffer.replace(/\r\n/g, '\n');
|
||
const frames = buffer.split('\n\n');
|
||
buffer = frames.pop() || '';
|
||
|
||
for (const frame of frames) {
|
||
const dataLines = frame
|
||
.split('\n')
|
||
.map((l) => l.trim())
|
||
.filter((l) => l.startsWith('data:'));
|
||
if (dataLines.length === 0) continue;
|
||
|
||
const payload = dataLines.map((l) => l.replace(/^data:\s?/, '')).join('\n');
|
||
if (!payload) continue;
|
||
|
||
try {
|
||
const eventMatch = payload.match(/"event"\s*:\s*"([^"]+)"/);
|
||
const fastEventName = eventMatch?.[1] || '';
|
||
if (
|
||
fastEventName === 'workflow_started'
|
||
|| fastEventName === 'node_started'
|
||
|| fastEventName === 'node_finished'
|
||
|| fastEventName === 'chat_perf'
|
||
) {
|
||
continue;
|
||
}
|
||
const data = JSON.parse(payload) as Record<string, unknown>;
|
||
|
||
if (data?.conversation_id) {
|
||
const cid = String(data.conversation_id);
|
||
if (!run.conversationId) run.conversationId = cid;
|
||
if (messages.value === runMessages) conversationId.value = cid;
|
||
}
|
||
|
||
const eventName = String(data.event || '');
|
||
const eventChatLogId = Number(data.chat_log_id || 0);
|
||
if (Number.isInteger(eventChatLogId) && eventChatLogId > 0) {
|
||
chatLogId = eventChatLogId;
|
||
}
|
||
if (ignoreFurtherStreamEvents && !isAllowedAfterStreamTerminal(eventName)) {
|
||
continue;
|
||
}
|
||
if (eventName === 'shipping_ui_state') {
|
||
const botMsg = ensureBotMessage();
|
||
if (!botMsg) continue;
|
||
applyShippingUiStateToMessage(botMsg, data);
|
||
} else if (eventName === 'shipping_order_extraction_state') {
|
||
const botMsg = ensureBotMessage();
|
||
if (!botMsg) continue;
|
||
applyShippingOrderExtractionStateToMessage(botMsg, data);
|
||
} else if (eventName === 'message' || eventName === 'agent_message') {
|
||
if (typeof data.answer === 'string' && data.answer.length > 0) {
|
||
const botMsg = ensureBotMessage();
|
||
if (!botMsg) continue;
|
||
botMsg.content += normalizeStreamText(data.answer);
|
||
hasAssistantContent = true;
|
||
armLikelyCompletedStreamTimer(controller, run, runMessages, botMsg.content || '', () => {
|
||
ignoreFurtherStreamEvents = true;
|
||
detachActiveStreamFromView();
|
||
});
|
||
}
|
||
if (botMsgIndex !== null) {
|
||
const currentBotMsg = runMessages[botMsgIndex];
|
||
if (currentBotMsg) applyEventMetadata(currentBotMsg, data);
|
||
}
|
||
} else if (eventName === 'message_end' || eventName === 'workflow_finished') {
|
||
const workflowFailureMessage = extractWorkflowFailureMessage(data);
|
||
hasTerminalEvent = true;
|
||
ignoreFurtherStreamEvents = true;
|
||
// [STEP 2] 一旦拿到终态事件,当前轮回答在用户视角已经结束;
|
||
// 这里立刻把旧流从活动视图脱离,允许用户继续提问,同时让底层连接在后台自然读到 EOF,
|
||
// 避免下一次 sendMessage 先 abort 旧请求,导致网络面板残留 ERR_ABORTED。
|
||
detachActiveStreamFromView();
|
||
const relay = (data.hxops_relay || {}) as Record<string, unknown>;
|
||
if (relay.total_relay_ms != null) {
|
||
// eslint-disable-next-line no-console
|
||
console.info(
|
||
`[chat-perf] hxops relay first_chunk=${String(relay.first_chunk_ms ?? '')}ms total=${String(relay.total_relay_ms ?? '')}ms`,
|
||
);
|
||
}
|
||
run.status = workflowFailureMessage ? 'error' : 'done';
|
||
clearLikelyCompletedStreamTimer();
|
||
if (messages.value === runMessages) isThinking.value = false;
|
||
if (workflowFailureMessage) {
|
||
const botMsg = ensureBotMessage();
|
||
if (!botMsg) continue;
|
||
applyStreamErrorToMessage(botMsg, workflowFailureMessage, streamErrorLabels());
|
||
}
|
||
if (typeof data.answer === 'string' && data.answer.length > 0) {
|
||
const botMsg = ensureBotMessage();
|
||
if (!botMsg) continue;
|
||
const normalizedAnswer = normalizeStreamText(data.answer);
|
||
hasAssistantContent = true;
|
||
const currentContent = botMsg.content || '';
|
||
if (data.replace_answer) {
|
||
botMsg.content = normalizedAnswer;
|
||
} else if (
|
||
normalizedAnswer
|
||
&& currentContent
|
||
&& normalizedAnswer.length >= currentContent.length
|
||
&& normalizedAnswer.includes(currentContent)
|
||
) {
|
||
// [STEP 1] 某些 Dify 结束事件会重复携带整段完整 answer,这里直接替换,避免正文和内嵌文件按钮重复。
|
||
botMsg.content = normalizedAnswer;
|
||
} else if (
|
||
normalizedAnswer
|
||
&& currentContent
|
||
&& currentContent.includes(normalizedAnswer)
|
||
) {
|
||
botMsg.content = currentContent;
|
||
} else {
|
||
botMsg.content += normalizedAnswer;
|
||
}
|
||
}
|
||
if (botMsgIndex !== null) {
|
||
const currentBotMsg = runMessages[botMsgIndex];
|
||
if (currentBotMsg) applyEventMetadata(currentBotMsg, data);
|
||
}
|
||
} else if (eventName === 'error') {
|
||
const botMsg = ensureBotMessage();
|
||
if (!botMsg) continue;
|
||
// [STEP 2] SSE error 对用户来说也是当前轮终态,脱离活动视图后可继续发下一问,
|
||
// 同时保留底层连接在后台自然收尾,避免后续交互误触 abort。
|
||
detachActiveStreamFromView();
|
||
applyStreamErrorToMessage(botMsg, formatStreamError(data.message), streamErrorLabels());
|
||
run.status = 'error';
|
||
clearLikelyCompletedStreamTimer();
|
||
if (messages.value === runMessages) isThinking.value = false;
|
||
} else if (typeof data.answer === 'string' && data.answer.length > 0) {
|
||
const botMsg = ensureBotMessage();
|
||
if (!botMsg) continue;
|
||
botMsg.content += normalizeStreamText(data.answer);
|
||
hasAssistantContent = true;
|
||
armLikelyCompletedStreamTimer(controller, run, runMessages, botMsg.content || '', () => {
|
||
ignoreFurtherStreamEvents = true;
|
||
detachActiveStreamFromView();
|
||
});
|
||
}
|
||
} catch {
|
||
// ignore malformed SSE frames
|
||
}
|
||
}
|
||
|
||
}
|
||
if (!hasTerminalEvent && hasAssistantContent && run.status === 'running') {
|
||
run.status = 'done';
|
||
}
|
||
} catch (e: unknown) {
|
||
clearLikelyCompletedStreamTimer();
|
||
if (controller.signal.aborted) {
|
||
if (run.status === 'running') {
|
||
run.status = hasAssistantContent || hasTerminalEvent ? 'done' : 'error';
|
||
}
|
||
} else {
|
||
run.status = 'error';
|
||
const botMsg = ensureBotMessage();
|
||
if (botMsg) {
|
||
const message = e instanceof Error ? e.message : 'Network Issue';
|
||
applyStreamErrorToMessage(botMsg, message, streamErrorLabels());
|
||
}
|
||
}
|
||
} finally {
|
||
clearLikelyCompletedStreamTimer();
|
||
if (activeStreamController.value === controller) {
|
||
activeStreamController.value = null;
|
||
}
|
||
if (run.abortController === controller) {
|
||
delete run.abortController;
|
||
}
|
||
if (messages.value === runMessages) {
|
||
isThinking.value = false;
|
||
}
|
||
if (run.status === 'done' && botMsgIndex !== null) {
|
||
const botMsg = runMessages[botMsgIndex];
|
||
if (botMsg) {
|
||
try {
|
||
await hooks?.onAssistantMessageFinished?.(botMsg, runMessages);
|
||
} catch (error) {
|
||
// 助手完成后的领域刷新属于附加动作,失败不能反向改变已被服务端接受的消息结果。
|
||
console.error('[chat] onAssistantMessageFinished failed', error);
|
||
}
|
||
}
|
||
}
|
||
if (!requestAccepted) {
|
||
const removeCount = botMsgIndex === null ? 1 : Math.max(botMsgIndex - userMessageIndex + 1, 1);
|
||
runMessages.splice(userMessageIndex, removeCount);
|
||
}
|
||
}
|
||
return {
|
||
accepted: requestAccepted,
|
||
completed: requestAccepted && run.status === 'done',
|
||
...(chatLogId ? { chatLogId } : {}),
|
||
};
|
||
};
|
||
|
||
return {
|
||
messages,
|
||
isThinking,
|
||
conversationId,
|
||
viewId,
|
||
runs,
|
||
activeRunId,
|
||
activateRun,
|
||
createNewChatView,
|
||
loadConversationState,
|
||
sendMessage,
|
||
startChatTurn,
|
||
stopActiveGeneration,
|
||
};
|
||
}
|