fix: 优化错误提示
This commit is contained in:
1 parent
d57ecc62f9
commit
239d373503
14 files changed
+333
-38
No files matched your search
@@ -141,7 +141,21 @@ def emit_run_failed(
|
||||
conversation_id: str,
|
||||
message: str,
|
||||
code: str | None = None,
|
||||
user_facing: bool = False,
|
||||
) -> str:
|
||||
"""
|
||||
发出本轮失败事件,并附带兼容用的 error 帧。
|
||||
|
||||
核心逻辑:user_facing 为 True 时两帧都带标记,前端原样展示 message。
|
||||
|
||||
Args:
|
||||
message: 失败说明。user_facing 为 True 时必须已是给用户看的句子。
|
||||
code: 业务错误码,可选。
|
||||
user_facing: 为 True 时前端不再把 message 收成通用失败提示。
|
||||
|
||||
Returns:
|
||||
连续两段 SSE 帧:run.failed 与 error。
|
||||
"""
|
||||
error_payload: dict[str, Any] = {
|
||||
"event": "run.failed",
|
||||
"run_id": run_id,
|
||||
@@ -150,10 +164,18 @@ def emit_run_failed(
|
||||
"message": message,
|
||||
"session_status": "error",
|
||||
}
|
||||
legacy_payload: dict[str, Any] = {
|
||||
"event": "error",
|
||||
"message": message,
|
||||
"conversation_id": conversation_id,
|
||||
"session_status": "error",
|
||||
}
|
||||
if code:
|
||||
error_payload["code"] = code
|
||||
legacy = sse_frame({"event": "error", "message": message, "conversation_id": conversation_id, "session_status": "error"})
|
||||
return sse_frame(error_payload) + legacy
|
||||
if user_facing:
|
||||
error_payload["user_facing"] = True
|
||||
legacy_payload["user_facing"] = True
|
||||
return sse_frame(error_payload) + sse_frame(legacy_payload)
|
||||
|
||||
|
||||
def emit_turn_event(event: TurnEvent, *, conversation_id: str) -> str:
|
||||
|
||||
@@ -194,6 +194,7 @@ class ChatTurnRuntime:
|
||||
conversation_id=session.session_id,
|
||||
message=exc.message,
|
||||
code=str(getattr(exc, "code", "") or "") or None,
|
||||
user_facing=True,
|
||||
)
|
||||
except Exception as exc:
|
||||
current_app.logger.exception("[chat-turn] unexpected failure request_id=%s turn_id=%s", req_id, turn_id)
|
||||
|
||||
@@ -103,6 +103,9 @@ class DifyService:
|
||||
def _friendly_workflow_failure_message(raw_error: str, agent_name: str | None = None) -> str:
|
||||
"""
|
||||
将 Dify/Tool 技术错误转成用户可读提示。
|
||||
|
||||
核心逻辑:优先识别知识库重排授权和知识检索失败,再按工具、上下文长度等归类。
|
||||
|
||||
Args:
|
||||
raw_error: Dify 返回的原始错误文本。
|
||||
agent_name: 当前触发错误的 Agent 名称,用于返回更贴合页面上下文的提示文案。
|
||||
@@ -112,6 +115,19 @@ class DifyService:
|
||||
text = str(raw_error or "")
|
||||
lower = text.lower()
|
||||
resolved_agent_name = str(agent_name or "").strip() or "当前智能体"
|
||||
if "rerank" in lower and ("403" in lower or "forbidden" in lower):
|
||||
return (
|
||||
f"{resolved_agent_name}的知识检索重排服务授权失败。"
|
||||
"请联系管理员在 Dify 中更新 Rerank 模型供应商的 API Key 后重新发布应用。"
|
||||
)
|
||||
if any(token in lower for token in (
|
||||
"knowledge-retrieval",
|
||||
"knowledge retrieval",
|
||||
"dataset not found",
|
||||
"embedding model",
|
||||
"知识库",
|
||||
)):
|
||||
return f"{resolved_agent_name}的知识库检索失败,请稍后重试;如持续失败请联系管理员检查知识库与模型配置。"
|
||||
if "keyword is required" in lower or re.search(r"\bstatus code 400\b", lower):
|
||||
return "没有识别到要查询的设备编号或设备名称,请补充完整设备信息后再试。"
|
||||
if re.search(r"\b(401|403)\b", lower) or "unauthorized" in lower or "invalid_auth" in lower:
|
||||
@@ -124,6 +140,52 @@ class DifyService:
|
||||
return "当前会话上下文过长,模型无法继续回答。请新建对话后重新查询。"
|
||||
return f"{resolved_agent_name}暂时无法完成查询,请稍后重试。"
|
||||
|
||||
@staticmethod
|
||||
def _present_stream_error_message(raw_message: str, status_code: int | None, agent_name: str | None = None) -> str:
|
||||
"""
|
||||
把 Dify 流内 error 事件转成可直接展示的提示。
|
||||
|
||||
核心逻辑:重排授权、鉴权、地址和网关状态走上游 HTTP 文案;其余走工作流失败文案。
|
||||
|
||||
Args:
|
||||
raw_message: Dify error 事件的 message。
|
||||
status_code: 事件里的 HTTP 状态;没有时传 0。
|
||||
agent_name: 当前智能体名称。
|
||||
|
||||
Returns:
|
||||
面向用户的中文提示。
|
||||
"""
|
||||
text = str(raw_message or "")
|
||||
lower = text.lower()
|
||||
try:
|
||||
code = int(status_code or 0)
|
||||
except (TypeError, ValueError):
|
||||
code = 0
|
||||
if "rerank" in lower or code in (401, 403, 404, 429, 502, 503, 504):
|
||||
return DifyService._friendly_upstream_error_message(code, text, agent_name)
|
||||
return DifyService._friendly_workflow_failure_message(text, agent_name)
|
||||
|
||||
@staticmethod
|
||||
def _friendly_stream_request_failure_message(exc: Exception, agent_name: str | None = None) -> str:
|
||||
"""
|
||||
将连接 Dify 时的网络异常转成用户可读提示。
|
||||
|
||||
核心逻辑:超时和连接失败分开说明;其余 RequestException 使用当前智能体名称的通用失败句。
|
||||
|
||||
Args:
|
||||
exc: requests 抛出的连接、超时或协议异常。
|
||||
agent_name: 当前智能体名称。
|
||||
|
||||
Returns:
|
||||
面向用户的中文提示,不包含异常原文。
|
||||
"""
|
||||
resolved_agent_name = str(agent_name or "").strip() or "当前智能体"
|
||||
if isinstance(exc, (requests.exceptions.ReadTimeout, requests.exceptions.ConnectTimeout)):
|
||||
return f"{resolved_agent_name}等待 AI 服务响应超时,请稍后重试。"
|
||||
if isinstance(exc, requests.exceptions.ConnectionError):
|
||||
return f"暂时无法连接{resolved_agent_name}的 AI 服务,请稍后重试。"
|
||||
return f"{resolved_agent_name}暂时无法完成查询,请稍后重试。"
|
||||
|
||||
@staticmethod
|
||||
def _friendly_upstream_error_message(status_code: int, raw_body: str, agent_name: str | None = None) -> str:
|
||||
"""将 Dify HTTP 错误转换为可执行的用户提示。
|
||||
@@ -1106,7 +1168,7 @@ class DifyService:
|
||||
},
|
||||
'error',
|
||||
)
|
||||
yield f"data: {json.dumps({'event': 'error', 'message': message}, ensure_ascii=False)}\n\n"
|
||||
yield f"data: {json.dumps({'event': 'error', 'message': message, 'user_facing': True}, ensure_ascii=False)}\n\n"
|
||||
return
|
||||
response.raise_for_status()
|
||||
yield f"data: {json.dumps({'event': 'upstream_connected', 'message': 'Dify 已连接'}, ensure_ascii=False)}\n\n"
|
||||
@@ -1140,7 +1202,29 @@ class DifyService:
|
||||
data.get('conversation_id') or normalized_conversation_id,
|
||||
)
|
||||
|
||||
if event == 'node_finished':
|
||||
if event == 'error':
|
||||
status_raw = data.get('status')
|
||||
try:
|
||||
status_code = int(status_raw)
|
||||
except (TypeError, ValueError):
|
||||
status_code = 0
|
||||
raw_message = str(data.get('message') or '')
|
||||
# [STEP] 流内 error 先转成用户提示再转发,避免前端只能看到笼统的请求失败。
|
||||
data['message'] = DifyService._present_stream_error_message(
|
||||
raw_message,
|
||||
status_code,
|
||||
getattr(agent, 'name', None),
|
||||
)
|
||||
data['user_facing'] = True
|
||||
if current_app:
|
||||
current_app.logger.warning(
|
||||
"[chat-stream] dify error event request_id=%s agent_id=%s status=%s raw_error=%s",
|
||||
request_id,
|
||||
getattr(agent, 'id', None),
|
||||
status_code,
|
||||
raw_message,
|
||||
)
|
||||
elif event == 'node_finished':
|
||||
# [STEP] Chatflow 知识检索结果在 node_finished.outputs.result,不在 message_end
|
||||
DifyService._collect_knowledge_retrieval_from_node(retriever_resources, data)
|
||||
|
||||
@@ -1180,6 +1264,7 @@ class DifyService:
|
||||
)
|
||||
data['message'] = friendly_error
|
||||
data['error'] = friendly_error
|
||||
data['user_facing'] = True
|
||||
if isinstance(data.get('data'), dict):
|
||||
data['data']['message'] = friendly_error
|
||||
data['data']['error'] = friendly_error
|
||||
@@ -1226,13 +1311,17 @@ class DifyService:
|
||||
if not is_timeout and attempt < max_retries:
|
||||
time.sleep(attempt * 2)
|
||||
continue
|
||||
message = DifyService._friendly_stream_request_failure_message(e)
|
||||
message = DifyService._friendly_stream_request_failure_message(
|
||||
e,
|
||||
getattr(agent, 'name', None),
|
||||
)
|
||||
# [STEP 4] 错误事件与持久化对象必须是同一个 dict,确保 chat_log_id 能继续传给 relay/领域 Handler。
|
||||
error_event = {
|
||||
'event': 'error',
|
||||
'conversation_id': normalized_conversation_id,
|
||||
'answer': message,
|
||||
'message': message,
|
||||
'user_facing': True,
|
||||
'metadata': {},
|
||||
}
|
||||
persist_stream_chat(error_event, 'error')
|
||||
|
||||
@@ -78,6 +78,38 @@ def test_friendly_workflow_failure_message_rewrites_tool_error_with_current_agen
|
||||
assert message == '员工培训查询工具调用失败,请稍后重试;如持续失败请联系管理员。'
|
||||
|
||||
|
||||
def test_friendly_workflow_failure_message_identifies_knowledge_retrieval_failure():
|
||||
"""知识检索节点失败应说明是知识库,而不是笼统的查询失败。"""
|
||||
message = DifyService._friendly_workflow_failure_message(
|
||||
'Node knowledge-retrieval run failed: dataset not found',
|
||||
agent_name='研发培训',
|
||||
)
|
||||
assert message == '研发培训的知识库检索失败,请稍后重试;如持续失败请联系管理员检查知识库与模型配置。'
|
||||
|
||||
|
||||
def test_friendly_stream_request_failure_message_distinguishes_timeout():
|
||||
"""连接 Dify 读超时应提示等待超时,且不带异常原文。"""
|
||||
import requests
|
||||
|
||||
message = DifyService._friendly_stream_request_failure_message(
|
||||
requests.exceptions.ReadTimeout('read timed out'),
|
||||
agent_name='研发培训',
|
||||
)
|
||||
assert message == '研发培训等待 AI 服务响应超时,请稍后重试。'
|
||||
assert 'read timed out' not in message
|
||||
|
||||
|
||||
def test_present_stream_error_message_keeps_rerank_authorization_copy():
|
||||
"""流内 error 事件里的重排 403 应沿用授权失败文案。"""
|
||||
message = DifyService._present_stream_error_message(
|
||||
'PluginInvokeError: 403 Forbidden for url https://api.example/v1/rerank',
|
||||
400,
|
||||
'研发培训',
|
||||
)
|
||||
assert '知识检索重排服务授权失败' in message
|
||||
assert 'https://api.example' not in message
|
||||
|
||||
|
||||
def test_friendly_upstream_error_message_identifies_rerank_authorization_failure():
|
||||
"""断言:Dify 重排插件 403 应提示修复模型授权,而非误导为网络超时。"""
|
||||
message = DifyService._friendly_upstream_error_message(
|
||||
|
||||
+16
-5
@@ -4,6 +4,7 @@
|
||||
* 根组件:主题初始化、全局消息弹窗、401 登出监听、html lang 与 i18n locale 同步。
|
||||
* 依赖:useTheme、useGlobalMessageDialog、auth、linked-nav.store。
|
||||
* 逻辑:已登录时预取关联服务侧栏入口,避免页面切换后入口后闪现。
|
||||
* 书签/刷新冷启动遇到 401 时只回登录页;本页已确认会话后中途失效才弹窗。
|
||||
*/
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { watch, onMounted, onBeforeUnmount } from 'vue';
|
||||
@@ -11,7 +12,7 @@ import { useTheme } from '@/shared/composables/useTheme';
|
||||
import LevelMessageDialog from '@/shared/components/LevelMessageDialog.vue';
|
||||
import { useGlobalMessageDialog } from '@/shared/composables/useGlobalMessageDialog';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { getAuthHeaders, logoutAuth } from '@/shared/utils/auth';
|
||||
import { getAuthHeaders, logoutAuth, markAuthSessionConfirmed, shouldPromptOnSessionUnauthorized } from '@/shared/utils/auth';
|
||||
import { isPublicPath } from '@/shared/constants/routes';
|
||||
import { useLinkedNavStore } from '@/features/sso/stores/linked-nav.store';
|
||||
|
||||
@@ -66,8 +67,9 @@ watch(themePreference, (newTheme) => {
|
||||
});
|
||||
|
||||
/**
|
||||
* 处理接口返回未登录状态,提示用户重新登录并清理失效的本地登录信息。
|
||||
* 核心逻辑:忽略可选的关联服务/SSO 目录请求;其余未授权请求统一展示易懂提示,再执行登出。
|
||||
* 处理接口返回未登录状态,清理失效的本地登录信息。
|
||||
* 核心逻辑:忽略可选的关联服务/SSO 目录请求。书签或刷新带来的冷启动 401 只回登录页;
|
||||
* 本页已经成功加载过首页后会话才中途失效时,再提示重新登录。
|
||||
* @param event - 包含请求地址和状态码的全局未授权事件。
|
||||
*/
|
||||
const onUnauthorized = (event: Event) => {
|
||||
@@ -75,10 +77,17 @@ const onUnauthorized = (event: Event) => {
|
||||
// 侧栏入口目录是可选导航能力,加载失败只能隐藏入口,不能清除有效 HXOPS 登录态。
|
||||
if (/\/api\/sso\/apps(?:\?|$)/.test(url)) return;
|
||||
if (/\/api\/linked-services(?:\?|$)/.test(url)) return;
|
||||
showMessageDialog('error', t('login.sessionExpiredHint'), t('login.sessionExpired'));
|
||||
if (shouldPromptOnSessionUnauthorized()) {
|
||||
showMessageDialog('error', t('login.sessionExpiredHint'), t('login.sessionExpired'));
|
||||
}
|
||||
logoutAuth();
|
||||
};
|
||||
|
||||
/**
|
||||
* 登出后离开需要登录的页面。
|
||||
* 核心逻辑:带上当前 fullPath 作为 redirect,登录成功后回到书签原来的地址。
|
||||
* @param event - hxops:logout,remote 为 true 表示其他标签页触发。
|
||||
*/
|
||||
const onLogout = (event: Event) => {
|
||||
useLinkedNavStore().reset();
|
||||
const detail = (event as CustomEvent<{ remote?: boolean }>).detail;
|
||||
@@ -87,7 +96,8 @@ const onLogout = (event: Event) => {
|
||||
}
|
||||
const path = router.currentRoute.value.path;
|
||||
if (!isPublicPath(path)) {
|
||||
router.push('/login');
|
||||
const redirect = router.currentRoute.value.fullPath;
|
||||
router.push({ path: '/login', query: { redirect } });
|
||||
}
|
||||
};
|
||||
|
||||
@@ -104,6 +114,7 @@ onMounted(async () => {
|
||||
try {
|
||||
const res = await fetch('/api/user/home', { headers });
|
||||
if (res.ok) {
|
||||
markAuthSessionConfirmed();
|
||||
const data = await res.json();
|
||||
if (data.user && data.user.language) {
|
||||
locale.value = data.user.language;
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -11,9 +11,13 @@ import {
|
||||
getRememberedLoginPreference,
|
||||
getRememberedLoginProfile,
|
||||
getStoredAuthUser,
|
||||
isAuthSessionConfirmed,
|
||||
logoutAuth,
|
||||
markAuthSessionConfirmed,
|
||||
saveAuthUser,
|
||||
saveRememberedLoginPreference,
|
||||
saveRememberedLoginProfile,
|
||||
shouldPromptOnSessionUnauthorized,
|
||||
} from './auth';
|
||||
|
||||
class MemoryStorage implements Storage {
|
||||
@@ -101,6 +105,21 @@ describe('shared/utils/auth remember me helpers', () => {
|
||||
expect(localStorage.getItem('hxops_user')).toBeNull();
|
||||
});
|
||||
|
||||
it('does not prompt when a bookmarked page hits 401 before home succeeds', () => {
|
||||
// 冷启动默认未确认:书签打开 /workspace 时失效会话不应弹错误框
|
||||
expect(isAuthSessionConfirmed()).toBe(false);
|
||||
expect(shouldPromptOnSessionUnauthorized()).toBe(false);
|
||||
|
||||
markAuthSessionConfirmed();
|
||||
// 首页已成功后,使用中途 401 才提示登录失效
|
||||
expect(shouldPromptOnSessionUnauthorized()).toBe(true);
|
||||
|
||||
logoutAuth();
|
||||
// 登出收回确认标记,下一次书签进入仍不弹窗
|
||||
expect(isAuthSessionConfirmed()).toBe(false);
|
||||
expect(shouldPromptOnSessionUnauthorized()).toBe(false);
|
||||
});
|
||||
|
||||
it('removes remembered login preference when user cancels remember me', () => {
|
||||
saveRememberedLoginPreference(true);
|
||||
saveRememberedLoginProfile('26040006', 'Hxit@54321');
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
* 用途:统一封装登录态、记住我偏好、登录页账号密码自动回填、跨标签登出同步,以及 401 是否表示会话失效的判断。
|
||||
* 依赖:浏览器 localStorage/sessionStorage、Casdoor refresh 接口。
|
||||
* 逻辑:把“认证凭据”和“登录页自动回填资料”分开管理;改密等业务 401 不得触发全局登出。
|
||||
* 冷启动(书签/刷新)在首页请求成功前不算已确认会话,401 只回登录页,不弹错误框。
|
||||
*/
|
||||
export type FeaturePermissions = {
|
||||
training_hr_manage?: boolean;
|
||||
@@ -179,10 +180,45 @@ export const saveAuthUser = (user: AuthUser, remember = false): void => {
|
||||
const AUTH_LOGOUT_KEY = 'hxops_auth_logout';
|
||||
const AUTH_BC_NAME = 'hxops_auth';
|
||||
|
||||
/** 本页生命周期内,是否已有一次带登录态的首页请求成功。冷启动 401 用它决定要不要弹窗。 */
|
||||
let _authSessionConfirmed = false;
|
||||
|
||||
/**
|
||||
* 标记当前页的登录会话已被成功的首页数据确认。
|
||||
* 核心逻辑:仅 /api/user/home 成功后调用;刷新或书签进入时默认未确认。
|
||||
*/
|
||||
export function markAuthSessionConfirmed(): void {
|
||||
_authSessionConfirmed = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前页是否已确认过有效登录会话。
|
||||
* @returns 首页请求成功过则为 true;登出或尚未成功拉取首页时为 false
|
||||
*/
|
||||
export function isAuthSessionConfirmed(): boolean {
|
||||
return _authSessionConfirmed;
|
||||
}
|
||||
|
||||
/**
|
||||
* 会话类 401 是否要弹出「登录已失效」。
|
||||
* 核心逻辑:书签、地址栏回车、刷新等冷启动还没有成功加载过首页,此时用户预期就是登录页,不能再盖一层错误框。
|
||||
* 使用过程中会话中途失效(本页已经确认过登录)才提示。
|
||||
* @returns true 时由 App 弹出登录失效提示
|
||||
*/
|
||||
export function shouldPromptOnSessionUnauthorized(): boolean {
|
||||
return _authSessionConfirmed;
|
||||
}
|
||||
|
||||
/** 登出或清理登录态时收回“已确认会话”标记,避免下一次冷启动误弹窗。 */
|
||||
function resetAuthSessionConfirmed(): void {
|
||||
_authSessionConfirmed = false;
|
||||
}
|
||||
|
||||
let _authBroadcast: BroadcastChannel | null = null;
|
||||
let _authSyncInitialized = false;
|
||||
|
||||
const clearAuthStorage = (): void => {
|
||||
resetAuthSessionConfirmed();
|
||||
localStorage.removeItem(AUTH_USER_KEY);
|
||||
sessionStorage.removeItem(AUTH_USER_KEY);
|
||||
sessionStorage.removeItem('hxops_wecom_state');
|
||||
|
||||
Reference in new issue
Block a user