1043 lines
36 KiB
React
1043 lines
36 KiB
React
/*
|
||
Copyright (C) 2025 QuantumNous
|
||
|
||
This program is free software: you can redistribute it and/or modify
|
||
it under the terms of the GNU Affero General Public License as
|
||
published by the Free Software Foundation, either version 3 of the
|
||
License, or (at your option) any later version.
|
||
|
||
This program is distributed in the hope that it will be useful,
|
||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||
GNU Affero General Public License for more details.
|
||
|
||
You should have received a copy of the GNU Affero General Public License
|
||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||
|
||
For commercial licensing, please contact support@quantumnous.com
|
||
*/
|
||
|
||
import { useCallback } from 'react';
|
||
import { useTranslation } from 'react-i18next';
|
||
import { Toast } from '@douyinfe/semi-ui';
|
||
import { SSE } from 'sse.js';
|
||
import {
|
||
API_ENDPOINTS,
|
||
MESSAGE_STATUS,
|
||
DEBUG_TABS,
|
||
} from '../../constants/playground.constants';
|
||
import {
|
||
getUserIdFromLocalStorage,
|
||
handleApiError,
|
||
extractErrorMessage,
|
||
processThinkTags,
|
||
processIncompleteThinkTags,
|
||
} from '../../helpers';
|
||
import { getServerURL } from '../../helpers/config';
|
||
|
||
// extractWebSearchSources 把 base64(JSON([{title, url, i}])) 头解码成数组,
|
||
// 失败 / 空头一律返回 null(不要 throw 阻断主流程)
|
||
//
|
||
// 关键:后端的 JSON 是 UTF-8 字节(中文 / emoji 等),base64 解码后用 atob 拿到的是
|
||
// "字节字符串"(每个 char 是一个 byte 的 Latin-1 视图)。如果直接 JSON.parse(atob(raw)),
|
||
// 多字节字符会被错误地解读为多个 Latin-1 字符,渲染出 "广州天æ°" 这种乱码。
|
||
// 正确流程:atob → Uint8Array → TextDecoder('utf-8') → JSON.parse。
|
||
const extractWebSearchSources = (getHeader) => {
|
||
let raw;
|
||
try {
|
||
raw = getHeader('X-Web-Search-Sources');
|
||
} catch (_) {
|
||
return null;
|
||
}
|
||
if (!raw) return null;
|
||
try {
|
||
const binary = atob(raw);
|
||
const bytes = new Uint8Array(binary.length);
|
||
for (let i = 0; i < binary.length; i++) {
|
||
bytes[i] = binary.charCodeAt(i);
|
||
}
|
||
const json = new TextDecoder('utf-8').decode(bytes);
|
||
const arr = JSON.parse(json);
|
||
if (!Array.isArray(arr)) return null;
|
||
// 防御:只保留有 url 的项,其它字段宽容
|
||
return arr
|
||
.filter((s) => s && typeof s.url === 'string' && s.url)
|
||
.map((s) => ({
|
||
title: typeof s.title === 'string' && s.title ? s.title : s.url,
|
||
url: s.url,
|
||
index: typeof s.i === 'number' ? s.i : 0,
|
||
}));
|
||
} catch (_) {
|
||
return null;
|
||
}
|
||
};
|
||
|
||
// attachWebSearchSourcesToLastAssistant 把 sources 挂到最后一条助手消息上,渲染参考来源卡片
|
||
const attachWebSearchSourcesToLastAssistant = (setMessage, sources) => {
|
||
if (!sources || sources.length === 0) return;
|
||
setMessage((prev) => {
|
||
if (!prev || prev.length === 0) return prev;
|
||
const last = prev[prev.length - 1];
|
||
if (!last || last.role !== 'assistant') return prev;
|
||
return [...prev.slice(0, -1), { ...last, webSearchSources: sources }];
|
||
});
|
||
};
|
||
|
||
// 请求级看门狗超时:服务端如果在 STREAM_WATCHDOG_MS 内既不下推数据也不关闭连接,
|
||
// 前端会主动 abort 并把 loading 消息切到错误态,避免用户对着无限转圈。
|
||
// 选 120s 是因为 reasoning 模型(o1/o3 等)首个 token 之前可能空跑 60-90s,太短会误杀;
|
||
// 任何一次 SSE 事件 / readystatechange 都会把计时器复位。
|
||
const STREAM_WATCHDOG_MS = 120 * 1000;
|
||
|
||
// notifyWebSearchStatus 根据后端 X-Web-Search-* 响应头给用户透出搜索状态
|
||
// getHeader: (name) => string|null
|
||
const notifyWebSearchStatus = (getHeader, t) => {
|
||
let status;
|
||
let provider;
|
||
let count;
|
||
try {
|
||
status = getHeader('X-Web-Search-Status');
|
||
provider = getHeader('X-Web-Search-Provider');
|
||
count = getHeader('X-Web-Search-Result-Count');
|
||
} catch (_) {
|
||
return;
|
||
}
|
||
if (!status) return;
|
||
|
||
switch (status) {
|
||
case 'success':
|
||
case 'partial':
|
||
Toast.info({
|
||
content: t('已联网搜索 ({{provider}},{{count}} 条结果)', {
|
||
provider: provider || '-',
|
||
count: count || 0,
|
||
}),
|
||
duration: 2,
|
||
});
|
||
break;
|
||
case 'fallback':
|
||
Toast.info({
|
||
content: t('主搜索引擎不可用,已使用备用 ({{provider}})', {
|
||
provider: provider || '-',
|
||
}),
|
||
duration: 2,
|
||
});
|
||
break;
|
||
case 'native':
|
||
Toast.info({
|
||
content: t('已使用模型原生联网搜索 ({{provider}})', {
|
||
provider: provider || '-',
|
||
}),
|
||
duration: 2,
|
||
});
|
||
break;
|
||
case 'no_results':
|
||
Toast.warning({
|
||
content: t('联网搜索未返回结果,已按模型自身知识回答'),
|
||
duration: 3,
|
||
});
|
||
break;
|
||
case 'failed':
|
||
Toast.warning({
|
||
content: t('联网搜索失败,已按模型自身知识回答'),
|
||
duration: 3,
|
||
});
|
||
break;
|
||
case 'unconfigured':
|
||
Toast.warning({
|
||
content: t('管理员尚未配置搜索 API Key,联网搜索已跳过'),
|
||
duration: 3,
|
||
});
|
||
break;
|
||
case 'disabled':
|
||
Toast.warning({ content: t('联网搜索功能已被管理员禁用'), duration: 3 });
|
||
break;
|
||
default:
|
||
break;
|
||
}
|
||
};
|
||
|
||
const extractResponsesOutputText = (data) => {
|
||
if (!data) return '';
|
||
if (typeof data.output_text === 'string') return data.output_text;
|
||
if (!Array.isArray(data.output)) return '';
|
||
|
||
return data.output
|
||
.flatMap((item) => (Array.isArray(item?.content) ? item.content : []))
|
||
.map((content) => {
|
||
if (typeof content?.text === 'string') return content.text;
|
||
if (typeof content?.output_text === 'string') return content.output_text;
|
||
return '';
|
||
})
|
||
.filter(Boolean)
|
||
.join('');
|
||
};
|
||
|
||
const isResponsesPayload = (data) =>
|
||
!!data &&
|
||
(data.object === 'response' ||
|
||
typeof data.output_text === 'string' ||
|
||
Array.isArray(data.output));
|
||
|
||
const extractResponsesStreamText = (payload) =>
|
||
extractResponsesOutputText(payload?.response || payload);
|
||
|
||
export const useApiRequest = (
|
||
setMessage,
|
||
setDebugData,
|
||
setActiveDebugTab,
|
||
sseSourceRef,
|
||
saveMessages,
|
||
onConversationIdReceived,
|
||
onUserMessageIdReceived,
|
||
) => {
|
||
const { t } = useTranslation();
|
||
|
||
// 处理消息自动关闭逻辑的公共函数
|
||
const applyAutoCollapseLogic = useCallback(
|
||
(message, isThinkingComplete = true) => {
|
||
const shouldAutoCollapse =
|
||
isThinkingComplete && !message.hasAutoCollapsed;
|
||
return {
|
||
isThinkingComplete,
|
||
hasAutoCollapsed: shouldAutoCollapse || message.hasAutoCollapsed,
|
||
isReasoningExpanded: shouldAutoCollapse
|
||
? false
|
||
: message.isReasoningExpanded,
|
||
};
|
||
},
|
||
[],
|
||
);
|
||
|
||
// 流式消息更新
|
||
const streamMessageUpdate = useCallback(
|
||
(textChunk, type) => {
|
||
setMessage((prevMessage) => {
|
||
const lastMessage = prevMessage[prevMessage.length - 1];
|
||
if (!lastMessage) return prevMessage;
|
||
if (lastMessage.role !== 'assistant') return prevMessage;
|
||
if (lastMessage.status === MESSAGE_STATUS.ERROR) {
|
||
return prevMessage;
|
||
}
|
||
|
||
if (
|
||
lastMessage.status === MESSAGE_STATUS.LOADING ||
|
||
lastMessage.status === MESSAGE_STATUS.INCOMPLETE
|
||
) {
|
||
let newMessage = { ...lastMessage };
|
||
|
||
if (type === 'reasoning') {
|
||
newMessage = {
|
||
...newMessage,
|
||
reasoningContent:
|
||
(lastMessage.reasoningContent || '') + textChunk,
|
||
status: MESSAGE_STATUS.INCOMPLETE,
|
||
isThinkingComplete: false,
|
||
};
|
||
} else if (type === 'content') {
|
||
const newContent = (lastMessage.content || '') + textChunk;
|
||
|
||
let thinkingCompleteFromTags = lastMessage.isThinkingComplete;
|
||
|
||
if (
|
||
lastMessage.isReasoningExpanded &&
|
||
newContent.includes('</think>')
|
||
) {
|
||
const thinkMatches = newContent.match(/<think>/g);
|
||
const thinkCloseMatches = newContent.match(/<\/think>/g);
|
||
if (
|
||
thinkMatches &&
|
||
thinkCloseMatches &&
|
||
thinkCloseMatches.length >= thinkMatches.length
|
||
) {
|
||
thinkingCompleteFromTags = true; // think标签闭合也标记思考完成
|
||
}
|
||
}
|
||
|
||
// 如果开始接收content内容,且之前有reasoning内容,或者think标签已闭合,则标记思考完成
|
||
const isThinkingComplete =
|
||
(lastMessage.reasoningContent &&
|
||
!lastMessage.isThinkingComplete) ||
|
||
thinkingCompleteFromTags;
|
||
|
||
const autoCollapseState = applyAutoCollapseLogic(
|
||
lastMessage,
|
||
isThinkingComplete,
|
||
);
|
||
|
||
newMessage = {
|
||
...newMessage,
|
||
content: newContent,
|
||
status: MESSAGE_STATUS.INCOMPLETE,
|
||
...autoCollapseState,
|
||
};
|
||
}
|
||
|
||
return [...prevMessage.slice(0, -1), newMessage];
|
||
}
|
||
|
||
return prevMessage;
|
||
});
|
||
},
|
||
[setMessage, applyAutoCollapseLogic],
|
||
);
|
||
|
||
// 完成消息
|
||
const completeMessage = useCallback(
|
||
(status = MESSAGE_STATUS.COMPLETE) => {
|
||
// 保存副作用放 updater 外(StrictMode 下 updater 会执行两次),结果用 let 捕获
|
||
let capturedUpdated = null;
|
||
setMessage((prevMessage) => {
|
||
const lastMessage = prevMessage[prevMessage.length - 1];
|
||
// 列表可能已被清空(清空对话 / 切换会话),此时没有可完成的消息
|
||
if (!lastMessage) return prevMessage;
|
||
if (
|
||
lastMessage.status === MESSAGE_STATUS.COMPLETE ||
|
||
lastMessage.status === MESSAGE_STATUS.ERROR
|
||
) {
|
||
return prevMessage;
|
||
}
|
||
|
||
const autoCollapseState = applyAutoCollapseLogic(lastMessage, true);
|
||
|
||
const updatedMessages = [
|
||
...prevMessage.slice(0, -1),
|
||
{
|
||
...lastMessage,
|
||
status: status,
|
||
...autoCollapseState,
|
||
},
|
||
];
|
||
|
||
capturedUpdated = updatedMessages;
|
||
return updatedMessages;
|
||
});
|
||
|
||
// 在消息完成时保存,传入更新后的消息列表
|
||
if (
|
||
status === MESSAGE_STATUS.COMPLETE ||
|
||
status === MESSAGE_STATUS.ERROR
|
||
) {
|
||
setTimeout(() => {
|
||
if (capturedUpdated) saveMessages(capturedUpdated);
|
||
}, 0);
|
||
}
|
||
},
|
||
[setMessage, applyAutoCollapseLogic, saveMessages],
|
||
);
|
||
|
||
// 非流式请求
|
||
const handleNonStreamRequest = useCallback(
|
||
async (payload) => {
|
||
setDebugData((prev) => ({
|
||
...prev,
|
||
request: payload,
|
||
timestamp: new Date().toISOString(),
|
||
response: null,
|
||
sseMessages: null, // 非流式请求清除 SSE 消息
|
||
isStreaming: false,
|
||
}));
|
||
setActiveDebugTab(DEBUG_TABS.REQUEST);
|
||
|
||
// 看门狗:非流式 fetch 默认无超时,服务端挂住会让用户对着空白等。
|
||
// 这里直接给 AbortController + setTimeout 兜底,到时主动 abort。
|
||
const abortCtl = new AbortController();
|
||
const watchdogId = setTimeout(() => {
|
||
try {
|
||
abortCtl.abort();
|
||
} catch (_) {
|
||
/* ignore */
|
||
}
|
||
}, STREAM_WATCHDOG_MS);
|
||
|
||
try {
|
||
const response = await fetch(API_ENDPOINTS.CHAT_COMPLETIONS, {
|
||
method: 'POST',
|
||
headers: {
|
||
'Content-Type': 'application/json',
|
||
'New-Api-User': getUserIdFromLocalStorage(),
|
||
},
|
||
credentials: getServerURL() ? 'include' : 'same-origin',
|
||
body: JSON.stringify(payload),
|
||
signal: abortCtl.signal,
|
||
});
|
||
|
||
notifyWebSearchStatus((name) => response.headers.get(name), t);
|
||
// 挂"参考来源"到当前 loading 助手消息上 —— 即便流式还没到第一字节,UI 也能立刻看到
|
||
attachWebSearchSourcesToLastAssistant(
|
||
setMessage,
|
||
extractWebSearchSources((name) => response.headers.get(name)),
|
||
);
|
||
|
||
// 体验中心:从响应头读取会话 ID(首次发送时后端会自动建会话)
|
||
try {
|
||
const convIdHeader = response.headers.get(
|
||
'X-Playground-Conversation-Id',
|
||
);
|
||
if (convIdHeader && onConversationIdReceived) {
|
||
const convId = parseInt(convIdHeader, 10);
|
||
if (!Number.isNaN(convId)) onConversationIdReceived(convId);
|
||
}
|
||
const userMsgIdHeader = response.headers.get(
|
||
'X-Playground-User-Message-Id',
|
||
);
|
||
if (userMsgIdHeader && onUserMessageIdReceived) {
|
||
const userMsgId = parseInt(userMsgIdHeader, 10);
|
||
if (!Number.isNaN(userMsgId)) onUserMessageIdReceived(userMsgId);
|
||
}
|
||
} catch (_) {
|
||
// 忽略
|
||
}
|
||
|
||
if (!response.ok) {
|
||
let errorBody = '';
|
||
try {
|
||
errorBody = await response.text();
|
||
} catch (e) {
|
||
errorBody = '无法读取错误响应体';
|
||
}
|
||
|
||
const errorInfo = handleApiError(
|
||
new Error(
|
||
`HTTP error! status: ${response.status}, body: ${errorBody}`,
|
||
),
|
||
response,
|
||
);
|
||
|
||
setDebugData((prev) => ({
|
||
...prev,
|
||
response: JSON.stringify(errorInfo, null, 2),
|
||
}));
|
||
setActiveDebugTab(DEBUG_TABS.RESPONSE);
|
||
|
||
// 提取上游/适配器的人类可读 message(OpenAI 兼容 `{"error":{"message"}}` 等格式)。
|
||
// 找不到时退回通用文案 + HTTP 状态码,而不是直接展示原始 JSON body —
|
||
// 那会让用户看到一坨看不懂的字符串
|
||
const friendly = extractErrorMessage(errorBody);
|
||
const userMessage = friendly || t('上游返回了未识别的错误响应');
|
||
throw new Error(`HTTP ${response.status}: ${userMessage}`);
|
||
}
|
||
|
||
const data = await response.json();
|
||
|
||
setDebugData((prev) => ({
|
||
...prev,
|
||
response: JSON.stringify(data, null, 2),
|
||
}));
|
||
setActiveDebugTab(DEBUG_TABS.RESPONSE);
|
||
|
||
if (data.choices?.[0]) {
|
||
const choice = data.choices[0];
|
||
let content = choice.message?.content || '';
|
||
let reasoningContent =
|
||
choice.message?.reasoning_content ||
|
||
choice.message?.reasoning ||
|
||
'';
|
||
|
||
const processed = processThinkTags(content, reasoningContent);
|
||
|
||
setMessage((prevMessage) => {
|
||
const newMessages = [...prevMessage];
|
||
const lastMessage = newMessages[newMessages.length - 1];
|
||
if (lastMessage?.status === MESSAGE_STATUS.LOADING) {
|
||
const autoCollapseState = applyAutoCollapseLogic(
|
||
lastMessage,
|
||
true,
|
||
);
|
||
|
||
newMessages[newMessages.length - 1] = {
|
||
...lastMessage,
|
||
content: processed.content,
|
||
reasoningContent: processed.reasoningContent,
|
||
status: MESSAGE_STATUS.COMPLETE,
|
||
finishReason: choice.finish_reason,
|
||
...autoCollapseState,
|
||
};
|
||
}
|
||
return newMessages;
|
||
});
|
||
} else if (isResponsesPayload(data)) {
|
||
const content = extractResponsesOutputText(data);
|
||
const processed = processThinkTags(content, '');
|
||
|
||
setMessage((prevMessage) => {
|
||
const newMessages = [...prevMessage];
|
||
const lastMessage = newMessages[newMessages.length - 1];
|
||
if (lastMessage?.status === MESSAGE_STATUS.LOADING) {
|
||
const autoCollapseState = applyAutoCollapseLogic(
|
||
lastMessage,
|
||
true,
|
||
);
|
||
|
||
newMessages[newMessages.length - 1] = {
|
||
...lastMessage,
|
||
content: processed.content,
|
||
reasoningContent: processed.reasoningContent,
|
||
status: MESSAGE_STATUS.COMPLETE,
|
||
...autoCollapseState,
|
||
};
|
||
}
|
||
return newMessages;
|
||
});
|
||
} else {
|
||
// HTTP 200 但响应既不是 chat completions 也不是 Responses 格式:
|
||
// 必须把 loading 消息置为错误态。否则它永远停在 loading,
|
||
// onMessageSend 的"生成中防重发"检查会从此拦住一切后续发送。
|
||
setMessage((prevMessage) => {
|
||
const newMessages = [...prevMessage];
|
||
const lastMessage = newMessages[newMessages.length - 1];
|
||
if (lastMessage?.status === MESSAGE_STATUS.LOADING) {
|
||
newMessages[newMessages.length - 1] = {
|
||
...lastMessage,
|
||
content: t('上游返回了无法识别的响应格式'),
|
||
status: MESSAGE_STATUS.ERROR,
|
||
...applyAutoCollapseLogic(lastMessage, true),
|
||
};
|
||
}
|
||
return newMessages;
|
||
});
|
||
}
|
||
} catch (error) {
|
||
console.error('Non-stream request error:', error);
|
||
|
||
// 看门狗触发的 abort:换更清晰的错误消息,避免出现 "AbortError" 之类的术语
|
||
const isWatchdogAbort =
|
||
error?.name === 'AbortError' && abortCtl.signal.aborted;
|
||
const friendlyMessage = isWatchdogAbort
|
||
? t('服务器长时间未响应,请求已自动中止,请重试')
|
||
: t('请求发生错误: ') + (error?.message || '');
|
||
|
||
const errorInfo = handleApiError(error);
|
||
setDebugData((prev) => ({
|
||
...prev,
|
||
response: JSON.stringify(errorInfo, null, 2),
|
||
}));
|
||
setActiveDebugTab(DEBUG_TABS.RESPONSE);
|
||
|
||
if (isWatchdogAbort) {
|
||
Toast.warning({ content: friendlyMessage, duration: 4 });
|
||
}
|
||
|
||
setMessage((prevMessage) => {
|
||
const newMessages = [...prevMessage];
|
||
const lastMessage = newMessages[newMessages.length - 1];
|
||
if (lastMessage?.status === MESSAGE_STATUS.LOADING) {
|
||
const autoCollapseState = applyAutoCollapseLogic(lastMessage, true);
|
||
|
||
newMessages[newMessages.length - 1] = {
|
||
...lastMessage,
|
||
content: friendlyMessage,
|
||
status: MESSAGE_STATUS.ERROR,
|
||
...autoCollapseState,
|
||
};
|
||
}
|
||
return newMessages;
|
||
});
|
||
} finally {
|
||
clearTimeout(watchdogId);
|
||
}
|
||
},
|
||
[
|
||
setDebugData,
|
||
setActiveDebugTab,
|
||
setMessage,
|
||
t,
|
||
applyAutoCollapseLogic,
|
||
onConversationIdReceived,
|
||
onUserMessageIdReceived,
|
||
],
|
||
);
|
||
|
||
// SSE请求
|
||
const handleSSE = useCallback(
|
||
(payload) => {
|
||
setDebugData((prev) => ({
|
||
...prev,
|
||
request: payload,
|
||
timestamp: new Date().toISOString(),
|
||
response: null,
|
||
sseMessages: [], // 新增:存储 SSE 消息数组
|
||
isStreaming: true, // 新增:标记流式状态
|
||
}));
|
||
setActiveDebugTab(DEBUG_TABS.REQUEST);
|
||
|
||
const source = new SSE(API_ENDPOINTS.CHAT_COMPLETIONS, {
|
||
headers: {
|
||
'Content-Type': 'application/json',
|
||
'New-Api-User': getUserIdFromLocalStorage(),
|
||
},
|
||
method: 'POST',
|
||
payload: JSON.stringify(payload),
|
||
withCredentials: getServerURL() !== '',
|
||
});
|
||
|
||
sseSourceRef.current = source;
|
||
|
||
let responseData = '';
|
||
let responsesStreamText = '';
|
||
let hasReceivedFirstResponse = false;
|
||
let isStreamComplete = false; // 添加标志位跟踪流是否正常完成
|
||
let webSearchHeadersNotified = false; // SSE 仅在 HEADERS_RECEIVED 后读取一次
|
||
|
||
// ─── 看门狗 ─────────────────────────────────────────────────────────
|
||
// 任何 SSE 事件到达都 feed 一次,让计时复位;STREAM_WATCHDOG_MS 内没动静就强制超时。
|
||
// 已经 isStreamComplete 之后不再 feed(避免完成态再被狗咬一口)。
|
||
let watchdogTimer = null;
|
||
const clearWatchdog = () => {
|
||
if (watchdogTimer) {
|
||
clearTimeout(watchdogTimer);
|
||
watchdogTimer = null;
|
||
}
|
||
};
|
||
const feedWatchdog = () => {
|
||
if (isStreamComplete) return;
|
||
clearWatchdog();
|
||
watchdogTimer = setTimeout(() => {
|
||
// 守卫:用户手动停止 / 已有新请求把 ref 顶掉 / 流已完成 —— 都直接放过
|
||
if (isStreamComplete) return;
|
||
if (sseSourceRef.current !== source) return;
|
||
isStreamComplete = true;
|
||
console.warn(
|
||
`SSE watchdog: no data for ${STREAM_WATCHDOG_MS}ms, aborting`,
|
||
);
|
||
try {
|
||
source.close();
|
||
} catch (_) {
|
||
/* ignore */
|
||
}
|
||
sseSourceRef.current = null;
|
||
setDebugData((prev) => ({
|
||
...prev,
|
||
response:
|
||
responseData +
|
||
`\n\n[watchdog] no SSE activity for ${STREAM_WATCHDOG_MS}ms`,
|
||
isStreaming: false,
|
||
}));
|
||
setActiveDebugTab(DEBUG_TABS.RESPONSE);
|
||
// 把当前 loading 助手消息切成错误态,附上提示而不是让用户对着空气干等
|
||
streamMessageUpdate(
|
||
t('服务器长时间未响应,请求已自动中止,请重试'),
|
||
'content',
|
||
);
|
||
completeMessage(MESSAGE_STATUS.ERROR);
|
||
Toast.warning({
|
||
content: t('服务器长时间未响应,请求已自动中止,请重试'),
|
||
duration: 4,
|
||
});
|
||
}, STREAM_WATCHDOG_MS);
|
||
};
|
||
feedWatchdog();
|
||
|
||
source.addEventListener('message', (e) => {
|
||
feedWatchdog();
|
||
if (e.data === '[DONE]') {
|
||
isStreamComplete = true; // 标记流正常完成
|
||
clearWatchdog();
|
||
source.close();
|
||
sseSourceRef.current = null;
|
||
setDebugData((prev) => ({
|
||
...prev,
|
||
response: responseData,
|
||
sseMessages: [...(prev.sseMessages || []), '[DONE]'], // 添加 DONE 标记
|
||
isStreaming: false,
|
||
}));
|
||
completeMessage();
|
||
return;
|
||
}
|
||
|
||
try {
|
||
const payload = JSON.parse(e.data);
|
||
responseData += e.data + '\n';
|
||
|
||
if (!hasReceivedFirstResponse) {
|
||
setActiveDebugTab(DEBUG_TABS.RESPONSE);
|
||
hasReceivedFirstResponse = true;
|
||
}
|
||
|
||
// 新增:将 SSE 消息添加到数组
|
||
setDebugData((prev) => ({
|
||
...prev,
|
||
sseMessages: [...(prev.sseMessages || []), e.data],
|
||
}));
|
||
|
||
// 追踪 finish_reason —— 'length' 时前端会显示"继续生成"按钮,让用户一键续写
|
||
const finishReason = payload.choices?.[0]?.finish_reason;
|
||
if (finishReason) {
|
||
setMessage((prev) => {
|
||
if (!prev || prev.length === 0) return prev;
|
||
const last = prev[prev.length - 1];
|
||
if (!last || last.role !== 'assistant') return prev;
|
||
return [...prev.slice(0, -1), { ...last, finishReason }];
|
||
});
|
||
}
|
||
|
||
const delta = payload.choices?.[0]?.delta;
|
||
if (delta) {
|
||
if (delta.reasoning_content) {
|
||
streamMessageUpdate(delta.reasoning_content, 'reasoning');
|
||
}
|
||
if (delta.reasoning) {
|
||
streamMessageUpdate(delta.reasoning, 'reasoning');
|
||
}
|
||
if (delta.content) {
|
||
streamMessageUpdate(delta.content, 'content');
|
||
}
|
||
}
|
||
} catch (error) {
|
||
console.error('Failed to parse SSE message:', error);
|
||
const errorInfo = `解析错误: ${error.message}`;
|
||
|
||
setDebugData((prev) => ({
|
||
...prev,
|
||
response: responseData + `\n\nError: ${errorInfo}`,
|
||
sseMessages: [...(prev.sseMessages || []), e.data], // 即使解析失败也保存原始数据
|
||
isStreaming: false,
|
||
}));
|
||
setActiveDebugTab(DEBUG_TABS.RESPONSE);
|
||
|
||
streamMessageUpdate(t('解析响应数据时发生错误'), 'content');
|
||
completeMessage(MESSAGE_STATUS.ERROR);
|
||
}
|
||
});
|
||
|
||
source.addEventListener('response.output_text.delta', (e) => {
|
||
feedWatchdog();
|
||
try {
|
||
const payload = JSON.parse(e.data);
|
||
responseData += e.data + '\n';
|
||
|
||
if (!hasReceivedFirstResponse) {
|
||
setActiveDebugTab(DEBUG_TABS.RESPONSE);
|
||
hasReceivedFirstResponse = true;
|
||
}
|
||
|
||
setDebugData((prev) => ({
|
||
...prev,
|
||
sseMessages: [...(prev.sseMessages || []), e.data],
|
||
}));
|
||
|
||
if (payload.delta) {
|
||
responsesStreamText += payload.delta;
|
||
streamMessageUpdate(payload.delta, 'content');
|
||
}
|
||
} catch (error) {
|
||
console.error('Failed to parse Responses stream delta:', error);
|
||
}
|
||
});
|
||
|
||
source.addEventListener('response.reasoning_summary_text.delta', (e) => {
|
||
feedWatchdog();
|
||
try {
|
||
const payload = JSON.parse(e.data);
|
||
responseData += e.data + '\n';
|
||
|
||
setDebugData((prev) => ({
|
||
...prev,
|
||
sseMessages: [...(prev.sseMessages || []), e.data],
|
||
}));
|
||
|
||
if (payload.delta) {
|
||
streamMessageUpdate(payload.delta, 'reasoning');
|
||
}
|
||
} catch (error) {
|
||
console.error('Failed to parse Responses reasoning delta:', error);
|
||
}
|
||
});
|
||
|
||
source.addEventListener('response.completed', (e) => {
|
||
clearWatchdog();
|
||
responseData += e.data + '\n';
|
||
isStreamComplete = true;
|
||
|
||
try {
|
||
const payload = JSON.parse(e.data);
|
||
const finalText = extractResponsesStreamText(payload);
|
||
if (!responsesStreamText && finalText) {
|
||
responsesStreamText = finalText;
|
||
streamMessageUpdate(finalText, 'content');
|
||
}
|
||
} catch (error) {
|
||
console.error('Failed to parse Responses completed event:', error);
|
||
}
|
||
|
||
setDebugData((prev) => ({
|
||
...prev,
|
||
response: responseData,
|
||
sseMessages: [...(prev.sseMessages || []), e.data, '[DONE]'],
|
||
isStreaming: false,
|
||
}));
|
||
setActiveDebugTab(DEBUG_TABS.RESPONSE);
|
||
|
||
completeMessage();
|
||
sseSourceRef.current = null;
|
||
source.close();
|
||
});
|
||
|
||
const handleResponsesTerminalError = (e) => {
|
||
clearWatchdog();
|
||
const errorMessage = e.data || t('请求发生错误');
|
||
responseData += errorMessage + '\n';
|
||
isStreamComplete = true;
|
||
|
||
setDebugData((prev) => ({
|
||
...prev,
|
||
response: responseData,
|
||
sseMessages: [...(prev.sseMessages || []), errorMessage],
|
||
isStreaming: false,
|
||
}));
|
||
setActiveDebugTab(DEBUG_TABS.RESPONSE);
|
||
|
||
streamMessageUpdate(errorMessage, 'content');
|
||
completeMessage(MESSAGE_STATUS.ERROR);
|
||
sseSourceRef.current = null;
|
||
source.close();
|
||
};
|
||
|
||
source.addEventListener('response.failed', handleResponsesTerminalError);
|
||
source.addEventListener(
|
||
'response.incomplete',
|
||
handleResponsesTerminalError,
|
||
);
|
||
|
||
// 用户手动停止(onStopGenerator → source.close() → xhr.abort()):
|
||
// 消息收尾由 onStopGenerator 负责,这里只标记完结,
|
||
// 防止随后的 readystatechange(CLOSED) 走"意外断流"分支覆盖成错误态
|
||
source.addEventListener('abort', () => {
|
||
isStreamComplete = true;
|
||
clearWatchdog();
|
||
});
|
||
|
||
source.addEventListener('error', (e) => {
|
||
clearWatchdog();
|
||
// 只有在流没有正常完成且连接状态异常时才处理错误
|
||
if (!isStreamComplete && source.readyState !== 2) {
|
||
// 标记完结:错误已在此处理,随后的 readystatechange(CLOSED) 不应再收尾一次
|
||
isStreamComplete = true;
|
||
console.error('SSE Error:', e);
|
||
// e.data 通常是上游或后端返回的原始错误 body(OpenAI 兼容 JSON / 文本)。
|
||
// 用 extractErrorMessage 把人类可读的 message 挖出来,否则用户在气泡里看到的
|
||
// 是一长串 JSON 字符串
|
||
const rawErrorBody = e.data || '';
|
||
const friendly =
|
||
extractErrorMessage(rawErrorBody) || t('请求发生错误');
|
||
|
||
const errorInfo = handleApiError(new Error(friendly));
|
||
errorInfo.readyState = source.readyState;
|
||
|
||
setDebugData((prev) => ({
|
||
...prev,
|
||
response:
|
||
responseData +
|
||
'\n\nSSE Error:\n' +
|
||
JSON.stringify(errorInfo, null, 2),
|
||
}));
|
||
setActiveDebugTab(DEBUG_TABS.RESPONSE);
|
||
|
||
streamMessageUpdate(friendly, 'content');
|
||
completeMessage(MESSAGE_STATUS.ERROR);
|
||
sseSourceRef.current = null;
|
||
source.close();
|
||
}
|
||
});
|
||
|
||
source.addEventListener('readystatechange', (e) => {
|
||
feedWatchdog();
|
||
// 一旦收到响应头就尝试读取联网搜索状态(sse.js 内部 xhr 暴露在 source.xhr)
|
||
// sse.js 使用 EventSource 风格的 readyState:CONNECTING=0, OPEN=1, CLOSED=2
|
||
// 当 readyState=1(OPEN) 时 headers 已可读且 source.xhr 仍存在;
|
||
// readyState=2(CLOSED) 时 source.xhr 已被置 null,无法再读取 header。
|
||
if (!webSearchHeadersNotified && e.readyState >= 1 && source.xhr) {
|
||
webSearchHeadersNotified = true;
|
||
try {
|
||
notifyWebSearchStatus(
|
||
(name) => source.xhr.getResponseHeader(name),
|
||
t,
|
||
);
|
||
attachWebSearchSourcesToLastAssistant(
|
||
setMessage,
|
||
extractWebSearchSources((name) =>
|
||
source.xhr.getResponseHeader(name),
|
||
),
|
||
);
|
||
// 体验中心:读取会话 ID
|
||
const convIdHeader = source.xhr.getResponseHeader(
|
||
'X-Playground-Conversation-Id',
|
||
);
|
||
if (convIdHeader && onConversationIdReceived) {
|
||
const convId = parseInt(convIdHeader, 10);
|
||
if (!Number.isNaN(convId)) onConversationIdReceived(convId);
|
||
}
|
||
// 体验中心:读取本次发送对应的 user 消息 ID(用于前端同步 backendId,
|
||
// 让重生成/编辑后重发能正确清理后端,避免 DB 累积重复消息)
|
||
const userMsgIdHeader = source.xhr.getResponseHeader(
|
||
'X-Playground-User-Message-Id',
|
||
);
|
||
if (userMsgIdHeader && onUserMessageIdReceived) {
|
||
const userMsgId = parseInt(userMsgIdHeader, 10);
|
||
if (!Number.isNaN(userMsgId)) onUserMessageIdReceived(userMsgId);
|
||
}
|
||
} catch (_) {
|
||
// 读取失败不影响主流程
|
||
}
|
||
}
|
||
|
||
// 检查 HTTP 状态错误,但避免与正常关闭重复处理
|
||
if (
|
||
e.readyState >= 2 &&
|
||
source.status !== undefined &&
|
||
source.status !== 200 &&
|
||
!isStreamComplete
|
||
) {
|
||
clearWatchdog();
|
||
// 标记完结 + 释放 ref:不标记的话后续 error 事件还可能重复走错误处理;
|
||
// ref 不清会让 onStopGenerator 去 close 一个已关闭的连接
|
||
isStreamComplete = true;
|
||
if (sseSourceRef.current === source) {
|
||
sseSourceRef.current = null;
|
||
}
|
||
const errorInfo = handleApiError(new Error(t('HTTP状态错误')));
|
||
errorInfo.status = source.status;
|
||
errorInfo.readyState = source.readyState;
|
||
|
||
setDebugData((prev) => ({
|
||
...prev,
|
||
response:
|
||
responseData +
|
||
'\n\nHTTP Error:\n' +
|
||
JSON.stringify(errorInfo, null, 2),
|
||
}));
|
||
setActiveDebugTab(DEBUG_TABS.RESPONSE);
|
||
|
||
source.close();
|
||
streamMessageUpdate(t('连接已断开'), 'content');
|
||
completeMessage(MESSAGE_STATUS.ERROR);
|
||
return;
|
||
}
|
||
|
||
// 流被服务端"正常"关闭(HTTP 2xx、xhr load 完成)但始终没等到
|
||
// [DONE] / finish_reason / response.completed(上游异常掐断流):
|
||
// 立即收尾,不再让用户对着 loading 干等 120s 看门狗。
|
||
// 已收到的内容按 COMPLETE 保留(与手动停止的语义一致,后端 finalize
|
||
// 会独立判定 interrupted);一个字都没收到则置错误态提示重试。
|
||
// 用户手动停止(abort)与上游错误(error)都已先置 isStreamComplete,不会进来。
|
||
if (e.readyState >= 2 && !isStreamComplete) {
|
||
isStreamComplete = true;
|
||
clearWatchdog();
|
||
if (sseSourceRef.current === source) {
|
||
sseSourceRef.current = null;
|
||
}
|
||
setDebugData((prev) => ({
|
||
...prev,
|
||
response:
|
||
responseData + '\n\n[closed] stream ended without done marker',
|
||
isStreaming: false,
|
||
}));
|
||
if (hasReceivedFirstResponse) {
|
||
completeMessage();
|
||
} else {
|
||
streamMessageUpdate(
|
||
t('连接意外中断,未收到任何内容,请重试'),
|
||
'content',
|
||
);
|
||
completeMessage(MESSAGE_STATUS.ERROR);
|
||
}
|
||
}
|
||
});
|
||
|
||
try {
|
||
source.stream();
|
||
} catch (error) {
|
||
console.error('Failed to start SSE stream:', error);
|
||
const errorInfo = handleApiError(error);
|
||
|
||
setDebugData((prev) => ({
|
||
...prev,
|
||
response: 'Stream启动失败:\n' + JSON.stringify(errorInfo, null, 2),
|
||
}));
|
||
setActiveDebugTab(DEBUG_TABS.RESPONSE);
|
||
|
||
streamMessageUpdate(t('建立连接时发生错误'), 'content');
|
||
completeMessage(MESSAGE_STATUS.ERROR);
|
||
}
|
||
},
|
||
[
|
||
setDebugData,
|
||
setActiveDebugTab,
|
||
streamMessageUpdate,
|
||
completeMessage,
|
||
t,
|
||
applyAutoCollapseLogic,
|
||
onConversationIdReceived,
|
||
onUserMessageIdReceived,
|
||
],
|
||
);
|
||
|
||
// 停止生成
|
||
const onStopGenerator = useCallback(() => {
|
||
// 如果仍有活动的 SSE 连接,首先关闭
|
||
if (sseSourceRef.current) {
|
||
sseSourceRef.current.close();
|
||
sseSourceRef.current = null;
|
||
}
|
||
|
||
// 无论是否存在 SSE 连接,都尝试处理最后一条正在生成的消息
|
||
// 保存副作用放 updater 外(StrictMode 下 updater 会执行两次),结果用 let 捕获
|
||
let capturedUpdated = null;
|
||
setMessage((prevMessage) => {
|
||
if (prevMessage.length === 0) return prevMessage;
|
||
const lastMessage = prevMessage[prevMessage.length - 1];
|
||
|
||
if (
|
||
lastMessage.status === MESSAGE_STATUS.LOADING ||
|
||
lastMessage.status === MESSAGE_STATUS.INCOMPLETE
|
||
) {
|
||
const processed = processIncompleteThinkTags(
|
||
lastMessage.content || '',
|
||
lastMessage.reasoningContent || '',
|
||
);
|
||
|
||
const autoCollapseState = applyAutoCollapseLogic(lastMessage, true);
|
||
|
||
const updatedMessages = [
|
||
...prevMessage.slice(0, -1),
|
||
{
|
||
...lastMessage,
|
||
status: MESSAGE_STATUS.COMPLETE,
|
||
reasoningContent: processed.reasoningContent || null,
|
||
content: processed.content,
|
||
...autoCollapseState,
|
||
},
|
||
];
|
||
|
||
capturedUpdated = updatedMessages;
|
||
return updatedMessages;
|
||
}
|
||
return prevMessage;
|
||
});
|
||
|
||
// 停止生成时也保存,传入更新后的消息列表
|
||
setTimeout(() => {
|
||
if (capturedUpdated) saveMessages(capturedUpdated);
|
||
}, 0);
|
||
}, [setMessage, applyAutoCollapseLogic, saveMessages]);
|
||
|
||
// 发送请求
|
||
const sendRequest = useCallback(
|
||
(payload, isStream) => {
|
||
if (isStream) {
|
||
handleSSE(payload);
|
||
} else {
|
||
handleNonStreamRequest(payload);
|
||
}
|
||
},
|
||
[handleSSE, handleNonStreamRequest],
|
||
);
|
||
|
||
return {
|
||
sendRequest,
|
||
onStopGenerator,
|
||
streamMessageUpdate,
|
||
completeMessage,
|
||
};
|
||
};
|