fix(chat): 将流式错误信息映射为面向用户的提示方案

This commit is contained in:
sophie committed 2026-06-19 21:25:14 +08:00
1 parent 6757ad869f
commit 10b6f9b692
8 files changed
+127 -2

No files matched your search

@@ -3,7 +3,9 @@
* SSE 流式对话核心:消息列表、runs、发送与接收。 * SSE 流式对话核心:消息列表、runs、发送与接收。
*/ */
import { ref } from 'vue'; import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { getAuthHeaders } from '@/shared/utils/auth'; import { getAuthHeaders } from '@/shared/utils/auth';
import { applyStreamErrorToMessage, type StreamErrorLabels } from '../utils/streamErrorMessage';
import type { ChatMessage, ChatRun, RetrieverResource } from '../types/chat.types'; import type { ChatMessage, ChatRun, RetrieverResource } from '../types/chat.types';
const normalizeResources = (resources: unknown) => { const normalizeResources = (resources: unknown) => {
@@ -110,6 +112,7 @@ const applyEventMetadata = (msg: ChatMessage, data: Record<string, unknown>) =>
}; };
export function useChat() { export function useChat() {
const { t } = useI18n();
const messages = ref<ChatMessage[]>([]); const messages = ref<ChatMessage[]>([]);
const isThinking = ref(false); const isThinking = ref(false);
const viewId = ref(0); const viewId = ref(0);
@@ -169,6 +172,13 @@ export function useChat() {
return String(message ?? 'Unknown error'); return String(message ?? 'Unknown error');
}; };
const streamErrorLabels = (): StreamErrorLabels => ({
networkDisconnectedEmpty: t('chat.streamError.networkDisconnectedEmpty'),
partialInterrupted: t('chat.streamError.partialInterrupted'),
upstreamDisconnected: t('chat.streamError.upstreamDisconnected'),
generic: t('chat.streamError.generic'),
});
const sendMessage = async ( const sendMessage = async (
query: string, query: string,
agentId: number, agentId: number,
@@ -338,7 +348,7 @@ export function useChat() {
} else if (eventName === 'error') { } else if (eventName === 'error') {
const botMsg = ensureBotMessage(); const botMsg = ensureBotMessage();
if (!botMsg) continue; if (!botMsg) continue;
botMsg.content += `\n[Error: ${formatStreamError(data.message)}]`; applyStreamErrorToMessage(botMsg, formatStreamError(data.message), streamErrorLabels());
run.status = 'error'; run.status = 'error';
if (messages.value === runMessages) isThinking.value = false; if (messages.value === runMessages) isThinking.value = false;
} else if (typeof data.answer === 'string' && data.answer.length > 0) { } else if (typeof data.answer === 'string' && data.answer.length > 0) {
@@ -356,7 +366,7 @@ export function useChat() {
const botMsg = ensureBotMessage(); const botMsg = ensureBotMessage();
if (botMsg) { if (botMsg) {
const message = e instanceof Error ? e.message : 'Network Issue'; const message = e instanceof Error ? e.message : 'Network Issue';
botMsg.content += `\n[Error: ${message}]`; applyStreamErrorToMessage(botMsg, message, streamErrorLabels());
} }
} finally { } finally {
if (messages.value === runMessages) { if (messages.value === runMessages) {
@@ -35,6 +35,8 @@ export interface ChatMessage {
variant?: 'primary' | 'secondary' | 'danger'; variant?: 'primary' | 'secondary' | 'danger';
}>; }>;
shipping_actions_used?: boolean; shipping_actions_used?: boolean;
/** 流式对话是否因网络/上游中断而附带错误提示 */
stream_error?: boolean;
} }
export type ChatRunStatus = 'running' | 'done' | 'error'; export type ChatRunStatus = 'running' | 'done' | 'error';
@@ -0,0 +1,88 @@
/**
* features/chat/utils/streamErrorMessage.ts
* 用途:将 SSE / 浏览器流式读错映射为用户可读文案。
* 依赖:vue-i18n chat.streamError 词条。
* 逻辑:useChat 在 catch 与 error 事件中调用 applyStreamErrorToMessage。
*/
import type { ChatMessage } from '../types/chat.types';
const NETWORK_DISCONNECT_PATTERNS = [
'network error',
'failed to fetch',
'load failed',
'networkerror when attempting to fetch resource',
'network issue',
];
const UPSTREAM_DISCONNECT_PATTERNS = [
'response ended prematurely',
'chunkedencodingerror',
];
export interface StreamErrorLabels {
networkDisconnectedEmpty: string;
partialInterrupted: string;
upstreamDisconnected: string;
generic: string;
}
/**
* 判断是否为浏览器侧 SSE / fetch 连接中断类错误。
*/
export function isNetworkDisconnectError(message: string): boolean {
const normalized = message.trim().toLowerCase();
if (!normalized) return false;
return NETWORK_DISCONNECT_PATTERNS.some(
(pattern) => normalized === pattern || normalized.includes(pattern),
);
}
/**
* 判断是否为上游(Dify)流式响应提前结束。
*/
export function isUpstreamDisconnectError(message: string): boolean {
const normalized = message.trim().toLowerCase();
return UPSTREAM_DISCONNECT_PATTERNS.some((pattern) => normalized.includes(pattern));
}
/**
* 将原始错误信息映射为面向用户的提示文案。
*
* @param rawMessage - 浏览器或后端返回的原始错误
* @param hasContent - 是否已有部分回答内容
* @param labels - i18n 文案集合
*/
export function resolveStreamErrorText(
rawMessage: string,
hasContent: boolean,
labels: StreamErrorLabels,
): string {
if (isNetworkDisconnectError(rawMessage)) {
return hasContent ? labels.partialInterrupted : labels.networkDisconnectedEmpty;
}
if (isUpstreamDisconnectError(rawMessage)) {
return hasContent ? labels.partialInterrupted : labels.upstreamDisconnected;
}
if (/[\u4e00-\u9fff]/.test(rawMessage)) {
return rawMessage;
}
return labels.generic;
}
/**
* 把流式错误写入 assistant 消息:无内容时整段替换,有部分内容时在末尾追加提示。
*/
export function applyStreamErrorToMessage(
msg: ChatMessage,
rawMessage: string,
labels: StreamErrorLabels,
): void {
const hasContent = Boolean(msg.content.trim());
const text = resolveStreamErrorText(rawMessage, hasContent, labels);
msg.stream_error = true;
if (hasContent) {
msg.content += `\n\n${text}`;
} else {
msg.content = text;
}
}
@@ -41,6 +41,7 @@ export function resolveMessageAnchorKey(msg: ChatMessage, index: number): string
} }
export function assistantMessageHasError(msg: ChatMessage | null | undefined): boolean { export function assistantMessageHasError(msg: ChatMessage | null | undefined): boolean {
if (msg?.stream_error) return true;
return String(msg?.content || '').includes('[Error:'); return String(msg?.content || '').includes('[Error:');
} }
+6
View File
@@ -293,6 +293,12 @@
"searchByNameOrEmployeeId": "Search by name or employee ID, press Enter", "searchByNameOrEmployeeId": "Search by name or employee ID, press Enter",
"name": "Name", "name": "Name",
"employeeIdRequired": "Employee ID is required.", "employeeIdRequired": "Employee ID is required.",
"streamError": {
"networkDisconnectedEmpty": "Connection lost before a reply was received. Please try again.",
"partialInterrupted": "The reply was interrupted. The content above may be incomplete—please ask again.",
"upstreamDisconnected": "The AI service connection was interrupted. Please try again.",
"generic": "The request failed. Please try again."
},
"actions": { "actions": {
"copy": "Copy", "copy": "Copy",
"edit": "Edit", "edit": "Edit",
+6
View File
@@ -293,6 +293,12 @@
"searchByNameOrEmployeeId": "ค้นหาด้วยชื่อหรือรหัสพนักงาน แล้วกด Enter", "searchByNameOrEmployeeId": "ค้นหาด้วยชื่อหรือรหัสพนักงาน แล้วกด Enter",
"name": "ชื่อ", "name": "ชื่อ",
"employeeIdRequired": "รหัสพนักงานห้ามว่าง", "employeeIdRequired": "รหัสพนักงานห้ามว่าง",
"streamError": {
"networkDisconnectedEmpty": "การเชื่อมต่อขาดหายก่อนได้รับคำตอบ โปรดลองใหม่อีกครั้ง",
"partialInterrupted": "การสร้างคำตอบถูกขัดจังหวะ เนื้อหาด้านบนอาจไม่สมบูรณ์ โปรดถามใหม่",
"upstreamDisconnected": "การเชื่อมต่อบริการ AI ขาดหาย โปรดลองใหม่อีกครั้ง",
"generic": "คำขอล้มเหลว โปรดลองใหม่อีกครั้ง"
},
"actions": { "actions": {
"copy": "คัดลอก", "copy": "คัดลอก",
"edit": "แก้ไข", "edit": "แก้ไข",
+6
View File
@@ -293,6 +293,12 @@
"searchByNameOrEmployeeId": "输入姓名或工号搜索,按回车键查询", "searchByNameOrEmployeeId": "输入姓名或工号搜索,按回车键查询",
"name": "姓名", "name": "姓名",
"employeeIdRequired": "工号不能为空。", "employeeIdRequired": "工号不能为空。",
"streamError": {
"networkDisconnectedEmpty": "连接中断,未能获取回答,请稍后重试。",
"partialInterrupted": "回答生成中断,以上内容可能不完整,请重新提问。",
"upstreamDisconnected": "AI 服务连接中断,请稍后重试。",
"generic": "请求失败,请稍后重试。"
},
"actions": { "actions": {
"copy": "复制", "copy": "复制",
"edit": "编辑", "edit": "编辑",
+6
View File
@@ -293,6 +293,12 @@
"searchByNameOrEmployeeId": "輸入姓名或工號搜尋,按 Enter 查詢", "searchByNameOrEmployeeId": "輸入姓名或工號搜尋,按 Enter 查詢",
"name": "姓名", "name": "姓名",
"employeeIdRequired": "工號不能為空。", "employeeIdRequired": "工號不能為空。",
"streamError": {
"networkDisconnectedEmpty": "連線中斷,未能取得回答,請稍後重試。",
"partialInterrupted": "回答生成中斷,以上內容可能不完整,請重新提問。",
"upstreamDisconnected": "AI 服務連線中斷,請稍後重試。",
"generic": "請求失敗,請稍後重試。"
},
"actions": { "actions": {
"copy": "複製", "copy": "複製",
"edit": "編輯", "edit": "編輯",