Files
syops/frontend/src/features/chat/composables/useChat.ts
T

896 lines
37 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* features/chat/composables/useChat.ts
* 用途:维护聊天消息、并行 run 与 legacy SSE 流式收发,并投影普通货代 UI 状态。
* 依赖:Vue、vue-i18n、useChatTurn、streamErrorMessage、chat/shipping 类型。
* 逻辑:页面调用 useChat 发起消息;Dify/HXOPS SSE 被归并到当前助手消息,订单抽取状态由独立 Run API 维护。
*/
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,
} from '../types/chat.types';
import type { 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`;已删除的 shipping_batches 不再参与事件恢复。
* @param data - SSE 事件 JSON
* @returns 提炼后的单票 UI State
*/
export const resolveShippingUiStatePayload = (data: Record<string, unknown>): {
uiState?: ShippingTaskUiState;
} => {
const rawUiState = data.ui_state;
const uiState = rawUiState && typeof rawUiState === 'object'
? rawUiState as ShippingTaskUiState
: undefined;
return {
uiState,
};
};
/**
* 将发货通知状态机事件同步到当前助手消息。
*
* 说明:shipping_ui_state 是 HXOPS 自有 SSE 事件;收到后写入状态快照供会话摘要/通知展示,
* 不再把 action_buttons 挂到聊天消息(履约写操作改由任务处理工作台承接)。
*/
export const applyShippingUiStateToMessage = (msg: ChatMessage, data: Record<string, unknown>) => {
const { uiState } = resolveShippingUiStatePayload(data);
if (!uiState) return;
msg.shipping_ui_state = uiState;
msg.shipping_actions = undefined;
if (msg.type === 'shipping-match-result' && msg.payload && typeof msg.payload === 'object') {
delete (msg.payload as { action_buttons?: ChatMessage['shipping_actions'] }).action_buttons;
}
msg.payload = {
...(msg.payload && typeof msg.payload === 'object' ? msg.payload as Record<string, unknown> : {}),
shipping_ui_state: uiState,
};
};
export const isAllowedAfterStreamTerminal = (eventName: string): boolean => (
eventName === 'shipping_ui_state' || eventName === 'shipping_order_extraction_state'
);
const normalizeShippingOrderExtractionState = (
data: Record<string, unknown>,
): ShippingOrderExtractionState | null => {
const status = String(data.status || '').trim();
if (!['queued', 'processing', 'completed', 'partially_completed', 'review_required', 'failed', 'cancelled'].includes(status)) {
return null;
}
const rawSummary = data.summary && typeof data.summary === 'object'
? data.summary as Record<string, unknown>
: {};
const rawActivity = data.currentActivity && typeof data.currentActivity === 'object'
? data.currentActivity as Record<string, unknown>
: null;
const rawSelectionPlan = data.selectionPlan && typeof data.selectionPlan === 'object'
? data.selectionPlan as Record<string, unknown>
: null;
const rawUnitSummary = data.unitSummary && typeof data.unitSummary === 'object'
? data.unitSummary as Record<string, unknown>
: null;
return {
status: status as ShippingOrderExtractionState['status'],
uploadBatchId: String(data.uploadBatchId || '').trim() || null,
summary: {
totalDocuments: Math.max(0, Number(rawSummary.totalDocuments || 0)),
pendingDocuments: Math.max(0, Number(rawSummary.pendingDocuments || 0)),
processingDocuments: Math.max(0, Number(rawSummary.processingDocuments || 0)),
completedDocuments: Math.max(0, Number(rawSummary.completedDocuments || 0)),
reviewRequiredDocuments: Math.max(0, Number(rawSummary.reviewRequiredDocuments || 0)),
failedDocuments: Math.max(0, Number(rawSummary.failedDocuments || 0)),
candidateCount: Math.max(0, Number(rawSummary.candidateCount || 0)),
},
currentActivity: rawActivity
? {
unitId: Math.max(0, Number(rawActivity.unitId || 0)),
fileName: String(rawActivity.fileName || '').trim() || null,
eventCode: String(rawActivity.eventCode || '').trim(),
selectionBatch: rawActivity.selectionBatch != null
? Math.max(0, Number(rawActivity.selectionBatch || 0)) || null
: null,
reasonCodes: Array.isArray(rawActivity.reasonCodes)
? rawActivity.reasonCodes.map((item) => String(item || '').trim()).filter(Boolean)
: [],
}
: null,
documents: Array.isArray(data.documents)
? data.documents.map((item) => {
const row = item && typeof item === 'object' ? item as Record<string, unknown> : {};
return {
unitId: Math.max(0, Number(row.unitId || 0)),
documentId: Math.max(0, Number(row.documentId || 0)),
intakeId: row.intakeId != null ? Math.max(0, Number(row.intakeId || 0)) || null : null,
documentType: String(row.documentType || '').trim() || null,
fileName: String(row.fileName || '').trim() || null,
status: String(row.status || '').trim(),
userVisibleStage: String(row.userVisibleStage || '').trim() || null,
reasonCode: String(row.reasonCode || '').trim() || null,
explainability: row.explainability && typeof row.explainability === 'object'
? row.explainability as { message?: string | null }
: null,
emailSupplement: row.emailSupplement && typeof row.emailSupplement === 'object'
? row.emailSupplement as { status?: string | null }
: null,
};
})
: [],
selectionPlan: rawSelectionPlan
? {
selectionVersion: String(rawSelectionPlan.selectionVersion || '').trim() || null,
maxInitialAttachments: Math.max(0, Number(rawSelectionPlan.maxInitialAttachments || 0)),
maxInitialConcurrency: Math.max(0, Number(rawSelectionPlan.maxInitialConcurrency || 0)),
expansionBatchSize: Math.max(0, Number(rawSelectionPlan.expansionBatchSize || 0)),
maxTotalAttachments: Math.max(0, Number(rawSelectionPlan.maxTotalAttachments || 0)),
totalAttachmentCount: Math.max(0, Number(rawSelectionPlan.totalAttachmentCount || 0)),
eligibleAttachmentCount: Math.max(0, Number(rawSelectionPlan.eligibleAttachmentCount || 0)),
selectedAttachmentCount: Math.max(0, Number(rawSelectionPlan.selectedAttachmentCount || 0)),
plannedAttachmentCount: Math.max(0, Number(rawSelectionPlan.plannedAttachmentCount || 0)),
pendingExpansionAttachmentCount: Math.max(0, Number(rawSelectionPlan.pendingExpansionAttachmentCount || 0)),
pendingExpansionBatches: rawSelectionPlan.pendingExpansionBatches && typeof rawSelectionPlan.pendingExpansionBatches === 'object'
? rawSelectionPlan.pendingExpansionBatches as Record<string, number>
: {},
skippedAttachmentCount: Math.max(0, Number(rawSelectionPlan.skippedAttachmentCount || 0)),
duplicateAttachmentCount: Math.max(0, Number(rawSelectionPlan.duplicateAttachmentCount || 0)),
budgetLimitedAttachmentCount: Math.max(0, Number(rawSelectionPlan.budgetLimitedAttachmentCount || 0)),
groupCount: Math.max(0, Number(rawSelectionPlan.groupCount || 0)),
}
: null,
unitSummary: rawUnitSummary
? {
totalUnits: Math.max(0, Number(rawUnitSummary.totalUnits || 0)),
selectedUnits: Math.max(0, Number(rawUnitSummary.selectedUnits || 0)),
retryingUnits: Math.max(0, Number(rawUnitSummary.retryingUnits || 0)),
pendingRetryUnits: Math.max(0, Number(rawUnitSummary.pendingRetryUnits || 0)),
failedUnits: Math.max(0, Number(rawUnitSummary.failedUnits || 0)),
reviewRequiredUnits: Math.max(0, Number(rawUnitSummary.reviewRequiredUnits || 0)),
succeededUnits: Math.max(0, Number(rawUnitSummary.succeededUnits || 0)),
selectionBatches: rawUnitSummary.selectionBatches && typeof rawUnitSummary.selectionBatches === 'object'
? rawUnitSummary.selectionBatches as Record<string, number>
: {},
reviewRequiredReasonCodes: Array.isArray(rawUnitSummary.reviewRequiredReasonCodes)
? rawUnitSummary.reviewRequiredReasonCodes.map((item) => String(item || '').trim()).filter(Boolean)
: [],
expansionTriggerReasonCodes: Array.isArray(rawUnitSummary.expansionTriggerReasonCodes)
? rawUnitSummary.expansionTriggerReasonCodes.map((item) => String(item || '').trim()).filter(Boolean)
: [],
technicalFailureReasonCodes: Array.isArray(rawUnitSummary.technicalFailureReasonCodes)
? rawUnitSummary.technicalFailureReasonCodes.map((item) => String(item || '').trim()).filter(Boolean)
: [],
}
: null,
availableActions: Array.isArray(data.availableActions)
? data.availableActions.map((item) => String(item || '').trim()).filter(Boolean)
: [],
terminal: Boolean(data.terminal),
refreshFailed: Boolean(data.refreshFailed),
errorCode: String(data.errorCode || '').trim() || null,
startedAt: String(data.startedAt || '').trim() || null,
finishedAt: String(data.finishedAt || '').trim() || null,
};
};
/**
* 将订单抽取状态消息同步到当前助手消息。
*
* 说明:订单抽取已经迁移为 HXOPS 自有 Run 事实;即使流式正文已完成,
* 服务端后续补发的领域状态也允许继续覆盖当前卡片,但迟到的非终态不得回退终态展示。
*/
export const applyShippingOrderExtractionStateToMessage = (msg: ChatMessage, data: Record<string, unknown>) => {
const next = normalizeShippingOrderExtractionState(data);
if (!next) return;
const previous = msg.shipping_order_extraction_state;
if (previous?.terminal && !next.terminal) return;
msg.shipping_order_extraction_state = next;
msg.payload = {
...(msg.payload && typeof msg.payload === 'object' ? msg.payload as Record<string, unknown> : {}),
shipping_order_extraction_state: next,
};
};
/**
* 把 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 对象里抽取失败文案;
* - 上下文过长与缺省失败文案走 chat.streamError.contextTooLong / workflowFailed。
* @param data - SSE 事件 JSON
* @returns 用户可读错误;非失败终态返回空串
*/
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 t('chat.streamError.contextTooLong');
}
return normalized;
}
return t('chat.streamError.workflowFailed');
};
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; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: 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,
shipping_temporary_inventory_asset_no: context?.shipping_temporary_inventory_asset_no || undefined,
shipping_temporary_inventory_session_no: context?.shipping_temporary_inventory_session_no || 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,
};
}