fix: 优化错误提示

This commit is contained in:
sophie committed 2026-10-08 09:49:57 +08:00
1 parent d57ecc62f9
commit 239d373503
14 files changed
+333 -38

No files matched your search

@@ -7,7 +7,7 @@
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { getAuthHeaders } from '@/shared/utils/auth';
import { applyStreamErrorToMessage, type StreamErrorLabels } from '../utils/streamErrorMessage';
import { applyStreamErrorToMessage, isUserFacingStreamError, type StreamErrorLabels } from '../utils/streamErrorMessage';
import type {
ChatMessage,
ChatMessageAttachment,
@@ -533,7 +533,7 @@ export function useChat() {
* - Dify Chatflow 失败时常以 `workflow_finished + data.status=failed` 返回,HTTP 仍是 200;
* - 若这里只按“终态成功”处理,页面会出现“没有任何响应”;
* - 因此需要优先从 top-level / nested data / error 对象里抽取失败文案;
* - 上下文过长与缺省失败文案走 chat.streamError.contextTooLong / workflowFailed。
* - 上下文过长与缺省失败文案走 chat.streamError.contextTooLong / workflowFailed,并按用户可读文案展示。
* @param data - SSE 事件 JSON
* @returns 用户可读错误;非失败终态返回空串
*/
@@ -766,11 +766,6 @@ export function useChat() {
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;
@@ -797,6 +792,16 @@ export function useChat() {
botMsg.content += normalizedAnswer;
}
}
if (workflowFailureMessage) {
const botMsg = ensureBotMessage();
if (botMsg) {
// 后端 user_facing 与本函数生成的 i18n 文案都已是给用户看的,不再收成通用失败句。
const userFacing = isUserFacingStreamError(data)
|| workflowFailureMessage === t('chat.streamError.contextTooLong')
|| workflowFailureMessage === t('chat.streamError.workflowFailed');
applyStreamErrorToMessage(botMsg, workflowFailureMessage, streamErrorLabels(), { userFacing });
}
}
if (botMsgIndex !== null) {
const currentBotMsg = runMessages[botMsgIndex];
if (currentBotMsg) applyEventMetadata(currentBotMsg, data);
@@ -807,7 +812,12 @@ export function useChat() {
// [STEP 2] SSE error 对用户来说也是当前轮终态,脱离活动视图后可继续发下一问,
// 同时保留底层连接在后台自然收尾,避免后续交互误触 abort。
detachActiveStreamFromView();
applyStreamErrorToMessage(botMsg, formatStreamError(data.message), streamErrorLabels());
applyStreamErrorToMessage(
botMsg,
formatStreamError(data.message),
streamErrorLabels(),
{ userFacing: isUserFacingStreamError(data) },
);
run.status = 'error';
clearLikelyCompletedStreamTimer();
if (messages.value === runMessages) isThinking.value = false;
@@ -3,10 +3,11 @@
* 用途:统一发起 Chat Turn(POST /api/chat/turns/stream),复用与 sendMessage 相同的 SSE 渲染链路。
* 依赖:chat-turn.types、useChat 的 shipping UI 同步、streamErrorMessage、auth headers。
* 逻辑:useChat 构造 startChatTurn 并导出;货代/请假等业务只构造 actionType + payload。
* error / run.failed 若带 user_facing,则展示后端原文,同一轮只写一次。
*/
import { type Ref } from 'vue';
import { getAuthHeaders } from '@/shared/utils/auth';
import { applyStreamErrorToMessage, type StreamErrorLabels } from '../utils/streamErrorMessage';
import { applyStreamErrorToMessage, isUserFacingStreamError, type StreamErrorLabels } from '../utils/streamErrorMessage';
import type { StartChatTurnOptions } from '../types/chat-turn.types';
import type { ChatMessage, ChatRun } from '../types/chat.types';
import { applyShippingUiStateToMessage } from './useChat';
@@ -210,8 +211,14 @@ export function createStartChatTurn(options: CreateStartChatTurnOptions) {
hasTerminalEvent = true;
run.status = 'error';
const botMsg = ensureBotMessage();
if (botMsg) {
applyStreamErrorToMessage(botMsg, options.formatStreamError(data.message), options.streamErrorLabels());
// run.failed 与兼容用的 error 帧会连发;已写入的失败提示不再追加第二遍。
if (botMsg && !botMsg.stream_error) {
applyStreamErrorToMessage(
botMsg,
options.formatStreamError(data.message),
options.streamErrorLabels(),
{ userFacing: isUserFacingStreamError(data) },
);
}
}
} catch {
@@ -1,8 +1,8 @@
/**
* features/chat/utils/streamErrorMessage.spec.ts
* 用途:验证流式异常不会把后端或浏览器技术正文展示给用户。
* 用途:验证流式异常的展示策略。
* 依赖:Vitest、streamErrorMessage。
* 逻辑:保留明确连接中断分类,其余中英文异常一律使用通用提示。
* 逻辑:已标记的用户提示原样展示;连接中断单独分类;未标记的技术正文使用通用提示。
*/
import { describe, expect, it } from 'vitest';
import { resolveStreamErrorText } from './streamErrorMessage';
@@ -20,8 +20,15 @@ describe('resolveStreamErrorText', () => {
expect(resolveStreamErrorText('response ended prematurely', true, labels)).toBe('回答不完整');
});
it('does not expose Chinese or English technical errors', () => {
it('shows backend user-facing copy instead of the generic fallback', () => {
const message = '研发培训的知识检索重排服务授权失败。请联系管理员在 Dify 中更新 Rerank 模型供应商的 API Key 后重新发布应用。';
expect(resolveStreamErrorText(message, false, labels, { userFacing: true })).toBe(message);
});
it('does not expose unmarked technical errors', () => {
// 未标记 user_facing 的技术正文仍收成通用提示,避免把节点 ID 或内部报错直接给用户。
expect(resolveStreamErrorText('Dify API Key 配置错误', false, labels)).toBe('请稍后重试');
expect(resolveStreamErrorText('HTTP 500 node_execution_id=abc', false, labels)).toBe('请稍后重试');
expect(resolveStreamErrorText('HTTP 500 node_execution_id=abc', false, labels, { userFacing: false })).toBe('请稍后重试');
});
});
@@ -2,8 +2,8 @@
* features/chat/utils/streamErrorMessage.ts
* 用途:将 SSE / 浏览器流式读错映射为用户可读文案。
* 依赖:vue-i18n chat.streamError 词条。
* 逻辑:useChat 在 catch 与 error 事件中调用 applyStreamErrorToMessage;
* 只识别明确的连接中断,其余异常正文不向用户透传。
* 逻辑:useChat / useChatTurn 在 catch 与 error 事件中调用 applyStreamErrorToMessage。
* 后端已标记 user_facing 的提示原样展示;连接中断单独分类;其余技术原文收成通用提示。
*/
import type { ChatMessage } from '../types/chat.types';
@@ -46,22 +46,44 @@ export function isUpstreamDisconnectError(message: string): boolean {
return UPSTREAM_DISCONNECT_PATTERNS.some((pattern) => normalized.includes(pattern));
}
export interface ResolveStreamErrorOptions {
/** 后端已转成可直接展示的提示(SSE user_facing=true,或前端自己的 i18n 文案)。 */
userFacing?: boolean;
}
/**
* 判断 SSE 事件是否携带后端已脱敏的用户提示。
* 核心逻辑:只认布尔 true,避免把字符串 "true" 或技术原文误当成可展示文案。
* @param data - SSE 事件 JSON
* @returns 为 true 时调用方应原样展示 message
*/
export function isUserFacingStreamError(data: Record<string, unknown>): boolean {
return data.user_facing === true;
}
/**
* 将原始错误信息映射为面向用户的提示文案。
* 核心逻辑:已标记的用户提示原样返回;浏览器断网和上游提前断开走专用文案;其余技术正文收成通用提示。
*
* @param rawMessage - 浏览器或后端返回的原始错误
* @param hasContent - 是否已有部分回答内容
* @param labels - i18n 文案集合
* @param options.userFacing - 为 true 时展示 rawMessage,不再收成通用提示
*/
export function resolveStreamErrorText(
rawMessage: string,
hasContent: boolean,
labels: StreamErrorLabels,
options?: ResolveStreamErrorOptions,
): string {
if (isNetworkDisconnectError(rawMessage)) {
const message = rawMessage.trim();
if (options?.userFacing && message) {
return message;
}
if (isNetworkDisconnectError(message)) {
return hasContent ? labels.partialInterrupted : labels.networkDisconnectedEmpty;
}
if (isUpstreamDisconnectError(rawMessage)) {
if (isUpstreamDisconnectError(message)) {
return hasContent ? labels.partialInterrupted : labels.upstreamDisconnected;
}
return labels.generic;
@@ -69,14 +91,16 @@ export function resolveStreamErrorText(
/**
* 把流式错误写入 assistant 消息:无内容时整段替换,有部分内容时在末尾追加提示。
* @param options.userFacing - 为 true 时保留后端或 i18n 已写好的句子
*/
export function applyStreamErrorToMessage(
msg: ChatMessage,
rawMessage: string,
labels: StreamErrorLabels,
options?: ResolveStreamErrorOptions,
): void {
const hasContent = Boolean(msg.content.trim());
const text = resolveStreamErrorText(rawMessage, hasContent, labels);
const text = resolveStreamErrorText(rawMessage, hasContent, labels, options);
msg.stream_error = true;
if (hasContent) {
msg.content += `\n\n${text}`;