fix: 优化错误提示
This commit is contained in:
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}`;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/**
|
||||
* features/workspace/composables/useWorkspace.ts
|
||||
* 工作台编排层:组合各子 composable,挂载生命周期,provide 给 Layout 与子页面。
|
||||
* 未登录进入时跳登录页并保留当前 fullPath,供书签登录后回跳。
|
||||
*/
|
||||
import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue';
|
||||
import { useRouter, useRoute } from 'vue-router';
|
||||
@@ -10,6 +11,7 @@ import { useTheme } from '@/shared/composables/useTheme';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { useIsMobile } from '@/shared/composables/useIsMobile';
|
||||
import { WORKSPACE_PATHS } from '../constants/routes';
|
||||
import { isPublicPath } from '@/shared/constants/routes';
|
||||
import type { WorkspaceUser } from '../types/workspace.types';
|
||||
import { useChatHistory } from '@/features/chat/composables/useChatHistory';
|
||||
import { useWorkspaceHome } from './useWorkspaceHome';
|
||||
@@ -32,17 +34,18 @@ export function useWorkspace() {
|
||||
const currentUser = ref<WorkspaceUser | null>(null);
|
||||
const isSidebarCollapsed = ref(false);
|
||||
|
||||
const sessionRef: { handleLogout?: () => void } = {};
|
||||
const sessionRef: { handleSessionExpired?: () => void } = {};
|
||||
const home = useWorkspaceHome(deps, {
|
||||
currentUser,
|
||||
isLoading,
|
||||
onUnauthorized: () => sessionRef.handleLogout?.(),
|
||||
// 401 只清工作台状态并回到登录页(保留 redirect)。不走手动登出,避免丢掉书签回跳地址。
|
||||
onUnauthorized: () => sessionRef.handleSessionExpired?.(),
|
||||
});
|
||||
const session = useWorkspaceSession(deps, {
|
||||
currentUser,
|
||||
clearHome: home.clearHomeData,
|
||||
});
|
||||
sessionRef.handleLogout = session.handleLogout;
|
||||
sessionRef.handleSessionExpired = session.handleSessionExpired;
|
||||
|
||||
const profile = useWorkspaceProfile(deps);
|
||||
const schedule = useWorkspaceSchedule(deps);
|
||||
@@ -69,7 +72,11 @@ export function useWorkspace() {
|
||||
|
||||
session.loadAuthUser();
|
||||
if (!session.isLoggedIn.value) {
|
||||
await router.replace('/login');
|
||||
// 保留书签地址。裸跳 /login 会丢掉 redirect,登录后回不到 /workspace。
|
||||
const redirect = route.fullPath;
|
||||
await router.replace(
|
||||
isPublicPath(route.path) ? '/login' : { path: '/login', query: { redirect } },
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -3,10 +3,11 @@
|
||||
* 应用管理/最近更新:首页数据、布局分区、收藏、快捷问题。
|
||||
* 依赖:requestJson、auth 存储、auth.store。
|
||||
* 逻辑:拉取 /api/user/home 后把 feature_permissions 写回登录态,供侧栏和路由守卫使用。
|
||||
* 首页成功才标记会话已确认;401 只交给全局登出回登录页,冷启动不弹「请先登录」。
|
||||
*/
|
||||
import { computed, ref, type Ref } from 'vue';
|
||||
import { config } from '@/config';
|
||||
import { getAuthHeaders, patchStoredAuthUser } from '@/shared/utils/auth';
|
||||
import { getAuthHeaders, markAuthSessionConfirmed, patchStoredAuthUser } from '@/shared/utils/auth';
|
||||
import { BusinessError, requestJson } from '@/shared/api/client';
|
||||
import { useAuthStore } from '@/features/auth/stores/auth.store';
|
||||
import {
|
||||
@@ -103,6 +104,12 @@ export function useWorkspaceHome(deps: WorkspaceDeps, options: HomeOptions) {
|
||||
selectedCategory.value = null;
|
||||
};
|
||||
|
||||
/**
|
||||
* 拉取工作台首页。
|
||||
* 核心逻辑:成功后标记本页会话已确认。401 不再弹出「请先登录」——书签或刷新带失效登录态时,
|
||||
* 全局 hxops:unauthorized 会清会话并带回登录页;使用中途失效才由 App 提示。
|
||||
* @returns 无;失败时 401 走 onUnauthorized,其他错误只打日志
|
||||
*/
|
||||
const fetchHome = async () => {
|
||||
try {
|
||||
const data = await requestJson<any>('/api/user/home', { headers: getAuthHeaders() });
|
||||
@@ -187,9 +194,10 @@ export function useWorkspaceHome(deps: WorkspaceDeps, options: HomeOptions) {
|
||||
return config.workspace.modules[key] !== false;
|
||||
});
|
||||
}
|
||||
markAuthSessionConfirmed();
|
||||
} catch (e) {
|
||||
if ((e as BusinessError)?.status === 401) {
|
||||
msg.error(t('login.loginRequired'));
|
||||
// 冷启动(书签 /workspace)失效会话会走到这里。不弹错误框,避免登录页上盖一层「请先登录」。
|
||||
onUnauthorized();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
/**
|
||||
* features/workspace/composables/useWorkspaceSession.ts
|
||||
* 登录态:当前用户、知识库权限判断、登出与 401 清理。
|
||||
* 依赖:logoutAuth、getStoredAuthUser。
|
||||
* 依赖:logoutAuth、getStoredAuthUser、isPublicPath。
|
||||
* 逻辑:从本地登录态恢复 id/username/role/feature_permissions,供工作台侧栏判断专项权限。
|
||||
* 会话失效回登录页时保留当前 fullPath,登录成功后回到书签地址。
|
||||
*/
|
||||
import { computed, type Ref } from 'vue';
|
||||
import { logoutAuth, getStoredAuthUser, isPlatformAdminUser } from '@/shared/utils/auth';
|
||||
import { isPublicPath } from '@/shared/constants/routes';
|
||||
import { KB_ACCESS_DENIED_MESSAGE } from '../types/workspace.types';
|
||||
import type { WorkspaceUser } from '../types/workspace.types';
|
||||
import type { WorkspaceDeps } from './workspace.deps';
|
||||
@@ -16,7 +18,7 @@ interface SessionOptions {
|
||||
}
|
||||
|
||||
export function useWorkspaceSession(deps: WorkspaceDeps, options: SessionOptions) {
|
||||
const { router } = deps;
|
||||
const { router, route } = deps;
|
||||
const { currentUser } = options;
|
||||
|
||||
const isLoggedIn = computed(() => !!currentUser.value && currentUser.value.role !== 'guest');
|
||||
@@ -68,10 +70,29 @@ export function useWorkspaceSession(deps: WorkspaceDeps, options: SessionOptions
|
||||
options.clearHome();
|
||||
};
|
||||
|
||||
/**
|
||||
* 用户主动退出。
|
||||
* 核心逻辑:清登录态后进入登录页,不带回跳,避免退出后又进刚才的页面。
|
||||
*/
|
||||
const handleLogout = () => {
|
||||
logoutAuth();
|
||||
applyLoggedOutState();
|
||||
router.push('/login');
|
||||
// replace 清掉全局登出监听先写入的 redirect,主动退出后不再回到刚才的页面。
|
||||
router.replace('/login');
|
||||
};
|
||||
|
||||
/**
|
||||
* 首页等接口 401 后的会话失效处理。
|
||||
* 核心逻辑:先记下当前 fullPath,再清登录态;登录页带 redirect,成功后回到书签原来的地址。
|
||||
* 不弹错误框,冷启动打开 /workspace 时登录页就是结果。
|
||||
*/
|
||||
const handleSessionExpired = () => {
|
||||
const redirect = route.fullPath;
|
||||
logoutAuth();
|
||||
applyLoggedOutState();
|
||||
if (!isPublicPath(route.path)) {
|
||||
router.replace({ path: '/login', query: { redirect } });
|
||||
}
|
||||
};
|
||||
|
||||
const onAuthLogout = () => {
|
||||
@@ -86,6 +107,7 @@ export function useWorkspaceSession(deps: WorkspaceDeps, options: SessionOptions
|
||||
loadAuthUser,
|
||||
applyLoggedOutState,
|
||||
handleLogout,
|
||||
handleSessionExpired,
|
||||
onAuthLogout,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user