Initial import of weiyuan frontend

This commit is contained in:
qiubaishen
2026-10-15 16:33:46 +08:00
commit d8f3aee261
774 changed files with 374914 additions and 0 deletions
+82
View File
@@ -0,0 +1,82 @@
/*
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
*/
export const shouldRequireExplicitSession = ({
sessionEnabled = false,
activeSessionId = null,
} = {}) => Boolean(sessionEnabled && !activeSessionId);
export const shouldCreateDefaultSession = (sessions) =>
Array.isArray(sessions) && sessions.length === 0;
export const prependCreatedSession = (sessions = [], createdSession) => {
if (!createdSession?.id) {
return Array.isArray(sessions) ? [...sessions] : [];
}
const list = Array.isArray(sessions) ? sessions : [];
return [
createdSession,
...list.filter((session) => session.id !== createdSession.id),
];
};
export const removeSessionAndResolveNext = ({
sessions = [],
deletedSessionId = null,
activeSessionId = null,
} = {}) => {
const list = Array.isArray(sessions) ? sessions : [];
const remainingSessions = list.filter(
(session) => session.id !== deletedSessionId,
);
const deletedActiveSession = deletedSessionId === activeSessionId;
return {
remainingSessions,
deletedActiveSession,
nextActiveSessionId: deletedActiveSession
? (remainingSessions[0]?.id ?? null)
: activeSessionId,
};
};
export const bindConversationIdToPayload = (
payload,
{ sessionEnabled = false, activeSessionId = null, force = false } = {},
) => {
if (
!sessionEnabled ||
!activeSessionId ||
!payload ||
typeof payload !== 'object' ||
Array.isArray(payload)
) {
return payload;
}
if (!force && payload.conversation_id != null) {
return payload;
}
return {
...payload,
conversation_id: activeSessionId,
};
};
+126
View File
@@ -0,0 +1,126 @@
/*
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 test from 'node:test';
import assert from 'node:assert/strict';
import {
bindConversationIdToPayload,
prependCreatedSession,
removeSessionAndResolveNext,
shouldCreateDefaultSession,
shouldRequireExplicitSession,
} from './sessionFlow.js';
test('shouldRequireExplicitSession blocks sends only when session mode is enabled without a selection', () => {
assert.equal(
shouldRequireExplicitSession({
sessionEnabled: true,
activeSessionId: null,
}),
true,
);
assert.equal(
shouldRequireExplicitSession({ sessionEnabled: true, activeSessionId: 42 }),
false,
);
assert.equal(
shouldRequireExplicitSession({
sessionEnabled: false,
activeSessionId: null,
}),
false,
);
});
test('shouldCreateDefaultSession only creates after a successful empty list response', () => {
assert.equal(shouldCreateDefaultSession([]), true);
assert.equal(shouldCreateDefaultSession([{ id: 1 }]), false);
assert.equal(shouldCreateDefaultSession(null), false);
assert.equal(shouldCreateDefaultSession(undefined), false);
});
test('prependCreatedSession keeps the new session at the top without duplicates', () => {
const created = { id: 3, title: 'New' };
const sessions = [
{ id: 1, title: 'First' },
{ id: 3, title: 'Stale copy' },
{ id: 2, title: 'Second' },
];
assert.deepEqual(prependCreatedSession(sessions, created), [
{ id: 3, title: 'New' },
{ id: 1, title: 'First' },
{ id: 2, title: 'Second' },
]);
});
test('removeSessionAndResolveNext clears the active selection instead of creating a replacement session', () => {
const result = removeSessionAndResolveNext({
sessions: [{ id: 9, title: 'Only one' }],
deletedSessionId: 9,
activeSessionId: 9,
});
assert.deepEqual(result.remainingSessions, []);
assert.equal(result.deletedActiveSession, true);
assert.equal(result.nextActiveSessionId, null);
});
test('removeSessionAndResolveNext switches to the first remaining session after deleting the active one', () => {
const result = removeSessionAndResolveNext({
sessions: [
{ id: 4, title: 'Active' },
{ id: 5, title: 'Next' },
{ id: 6, title: 'Later' },
],
deletedSessionId: 4,
activeSessionId: 4,
});
assert.deepEqual(result.remainingSessions, [
{ id: 5, title: 'Next' },
{ id: 6, title: 'Later' },
]);
assert.equal(result.nextActiveSessionId, 5);
});
test('bindConversationIdToPayload always follows the active session in explicit-session mode when forced', () => {
const payload = bindConversationIdToPayload(
{ stream: true, conversation_id: 7 },
{ sessionEnabled: true, activeSessionId: 12, force: true },
);
assert.deepEqual(payload, {
stream: true,
conversation_id: 12,
});
});
test('bindConversationIdToPayload preserves an existing conversation_id when force is not requested', () => {
const payload = bindConversationIdToPayload(
{ stream: true, conversation_id: 7 },
{ sessionEnabled: true, activeSessionId: 12 },
);
assert.deepEqual(payload, {
stream: true,
conversation_id: 7,
});
});
File diff suppressed because it is too large Load Diff
+136
View File
@@ -0,0 +1,136 @@
/*
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, useEffect, useRef, useState } from 'react';
/**
* useChatScroll —— 在 wrapper 内查找 Semi Chat 的滚动容器,跟踪是否在底部。
*
* 为什么不用 ScrollableContainer?
* Semi Chat 自带的滚动容器是组件内部 DOM,我们没法把它包到 ScrollableContainer 里。
* 只能拿外层 wrapperRef,向下 querySelector 找到那个 scrollable 的 inner 元素,再挂监听。
*
* 返回:
* isAtBottom (boolean) — 用户当前是否贴在底部(含 80px 容差,避免抖动)
* scrollToBottom() — 平滑滚到底部
*/
const NEAR_BOTTOM_PX = 80;
const findScrollable = (rootEl) => {
if (!rootEl) return null;
try {
const direct = rootEl.querySelector('[class*="semi-chat-container"]');
if (direct && direct.scrollHeight > direct.clientHeight) return direct;
if (direct) {
const inner = Array.from(direct.querySelectorAll('*')).find((el) => {
const cs = window.getComputedStyle(el);
return (
(cs.overflowY === 'auto' || cs.overflowY === 'scroll') &&
el.scrollHeight > el.clientHeight
);
});
if (inner) return inner;
}
} catch (_) {
// ignore
}
return null;
};
export const useChatScroll = (wrapperRef, deps = []) => {
const [isAtBottom, setIsAtBottom] = useState(true);
const containerRef = useRef(null);
const observerRef = useRef(null);
// 缓存当前的 deps 字符串,方便重定位 scroll 容器 / 重检 isAtBottom
const depsKey = deps
.map((d) => (typeof d === 'object' ? '' : String(d)))
.join('|');
const checkPosition = useCallback(() => {
const el = containerRef.current;
if (!el) return;
const fromBottom = el.scrollHeight - el.scrollTop - el.clientHeight;
setIsAtBottom(fromBottom <= NEAR_BOTTOM_PX);
}, []);
// 找滚动容器 + 装监听;容器可能在 mount 后才出现(Semi Chat 异步渲染),用 MutationObserver 兜底
useEffect(() => {
const root = wrapperRef.current;
if (!root) return undefined;
const attach = () => {
const el = findScrollable(root);
if (!el || el === containerRef.current) return;
// 旧的卸载
if (containerRef.current) {
containerRef.current.removeEventListener('scroll', checkPosition);
}
containerRef.current = el;
el.addEventListener('scroll', checkPosition, { passive: true });
checkPosition();
};
attach();
if (!observerRef.current) {
observerRef.current = new MutationObserver(() => {
// Chat 组件改 DOM 时只尝试重附加 listener;不在这里调 checkPosition ——
// 流式响应下子树每秒会有几十次 mutation,每次都读 scrollHeight/scrollTop
// 会触发 layout reflow,慢设备明显卡。scroll 事件 + deps 变化的 effect
// 已经足以维护 isAtBottom 的正确性。
attach();
});
observerRef.current.observe(root, { childList: true, subtree: true });
}
return () => {
if (containerRef.current) {
containerRef.current.removeEventListener('scroll', checkPosition);
}
if (observerRef.current) {
observerRef.current.disconnect();
observerRef.current = null;
}
containerRef.current = null;
};
// wrapperRef 是 ref,不放进 deps;其它依赖通过 depsKey 收敛
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [depsKey]);
// deps 改变时(消息列表变了/会话切了)也重测位置
useEffect(() => {
// 等下一帧,让 Chat 把新内容渲染完再判断
const id = requestAnimationFrame(checkPosition);
return () => cancelAnimationFrame(id);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [depsKey]);
const scrollToBottom = useCallback(
(opts = { behavior: 'smooth' }) => {
const el = containerRef.current || findScrollable(wrapperRef.current);
if (!el) return;
el.scrollTo({ top: el.scrollHeight, ...opts });
},
[wrapperRef],
);
return { isAtBottom, scrollToBottom };
};
export default useChatScroll;
@@ -0,0 +1,251 @@
/*
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
*/
// 体验中心长会话自动摘要:未摘要区间累积超过阈值时,把较早的对话压缩成一段摘要。
//
// 关键设计:
// - 【后台触发、不阻塞发送】:maybeSummarize 是 fire-and-forget,不增加用户发送消息的延迟。
// - 【锚点切片】:按 summarizedUpToMessageId 锚点之后的位置切片,assistant 消息没有
// backendId 也能随相邻 user 消息一起进入摘要范围(直播会话里 assistant 消息无 backendId)。
// - 摘要请求是普通 POST /pg/chat/completions,但【不带 source、不带 conversation_id】,
// 因此后端计费(用户为摘要付费,符合预期)但【不落库为对话轮次】。摘要复用当前对话模型。
// - 失败/超时一律不抛错、不打断用户;会话切换后只跳过内存 setState,PUT 仍写回原会话。
import { useCallback } from 'react';
import { Toast } from '@douyinfe/semi-ui';
import { useTranslation } from 'react-i18next';
import { API_ENDPOINTS } from '../../constants/playground.constants';
import {
getUserIdFromLocalStorage,
getExperienceCenterPositiveInt,
countRounds,
getMessagesAfterAnchor,
getMessagesBeforeWindow,
buildSummaryInstructionMessages,
} from '../../helpers';
import { getServerURL } from '../../helpers/config';
import { updateConversationSummary } from '../../services/playgroundConversation';
// 摘要请求超时,避免后台摘要请求长时间挂起
const SUMMARY_TIMEOUT_MS = 60 * 1000;
// 摘要输出的 max_tokens,摘要本身有界,显式带上让后端预扣费更准
const SUMMARY_MAX_TOKENS = 1024;
export const useConversationSummary = ({
appStatus,
apiInputs,
activeSessionId,
activeSessionIdRef,
sessionEnabled,
conversationSummary,
setConversationSummary,
summarizedUpToMessageId,
setSummarizedUpToMessageId,
summarizingRef,
summaryGenRef,
}) => {
const { t } = useTranslation();
/**
* 后台按需触发一次摘要(fire-and-forget,调用方不应 await)。
* @param {Array} currentMessages 当前完整消息数组(含刚加入、还没 backendId 的新 user 消息)
* @param {{force?: boolean}} options force=true 时绕过阈值/轮数检查,立刻对窗口外的全部历史做一次摘要;
* 用于用户在 UI 上点「重新生成摘要」时手动触发。
*/
const maybeSummarize = useCallback(
async (currentMessages, options = {}) => {
const { force = false } = options;
const threshold = getExperienceCenterPositiveInt(
appStatus,
'experience_center_summary_threshold',
'experience_center_summary_threshold',
0,
);
const maxRounds = getExperienceCenterPositiveInt(
appStatus,
'experience_center_max_history_rounds',
'experience_center_max_history_rounds',
0,
);
if (!force) {
// 摘要关闭,或阈值不大于保留轮数(误配,摘要会覆盖窗口内消息)→ 不触发
if (threshold <= 0 || threshold <= maxRounds) return;
}
// 非会话模式没有持久化载体,跳过
if (!sessionEnabled || !activeSessionId) return;
// 已有摘要任务在跑,避免并发重复摘要。
// force=true(用户手动点「重新生成」)时给一个 Toast 反馈,避免点了没反应。
if (summarizingRef.current) {
if (force) {
Toast.info({
content: t('上一次摘要任务还在进行中,请稍后再试'),
duration: 2,
});
}
return;
}
// 锚点之后的「未摘要区间」;累积轮数还没到阈值就不触发(批量摘要,不是每条都摘)。
// force=true 时锚点统一从 0 开始,覆盖完整历史,等价于「重新生成摘要」。
const anchor = force ? 0 : summarizedUpToMessageId;
const tail = getMessagesAfterAnchor(currentMessages, anchor);
if (!force && countRounds(tail) <= threshold) return;
if (force && countRounds(tail) === 0) return;
// 未摘要区间里、留出最近 maxRounds 轮之外的部分 = 本次要摘要的内容。
// 至少保留 1 轮不摘要(兜底 maxRounds=0 的退化配置,否则会把刚发的内容也摘掉)。
const toSummarize = getMessagesBeforeWindow(tail, Math.max(maxRounds, 1));
if (toSummarize.length === 0) return;
// newUpTo = toSummarize 里最后一条带 backendId 的 user 消息(user 消息一定有 backendId)。
// force=true 时基线取 0(重新生成 → 锚点应推进到 toSummarize 末尾,不和旧值比较)。
const baseline = force ? 0 : summarizedUpToMessageId || 0;
let newUpTo = baseline;
for (const m of toSummarize) {
if (m && m.role === 'user' && m.backendId && m.backendId > newUpTo) {
newUpTo = m.backendId;
}
}
if (newUpTo <= baseline) return;
summarizingRef.current = true;
const sessionIdAtStart = activeSessionId;
// 快照 generation:commit 前再次比对,若已变(清空 / 失效)则丢弃本次结果,
// 避免「用户清了摘要,几秒后旧 fetch 回来又把摘要写回」
const genAtStart = summaryGenRef?.current ?? 0;
const controller = new AbortController();
const timer = setTimeout(() => {
try {
controller.abort();
} catch (_) {
/* ignore */
}
}, SUMMARY_TIMEOUT_MS);
try {
// 透明计费提示:明确告知用户这是一次会计费的模型调用
Toast.info({
content: force
? t('正在重新生成对话摘要(一次模型调用,会产生计费)')
: t('正在后台压缩较早的对话以降低后续消耗(一次模型调用)'),
duration: 2,
});
const body = {
model: apiInputs?.model,
group: apiInputs?.group,
stream: false,
max_tokens: SUMMARY_MAX_TOKENS,
// 故意不带 source / conversation_id:计费但不落库为对话轮次。
// force=true 时不携带旧摘要,让模型基于全量历史生成全新摘要(用户重新生成的语义)。
messages: buildSummaryInstructionMessages(
toSummarize,
force ? '' : conversationSummary,
),
};
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(body),
signal: controller.signal,
});
if (!response.ok) {
console.warn('Conversation summary request failed:', response.status);
// force 模式是用户主动触发,必须给可见反馈
if (force) {
Toast.error({
content: t('重新生成摘要失败:上游返回 {{status}}', {
status: response.status,
}),
duration: 3,
});
}
return;
}
const data = await response.json();
const newSummary = data?.choices?.[0]?.message?.content;
if (!newSummary || typeof newSummary !== 'string') {
console.warn('Conversation summary returned empty content');
if (force) {
Toast.error({
content: t('重新生成摘要失败:模型返回空内容'),
duration: 3,
});
}
return;
}
// 落库 / setState 前再次校对 generation;若期间有 clear / invalidate 操作发生,
// 丢弃本次结果,避免覆盖用户的「清空」动作。
if (summaryGenRef && (summaryGenRef.current ?? 0) !== genAtStart) {
return;
}
// 写回后端持久化:用启动时捕获的会话 ID,确保写到被摘要的那个会话
updateConversationSummary(sessionIdAtStart, newSummary, newUpTo).catch(
(e) => console.warn('Persist conversation summary failed:', e),
);
// 仅当用户仍停留在该会话时才更新内存状态,避免污染切换后的其它会话
if (activeSessionIdRef?.current === sessionIdAtStart) {
setConversationSummary(newSummary);
setSummarizedUpToMessageId(newUpTo);
}
} catch (e) {
if (e?.name !== 'AbortError') {
console.warn('Conversation summary error:', e);
if (force) {
Toast.error({
content: t('重新生成摘要失败:{{msg}}', {
msg: e?.message || String(e),
}),
duration: 3,
});
}
} else if (force) {
Toast.warning({
content: t('重新生成摘要超时,请稍后重试'),
duration: 3,
});
}
} finally {
clearTimeout(timer);
summarizingRef.current = false;
}
},
[
appStatus,
apiInputs,
activeSessionId,
activeSessionIdRef,
sessionEnabled,
conversationSummary,
setConversationSummary,
summarizedUpToMessageId,
setSummarizedUpToMessageId,
summarizingRef,
summaryGenRef,
t,
],
);
return { maybeSummarize };
};
+241
View File
@@ -0,0 +1,241 @@
/*
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, useContext, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import {
API,
getExperienceCenterBool,
getExperienceCenterValue,
processModelsData,
processGroupsData,
showError,
} from '../../helpers';
import { API_ENDPOINTS } from '../../constants/playground.constants';
import { StatusContext } from '../../context/Status';
export const useDataLoader = (
userState,
inputs,
handleInputChange,
setModels,
setGroups,
isExperienceMode = false,
) => {
const { t } = useTranslation();
const [statusState] = useContext(StatusContext);
const status = statusState?.status;
const inputsGroupRef = useRef(inputs.group);
// model 也走 ref:loadModels 只在"读当前选中模型"时需要它,若直接依赖 inputs.model,
// 每次用户切换模型都会让 loadModels 换新引用 → 触发下面的 effect 重新拉一遍模型列表
//(纯浪费的网络请求,还可能在响应乱序时闪一下选中态)
const inputsModelRef = useRef(inputs.model);
// 防止 loadGroups 因 status 变化被反复触发时,"白名单无交集" Toast 也反复弹出
const emptyIntersectionToastShownRef = useRef(false);
useEffect(() => {
inputsGroupRef.current = inputs.group;
}, [inputs.group]);
useEffect(() => {
inputsModelRef.current = inputs.model;
}, [inputs.model]);
const getUserGroup = useCallback(() => {
if (userState?.user?.group) {
return userState.user.group;
}
try {
return JSON.parse(localStorage.getItem('user') || '{}')?.group || '';
} catch {
return '';
}
}, [userState]);
const resolveEffectiveGroup = useCallback(
(groupOptions = [], currentGroup = '') => {
const isGroupSelectEnabled =
!isExperienceMode ||
getExperienceCenterBool(
status,
'experience_center_enable_group_select',
'experience_center_enable_group_select',
true,
);
const hasGroup = (group) =>
!!group && groupOptions.some((option) => option.value === group);
if (groupOptions.length === 0) {
return currentGroup || '';
}
if (!isGroupSelectEnabled) {
if (hasGroup('default')) {
return 'default';
}
const userGroup = getUserGroup();
if (hasGroup(userGroup)) {
return userGroup;
}
if (hasGroup(currentGroup)) {
return currentGroup;
}
return groupOptions[0]?.value || '';
}
if (hasGroup(currentGroup)) {
return currentGroup;
}
const userGroup = getUserGroup();
if (hasGroup(userGroup)) {
return userGroup;
}
if (hasGroup('default')) {
return 'default';
}
return groupOptions[0]?.value || '';
},
[getUserGroup, isExperienceMode, status],
);
const loadModels = useCallback(
async (groupOverride) => {
try {
const group = groupOverride || inputsGroupRef.current;
const groupParam = group ? `?group=${encodeURIComponent(group)}` : '';
const modelEndpoint = isExperienceMode
? API_ENDPOINTS.EXPERIENCE_USER_MODELS
: API_ENDPOINTS.USER_MODELS;
const res = await API.get(`${modelEndpoint}${groupParam}`);
const { success, message, data, level_states } = res.data;
if (success) {
// 通过 ref 读当前选中模型(响应回来时可能已被用户切换,ref 保证读到最新值)
const currentModel = inputsModelRef.current;
const { modelOptions, selectedModel } = processModelsData(
data,
currentModel,
level_states,
);
setModels(modelOptions);
if (selectedModel !== currentModel) {
handleInputChange('model', selectedModel);
}
} else {
showError(t(message));
}
} catch (error) {
showError(t('加载模型失败'));
}
},
[handleInputChange, isExperienceMode, setModels, t],
);
const loadGroups = useCallback(async () => {
try {
const res = await API.get(API_ENDPOINTS.USER_GROUPS);
const { success, message, data } = res.data;
if (success) {
let groupOptions = processGroupsData(data, getUserGroup());
// 体验中心:根据管理员配置过滤可见分组(白名单)
// 仅当 isExperienceMode=true 且配置了非空白名单时才过滤
if (isExperienceMode) {
const allowedRaw = getExperienceCenterValue(
status,
'experience_center_allowed_groups',
'experience_center_allowed_groups',
'',
);
const allowedList = String(allowedRaw)
.split(',')
.map((g) => g.trim())
.filter((g) => g !== '');
if (allowedList.length > 0) {
const allowedSet = new Set(allowedList);
const filtered = groupOptions.filter((g) =>
allowedSet.has(g.value),
);
// 防御:如果过滤后为空(白名单与实际分组无交集),保留原列表避免页面不可用,
// 同时通过 Toast 让用户能感知到(管理员配错时也方便排查)。
// 用 ref 防止 status 频繁变化导致 loadGroups 重新触发时反复弹 Toast
if (filtered.length > 0) {
groupOptions = filtered;
emptyIntersectionToastShownRef.current = false;
} else if (!emptyIntersectionToastShownRef.current) {
showError(
t('体验中心分组白名单与当前账号可用分组无交集,已展示全部分组'),
);
emptyIntersectionToastShownRef.current = true;
}
}
}
setGroups(groupOptions);
const currentGroup = inputsGroupRef.current;
const effectiveGroup = resolveEffectiveGroup(
groupOptions,
currentGroup,
);
if (effectiveGroup && effectiveGroup !== currentGroup) {
handleInputChange('group', effectiveGroup);
}
} else {
showError(t(message));
}
} catch (error) {
showError(t('加载分组失败'));
}
}, [
getUserGroup,
handleInputChange,
resolveEffectiveGroup,
setGroups,
t,
isExperienceMode,
status,
]);
useEffect(() => {
if (userState?.user) {
loadGroups();
}
}, [userState?.user, loadGroups]);
useEffect(() => {
if (userState?.user && inputs.group) {
loadModels(inputs.group);
}
}, [userState?.user, inputs.group, loadModels]);
return {
loadModels,
loadGroups,
};
};
+464
View File
@@ -0,0 +1,464 @@
/*
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, useRef, useState } from 'react';
import { Toast } from '@douyinfe/semi-ui';
import { useTranslation } from 'react-i18next';
import { API } from '../../helpers';
// 唯一 ID 生成(不依赖 crypto.randomUUID 以兼容旧浏览器)
const genId = () =>
`f_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
// 仅当图片上传失败原因看起来是临时性的(网络中断、5xx)时才回退到 base64
// 业务错误(4xx,含 401/403/413/429)保留 failed 状态让用户重试或换文件
const isTransientError = (err) => {
const status = err?.response?.status;
return !status || status >= 500;
};
// 后端如果在错误里返回了真实的 max_size_mb,优先用它显示
const extractMaxSize = (err, fallback) => {
const raw = err?.response?.data?.data?.max_size_mb;
const n = parseInt(raw, 10);
return Number.isFinite(n) && n > 0 ? n : fallback;
};
// 给图片生成 96px 长边的缩略图,用于附件 chip 上的预览
const buildImageThumbnail = (file) =>
new Promise((resolve) => {
if (!file || !file.type?.startsWith('image/')) {
resolve(null);
return;
}
try {
const reader = new FileReader();
reader.onload = (event) => {
const img = new Image();
img.onload = () => {
const MAX = 96;
const scale = Math.min(MAX / img.width, MAX / img.height, 1);
const w = Math.max(1, Math.round(img.width * scale));
const h = Math.max(1, Math.round(img.height * scale));
try {
const canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, w, h);
resolve(canvas.toDataURL('image/jpeg', 0.7));
} catch {
resolve(event.target.result);
}
};
img.onerror = () => resolve(null);
img.src = event.target.result;
};
reader.onerror = () => resolve(null);
reader.readAsDataURL(file);
} catch {
resolve(null);
}
});
const readAsDataURL = (file) =>
new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => resolve(e.target.result);
reader.onerror = () => reject(reader.error);
reader.readAsDataURL(file);
});
/**
* useFileUpload — 体验中心文件上传统一 Hook
*
* 状态:files 数组,每项 { id, name, size, fileType, status, progress, url, thumbnail, error, _rawFile, _abort }
* - fileType: 'image' | 'file'
* - status: 'uploading' | 'success' | 'failed'
* - progress: 0..1(axios 真实上传进度)
*
* @param {object} opts
* @param {number} opts.maxSizeMB 单文件大小上限(MB)
* @param {number} opts.maxCount 队列最大容量(默认 10)
* @param {(file)=>void} opts.onSuccess 每个文件传完后回调(拿到 url/type 写入消息附件区)
*/
export const useFileUpload = ({ maxSizeMB, maxCount = 10, onSuccess } = {}) => {
const { t } = useTranslation();
const [files, setFiles] = useState([]);
// 用 ref 保证 retry/remove 在闭包里看到最新列表
const filesRef = useRef([]);
filesRef.current = files;
// 双击 retry 的硬隔离:React 的 setState 不是同步 commit 的,filesRef 在两次同步点击之间
// 可能还来不及刷成 'uploading',下面 retry 检查 entry.status 就会漏判。用同步 Set 兜底,
// 进入 runUpload 时立刻 add,结束时(成功/失败/取消)remove。
const inFlightIds = useRef(new Set());
const updateFile = useCallback((id, patch) => {
setFiles((prev) => {
const next = prev.map((f) => (f.id === id ? { ...f, ...patch } : f));
filesRef.current = next;
return next;
});
}, []);
const replaceFiles = useCallback((updater) => {
setFiles((prev) => {
const next = typeof updater === 'function' ? updater(prev) : updater;
filesRef.current = next;
return next;
});
}, []);
// 执行单个文件的真实上传(被 add 和 retry 共用)
const runUpload = useCallback(
async (entry) => {
if (!entry || !entry._rawFile) return;
// 同步占位 — 任何并发 retry 都会被 retry() 的 inFlight 检查挡住
inFlightIds.current.add(entry.id);
const rawFile = entry._rawFile;
const abortCtrl = new AbortController();
updateFile(entry.id, {
status: 'uploading',
progress: 0,
error: null,
_abort: abortCtrl,
});
try {
const formData = new FormData();
formData.append('file', rawFile);
const res = await API.post('/api/user/upload/file', formData, {
skipErrorHandler: true,
signal: abortCtrl.signal,
onUploadProgress: (e) => {
if (!e.total) return;
updateFile(entry.id, {
progress: Math.min(0.99, e.loaded / e.total),
});
},
});
if (res?.data?.success) {
const url = res.data.data.url;
updateFile(entry.id, {
status: 'success',
progress: 1,
url,
error: null,
_abort: null,
_rawFile: null, // 释放内存
});
onSuccess?.({
name: entry.name,
size: entry.size,
type: entry.fileType,
url,
thumbnail: entry.thumbnail,
});
// 老二进制 Office 格式(.doc/.ppt/.xls)OpenAI 解析率极低,
// 大概率"模型说看不到文件内容",给用户一次明确提示,引导改用新格式
const lowerName = (entry.name || '').toLowerCase();
if (/\.(doc|ppt|xls)$/.test(lowerName)) {
const newFormat = lowerName.endsWith('.doc')
? '.docx'
: lowerName.endsWith('.ppt')
? '.pptx'
: '.xlsx';
Toast.warning({
content: t(
'老格式 {{old}} 大模型解析效果不佳,建议另存为 {{new}} 后再上传',
{
old: lowerName.match(/\.(doc|ppt|xls)$/)[0],
new: newFormat,
},
),
// 6 秒:默认 3 秒会让用户在阅读完文件名前就消失。chip 上还有持久角标兜底,
// 但 Toast 是上传完瞬间的提醒,必须让用户来得及看完
duration: 6,
});
}
return;
}
// 后端返回 success=false(业务错)
const message = res?.data?.message || t('文件上传失败');
updateFile(entry.id, {
status: 'failed',
progress: 0,
error: message,
_abort: null,
});
Toast.error({ content: message, duration: 3 });
} catch (err) {
// 取消请求 → 直接移除条目(取消由 abort() 触发,无需 toast)
if (
err?.name === 'CanceledError' ||
err?.code === 'ERR_CANCELED' ||
abortCtrl.signal.aborted
) {
replaceFiles((prev) => prev.filter((f) => f.id !== entry.id));
return;
}
// 临时错误 + 是图片 → 自动回退 base64,仍可送入对话
if (entry.fileType === 'image' && isTransientError(err)) {
try {
const dataUrl = await readAsDataURL(rawFile);
updateFile(entry.id, {
status: 'success',
progress: 1,
url: dataUrl,
error: null,
_abort: null,
_rawFile: null,
});
onSuccess?.({
name: entry.name,
size: entry.size,
type: 'image',
url: dataUrl,
thumbnail: entry.thumbnail || dataUrl,
fromLocalFallback: true,
});
Toast.info({
content: t('网络异常,图片以本地数据上送'),
duration: 3,
});
return;
} catch {
// fall through to failed state
}
}
// 文件超大 → 显示后端返回的真实限制
if (
err?.response?.status === 400 &&
err?.response?.data?.data?.max_size_mb
) {
const limit = extractMaxSize(err, maxSizeMB);
const msg = t('文件大小不能超过 {{size}}MB', { size: limit });
updateFile(entry.id, {
status: 'failed',
progress: 0,
error: msg,
_abort: null,
});
Toast.error({ content: msg, duration: 3 });
return;
}
// 限流 / 鉴权 / 服务器错误
const status = err?.response?.status;
let message =
err?.response?.data?.message || t('文件上传失败,请稍后重试');
if (status === 429) message = t('上传太频繁,请稍后再试');
if (status === 401) message = t('登录已过期,请重新登录');
if (status === 403) message = t('没有上传权限');
updateFile(entry.id, {
status: 'failed',
progress: 0,
error: message,
_abort: null,
});
Toast.error({ content: message, duration: 3 });
} finally {
inFlightIds.current.delete(entry.id);
}
},
[updateFile, replaceFiles, onSuccess, maxSizeMB, t],
);
/**
* upload — 接收一个 FileList / File[] 并行上传
* 自动做:大小校验、数量校验、同名同大小去重、图片缩略图、并行 axios 上传
*/
const upload = useCallback(
async (rawFiles) => {
const arr = Array.from(rawFiles || []);
if (arr.length === 0) return;
const current = filesRef.current;
const slotsLeft = Math.max(0, maxCount - current.length);
if (slotsLeft === 0) {
Toast.warning({
content: t('附件数量已达上限({{max}} 个)', { max: maxCount }),
duration: 3,
});
return;
}
const accepted = [];
for (const file of arr) {
if (accepted.length >= slotsLeft) {
Toast.warning({
content: t('附件数量已达上限({{max}} 个)', { max: maxCount }),
duration: 3,
});
break;
}
// 大小校验:本地阈值,后端会再校验一次
const limitMB = maxSizeMB || 10;
if (file.size > limitMB * 1024 * 1024) {
Toast.error({
content: t('文件「{{name}}」超过 {{size}}MB 限制', {
name: file.name,
size: limitMB,
}),
duration: 3,
});
continue;
}
// 去重:同名 + 同大小视为重复
const dup = [...current, ...accepted].some(
(f) => f.name === file.name && f.size === file.size,
);
if (dup) {
Toast.info({
content: t('文件「{{name}}」已添加', { name: file.name }),
duration: 2,
});
continue;
}
accepted.push({
id: genId(),
name: file.name,
size: file.size,
// SVG 虽然 MIME 是 image/*,但本质是 XML 文本,多数大模型不接受 SVG 作为
// input_image(OpenAI vision 会返 "invalid image"),所以当 file 处理走文件分支。
fileType:
file.type?.startsWith('image/') &&
file.type !== 'image/svg+xml'
? 'image'
: 'file',
status: 'uploading',
progress: 0,
url: null,
thumbnail: null,
error: null,
_rawFile: file,
_abort: null,
});
}
if (accepted.length === 0) return;
// 先入队(UI 立即反馈),再异步起上传
replaceFiles((prev) => [...prev, ...accepted]);
// 并行起:缩略图 + 真实上传,每个文件独立
await Promise.all(
accepted.map(async (entry) => {
// 图片预生成缩略图(不阻塞上传)
if (entry.fileType === 'image') {
buildImageThumbnail(entry._rawFile).then((thumb) => {
if (thumb) updateFile(entry.id, { thumbnail: thumb });
});
}
await runUpload(entry);
}),
);
},
[maxCount, maxSizeMB, replaceFiles, runUpload, updateFile, t],
);
const retry = useCallback(
(id) => {
const entry = filesRef.current.find((f) => f.id === id);
if (!entry) return;
// 与 entry.status 双重保险:inFlightIds 是同步状态,能挡住 React 还没 flush 的并发点击
if (entry.status === 'uploading' || inFlightIds.current.has(id)) return;
if (!entry._rawFile) {
Toast.error({ content: t('原文件已释放,请重新选择'), duration: 3 });
return;
}
runUpload(entry);
},
[runUpload, t],
);
const remove = useCallback(
(id) => {
const entry = filesRef.current.find((f) => f.id === id);
if (!entry) return null;
const wasUploading = entry.status === 'uploading';
if (entry._abort) {
try {
entry._abort.abort();
} catch {
/* ignore */
}
}
replaceFiles((prev) => prev.filter((f) => f.id !== id));
// 返回被删条目供 UI 层做 undo —— uploading 状态的 abort 不可逆,返回 null 表示
// "无法撤销",调用方据此决定是否显示撤销按钮
return wasUploading ? null : entry;
},
[replaceFiles],
);
// 把被 remove 还回去的条目重新挂回列表末尾。简单实现:append 而不还原原 index,
// 避免在频繁删除时维护精确位置的复杂度;用户感受是"它回来了",足够好。
// 如果同 id 已经存在(罕见,比如用户飞快重传同名文件)就静默忽略不重复加。
const restore = useCallback(
(entry) => {
if (!entry || !entry.id) return;
replaceFiles((prev) => {
if (prev.some((f) => f.id === entry.id)) return prev;
return [...prev, entry];
});
},
[replaceFiles],
);
const clearAll = useCallback(() => {
filesRef.current.forEach((f) => {
if (f._abort) {
try {
f._abort.abort();
} catch {
/* ignore */
}
}
});
replaceFiles([]);
}, [replaceFiles]);
// clearSucceeded:仅清掉已成功发送的附件,保留失败状态的让用户继续重试 / 移除。
// 用在"发送完消息后"的场景 —— 用户明确感知到的成功附件已经走出去了,但失败的还没被处理,
// 一并清掉等于把用户的重试机会偷偷拿走。
const clearSucceeded = useCallback(() => {
replaceFiles((prev) => prev.filter((f) => f.status !== 'success'));
}, [replaceFiles]);
const isUploading = files.some((f) => f.status === 'uploading');
return {
files,
upload,
retry,
remove,
restore,
clearAll,
clearSucceeded,
isUploading,
};
};
export default useFileUpload;
+100
View File
@@ -0,0 +1,100 @@
/*
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 { useState, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { API } from '../../helpers';
import { API_ENDPOINTS } from '../../constants/playground.constants';
import { buildImageRequestBody } from '../../constants/imageModelCapabilities';
export const useImageGen = () => {
const { t } = useTranslation();
const [isImageGenerating, setIsImageGenerating] = useState(false);
const pollForResult = useCallback(
async (taskId) => {
const maxAttempts = 60;
for (let i = 0; i < maxAttempts; i++) {
await new Promise((r) => setTimeout(r, 2000));
try {
const res = await API.get(
`${API_ENDPOINTS.IMAGE_GENERATIONS}/${taskId}`,
);
if (res.data?.success && res.data?.data) {
const task = res.data.data;
if (task.status === 'SUCCESS') {
let imageUrl = null;
let revisedPrompt = '';
if (
task.data?.data &&
Array.isArray(task.data.data) &&
task.data.data.length > 0
) {
imageUrl = task.data.data[0].url;
revisedPrompt = task.data.data[0].revised_prompt || '';
}
return imageUrl
? { url: imageUrl, revised_prompt: revisedPrompt }
: null;
}
if (task.status === 'FAILURE') {
return { error: task.fail_reason || t('图片生成失败') };
}
}
} catch {
// Ignore transient polling errors.
}
}
return { error: t('图片生成超时,请重试') };
},
[t],
);
const generateImage = useCallback(
async ({ prompt, model, size }) => {
setIsImageGenerating(true);
try {
const body = buildImageRequestBody(model, {
prompt,
size,
mode: 'text-to-image',
source: 'experience_center_text_model',
});
const res = await API.post(API_ENDPOINTS.IMAGE_GENERATIONS, body);
if (res.data?.success && res.data?.data?.task_id) {
return await pollForResult(res.data.data.task_id);
}
return { error: res.data?.message || t('图片生成失败') };
} catch (err) {
const backendMessage =
err?.response?.data?.message ||
err?.response?.data?.error?.message ||
err?.response?.data?.error;
return { error: backendMessage || t('图片生成失败,请检查网络连接') };
} finally {
setIsImageGenerating(false);
}
},
[t, pollForResult],
);
return { generateImage, isImageGenerating };
};
@@ -0,0 +1,91 @@
/*
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 { useEffect } from 'react';
// 是否处于"用户正在输入框里打字"的状态 —— 这种时候单字符快捷键(如 ?)不该触发,
// 否则用户按 ? 想打个问号,结果触发了帮助弹窗
const isTypingInField = (target) => {
if (!target) return false;
const tag = (target.tagName || '').toLowerCase();
if (tag === 'input' || tag === 'textarea') return true;
if (target.isContentEditable) return true;
return false;
};
/**
* useKeyboardShortcuts 注册全局键盘快捷键。
*
* 默认绑定:
* - Ctrl/Cmd + K → focusInput() 聚焦输入框
* - Ctrl/Cmd + E → exportSession() 导出当前会话
* - Ctrl/Cmd + / → toggleHelp() 打开/关闭快捷键面板
* - ? → toggleHelp() (仅在不在输入框打字时)
* - Esc → closeHelp() 关闭快捷键面板
*
* 所有 handler 都可选;只传你需要的。
*/
export const useKeyboardShortcuts = ({
enabled = true,
focusInput,
exportSession,
toggleHelp,
closeHelp,
}) => {
useEffect(() => {
if (!enabled) return undefined;
const onKeyDown = (e) => {
// mac vs windows 统一处理;用 metaKey || ctrlKey 兜底
const mod = e.metaKey || e.ctrlKey;
// Esc:关闭帮助;不阻断默认(其它 Modal 也想监听 Esc)
if (e.key === 'Escape') {
closeHelp?.();
return;
}
// ?:打开帮助,但要求用户不在输入框里(否则误触发)
if (e.key === '?' && !isTypingInField(e.target)) {
e.preventDefault();
toggleHelp?.();
return;
}
if (!mod) return;
const key = (e.key || '').toLowerCase();
if (key === 'k') {
e.preventDefault();
focusInput?.();
} else if (key === 'e') {
e.preventDefault();
exportSession?.();
} else if (key === '/') {
e.preventDefault();
toggleHelp?.();
}
};
window.addEventListener('keydown', onKeyDown);
return () => window.removeEventListener('keydown', onKeyDown);
}, [enabled, focusInput, exportSession, toggleHelp, closeHelp]);
};
export default useKeyboardShortcuts;
+435
View File
@@ -0,0 +1,435 @@
/*
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 { Toast, Modal } from '@douyinfe/semi-ui';
import { useTranslation } from 'react-i18next';
import { getTextContent } from '../../helpers';
import { ERROR_MESSAGES } from '../../constants/playground.constants';
import {
deleteMessage,
deleteMessagePair,
deleteMessagesFrom,
} from '../../services/playgroundConversation';
export const useMessageActions = (
message,
setMessage,
onMessageSend,
saveMessages,
options = {},
) => {
const { t } = useTranslation();
const {
activeSessionId,
sessionEnabled = false,
// 归档会话只读:handleMessageReset / handleMessageDelete 都涉及后端写
// (deleteMessagesFrom / deleteMessage),后端会拒绝但前端 setMessage 已经先动了,
// 必须在动手前拦截避免本地与服务端分叉
activeSessionArchived = false,
// 摘要锚点 + 失效回调(与 useMessageEdit 对齐):重新生成 / 删除若命中已被摘要
// 覆盖的消息(backendId ≤ 锚点),摘要里保留的是旧内容;更糟的是锚点消息本身
// 被删后 applySummaryAndWindow 找不到锚点会兜底发全量历史,变成
// 「陈旧摘要 + 全量历史」双份上下文。此时必须让摘要失效。
summarizedUpToMessageId = 0,
onSummaryInvalidate,
} = options;
// 命中摘要覆盖范围(消息有 backendId 且 ≤ 锚点)时使摘要失效
const invalidateSummaryIfCovered = useCallback(
(msgs) => {
if (!(summarizedUpToMessageId > 0)) return;
if (typeof onSummaryInvalidate !== 'function') return;
const covered = (Array.isArray(msgs) ? msgs : [msgs]).some(
(m) => m?.backendId && m.backendId <= summarizedUpToMessageId,
);
if (covered) onSummaryInvalidate();
},
[summarizedUpToMessageId, onSummaryInvalidate],
);
// 后端同步删除:仅当消息有 backendId(来自后端)时调用
const syncDeleteMessage = useCallback(
async (msg) => {
if (!sessionEnabled || !msg?.backendId) return;
try {
await deleteMessage(msg.backendId);
} catch (e) {
console.warn('后端删除消息失败:', e);
}
},
[sessionEnabled],
);
// 后端同步:删除 user 消息 + 紧随其后的 assistant 回复(问答对,assistant 无 backendId 时用)
const syncDeleteMessagePair = useCallback(
async (userMsg) => {
if (!sessionEnabled || !userMsg?.backendId) return;
try {
await deleteMessagePair(userMsg.backendId);
} catch (e) {
console.warn('后端删除问答对失败:', e);
}
},
[sessionEnabled],
);
// 后端同步:删除某条消息及之后所有(用于重新生成 / 编辑后重发)
const syncDeleteMessagesFrom = useCallback(
async (fromMsg) => {
if (!sessionEnabled || !activeSessionId || !fromMsg?.backendId) return;
try {
await deleteMessagesFrom(activeSessionId, fromMsg.backendId);
} catch (e) {
console.warn('后端删除消息序列失败:', e);
}
},
[sessionEnabled, activeSessionId],
);
// 复制消息
const handleMessageCopy = useCallback(
(targetMessage) => {
const textToCopy = getTextContent(targetMessage);
// 检测消息里有没有附件(图片 / 文件)— 因为剪贴板只能粘文本,附件会被静默丢掉,
// 必须明确告知用户,否则会出现"我刚复制的不是这个"的诡异体验
const hasAttachments =
Array.isArray(targetMessage?.content) &&
targetMessage.content.some(
(p) => p?.type === 'image_url' || p?.type === 'file',
);
if (!textToCopy) {
Toast.warning({
content: t(ERROR_MESSAGES.NO_TEXT_CONTENT),
duration: 2,
});
return;
}
const copyToClipboard = async (text) => {
if (navigator.clipboard?.writeText) {
try {
await navigator.clipboard.writeText(text);
Toast.success({
content: hasAttachments
? t('已复制文本(附件未包含)')
: t('消息已复制到剪贴板'),
duration: 2,
});
} catch (err) {
console.error('Clipboard API 复制失败:', err);
fallbackCopy(text);
}
} else {
fallbackCopy(text);
}
};
const fallbackCopy = (text) => {
try {
const textArea = document.createElement('textarea');
textArea.value = text;
textArea.style.cssText = `
position: fixed;
top: -9999px;
left: -9999px;
opacity: 0;
pointer-events: none;
z-index: -1;
`;
textArea.setAttribute('readonly', '');
document.body.appendChild(textArea);
textArea.select();
textArea.setSelectionRange(0, text.length);
const successful = document.execCommand('copy');
document.body.removeChild(textArea);
if (successful) {
Toast.success({
content: hasAttachments
? t('已复制文本(附件未包含)')
: t('消息已复制到剪贴板'),
duration: 2,
});
} else {
throw new Error('execCommand copy failed');
}
} catch (err) {
console.error('回退复制方案也失败:', err);
let errorMessage = t(ERROR_MESSAGES.COPY_FAILED);
if (
window.location.protocol === 'http:' &&
window.location.hostname !== 'localhost'
) {
errorMessage = t(ERROR_MESSAGES.COPY_HTTPS_REQUIRED);
} else if (!navigator.clipboard && !document.execCommand) {
errorMessage = t(ERROR_MESSAGES.BROWSER_NOT_SUPPORTED);
}
Toast.error({
content: errorMessage,
duration: 4,
});
}
};
copyToClipboard(textToCopy);
},
[t],
);
// 重新生成消息
// 注意:查找/切片/删除后端/重发等逻辑全部在 setMessage updater 外完成 ——
// StrictMode / 并发模式下 updater 可能执行两次,把 syncDeleteMessagesFrom 和
// setTimeout(onMessageSend) 放进 updater 会导致重复删除 + 重复发送(双请求双扣费)。
const handleMessageReset = useCallback(
(targetMessage) => {
// 归档会话拦截:handleMessageReset 会调用 onMessageSend(已拦截) + syncDeleteMessagesFrom(后端拒)
// 后者 catch 静默吞错,本地却已 slice 截断消息列表 → 刷新后老消息回来,体验诡异
if (activeSessionArchived) {
Toast.warning({
content: t('当前会话已归档,无法重新生成回复'),
duration: 2,
});
return;
}
// 使用引用查找索引,防止重复 id 造成误匹配;回退到 id 匹配兼容不同引用场景
let messageIndex = message.findIndex((msg) => msg === targetMessage);
if (messageIndex === -1) {
messageIndex = message.findIndex((msg) => msg.id === targetMessage.id);
}
if (messageIndex === -1) return;
// 从指定 user 消息处截断并重发。重发时若原消息带图片/文件附件,
// 把原 content 数组一并传给 onMessageSend(第三参数),保留附件 ——
// 只发纯文本会让附件在「后端已删、前端重发不带」的组合下彻底丢失。
const resendFromUser = (userMessage, sliceEnd) => {
const newMessages = message.slice(0, sliceEnd);
const contentToSend = getTextContent(userMessage);
const hasAttachmentParts =
Array.isArray(userMessage.content) &&
userMessage.content.some(
(p) => p && (p.type === 'image_url' || p.type === 'file'),
);
setMessage(newMessages);
// 重新生成命中摘要覆盖范围:锚点及旧回复即将被删,摘要必须失效
invalidateSummaryIfCovered(userMessage);
// 后端同步:删除该 user 消息及之后所有消息(重发会重新落库)。
// 必须等删除落地后再重发 —— 删除接口语义是「删 id ≥ fromId」,若重发的
// 新消息先落库、删除后执行,新消息(id 更大)会被一并删掉,DB 丢当前轮。
// syncDeleteMessagesFrom 内部吞错,不会 reject。100ms 延迟保留给 React
// 提交截断后的列表,让 onMessageSend 经 messageRef 读到新状态。
(async () => {
await syncDeleteMessagesFrom(userMessage);
setTimeout(() => {
onMessageSend(
contentToSend,
undefined,
hasAttachmentParts ? userMessage.content : undefined,
);
}, 100);
})();
};
if (targetMessage.role === 'user') {
resendFromUser(targetMessage, messageIndex);
return;
}
if (
targetMessage.role === 'assistant' ||
targetMessage.role === 'system'
) {
let userMessageIndex = messageIndex - 1;
while (
userMessageIndex >= 0 &&
message[userMessageIndex].role !== 'user'
) {
userMessageIndex--;
}
if (userMessageIndex >= 0) {
resendFromUser(message[userMessageIndex], userMessageIndex);
}
}
},
[
message,
setMessage,
onMessageSend,
syncDeleteMessagesFrom,
invalidateSummaryIfCovered,
activeSessionArchived,
t,
],
);
// 删除消息
const handleMessageDelete = useCallback(
(targetMessage) => {
// 归档会话拦截:后端 DeletePlaygroundMessageByUser 的子查询限定主表,
// 归档消息删不到,但前端 setMessage 会先把本地的删掉 → 刷新又回来,体验割裂
if (activeSessionArchived) {
Toast.warning({
content: t('当前会话已归档,无法删除消息'),
duration: 2,
});
return;
}
Modal.confirm({
title: t('确认删除'),
content: t('确定要删除这条消息吗?'),
okText: t('确定'),
cancelText: t('取消'),
okButtonProps: {
type: 'danger',
},
onOk: () => {
// Toast / 后端删除等副作用全部在 setMessage updater 外完成 ——
// StrictMode 下 updater 会执行两次,放里面会重复调删除接口、重复弹 Toast。
// 查找基于 Modal 弹出时捕获的 message 快照;本地过滤走函数式 updater
// (按 id 过滤,容忍弹窗期间列表发生的其它变化),结果用 let 捕获到外面做保存。
let messageIndex = message.findIndex((msg) => msg === targetMessage);
if (messageIndex === -1) {
messageIndex = message.findIndex(
(msg) => msg.id === targetMessage.id,
);
}
if (messageIndex === -1) return;
const nextMessage =
messageIndex < message.length - 1
? message[messageIndex + 1]
: null;
const deletePair =
targetMessage.role === 'user' &&
nextMessage &&
nextMessage.role === 'assistant';
const idsToRemove = new Set(
deletePair
? [targetMessage.id, nextMessage.id]
: [targetMessage.id],
);
// 删除命中摘要覆盖范围的消息:摘要里还留着它的内容(甚至它可能就是锚点,
// 锚点丢失会让下次发送退化为「摘要 + 全量历史」),一并失效
invalidateSummaryIfCovered(
deletePair ? [targetMessage, nextMessage] : targetMessage,
);
if (deletePair) {
Toast.success({ content: t('已删除消息及其回复'), duration: 2 });
// 后端同步。直播会话里 assistant 消息没有 backendId(响应头只回传 user 消息 ID),
// 逐条删会在 DB 留下孤儿 assistant 行,刷新后"复活"——此时改走 pair 接口,
// 由后端把「user 消息 + 紧随其后的 assistant 行」一并删掉(不限尾部)。
if (nextMessage.backendId) {
syncDeleteMessage(targetMessage);
syncDeleteMessage(nextMessage);
} else if (targetMessage.backendId) {
syncDeleteMessagePair(targetMessage);
}
// 两条都无 backendId:后端本就没有记录,仅前端移除即可
} else {
Toast.success({ content: t('消息已删除'), duration: 2 });
syncDeleteMessage(targetMessage);
}
let capturedUpdated = null;
setMessage((prevMessages) => {
const updated = prevMessages.filter(
(msg) => !idsToRemove.has(msg.id),
);
// 纯赋值捕获(幂等),StrictMode 双执行也只是重复赋同一个值
capturedUpdated = updated;
return updated;
});
// 删除消息后保存,传入更新后的消息列表
setTimeout(() => {
if (capturedUpdated) saveMessages(capturedUpdated);
}, 0);
},
});
},
[
message,
setMessage,
t,
saveMessages,
syncDeleteMessage,
syncDeleteMessagePair,
invalidateSummaryIfCovered,
activeSessionArchived,
],
);
// 切换角色
const handleRoleToggle = useCallback(
(targetMessage) => {
if (
!(targetMessage.role === 'assistant' || targetMessage.role === 'system')
) {
return;
}
const newRole =
targetMessage.role === 'assistant' ? 'system' : 'assistant';
// 保存副作用放 updater 外(StrictMode 下 updater 会执行两次),结果用 let 捕获
let capturedUpdated = null;
setMessage((prevMessages) => {
const updatedMessages = prevMessages.map((msg) => {
if (
msg.id === targetMessage.id &&
(msg.role === 'assistant' || msg.role === 'system')
) {
return { ...msg, role: newRole };
}
return msg;
});
capturedUpdated = updatedMessages;
return updatedMessages;
});
// 切换角色后保存,传入更新后的消息列表
setTimeout(() => {
if (capturedUpdated) saveMessages(capturedUpdated);
}, 0);
Toast.success({
content: t('已切换为{{role}}角色', {
role: newRole === 'system' ? 'System' : 'Assistant',
}),
duration: 2,
});
},
[setMessage, t, saveMessages],
);
return {
handleMessageCopy,
handleMessageReset,
handleMessageDelete,
handleRoleToggle,
};
};
+255
View File
@@ -0,0 +1,255 @@
/*
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, useState, useRef } from 'react';
import { Toast, Modal } from '@douyinfe/semi-ui';
import { useTranslation } from 'react-i18next';
import {
getTextContent,
buildApiPayload,
createLoadingAssistantMessage,
applySummaryAndWindow,
} from '../../helpers';
import { MESSAGE_ROLES } from '../../constants/playground.constants';
import { deleteMessagesFrom } from '../../services/playgroundConversation';
export const useMessageEdit = (
setMessage,
inputs,
parameterEnabled,
sendRequest,
saveMessages,
options = {},
) => {
const {
// 当前消息列表快照(由调用方每次渲染传入)。handleEditSave 的查找/确认弹窗/后端删除
// 必须在 setMessage updater 外完成 —— StrictMode 下 updater 会执行两次,
// 放里面会双弹 Modal、双发请求。
messages = [],
activeSessionId,
sessionEnabled = false,
maxHistoryRounds = 0,
conversationSummary = '',
summarizedUpToMessageId = 0,
summaryEnabled = false,
// 当编辑触发的消息在摘要覆盖范围内(其 backendId ≤ summarizedUpToMessageId)时调用,
// 用于使过时的摘要失效,避免模型同时看到「摘要里的旧版本」+「正文里的新版本」
onSummaryInvalidate,
// 归档会话只读:handleEditSave 进入即拦截,否则"重新生成"路径会发起
// deleteMessagesFrom + sendRequest 两个被后端拒的请求,本地状态与服务端永久分叉
activeSessionArchived = false,
} = options;
const { t } = useTranslation();
const [editingMessageId, setEditingMessageId] = useState(null);
const [editValue, setEditValue] = useState('');
const editingMessageRef = useRef(null);
const handleMessageEdit = useCallback((targetMessage) => {
const editableContent = getTextContent(targetMessage);
setEditingMessageId(targetMessage.id);
editingMessageRef.current = targetMessage;
setEditValue(editableContent);
}, []);
const handleEditSave = useCallback(() => {
if (!editingMessageId || !editValue.trim()) return;
// 归档会话只读拦截:任何路径(仅保存 / 重新生成)都会导致本地与服务端分叉,直接拒绝
if (activeSessionArchived) {
Toast.warning({
content: t('当前会话已归档,无法编辑消息'),
duration: 2,
});
setEditingMessageId(null);
editingMessageRef.current = null;
setEditValue('');
return;
}
// 查找目标消息:全部基于当前渲染传入的 messages 快照,在 updater 外完成。
let messageIndex = messages.findIndex(
(msg) => msg === editingMessageRef.current,
);
if (messageIndex === -1) {
messageIndex = messages.findIndex((msg) => msg.id === editingMessageId);
}
const targetMessage = messages[messageIndex];
// 目标消息已不存在(被删除 / 切换会话):静默退出编辑态,不能继续往下走
// (原实现会直接读 undefined.content 抛 TypeError)
if (!targetMessage) {
setEditingMessageId(null);
editingMessageRef.current = null;
setEditValue('');
return;
}
let newContent;
if (Array.isArray(targetMessage.content)) {
newContent = targetMessage.content.map((item) =>
item.type === 'text' ? { ...item, text: editValue.trim() } : item,
);
} else {
newContent = editValue.trim();
}
const updatedMessages = messages.map((msg) =>
msg.id === editingMessageId ? { ...msg, content: newContent } : msg,
);
// 编辑命中已被摘要覆盖的历史消息时,让摘要失效(next send 退化为不带摘要,再下一次到阈值时重摘)
const summaryInvalidated =
targetMessage.backendId &&
summarizedUpToMessageId > 0 &&
targetMessage.backendId <= summarizedUpToMessageId &&
typeof onSummaryInvalidate === 'function';
if (summaryInvalidated) {
onSummaryInvalidate();
}
const finishEditing = () => {
setEditingMessageId(null);
editingMessageRef.current = null;
setEditValue('');
};
// 处理用户消息编辑后的重新生成
const hasSubsequentAssistantReply =
targetMessage.role === MESSAGE_ROLES.USER &&
messageIndex < messages.length - 1 &&
messages[messageIndex + 1].role === MESSAGE_ROLES.ASSISTANT;
if (hasSubsequentAssistantReply) {
Modal.confirm({
title: t('消息已编辑'),
content: t('检测到该消息后有AI回复,是否删除后续回复并重新生成?'),
okText: t('重新生成'),
cancelText: t('仅保存'),
onOk: () => {
const messagesUntilUser = updatedMessages.slice(0, messageIndex + 1);
setMessage(messagesUntilUser);
// 编辑后保存(重新生成的情况),传入更新后的消息列表
setTimeout(() => saveMessages(messagesUntilUser), 0);
// 用 IIFE 而不是把 onOk 写成 async —— Semi Modal 会 await onOk 的返回值,
// 那样弹窗会挂着 loading 等删除接口返回,这里希望弹窗立即关闭
(async () => {
// 后端同步:删除被编辑的 user 消息及之后所有消息(重发时后端会基于
// 新内容重新落库)。必须等删除落地后再重发 —— 删除接口语义是
// 「删 id ≥ fromId」,若重发的新消息先落库、删除后执行,
// 新消息(id 更大)会被一并删掉,DB 丢当前轮。
if (sessionEnabled && activeSessionId && targetMessage.backendId) {
try {
await deleteMessagesFrom(
activeSessionId,
targetMessage.backendId,
);
} catch (e) {
console.warn('编辑后重发,后端删除消息序列失败:', e);
}
}
setTimeout(() => {
// 编辑后重发同样应用「摘要 + 窗口」处理(Feature A + B)。
// 不在编辑路径触发新摘要,沿用会话已有摘要(接受轻微陈旧)。
// 注意:本次编辑若已使摘要失效,这里必须用失效后的空值 ——
// 闭包里的 conversationSummary 是失效前的旧状态,直接用会把
// 「陈旧摘要 + 全量历史」双份上下文发给模型。
const payload = buildApiPayload(
applySummaryAndWindow(messagesUntilUser, {
maxRounds: maxHistoryRounds,
summary: summaryInvalidated ? '' : conversationSummary,
summarizedUpToMessageId: summaryInvalidated
? 0
: summarizedUpToMessageId,
summaryEnabled,
}),
null,
inputs,
parameterEnabled,
);
// 与 onMessageSend 对齐:若被编辑的 user 消息含 file 附件,
// loading 显示"正在处理 N 个附件…",避免重发时用户体感卡顿无反馈
const lastUserMsg =
messagesUntilUser[messagesUntilUser.length - 1];
const fileCount = Array.isArray(lastUserMsg?.content)
? lastUserMsg.content.filter((p) => p && p.type === 'file')
.length
: 0;
setMessage((prevMsg) => [
...prevMsg,
createLoadingAssistantMessage(
fileCount > 0 ? { processingAttachments: fileCount } : {},
),
]);
sendRequest(payload, inputs.stream);
}, 100);
})();
},
onCancel: () => {
setMessage(updatedMessages);
// 编辑后保存(仅保存的情况),传入更新后的消息列表
setTimeout(() => saveMessages(updatedMessages), 0);
Toast.success({ content: t('消息已更新'), duration: 2 });
},
});
finishEditing();
return;
}
// 编辑后保存(普通情况),传入更新后的消息列表
setMessage(updatedMessages);
setTimeout(() => saveMessages(updatedMessages), 0);
finishEditing();
Toast.success({ content: t('消息已更新'), duration: 2 });
}, [
editingMessageId,
editValue,
messages,
t,
inputs,
parameterEnabled,
sendRequest,
setMessage,
saveMessages,
sessionEnabled,
activeSessionId,
maxHistoryRounds,
conversationSummary,
summarizedUpToMessageId,
summaryEnabled,
onSummaryInvalidate,
activeSessionArchived,
]);
const handleEditCancel = useCallback(() => {
setEditingMessageId(null);
editingMessageRef.current = null;
setEditValue('');
}, []);
return {
editingMessageId,
editValue,
setEditValue,
handleMessageEdit,
handleEditSave,
handleEditCancel,
};
};
+96
View File
@@ -0,0 +1,96 @@
/*
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 { useState, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { API } from '../../helpers';
import { API_ENDPOINTS } from '../../constants/playground.constants';
const SYSTEM_PROMPT = `你是一个 AI 图像生成的提示词工程师。请把用户输入的提示词改写得更具体、更有画面感,让 AI 图像模型能产出更好的图。
要求:
1. 保留原意,但补充细节:构图、光线、风格、材质、镜头感、画质修饰词等
2. 用与输入相同的语言输出(中文输入 -> 中文输出,英文输入 -> 英文输出)
3. 控制在 100 字以内
4. 只输出优化后的提示词,不要解释、不要引号、不要标题`;
// 提取首尾包裹(引号 / 反引号 / 三连反引号代码块)
const stripWrappers = (s) => {
if (!s) return s;
let t = s.trim();
// ``` ... ```
const fence = t.match(/^```[a-zA-Z]*\s*\n([\s\S]*?)\n```$/);
if (fence) t = fence[1].trim();
// 引号
t = t.replace(/^["'`“”‘’]+|["'`“”‘’]+$/g, '');
return t.trim();
};
export const useOptimizePrompt = () => {
const { t } = useTranslation();
const [optimizing, setOptimizing] = useState(false);
const optimize = useCallback(
async (prompt, modelName) => {
if (!prompt || !prompt.trim()) return null;
if (!modelName) {
return { error: t('未配置文本模型,无法优化') };
}
setOptimizing(true);
try {
// 用项目统一的 API helper —— 自动带 cookies / New-API-User 头 / 错误拦截
const res = await API.post(
API_ENDPOINTS.CHAT_COMPLETIONS,
{
model: modelName,
source: 'experience_center_text_model',
stream: false,
messages: [
{ role: 'system', content: SYSTEM_PROMPT },
{ role: 'user', content: prompt },
],
max_tokens: 400,
temperature: 0.7,
},
{ skipErrorHandler: true },
);
const data = res?.data;
const content = data?.choices?.[0]?.message?.content;
if (!content || !content.trim()) {
return { error: t('模型未返回内容') };
}
return { content: stripWrappers(content) };
} catch (err) {
const msg =
err?.response?.data?.error?.message ||
err?.response?.data?.message ||
err?.message ||
t('优化失败');
return { error: msg };
} finally {
setOptimizing(false);
}
},
[t],
);
return { optimizing, optimize };
};
export default useOptimizePrompt;
+658
View File
@@ -0,0 +1,658 @@
/*
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 { useState, useCallback, useRef, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Toast } from '@douyinfe/semi-ui';
import {
getDefaultMessages,
DEFAULT_CONFIG,
DEBUG_TABS,
MESSAGE_STATUS,
} from '../../constants/playground.constants';
import {
loadConfig,
saveConfig,
loadMessages,
saveMessages,
clearMessages,
migrateOldStorage,
loadActiveSessionId,
saveActiveSessionId,
} from '../../components/playground/configStorage';
import { processIncompleteThinkTags } from '../../helpers';
import {
listConversations,
createConversation,
getConversation,
deleteConversation,
updateConversationTitle,
} from '../../services/playgroundConversation';
import {
prependCreatedSession,
removeSessionAndResolveNext,
} from './sessionFlow';
const isMissingConversationMessage = (message = '') => {
const normalized = String(message).toLowerCase();
return (
normalized.includes('conversation_id is required') ||
(normalized.includes('conversation') && normalized.includes('not found')) ||
normalized.includes('not authorized') ||
normalized.includes('\u4f1a\u8bdd\u4e0d\u5b58\u5728') ||
normalized.includes('\u65e0\u6743') ||
normalized.includes('\u65e0\u6548\u4f1a\u8bdd')
);
};
export const usePlaygroundState = (options = {}) => {
const { t } = useTranslation();
const { experienceMode = false } = options;
const [savedConfig] = useState(() => {
migrateOldStorage();
return loadConfig();
});
const [initialMessages] = useState(() => {
if (experienceMode) {
return [];
}
const loaded = loadMessages();
if (
loaded &&
loaded.length === 2 &&
loaded[0].id === '2' &&
loaded[1].id === '3'
) {
const hasOldChinese = false;
if (hasOldChinese) {
clearMessages();
return null;
}
}
return loaded;
});
const [inputs, setInputs] = useState(
savedConfig.inputs || DEFAULT_CONFIG.inputs,
);
const [parameterEnabled, setParameterEnabled] = useState(
savedConfig.parameterEnabled || DEFAULT_CONFIG.parameterEnabled,
);
const [showDebugPanel, setShowDebugPanel] = useState(
savedConfig.showDebugPanel || DEFAULT_CONFIG.showDebugPanel,
);
const [customRequestMode, setCustomRequestMode] = useState(
savedConfig.customRequestMode || DEFAULT_CONFIG.customRequestMode,
);
const [customRequestBody, setCustomRequestBody] = useState(
savedConfig.customRequestBody || DEFAULT_CONFIG.customRequestBody,
);
const [showSettings, setShowSettings] = useState(false);
const [models, setModels] = useState([]);
const [groups, setGroups] = useState([]);
const [status, setStatus] = useState({});
const [message, setMessage] = useState(() => {
if (experienceMode) return [];
return initialMessages || getDefaultMessages(t);
});
useEffect(() => {
if (experienceMode) return;
if (!initialMessages) {
setMessage(getDefaultMessages(t));
}
}, [t, initialMessages, experienceMode]);
const [debugData, setDebugData] = useState({
request: null,
response: null,
timestamp: null,
previewRequest: null,
previewTimestamp: null,
});
const [activeDebugTab, setActiveDebugTab] = useState(DEBUG_TABS.PREVIEW);
const [previewPayload, setPreviewPayload] = useState(null);
const [editingMessageId, setEditingMessageId] = useState(null);
const [editValue, setEditValue] = useState('');
const [sessions, setSessions] = useState([]);
const [activeSessionId, setActiveSessionId] = useState(() =>
loadActiveSessionId(),
);
const [sessionsLoading, setSessionsLoading] = useState(false);
const [sessionPage, setSessionPage] = useState(1);
const [sessionHasMore, setSessionHasMore] = useState(false);
const [sessionSwitching, setSessionSwitching] = useState(false);
const [sessionCreating, setSessionCreating] = useState(false);
// 体验中心长会话自动摘要:当前会话的历史摘要 + 已被摘要覆盖到的最大消息 ID。
// 来自后端 conversation.summary / summarized_up_to_message_id,切换会话时载入、新建/清空时重置。
const [conversationSummary, setConversationSummary] = useState('');
const [summarizedUpToMessageId, setSummarizedUpToMessageId] = useState(0);
// 归档会话标记:后端 GetConversation 返回 is_archived=true 时为 true,
// 此时输入区禁用、发送按钮禁用、顶部展示"已归档(只读)"横幅。
// 强制只读是防止用户发消息触发后端 4xx 错误(playgroundPrepareSession 会拒绝)
const [activeSessionArchived, setActiveSessionArchived] = useState(false);
// Refs
const sseSourceRef = useRef(null);
const chatRef = useRef(null);
const saveConfigTimeoutRef = useRef(null);
const _saveMessagesTimeoutRef = useRef(null);
const sessionCreatePromiseRef = useRef(null);
const sessionLoadRequestRef = useRef(0);
// 摘要进行中标志,防止同一会话并发触发多次摘要请求
const summarizingRef = useRef(false);
// 摘要 generation:单调递增;任何使飞行中摘要的「结果」失效的动作(清空摘要 / 编辑命中摘要范围)
// 都把它 +1。maybeSummarize 在起跑前快照 gen,落库前对比 —— 不匹配则丢弃 setState + PUT,
// 避免「用户清了,几秒后旧的 fetch 回来把摘要又写回去」的竞态。
const summaryGenRef = useRef(0);
const handleInputChange = useCallback((name, value) => {
setInputs((prev) => ({ ...prev, [name]: value }));
}, []);
const handleParameterToggle = useCallback((paramName) => {
setParameterEnabled((prev) => ({
...prev,
[paramName]: !prev[paramName],
}));
}, []);
const saveMessagesImmediately = useCallback(
(messagesToSave) => {
// 体验模式:消息由后端会话逐条持久化,且本模式从不读 localStorage 的消息缓存。
// 若继续写共享的 playground_messages_user_* key,会把普通 Playground 页面
// 保存的本地对话悄悄覆盖掉(该 key 只有普通模式启动时会读)。
if (experienceMode) return;
saveMessages(messagesToSave || message);
},
[message, experienceMode],
);
const debouncedSaveConfig = useCallback(() => {
if (saveConfigTimeoutRef.current) {
clearTimeout(saveConfigTimeoutRef.current);
}
saveConfigTimeoutRef.current = setTimeout(() => {
const configToSave = {
inputs,
parameterEnabled,
showDebugPanel,
customRequestMode,
customRequestBody,
};
saveConfig(configToSave);
}, 1000);
}, [
inputs,
parameterEnabled,
showDebugPanel,
customRequestMode,
customRequestBody,
]);
const handleConfigImport = useCallback((importedConfig) => {
if (importedConfig.inputs) {
setInputs((prev) => ({ ...prev, ...importedConfig.inputs }));
}
if (importedConfig.parameterEnabled) {
setParameterEnabled((prev) => ({
...prev,
...importedConfig.parameterEnabled,
}));
}
if (typeof importedConfig.showDebugPanel === 'boolean') {
setShowDebugPanel(importedConfig.showDebugPanel);
}
if (importedConfig.customRequestMode) {
setCustomRequestMode(importedConfig.customRequestMode);
}
if (importedConfig.customRequestBody) {
setCustomRequestBody(importedConfig.customRequestBody);
}
if (importedConfig.messages && Array.isArray(importedConfig.messages)) {
setMessage(importedConfig.messages);
}
}, []);
const handleConfigReset = useCallback((options = {}) => {
const { resetMessages = false } = options;
setInputs(DEFAULT_CONFIG.inputs);
setParameterEnabled(DEFAULT_CONFIG.parameterEnabled);
setShowDebugPanel(DEFAULT_CONFIG.showDebugPanel);
setCustomRequestMode(DEFAULT_CONFIG.customRequestMode);
setCustomRequestBody(DEFAULT_CONFIG.customRequestBody);
if (resetMessages) {
setMessage([]);
setTimeout(() => {
setMessage(getDefaultMessages(t));
}, 0);
}
}, []);
const SESSIONS_PAGE_SIZE = 30;
const loadSessions = useCallback(async () => {
setSessionsLoading(true);
try {
const res = await listConversations(1, SESSIONS_PAGE_SIZE);
if (res?.data?.success) {
const list = res.data.data?.list || [];
const total = res.data.data?.total || 0;
setSessions(list);
setSessionPage(1);
setSessionHasMore(list.length < total);
return list;
}
} catch (e) {
console.error('Failed to load conversations', e);
} finally {
setSessionsLoading(false);
}
// null 表示加载失败;与“加载成功但列表为空”区分,避免误建重复会话。
return null;
}, []);
const loadMoreSessions = useCallback(async () => {
if (sessionsLoading || !sessionHasMore) return;
setSessionsLoading(true);
try {
const nextPage = sessionPage + 1;
const res = await listConversations(nextPage, SESSIONS_PAGE_SIZE);
if (res?.data?.success) {
const list = res.data.data?.list || [];
const total = res.data.data?.total || 0;
// setSessionHasMore 不能放进 setSessions updater(updater 必须纯函数,
// StrictMode 下会执行两次)。sessionsLoading 已挡住并发调用,直接基于
// 当前 sessions 状态合并即可。
const existing = new Set(sessions.map((s) => s.id));
const merged = [
...sessions,
...list.filter((s) => !existing.has(s.id)),
];
setSessions(merged);
setSessionHasMore(merged.length < total);
setSessionPage(nextPage);
}
} catch (e) {
console.error('Failed to load more conversations', e);
} finally {
setSessionsLoading(false);
}
}, [sessionsLoading, sessionHasMore, sessionPage, sessions]);
const abortInflightStream = useCallback(() => {
if (sseSourceRef.current) {
try {
sseSourceRef.current.close();
} catch (_) {
// ignore
}
sseSourceRef.current = null;
}
}, []);
const switchSession = useCallback(
async (id) => {
if (!id) {
return { success: false, missing: false };
}
abortInflightStream();
const requestId = sessionLoadRequestRef.current + 1;
sessionLoadRequestRef.current = requestId;
setSessionSwitching(true);
setActiveSessionId(id);
saveActiveSessionId(id);
setMessage([]);
try {
const res = await getConversation(id);
if (requestId !== sessionLoadRequestRef.current) {
return { success: false, missing: false };
}
if (!res?.data?.success) {
const errorMessage =
res?.data?.message || t('Failed to load conversation');
const missing = isMissingConversationMessage(errorMessage);
Toast.error(errorMessage);
if (missing) {
setSessions((prev) => prev.filter((session) => session.id !== id));
abortInflightStream();
sessionLoadRequestRef.current += 1;
setSessionSwitching(false);
setActiveSessionId(null);
saveActiveSessionId(null);
setMessage([]);
// 摘要/归档标记也要清:否则上一个会话的摘要 chip / 归档只读横幅会
// 残留在"无会话"状态上(与 clearActiveSessionSelection 保持一致)
setConversationSummary('');
setSummarizedUpToMessageId(0);
setActiveSessionArchived(false);
}
return { success: false, missing };
}
const data = res.data.data || {};
// 载入该会话已有的历史摘要(长会话上下文压缩)
setConversationSummary(data.conversation?.summary || '');
setSummarizedUpToMessageId(
data.conversation?.summarized_up_to_message_id || 0,
);
// 归档标记:来自后端 GetConversation 的 is_archived 字段(数据源是 *_archive 冷表)
setActiveSessionArchived(!!data.is_archived);
const msgs = (data.messages || []).map((m) => {
let parsedContent = m.content;
const trimmed = (m.content || '').trim();
if (trimmed.startsWith('[')) {
try {
parsedContent = JSON.parse(trimmed);
} catch {}
}
return {
id: `srv-${m.id}`,
backendId: m.id,
role: m.role,
content: parsedContent,
status:
m.status === 'error'
? MESSAGE_STATUS.ERROR
: m.status === 'interrupted'
? MESSAGE_STATUS.INCOMPLETE
: MESSAGE_STATUS.COMPLETE,
createAt: m.created_at,
promptTokens: m.prompt_tokens || 0,
completionTokens: m.completion_tokens || 0,
costQuota: m.cost_quota || 0,
};
});
if (requestId !== sessionLoadRequestRef.current) {
return { success: false, missing: false };
}
setMessage(msgs);
return { success: true, missing: false };
} catch (e) {
if (requestId !== sessionLoadRequestRef.current) {
return { success: false, missing: false };
}
console.error('Failed to switch conversation', e);
Toast.error(t('Failed to switch conversation'));
return { success: false, missing: false };
} finally {
if (requestId === sessionLoadRequestRef.current) {
setSessionSwitching(false);
}
}
},
[abortInflightStream, t],
);
const clearActiveSessionSelection = useCallback(() => {
abortInflightStream();
sessionLoadRequestRef.current += 1;
setSessionSwitching(false);
setActiveSessionId(null);
saveActiveSessionId(null);
setMessage([]);
setConversationSummary('');
setSummarizedUpToMessageId(0);
setActiveSessionArchived(false);
// 注意:不在此处重置 summarizingRef —— 若有摘要请求在飞行中,重置会让新会话能并发再起一次摘要。
// 飞行中的 maybeSummarize 自身的 finally 一定会把它复位,这里交给它处理。
}, [abortInflightStream]);
const createNewSession = useCallback(async () => {
if (sessionCreatePromiseRef.current) {
return sessionCreatePromiseRef.current;
}
const createPromise = (async () => {
setSessionCreating(true);
abortInflightStream();
sessionLoadRequestRef.current += 1;
setSessionSwitching(false);
try {
const res = await createConversation({
model: inputs.model,
group: inputs.group,
});
const createdConv = res?.data?.data;
const newId = createdConv?.id;
if (!res?.data?.success || !newId) {
Toast.error(res?.data?.message || t('Failed to create conversation'));
return null;
}
setSessions((prev) => prependCreatedSession(prev, createdConv));
setActiveSessionId(newId);
saveActiveSessionId(newId);
setMessage([]);
// 新会话没有历史摘要,重置(summarizingRef 交给飞行中的 maybeSummarize 自己复位)
setConversationSummary('');
setSummarizedUpToMessageId(0);
// 新会话不可能是归档
setActiveSessionArchived(false);
return createdConv;
} catch (e) {
console.error('Failed to create conversation', e);
Toast.error(t('Failed to create conversation'));
return null;
} finally {
setSessionCreating(false);
}
})();
sessionCreatePromiseRef.current = createPromise;
try {
return await createPromise;
} finally {
sessionCreatePromiseRef.current = null;
}
}, [abortInflightStream, inputs.group, inputs.model, t]);
const deleteSessionById = useCallback(
async (id) => {
if (!id) return;
const isDeletingActive = id === activeSessionId;
try {
const res = await deleteConversation(id);
if (!res?.data?.success) {
Toast.error(res?.data?.message || t('Failed to delete conversation'));
return;
}
Toast.success(t('Conversation deleted'));
if (isDeletingActive) {
abortInflightStream();
}
// 直接基于当前 sessions 状态计算"下一个会话",不能依赖 setSessions updater
// 的同步执行 —— React 只在特定条件下 eager 执行 updater,不保证在下一行代码
// 前跑完;靠 updater 里的赋值取 nextSessionId 会偶发拿到 null,
// 把"删除当前会话后自动切到下一个"退化成"清空选择"。
const resolved = removeSessionAndResolveNext({
sessions,
deletedSessionId: id,
activeSessionId,
});
const nextSessionId = resolved.nextActiveSessionId;
setSessions(resolved.remainingSessions);
if (isDeletingActive) {
if (nextSessionId) {
await switchSession(nextSessionId);
} else {
clearActiveSessionSelection();
}
}
} catch (e) {
console.error('Failed to delete conversation', e);
Toast.error(t('Failed to delete conversation'));
}
},
[
sessions,
activeSessionId,
switchSession,
clearActiveSessionSelection,
abortInflightStream,
t,
],
);
const renameSession = useCallback(
async (id, newTitle) => {
if (!id || !newTitle) return false;
try {
const res = await updateConversationTitle(id, newTitle);
if (!res?.data?.success) {
Toast.error(res?.data?.message || t('Failed to rename conversation'));
return false;
}
setSessions((prev) =>
prev.map((s) => (s.id === id ? { ...s, title: newTitle } : s)),
);
return true;
} catch (e) {
console.error('Failed to rename conversation', e);
Toast.error(t('Failed to rename conversation'));
return false;
}
},
[t],
);
useEffect(() => {
return () => {
if (saveConfigTimeoutRef.current) {
clearTimeout(saveConfigTimeoutRef.current);
}
};
}, []);
useEffect(() => {
if (!Array.isArray(message) || message.length === 0) return;
const lastMsg = message[message.length - 1];
if (
lastMsg.status === MESSAGE_STATUS.LOADING ||
lastMsg.status === MESSAGE_STATUS.INCOMPLETE
) {
const processed = processIncompleteThinkTags(
lastMsg.content || '',
lastMsg.reasoningContent || '',
);
const fixedLastMsg = {
...lastMsg,
status: MESSAGE_STATUS.COMPLETE,
content: processed.content,
reasoningContent: processed.reasoningContent || null,
isThinkingComplete: true,
};
const updatedMessages = [...message.slice(0, -1), fixedLastMsg];
setMessage(updatedMessages);
setTimeout(() => saveMessagesImmediately(updatedMessages), 0);
}
}, []);
return {
inputs,
parameterEnabled,
showDebugPanel,
customRequestMode,
customRequestBody,
showSettings,
models,
groups,
status,
message,
debugData,
activeDebugTab,
previewPayload,
editingMessageId,
editValue,
// Refs
sseSourceRef,
chatRef,
saveConfigTimeoutRef,
setInputs,
setParameterEnabled,
setShowDebugPanel,
setCustomRequestMode,
setCustomRequestBody,
setShowSettings,
setModels,
setGroups,
setStatus,
setMessage,
setDebugData,
setActiveDebugTab,
setPreviewPayload,
setEditingMessageId,
setEditValue,
handleInputChange,
handleParameterToggle,
debouncedSaveConfig,
saveMessagesImmediately,
handleConfigImport,
handleConfigReset,
sessions,
activeSessionId,
sessionsLoading,
sessionSwitching,
sessionCreating,
sessionHasMore,
setActiveSessionId,
setSessions,
loadSessions,
loadMoreSessions,
switchSession,
clearActiveSessionSelection,
createNewSession,
deleteSessionById,
renameSession,
// 长会话自动摘要
conversationSummary,
setConversationSummary,
summarizedUpToMessageId,
setSummarizedUpToMessageId,
summarizingRef,
summaryGenRef,
// 归档(只读)
activeSessionArchived,
};
};
@@ -0,0 +1,160 @@
/*
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, useEffect, useRef, useState } from 'react';
/**
* useSpeechRecognition —— 浏览器原生 STT,目前依赖 webkit / 标准 SpeechRecognition。
*
* 兼容性:
* - Chrome / Edge / 大部分移动 Safari 支持
* - Firefox 不原生支持(API 不存在),isSupported 会返回 false
*
* 行为:
* - 默认 zh-CN,连续模式 (continuous=true),开 interim 结果实时反馈
* - onResult(text, isFinal) 把识别结果回传给调用方,由调用方决定怎么塞进输入框
* - 错误(permission denied / no-speech / aborted 等)转 onError 给上层
* - 自动处理 onend:如果用户没主动 stop,自动 restart 维持长录音(部分浏览器会自动 stop)
*/
const getRecognitionCtor = () => {
if (typeof window === 'undefined') return null;
return window.SpeechRecognition || window.webkitSpeechRecognition || null;
};
export const useSpeechRecognition = ({
onResult,
onError,
lang = 'zh-CN',
} = {}) => {
const RecognitionCtor = getRecognitionCtor();
const isSupported = !!RecognitionCtor;
const [isListening, setIsListening] = useState(false);
const recognitionRef = useRef(null);
const userStoppedRef = useRef(false); // 用户主动 stop vs 浏览器 auto end
const stop = useCallback(() => {
userStoppedRef.current = true;
const rec = recognitionRef.current;
if (rec) {
try {
rec.stop();
} catch (_) {
/* ignore */
}
}
setIsListening(false);
}, []);
const start = useCallback(() => {
if (!isSupported) return;
// 已经在录就不重复 start —— 浏览器会抛 InvalidStateError
if (recognitionRef.current && isListening) return;
let rec;
try {
rec = new RecognitionCtor();
} catch (e) {
onError?.(e);
return;
}
rec.lang = lang;
rec.continuous = true;
rec.interimResults = true;
rec.maxAlternatives = 1;
rec.onresult = (event) => {
// event.results 是累加的 SpeechRecognitionResultList;遍历从 resultIndex 开始的新分段
let finalText = '';
let interimText = '';
for (let i = event.resultIndex; i < event.results.length; i++) {
const res = event.results[i];
const transcript = res[0]?.transcript || '';
if (res.isFinal) finalText += transcript;
else interimText += transcript;
}
if (finalText) onResult?.(finalText, true);
else if (interimText) onResult?.(interimText, false);
};
rec.onerror = (event) => {
// no-speech / aborted 都是常见的非致命错误,不一定要广播;只对真出错时通知
if (
event?.error &&
event.error !== 'no-speech' &&
event.error !== 'aborted'
) {
onError?.(event);
}
};
rec.onend = () => {
// Chrome 长时间没说话会自动 onend,要么用户停了,要么浏览器停了
if (userStoppedRef.current) {
setIsListening(false);
recognitionRef.current = null;
return;
}
// 浏览器自停 → 尝试无缝续上
try {
rec.start();
} catch (_) {
// 续上失败,照常结束
setIsListening(false);
recognitionRef.current = null;
}
};
recognitionRef.current = rec;
userStoppedRef.current = false;
try {
rec.start();
setIsListening(true);
} catch (e) {
onError?.(e);
recognitionRef.current = null;
setIsListening(false);
}
}, [isSupported, RecognitionCtor, lang, isListening, onResult, onError]);
// 卸载时确保停掉,避免麦克风指示灯一直亮
useEffect(() => {
return () => {
const rec = recognitionRef.current;
if (rec) {
userStoppedRef.current = true;
try {
rec.stop();
} catch (_) {
/* ignore */
}
recognitionRef.current = null;
}
};
}, []);
const toggle = useCallback(() => {
if (isListening) stop();
else start();
}, [isListening, start, stop]);
return { isSupported, isListening, start, stop, toggle };
};
export default useSpeechRecognition;
+170
View File
@@ -0,0 +1,170 @@
/*
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, useEffect, useRef, useState } from 'react';
/**
* useSpeechSynthesis —— 浏览器原生朗读 hook
*
* 设计要点:
* - speechSynthesis 是全局单例(同时只能播一个 utterance)。这里用一个全局 ref 跟踪"哪个消息在播",
* 避免多条助手消息的 TTS 按钮状态错位。
* - 中文响应默认挑 zh-* 的 voice;找不到就走系统默认。
* - 长文本会被部分浏览器(Chrome)在 ~15s 处自动断流,这里用 resume 心跳兜底;不完美但够用。
* - 卸载/路由切换时自动 cancel,避免后台还在念。
*/
// 模块级"当前正在播的 messageId",让所有调用 hook 的实例共享状态
let currentSpeakingId = null;
const listeners = new Set();
const notifyListeners = () => {
listeners.forEach((fn) => fn(currentSpeakingId));
};
export const useSpeechSynthesis = () => {
const isSupported =
typeof window !== 'undefined' && 'speechSynthesis' in window;
const [speakingId, setSpeakingId] = useState(currentSpeakingId);
const utteranceRef = useRef(null);
const heartbeatRef = useRef(null);
// 订阅模块级状态:任意 hook 实例改变了 currentSpeakingId,所有实例都收到
useEffect(() => {
const listener = (id) => setSpeakingId(id);
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}, []);
// 清掉 Chrome 长文本断流兜底
const clearHeartbeat = useCallback(() => {
if (heartbeatRef.current) {
clearInterval(heartbeatRef.current);
heartbeatRef.current = null;
}
}, []);
const stop = useCallback(() => {
if (!isSupported) return;
clearHeartbeat();
try {
window.speechSynthesis.cancel();
} catch (_) {
// ignore
}
utteranceRef.current = null;
currentSpeakingId = null;
notifyListeners();
}, [isSupported, clearHeartbeat]);
const speak = useCallback(
(id, text) => {
if (!isSupported || !text) return;
// 同一条消息再点 → 当作 stop 处理(按钮变 toggle)
if (currentSpeakingId === id) {
stop();
return;
}
// 抢占:之前在播别的就先停掉
try {
window.speechSynthesis.cancel();
} catch (_) {
/* ignore */
}
clearHeartbeat();
const utt = new SpeechSynthesisUtterance(text);
// 挑中文音色(如果是中文内容),否则用默认
try {
const voices = window.speechSynthesis.getVoices() || [];
const looksChinese = /[一-龥]/.test(text);
if (looksChinese) {
const zh = voices.find((v) => /zh|cmn|chinese/i.test(v.lang));
if (zh) utt.voice = zh;
utt.lang = 'zh-CN';
} else {
const en = voices.find((v) => /en[-_]US|english/i.test(v.lang));
if (en) utt.voice = en;
}
} catch (_) {
// 取 voices 失败也无所谓,用浏览器默认
}
utt.rate = 1;
utt.pitch = 1;
utt.onend = () => {
clearHeartbeat();
if (currentSpeakingId === id) {
currentSpeakingId = null;
notifyListeners();
}
};
utt.onerror = () => {
clearHeartbeat();
if (currentSpeakingId === id) {
currentSpeakingId = null;
notifyListeners();
}
};
utteranceRef.current = utt;
currentSpeakingId = id;
notifyListeners();
window.speechSynthesis.speak(utt);
// Chrome 长文本 bug 兜底:每 10s pause/resume 一次让它不要断
heartbeatRef.current = setInterval(() => {
try {
if (window.speechSynthesis.speaking) {
window.speechSynthesis.pause();
window.speechSynthesis.resume();
} else {
clearHeartbeat();
}
} catch (_) {
clearHeartbeat();
}
}, 10000);
},
[isSupported, stop, clearHeartbeat],
);
// 卸载时停止任何在播的 — 避免页面卸载后还在念
useEffect(() => {
return () => {
// 仅当当前 instance 正在播自己的 utterance 时才 cancel;其它实例还在使用就别打断
if (utteranceRef.current && window.speechSynthesis?.speaking) {
try {
window.speechSynthesis.cancel();
} catch (_) {
/* ignore */
}
clearHeartbeat();
}
};
}, [clearHeartbeat]);
return {
isSupported,
speakingId, // 当前模块内正在播放的消息 id,null 表示无
speak, // (id, text) => void;同 id 再次调用等同 stop
stop,
};
};
export default useSpeechSynthesis;
@@ -0,0 +1,149 @@
/*
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, useRef } from 'react';
import { MESSAGE_ROLES } from '../../constants/playground.constants';
export const useSyncMessageAndCustomBody = (
customRequestMode,
customRequestBody,
message,
inputs,
setCustomRequestBody,
setMessage,
debouncedSaveConfig,
) => {
const isUpdatingFromMessage = useRef(false);
const isUpdatingFromCustomBody = useRef(false);
const lastMessageHash = useRef('');
const lastCustomBodyHash = useRef('');
const getMessageHash = useCallback((messages) => {
return JSON.stringify(
messages.map((msg) => ({
id: msg.id,
role: msg.role,
content: msg.content,
})),
);
}, []);
const getCustomBodyHash = useCallback((customBody) => {
try {
const parsed = JSON.parse(customBody);
return JSON.stringify(parsed.messages || []);
} catch {
return '';
}
}, []);
const syncMessageToCustomBody = useCallback(() => {
if (!customRequestMode || isUpdatingFromCustomBody.current) return;
const currentMessageHash = getMessageHash(message);
if (currentMessageHash === lastMessageHash.current) return;
try {
isUpdatingFromMessage.current = true;
let customPayload;
try {
customPayload = JSON.parse(customRequestBody || '{}');
} catch {
customPayload = {
model: inputs.model || 'gpt-4o',
messages: [],
temperature: inputs.temperature || 0.7,
stream: inputs.stream !== false,
};
}
customPayload.messages = message.map((msg) => ({
role: msg.role,
content: msg.content,
}));
const newCustomBody = JSON.stringify(customPayload, null, 2);
setCustomRequestBody(newCustomBody);
lastMessageHash.current = currentMessageHash;
lastCustomBodyHash.current = getCustomBodyHash(newCustomBody);
setTimeout(() => {
debouncedSaveConfig();
}, 0);
} finally {
isUpdatingFromMessage.current = false;
}
}, [
customRequestMode,
customRequestBody,
message,
inputs.model,
inputs.temperature,
inputs.stream,
getMessageHash,
getCustomBodyHash,
setCustomRequestBody,
debouncedSaveConfig,
]);
const syncCustomBodyToMessage = useCallback(() => {
if (!customRequestMode || isUpdatingFromMessage.current) return;
const currentCustomBodyHash = getCustomBodyHash(customRequestBody);
if (currentCustomBodyHash === lastCustomBodyHash.current) return;
try {
isUpdatingFromCustomBody.current = true;
const customPayload = JSON.parse(customRequestBody || '{}');
if (customPayload.messages && Array.isArray(customPayload.messages)) {
const newMessages = customPayload.messages.map((msg, index) => ({
id: msg.id || (index + 1).toString(),
role: msg.role || MESSAGE_ROLES.USER,
content: msg.content || '',
createAt: Date.now(),
...(msg.role === MESSAGE_ROLES.ASSISTANT && {
reasoningContent: msg.reasoningContent || '',
isReasoningExpanded: false,
}),
}));
setMessage(newMessages);
lastCustomBodyHash.current = currentCustomBodyHash;
lastMessageHash.current = getMessageHash(newMessages);
}
} catch (error) {
console.warn('同步自定义请求体到消息失败:', error);
} finally {
isUpdatingFromCustomBody.current = false;
}
}, [
customRequestMode,
customRequestBody,
getCustomBodyHash,
getMessageHash,
setMessage,
]);
return {
syncMessageToCustomBody,
syncCustomBodyToMessage,
};
};