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
File diff suppressed because it is too large Load Diff
+357
View File
@@ -0,0 +1,357 @@
/*
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 React, { useState, useMemo, useCallback } from 'react';
import { Button, Tooltip, Toast } from '@douyinfe/semi-ui';
import { Copy, ChevronDown, ChevronUp } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { copy } from '../../helpers';
const PERFORMANCE_CONFIG = {
MAX_DISPLAY_LENGTH: 50000, // 最大显示字符数
PREVIEW_LENGTH: 5000, // 预览长度
VERY_LARGE_MULTIPLIER: 2, // 超大内容倍数
};
const codeThemeStyles = {
container: {
backgroundColor: '#1e1e1e',
color: '#d4d4d4',
fontFamily: 'Consolas, "Courier New", Monaco, "SF Mono", monospace',
fontSize: '13px',
lineHeight: '1.4',
borderRadius: '8px',
border: '1px solid #3c3c3c',
position: 'relative',
overflow: 'hidden',
boxShadow: '0 2px 8px rgba(0, 0, 0, 0.15)',
},
content: {
height: '100%',
overflowY: 'auto',
overflowX: 'auto',
padding: '16px',
margin: 0,
whiteSpace: 'pre',
wordBreak: 'normal',
background: '#1e1e1e',
},
actionButton: {
position: 'absolute',
zIndex: 10,
backgroundColor: 'rgba(45, 45, 45, 0.9)',
border: '1px solid rgba(255, 255, 255, 0.1)',
color: '#d4d4d4',
borderRadius: '6px',
transition: 'all 0.2s ease',
},
actionButtonHover: {
backgroundColor: 'rgba(60, 60, 60, 0.95)',
borderColor: 'rgba(255, 255, 255, 0.2)',
transform: 'scale(1.05)',
},
noContent: {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
height: '100%',
color: '#666',
fontSize: '14px',
fontStyle: 'italic',
backgroundColor: 'var(--semi-color-fill-0)',
borderRadius: '8px',
},
performanceWarning: {
padding: '8px 12px',
backgroundColor: 'rgba(255, 193, 7, 0.1)',
border: '1px solid rgba(255, 193, 7, 0.3)',
borderRadius: '6px',
color: '#ffc107',
fontSize: '12px',
marginBottom: '8px',
display: 'flex',
alignItems: 'center',
gap: '8px',
},
};
const highlightJson = (str) => {
return str.replace(
/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+-]?\d+)?)/g,
(match) => {
let color = '#b5cea8';
if (/^"/.test(match)) {
color = /:$/.test(match) ? '#9cdcfe' : '#ce9178';
} else if (/true|false|null/.test(match)) {
color = '#569cd6';
}
return `<span style="color: ${color}">${match}</span>`;
},
);
};
const isJsonLike = (content, language) => {
if (language === 'json') return true;
const trimmed = content.trim();
return (
(trimmed.startsWith('{') && trimmed.endsWith('}')) ||
(trimmed.startsWith('[') && trimmed.endsWith(']'))
);
};
const formatContent = (content) => {
if (!content) return '';
if (typeof content === 'object') {
try {
return JSON.stringify(content, null, 2);
} catch (e) {
return String(content);
}
}
if (typeof content === 'string') {
try {
const parsed = JSON.parse(content);
return JSON.stringify(parsed, null, 2);
} catch (e) {
return content;
}
}
return String(content);
};
const CodeViewer = ({ content, title, language = 'json' }) => {
const { t } = useTranslation();
const [copied, setCopied] = useState(false);
const [isHoveringCopy, setIsHoveringCopy] = useState(false);
const [isExpanded, setIsExpanded] = useState(false);
const [isProcessing, setIsProcessing] = useState(false);
const formattedContent = useMemo(() => formatContent(content), [content]);
const contentMetrics = useMemo(() => {
const length = formattedContent.length;
const isLarge = length > PERFORMANCE_CONFIG.MAX_DISPLAY_LENGTH;
const isVeryLarge =
length >
PERFORMANCE_CONFIG.MAX_DISPLAY_LENGTH *
PERFORMANCE_CONFIG.VERY_LARGE_MULTIPLIER;
return { length, isLarge, isVeryLarge };
}, [formattedContent.length]);
const displayContent = useMemo(() => {
if (!contentMetrics.isLarge || isExpanded) {
return formattedContent;
}
return (
formattedContent.substring(0, PERFORMANCE_CONFIG.PREVIEW_LENGTH) +
'\n\n// ... 内容被截断以提升性能 ...'
);
}, [formattedContent, contentMetrics.isLarge, isExpanded]);
const highlightedContent = useMemo(() => {
if (contentMetrics.isVeryLarge && !isExpanded) {
return displayContent;
}
if (isJsonLike(displayContent, language)) {
return highlightJson(displayContent);
}
return displayContent;
}, [displayContent, language, contentMetrics.isVeryLarge, isExpanded]);
const handleCopy = useCallback(async () => {
try {
const textToCopy =
typeof content === 'object' && content !== null
? JSON.stringify(content, null, 2)
: content;
const success = await copy(textToCopy);
setCopied(true);
Toast.success(t('已复制到剪贴板'));
setTimeout(() => setCopied(false), 2000);
if (!success) {
throw new Error('Copy operation failed');
}
} catch (err) {
Toast.error(t('复制失败'));
console.error('Copy failed:', err);
}
}, [content, t]);
const handleToggleExpand = useCallback(() => {
if (contentMetrics.isVeryLarge && !isExpanded) {
setIsProcessing(true);
setTimeout(() => {
setIsExpanded(true);
setIsProcessing(false);
}, 100);
} else {
setIsExpanded(!isExpanded);
}
}, [isExpanded, contentMetrics.isVeryLarge]);
if (!content) {
const placeholderText =
{
preview: t('正在构造请求体预览...'),
request: t('暂无请求数据'),
response: t('暂无响应数据'),
}[title] || t('暂无数据');
return (
<div style={codeThemeStyles.noContent}>
<span>{placeholderText}</span>
</div>
);
}
const warningTop = contentMetrics.isLarge ? '52px' : '12px';
const contentPadding = contentMetrics.isLarge ? '52px' : '16px';
return (
<div style={codeThemeStyles.container} className='h-full'>
{/* 性能警告 */}
{contentMetrics.isLarge && (
<div style={codeThemeStyles.performanceWarning}>
<span>⚡</span>
<span>
{contentMetrics.isVeryLarge
? t('内容较大,已启用性能优化模式')
: t('内容较大,部分功能可能受限')}
</span>
</div>
)}
{/* 复制按钮 */}
<div
style={{
...codeThemeStyles.actionButton,
...(isHoveringCopy ? codeThemeStyles.actionButtonHover : {}),
top: warningTop,
right: '12px',
}}
onMouseEnter={() => setIsHoveringCopy(true)}
onMouseLeave={() => setIsHoveringCopy(false)}
>
<Tooltip content={copied ? t('已复制') : t('复制代码')}>
<Button
icon={<Copy size={14} />}
onClick={handleCopy}
size='small'
theme='borderless'
style={{
backgroundColor: 'transparent',
border: 'none',
color: copied ? '#4ade80' : '#d4d4d4',
padding: '6px',
}}
/>
</Tooltip>
</div>
{/* 代码内容 */}
<div
style={{
...codeThemeStyles.content,
paddingTop: contentPadding,
}}
className='model-settings-scroll'
>
{isProcessing ? (
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
height: '200px',
color: '#888',
}}
>
<div
style={{
width: '20px',
height: '20px',
border: '2px solid #444',
borderTop: '2px solid #888',
borderRadius: '50%',
animation: 'spin 1s linear infinite',
marginRight: '8px',
}}
/>
{t('正在处理大内容...')}
</div>
) : (
<div dangerouslySetInnerHTML={{ __html: highlightedContent }} />
)}
</div>
{/* 展开/收起按钮 */}
{contentMetrics.isLarge && !isProcessing && (
<div
style={{
...codeThemeStyles.actionButton,
bottom: '12px',
left: '50%',
transform: 'translateX(-50%)',
}}
>
<Tooltip content={isExpanded ? t('收起内容') : t('显示完整内容')}>
<Button
icon={
isExpanded ? <ChevronUp size={14} /> : <ChevronDown size={14} />
}
onClick={handleToggleExpand}
size='small'
theme='borderless'
style={{
backgroundColor: 'transparent',
border: 'none',
color: '#d4d4d4',
padding: '6px 12px',
}}
>
{isExpanded ? t('收起') : t('展开')}
{!isExpanded && (
<span
style={{ fontSize: '11px', opacity: 0.7, marginLeft: '4px' }}
>
(+
{Math.round(
(contentMetrics.length -
PERFORMANCE_CONFIG.PREVIEW_LENGTH) /
1000,
)}
K)
</span>
)}
</Button>
</Tooltip>
</div>
)}
</div>
);
};
export default CodeViewer;
+281
View File
@@ -0,0 +1,281 @@
/*
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 React, { useRef } from 'react';
import { Button, Typography, Toast, Modal, Dropdown } from '@douyinfe/semi-ui';
import { Download, Upload, RotateCcw, Settings2 } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import {
exportConfig,
importConfig,
clearConfig,
hasStoredConfig,
getConfigTimestamp,
} from './configStorage';
const ConfigManager = ({
currentConfig,
onConfigImport,
onConfigReset,
styleState,
messages,
}) => {
const { t } = useTranslation();
const fileInputRef = useRef(null);
const handleExport = () => {
try {
// 在导出前先保存当前配置,确保导出的是最新内容
const configWithTimestamp = {
...currentConfig,
timestamp: new Date().toISOString(),
};
localStorage.setItem(
'playground_config',
JSON.stringify(configWithTimestamp),
);
exportConfig(currentConfig, messages);
Toast.success({
content: t('配置已导出到下载文件夹'),
duration: 3,
});
} catch (error) {
Toast.error({
content: t('导出配置失败: ') + error.message,
duration: 3,
});
}
};
const handleImportClick = () => {
fileInputRef.current?.click();
};
const handleFileChange = async (event) => {
const file = event.target.files[0];
if (!file) return;
try {
const importedConfig = await importConfig(file);
Modal.confirm({
title: t('确认导入配置'),
content: t('导入的配置将覆盖当前设置,是否继续?'),
okText: t('确定导入'),
cancelText: t('取消'),
onOk: () => {
onConfigImport(importedConfig);
Toast.success({
content: t('配置导入成功'),
duration: 3,
});
},
});
} catch (error) {
Toast.error({
content: t('导入配置失败: ') + error.message,
duration: 3,
});
} finally {
// 重置文件输入,允许重复选择同一文件
event.target.value = '';
}
};
const handleReset = () => {
Modal.confirm({
title: t('重置配置'),
content: t(
'将清除所有保存的配置并恢复默认设置,此操作不可撤销。是否继续?',
),
okText: t('确定重置'),
cancelText: t('取消'),
okButtonProps: {
type: 'danger',
},
onOk: () => {
// 询问是否同时重置消息
Modal.confirm({
title: t('重置选项'),
content: t(
'是否同时重置对话消息?选择"是"将清空所有对话记录并恢复默认示例;选择"否"将保留当前对话记录。',
),
okText: t('同时重置消息'),
cancelText: t('仅重置配置'),
okButtonProps: {
type: 'danger',
},
onOk: () => {
clearConfig();
onConfigReset({ resetMessages: true });
Toast.success({
content: t('配置和消息已全部重置'),
duration: 3,
});
},
onCancel: () => {
clearConfig();
onConfigReset({ resetMessages: false });
Toast.success({
content: t('配置已重置,对话消息已保留'),
duration: 3,
});
},
});
},
});
};
const getConfigStatus = () => {
if (hasStoredConfig()) {
const timestamp = getConfigTimestamp();
if (timestamp) {
const date = new Date(timestamp);
return t('上次保存: ') + date.toLocaleString();
}
return t('已有保存的配置');
}
return t('暂无保存的配置');
};
const dropdownItems = [
{
node: 'item',
name: 'export',
onClick: handleExport,
children: (
<div className='flex items-center gap-2'>
<Download size={14} />
{t('导出配置')}
</div>
),
},
{
node: 'item',
name: 'import',
onClick: handleImportClick,
children: (
<div className='flex items-center gap-2'>
<Upload size={14} />
{t('导入配置')}
</div>
),
},
{
node: 'divider',
},
{
node: 'item',
name: 'reset',
onClick: handleReset,
children: (
<div className='flex items-center gap-2 text-red-600'>
<RotateCcw size={14} />
{t('重置配置')}
</div>
),
},
];
if (styleState.isMobile) {
// 移动端显示简化的下拉菜单
return (
<>
<Dropdown
trigger='click'
position='bottomLeft'
showTick
menu={dropdownItems}
>
<Button
icon={<Settings2 size={14} />}
theme='borderless'
type='tertiary'
size='small'
className='!rounded-lg !text-gray-600 hover:!text-blue-600 hover:!bg-blue-50'
/>
</Dropdown>
<input
ref={fileInputRef}
type='file'
accept='.json'
onChange={handleFileChange}
style={{ display: 'none' }}
/>
</>
);
}
// 桌面端显示紧凑的按钮组
return (
<div className='space-y-3'>
{/* 配置状态信息和重置按钮 */}
<div className='flex items-center justify-between'>
<Typography.Text className='text-xs text-gray-500'>
{getConfigStatus()}
</Typography.Text>
<Button
icon={<RotateCcw size={12} />}
size='small'
theme='borderless'
type='danger'
onClick={handleReset}
className='!rounded-full !text-xs !px-2'
/>
</div>
{/* 导出和导入按钮 */}
<div className='flex gap-2'>
<Button
icon={<Download size={12} />}
size='small'
theme='solid'
type='primary'
onClick={handleExport}
className='!rounded-lg flex-1 !text-xs !h-7'
>
{t('导出')}
</Button>
<Button
icon={<Upload size={12} />}
size='small'
theme='outline'
type='primary'
onClick={handleImportClick}
className='!rounded-lg flex-1 !text-xs !h-7'
>
{t('导入')}
</Button>
</div>
<input
ref={fileInputRef}
type='file'
accept='.json'
onChange={handleFileChange}
style={{ display: 'none' }}
/>
</div>
);
};
export default ConfigManager;
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,217 @@
/*
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 React, { useState, useEffect } from 'react';
import {
TextArea,
Typography,
Button,
Switch,
Banner,
} from '@douyinfe/semi-ui';
import { Code, Edit, Check, X, AlertTriangle } from 'lucide-react';
import { useTranslation } from 'react-i18next';
const CustomRequestEditor = ({
customRequestMode,
customRequestBody,
onCustomRequestModeChange,
onCustomRequestBodyChange,
defaultPayload,
}) => {
const { t } = useTranslation();
const [isValid, setIsValid] = useState(true);
const [errorMessage, setErrorMessage] = useState('');
const [localValue, setLocalValue] = useState(customRequestBody || '');
// 当切换到自定义模式时,用默认payload初始化
useEffect(() => {
if (
customRequestMode &&
(!customRequestBody || customRequestBody.trim() === '')
) {
const defaultJson = defaultPayload
? JSON.stringify(defaultPayload, null, 2)
: '';
setLocalValue(defaultJson);
onCustomRequestBodyChange(defaultJson);
}
}, [
customRequestMode,
defaultPayload,
customRequestBody,
onCustomRequestBodyChange,
]);
// 同步外部传入的customRequestBody到本地状态
useEffect(() => {
if (customRequestBody !== localValue) {
setLocalValue(customRequestBody || '');
validateJson(customRequestBody || '');
}
}, [customRequestBody]);
// 验证JSON格式
const validateJson = (value) => {
if (!value.trim()) {
setIsValid(true);
setErrorMessage('');
return true;
}
try {
JSON.parse(value);
setIsValid(true);
setErrorMessage('');
return true;
} catch (error) {
setIsValid(false);
setErrorMessage(`${t('JSON格式错误')}: ${error.message}`);
return false;
}
};
const handleValueChange = (value) => {
setLocalValue(value);
validateJson(value);
// 始终保存用户输入,让预览逻辑处理JSON解析错误
onCustomRequestBodyChange(value);
};
const handleModeToggle = (enabled) => {
onCustomRequestModeChange(enabled);
if (enabled && defaultPayload) {
const defaultJson = JSON.stringify(defaultPayload, null, 2);
setLocalValue(defaultJson);
onCustomRequestBodyChange(defaultJson);
}
};
const formatJson = () => {
try {
const parsed = JSON.parse(localValue);
const formatted = JSON.stringify(parsed, null, 2);
setLocalValue(formatted);
onCustomRequestBodyChange(formatted);
setIsValid(true);
setErrorMessage('');
} catch (error) {
// 如果格式化失败,保持原样
}
};
return (
<div className='space-y-4'>
{/* 自定义模式开关 */}
<div className='flex items-center justify-between'>
<div className='flex items-center gap-2'>
<Code size={16} className='text-gray-500' />
<Typography.Text strong className='text-sm'>
{t('自定义请求体模式')}
</Typography.Text>
</div>
<Switch
checked={customRequestMode}
onChange={handleModeToggle}
checkedText={t('开')}
uncheckedText={t('关')}
size='small'
/>
</div>
{customRequestMode && (
<>
{/* 提示信息 */}
<Banner
type='warning'
description={t(
'启用此模式后,将使用您自定义的请求体发送API请求,模型配置面板的参数设置将被忽略。',
)}
icon={<AlertTriangle size={16} />}
className='!rounded-lg'
closeIcon={null}
/>
{/* JSON编辑器 */}
<div>
<div className='flex items-center justify-between mb-2'>
<Typography.Text strong className='text-sm'>
{t('请求体 JSON')}
</Typography.Text>
<div className='flex items-center gap-2'>
{isValid ? (
<div className='flex items-center gap-1 text-green-600'>
<Check size={14} />
<Typography.Text className='text-xs'>
{t('格式正确')}
</Typography.Text>
</div>
) : (
<div className='flex items-center gap-1 text-red-600'>
<X size={14} />
<Typography.Text className='text-xs'>
{t('格式错误')}
</Typography.Text>
</div>
)}
<Button
theme='borderless'
type='tertiary'
size='small'
icon={<Edit size={14} />}
onClick={formatJson}
disabled={!isValid}
className='!rounded-lg'
>
{t('格式化')}
</Button>
</div>
</div>
<TextArea
value={localValue}
onChange={handleValueChange}
placeholder='{"model": "gpt-4o", "messages": [...], ...}'
autosize={{ minRows: 8, maxRows: 20 }}
className={`custom-request-textarea !rounded-lg font-mono text-sm ${!isValid ? '!border-red-500' : ''}`}
style={{
fontFamily: 'Consolas, Monaco, "Courier New", monospace',
lineHeight: '1.5',
}}
/>
{!isValid && errorMessage && (
<Typography.Text type='danger' className='text-xs mt-1 block'>
{errorMessage}
</Typography.Text>
)}
<Typography.Text className='text-xs text-gray-500 mt-2 block'>
{t(
'请输入有效的JSON格式的请求体。您可以参考预览面板中的默认请求体格式。',
)}
</Typography.Text>
</div>
</>
)}
</div>
);
};
export default CustomRequestEditor;
+222
View File
@@ -0,0 +1,222 @@
/*
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 React, { useState, useEffect } from 'react';
import {
Card,
Typography,
Tabs,
TabPane,
Button,
Dropdown,
} from '@douyinfe/semi-ui';
import { Code, Zap, Clock, X, Eye, Send } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import CodeViewer from './CodeViewer';
import SSEViewer from './SSEViewer';
const DebugPanel = ({
debugData,
activeDebugTab,
onActiveDebugTabChange,
styleState,
onCloseDebugPanel,
customRequestMode,
}) => {
const { t } = useTranslation();
const [activeKey, setActiveKey] = useState(activeDebugTab);
useEffect(() => {
setActiveKey(activeDebugTab);
}, [activeDebugTab]);
const handleTabChange = (key) => {
setActiveKey(key);
onActiveDebugTabChange(key);
};
const renderArrow = (items, pos, handleArrowClick, defaultNode) => {
const style = {
width: 32,
height: 32,
margin: '0 12px',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
borderRadius: '100%',
background: 'rgba(var(--semi-grey-1), 1)',
color: 'var(--semi-color-text)',
cursor: 'pointer',
};
return (
<Dropdown
render={
<Dropdown.Menu>
{items.map((item) => {
return (
<Dropdown.Item
key={item.itemKey}
onClick={() => handleTabChange(item.itemKey)}
>
{item.tab}
</Dropdown.Item>
);
})}
</Dropdown.Menu>
}
>
{pos === 'start' ? (
<div style={style} onClick={handleArrowClick}>
←
</div>
) : (
<div style={style} onClick={handleArrowClick}>
→
</div>
)}
</Dropdown>
);
};
return (
<Card
className='h-full flex flex-col'
bordered={false}
bodyStyle={{
padding: styleState.isMobile ? '16px' : '24px',
height: '100%',
display: 'flex',
flexDirection: 'column',
}}
>
<div className='flex items-center justify-between mb-6 flex-shrink-0'>
<div className='flex items-center'>
<div className='w-10 h-10 rounded-full bg-gradient-to-r from-green-500 to-blue-500 flex items-center justify-center mr-3'>
<Code size={20} className='text-white' />
</div>
<Typography.Title heading={5} className='mb-0'>
{t('调试信息')}
</Typography.Title>
</div>
{styleState.isMobile && onCloseDebugPanel && (
<Button
icon={<X size={16} />}
onClick={onCloseDebugPanel}
theme='borderless'
type='tertiary'
size='small'
className='!rounded-lg'
/>
)}
</div>
<div className='flex-1 overflow-hidden debug-panel'>
<Tabs
renderArrow={renderArrow}
type='card'
collapsible
className='h-full'
style={{ height: '100%', display: 'flex', flexDirection: 'column' }}
activeKey={activeKey}
onChange={handleTabChange}
>
<TabPane
tab={
<div className='flex items-center gap-2'>
<Eye size={16} />
{t('预览请求体')}
{customRequestMode && (
<span className='px-1.5 py-0.5 text-xs bg-orange-100 text-orange-600 rounded-full'>{t('自定义')}</span>
)}
</div>
}
itemKey='preview'
>
<CodeViewer
content={debugData.previewRequest}
title='preview'
language='json'
/>
</TabPane>
<TabPane
tab={
<div className='flex items-center gap-2'>
<Send size={16} />
{t('实际请求体')}
</div>
}
itemKey='request'
>
<CodeViewer
content={debugData.request}
title='request'
language='json'
/>
</TabPane>
<TabPane
tab={
<div className='flex items-center gap-2'>
<Zap size={16} />
{t('响应')}
{debugData.sseMessages && debugData.sseMessages.length > 0 && (
<span className='px-1.5 py-0.5 text-xs bg-blue-100 text-blue-600 rounded-full'>
SSE ({debugData.sseMessages.length})
</span>
)}
</div>
}
itemKey='response'
>
{debugData.sseMessages && debugData.sseMessages.length > 0 ? (
<SSEViewer sseData={debugData.sseMessages} title='response' />
) : (
<CodeViewer
content={debugData.response}
title='response'
language='json'
/>
)}
</TabPane>
</Tabs>
</div>
<div className='flex items-center justify-between mt-4 pt-4 flex-shrink-0'>
{(debugData.timestamp || debugData.previewTimestamp) && (
<div className='flex items-center gap-2'>
<Clock size={14} className='text-gray-500' />
<Typography.Text className='text-xs text-gray-500'>
{activeKey === 'preview' && debugData.previewTimestamp
? `${t('预览更新')}: ${new Date(debugData.previewTimestamp).toLocaleString()}`
: debugData.timestamp
? `${t('最后请求')}: ${new Date(debugData.timestamp).toLocaleString()}`
: ''}
</Typography.Text>
</div>
)}
</div>
</Card>
);
};
export default DebugPanel;
@@ -0,0 +1,175 @@
/*
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 React, { useCallback, useMemo } from 'react';
import { Modal, Toast } from '@douyinfe/semi-ui';
import { Download, ExternalLink, X, FileText } from 'lucide-react';
import { useTranslation } from 'react-i18next';
// 体验中心消息气泡里"点击附件 chip 弹出预览"的统一入口。
// - PDF:用 <iframe> 嵌入,浏览器原生 viewer 性能足够;
// - 其它(DOC/XLSX/PPT/TXT/CSV 等):仅给"在新窗口打开 + 下载"两个按钮,不引入额外解析器。
// - 图片:交给独立的 ImagePreviewModal,本组件不处理(不要重复造 zoom/旋转控件)。
const PDF_EXT = ['pdf'];
const FilePreviewModal = ({ visible, file, onClose }) => {
const { t } = useTranslation();
const fileName =
file?.filename || file?.file_name || file?.name || t('未知文件');
const fileUrl = file?.file_data || file?.url;
const ext = useMemo(
() => (fileName || '').split('.').pop().toLowerCase(),
[fileName],
);
const isPdf = PDF_EXT.includes(ext);
const handleDownload = useCallback(async () => {
if (!fileUrl) return;
try {
const response = await fetch(fileUrl);
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = fileName;
document.body.appendChild(link);
link.click();
requestAnimationFrame(() => {
document.body.removeChild(link);
window.URL.revokeObjectURL(url);
});
} catch {
// CORS / 签名过期等场景:直接新开窗口让浏览器自己处理
Toast.info({ content: t('在新窗口打开'), duration: 2 });
window.open(fileUrl, '_blank');
}
}, [fileUrl, fileName, t]);
const handleOpenInNewTab = useCallback(() => {
if (!fileUrl) return;
window.open(fileUrl, '_blank', 'noopener,noreferrer');
}, [fileUrl]);
if (!file) return null;
const btnClass =
'inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-white/10 hover:bg-white/20 text-white/90 hover:text-white text-sm transition-all';
return (
<Modal
visible={visible}
onCancel={onClose}
footer={null}
closable={false}
maskClosable
width='100vw'
className='viewport-preview-modal'
style={{ maxWidth: '100vw', top: 0, padding: 0, margin: 0 }}
bodyStyle={{
padding: 0,
display: 'flex',
flexDirection: 'column',
// 移动端 URL bar 导致 vh 变化 → 用 dvh 取实际视口;老浏览器走 fallback 不崩
height: '100dvh',
background: 'rgba(0,0,0,0.92)',
}}
>
{/* Toolbar — 顶部 & 左右安全区,无刘海设备 env() 返回 0 行为一致 */}
<div
className='flex items-center justify-between px-4 py-3 bg-black/40 flex-shrink-0'
style={{
paddingTop: 'max(env(safe-area-inset-top), 0.75rem)',
paddingLeft: 'max(env(safe-area-inset-left), 1rem)',
paddingRight: 'max(env(safe-area-inset-right), 1rem)',
}}
>
<div className='flex items-center gap-2 min-w-0'>
<FileText size={18} className='text-white/70 flex-shrink-0' />
<span
className='text-white/90 text-sm truncate max-w-[40vw]'
title={fileName}
>
{fileName}
</span>
</div>
<div className='flex items-center gap-1.5'>
<button onClick={handleOpenInNewTab} className={btnClass}>
<ExternalLink size={14} />
{t('新窗口打开')}
</button>
<button onClick={handleDownload} className={btnClass}>
<Download size={14} />
{t('下载')}
</button>
<button
onClick={onClose}
className='w-9 h-9 flex items-center justify-center rounded-lg bg-white/10 hover:bg-white/20 text-white/80 hover:text-white transition-all'
title={t('关闭')}
>
<X size={20} />
</button>
</div>
</div>
{/* Preview body — 底部 home indicator + 左右安全区一并避开,PDF iframe 才不会被截一截 */}
<div
className='flex-1 flex items-center justify-center overflow-hidden p-4'
style={{
paddingBottom: 'max(env(safe-area-inset-bottom), 1rem)',
paddingLeft: 'max(env(safe-area-inset-left), 1rem)',
paddingRight: 'max(env(safe-area-inset-right), 1rem)',
}}
>
{isPdf ? (
<iframe
src={fileUrl}
title={fileName}
className='w-full h-full rounded-lg bg-white'
style={{ minHeight: '70dvh' }}
/>
) : (
<div className='flex flex-col items-center justify-center gap-4 px-6 py-10 rounded-2xl bg-white/5 border border-white/10 max-w-lg text-center'>
<FileText size={64} className='text-white/40' />
<div className='text-white/90 text-base font-medium break-all'>
{fileName}
</div>
<div className='text-white/50 text-sm'>
{t(
'此文件类型暂不支持在线预览,可下载到本地查看,或在新窗口打开。',
)}
</div>
<div className='flex items-center gap-2 mt-2'>
<button onClick={handleOpenInNewTab} className={btnClass}>
<ExternalLink size={14} />
{t('新窗口打开')}
</button>
<button onClick={handleDownload} className={btnClass}>
<Download size={14} />
{t('下载')}
</button>
</div>
</div>
)}
</div>
</Modal>
);
};
export default FilePreviewModal;
@@ -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 React from 'react';
import { Button } from '@douyinfe/semi-ui';
import { Settings, Eye, EyeOff } from 'lucide-react';
const FloatingButtons = ({
styleState,
showSettings,
showDebugPanel,
onToggleSettings,
onToggleDebugPanel,
hideSettingsButton = false,
}) => {
if (!styleState.isMobile) return null;
return (
<>
{/* 设置按钮(体验模式下设置面板不渲染,按钮也隐藏,避免出现死按钮) */}
{!showSettings && !hideSettingsButton && (
<Button
icon={<Settings size={18} />}
style={{
position: 'fixed',
right: 16,
// 跟随输入区实测高度避让(CustomInputRender 发布 --composer-top-offset)。
// 写死 90px 会正好压在手机端双行输入区的工具按钮行上。
bottom: 'calc(var(--composer-top-offset, 78px) + 12px)',
zIndex: 1000,
width: 36,
height: 36,
borderRadius: '50%',
padding: 0,
boxShadow: '0 4px 12px rgba(0, 0, 0, 0.2)',
background:
'linear-gradient(to right, var(--brand-gradient-via), var(--brand-primary))',
}}
onClick={onToggleSettings}
theme='solid'
type='primary'
className='lg:hidden'
/>
)}
{/* 调试按钮 */}
{!showSettings && (
<Button
icon={showDebugPanel ? <EyeOff size={18} /> : <Eye size={18} />}
onClick={onToggleDebugPanel}
theme='solid'
type={showDebugPanel ? 'danger' : 'primary'}
style={{
position: 'fixed',
right: 16,
// 叠在设置按钮之上一档(36px 按钮 + 12px 间距)
bottom: 'calc(var(--composer-top-offset, 78px) + 60px)',
zIndex: 1000,
width: 36,
height: 36,
borderRadius: '50%',
padding: 0,
boxShadow: '0 4px 12px rgba(0, 0, 0, 0.2)',
background: showDebugPanel
? 'linear-gradient(to right, #e11d48, #be123c)'
: 'linear-gradient(to right, var(--brand-primary-hover), var(--brand-primary))',
}}
className='lg:hidden'
/>
)}
</>
);
};
export default FloatingButtons;
@@ -0,0 +1,147 @@
/*
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 React, { useState, useCallback, useEffect } from 'react';
import { Modal } from '@douyinfe/semi-ui';
import { Download, ZoomIn, ZoomOut, X, RotateCw } from 'lucide-react';
const ImagePreviewModal = ({ visible, imageUrl, onClose }) => {
const [scale, setScale] = useState(1);
useEffect(() => {
setScale(1);
}, [imageUrl]);
const handleZoomIn = () => setScale((s) => Math.min(s + 0.25, 3));
const handleZoomOut = () => setScale((s) => Math.max(s - 0.25, 0.25));
const handleResetZoom = () => setScale(1);
const handleDownload = useCallback(async () => {
try {
const response = await fetch(imageUrl);
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = `image-${Date.now()}.png`;
document.body.appendChild(link);
link.click();
requestAnimationFrame(() => {
document.body.removeChild(link);
window.URL.revokeObjectURL(url);
});
} catch {
window.open(imageUrl, '_blank');
}
}, [imageUrl]);
const handleClose = useCallback(() => {
setScale(1);
onClose();
}, [onClose]);
if (!imageUrl) return null;
const btnClass =
'w-9 h-9 flex items-center justify-center rounded-lg bg-white/10 hover:bg-white/20 text-white/80 hover:text-white transition-all';
return (
<Modal
visible={visible}
onCancel={handleClose}
footer={null}
closable={false}
maskClosable
width='100vw'
className='viewport-preview-modal'
style={{ maxWidth: '100vw', top: 0, padding: 0, margin: 0 }}
bodyStyle={{
padding: 0,
display: 'flex',
flexDirection: 'column',
// 用 dvh 替代 vh:移动端浏览器 URL bar 收缩时 vh 会缩水露出底栏,dvh 始终对齐"实际可见高度"
// 老浏览器不识别 dvh 时 fallback 到 vh,不会崩
height: '100dvh',
background: 'rgba(0,0,0,0.92)',
}}
>
{/* Toolbar — 顶部安全区(刘海屏 / 状态栏)和左右安全区都用 env() 兜底,
没有刘海的设备拿到的是 0,行为一致 */}
<div
className='flex items-center justify-between px-4 py-3 bg-black/40 flex-shrink-0'
style={{
paddingTop: 'max(env(safe-area-inset-top), 0.75rem)',
paddingLeft: 'max(env(safe-area-inset-left), 1rem)',
paddingRight: 'max(env(safe-area-inset-right), 1rem)',
}}
>
<div className='flex items-center gap-1.5'>
<button onClick={handleZoomOut} className={btnClass}>
<ZoomOut size={18} />
</button>
<span className='text-white/70 text-sm min-w-[48px] text-center'>
{Math.round(scale * 100)}%
</span>
<button onClick={handleZoomIn} className={btnClass}>
<ZoomIn size={18} />
</button>
<button onClick={handleResetZoom} className={btnClass} title='Reset'>
<RotateCw size={16} />
</button>
</div>
<div className='flex items-center gap-1.5'>
<button onClick={handleDownload} className={btnClass}>
<Download size={18} />
</button>
<button onClick={handleClose} className={btnClass}>
<X size={20} />
</button>
</div>
</div>
{/* Image — 底部 home indicator 安全区也避一下 */}
<div
className='flex-1 flex items-center justify-center overflow-auto cursor-zoom-out'
style={{ paddingBottom: 'env(safe-area-inset-bottom)' }}
onClick={handleClose}
onWheel={(e) => {
e.preventDefault();
if (e.deltaY < 0) handleZoomIn();
else handleZoomOut();
}}
>
<img
src={imageUrl}
alt='preview'
style={{
transform: `scale(${scale})`,
transition: 'transform 0.2s ease',
maxWidth: '90vw',
maxHeight: '85vh',
objectFit: 'contain',
}}
className='rounded-lg shadow-2xl'
onClick={(e) => e.stopPropagation()}
/>
</div>
</Modal>
);
};
export default ImagePreviewModal;
+142
View File
@@ -0,0 +1,142 @@
/*
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 React from 'react';
import { Input, Typography, Button, Switch } from '@douyinfe/semi-ui';
import { IconFile } from '@douyinfe/semi-icons';
import { Plus, X, Image } from 'lucide-react';
import { useTranslation } from 'react-i18next';
const ImageUrlInput = ({
imageUrls,
imageEnabled,
onImageUrlsChange,
onImageEnabledChange,
disabled = false,
}) => {
const { t } = useTranslation();
const handleAddImageUrl = () => {
const newUrls = [...imageUrls, ''];
onImageUrlsChange(newUrls);
};
const handleUpdateImageUrl = (index, value) => {
const newUrls = [...imageUrls];
newUrls[index] = value;
onImageUrlsChange(newUrls);
};
const handleRemoveImageUrl = (index) => {
const newUrls = imageUrls.filter((_, i) => i !== index);
onImageUrlsChange(newUrls);
};
return (
<div className={disabled ? 'opacity-50' : ''}>
<div className='flex items-center justify-between mb-2'>
<div className='flex items-center gap-2'>
<Image
size={16}
className={
imageEnabled && !disabled ? 'text-blue-500' : 'text-gray-400'
}
/>
<Typography.Text strong className='text-sm'>
{t('图片地址')}
</Typography.Text>
{disabled && (
<Typography.Text className='text-xs text-orange-600'>
({t('已在自定义模式中忽略')})
</Typography.Text>
)}
</div>
<div className='flex items-center gap-2'>
<Switch
checked={imageEnabled}
onChange={onImageEnabledChange}
checkedText={t('启用')}
uncheckedText={t('停用')}
size='small'
className='flex-shrink-0'
disabled={disabled}
/>
<Button
icon={<Plus size={14} />}
size='small'
theme='solid'
type='primary'
onClick={handleAddImageUrl}
className='!rounded-full !w-4 !h-4 !p-0 !min-w-0'
disabled={!imageEnabled || disabled}
/>
</div>
</div>
{!imageEnabled ? (
<Typography.Text className='text-xs text-gray-500 mb-2 block'>
{disabled
? t('图片功能在自定义请求体模式下不可用')
: t('启用后可添加图片URL进行多模态对话')}
</Typography.Text>
) : imageUrls.length === 0 ? (
<Typography.Text className='text-xs text-gray-500 mb-2 block'>
{disabled
? t('图片功能在自定义请求体模式下不可用')
: t('点击 + 按钮添加图片URL进行多模态对话')}
</Typography.Text>
) : (
<Typography.Text className='text-xs text-gray-500 mb-2 block'>
{t('已添加')} {imageUrls.length} {t('张图片')}
{disabled ? ` (${t('自定义模式下不可用')})` : ''}
</Typography.Text>
)}
<div
className={`space-y-2 max-h-32 overflow-y-auto image-list-scroll ${!imageEnabled || disabled ? 'opacity-50' : ''}`}
>
{imageUrls.map((url, index) => (
<div key={index} className='flex items-center gap-2'>
<div className='flex-1'>
<Input
placeholder={`https://example.com/image${index + 1}.jpg`}
value={url}
onChange={(value) => handleUpdateImageUrl(index, value)}
className='!rounded-lg'
size='small'
prefix={<IconFile size='small' />}
disabled={!imageEnabled || disabled}
/>
</div>
<Button
icon={<X size={12} />}
size='small'
theme='borderless'
type='danger'
onClick={() => handleRemoveImageUrl(index)}
className='!rounded-full !w-6 !h-6 !p-0 !min-w-0 !text-red-500 hover:!bg-red-50 flex-shrink-0'
disabled={!imageEnabled || disabled}
/>
</div>
))}
</div>
</div>
);
};
export default ImageUrlInput;
@@ -0,0 +1,131 @@
/*
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 React, { useMemo } from 'react';
import { Modal } from '@douyinfe/semi-ui';
import { Keyboard } from 'lucide-react';
import { useTranslation } from 'react-i18next';
// Mac vs Win/Linux 修饰键名:⌘ 在 mac 上 / Ctrl 在其它平台
const getModKey = () => {
if (typeof navigator === 'undefined') return 'Ctrl';
return /Mac|iPhone|iPad/i.test(navigator.platform) ? '⌘' : 'Ctrl';
};
const Key = ({ children }) => (
<kbd className='inline-flex items-center justify-center min-w-[28px] px-1.5 py-0.5 rounded-md bg-gray-100 dark:bg-neutral-800 border border-gray-200/80 dark:border-neutral-700/80 text-[11px] font-mono text-gray-700 dark:text-gray-200 shadow-[inset_0_-1px_0_rgba(0,0,0,0.08)]'>
{children}
</kbd>
);
const KeyboardShortcutsModal = ({ visible, onClose }) => {
const { t } = useTranslation();
const mod = useMemo(getModKey, []);
const groups = useMemo(
() => [
{
title: t('全局'),
items: [
{ keys: [mod, 'K'], desc: t('聚焦输入框') },
{ keys: [mod, 'E'], desc: t('导出当前会话为 Markdown') },
{ keys: [mod, '/'], desc: t('显示 / 隐藏快捷键面板') },
{ keys: ['?'], desc: t('显示快捷键面板(输入框外按)') },
{ keys: ['Esc'], desc: t('关闭弹窗 / 退出') },
],
},
{
title: t('输入框'),
items: [
{ keys: ['Enter'], desc: t('发送消息') },
{ keys: ['Shift', 'Enter'], desc: t('换行') },
{ keys: ['Ctrl', 'V'], desc: t('粘贴图片或文件') },
],
},
{
title: t('消息'),
items: [
{
keys: [t('点击消息')],
desc: t('调出操作菜单(复制 / 编辑 / 重新生成 / 删除)'),
},
{ keys: [t('点击附件 chip')], desc: t('打开预览(图片 / PDF)') },
{ keys: [t('点击参考来源')], desc: t('在新窗口打开来源') },
],
},
],
[mod, t],
);
return (
<Modal
visible={visible}
onCancel={onClose}
footer={null}
closable
maskClosable
width={520}
title={
<span className='flex items-center gap-2'>
<Keyboard size={18} className='text-brand' />
{t('键盘快捷键')}
</span>
}
>
<div className='space-y-5 py-1'>
{groups.map((group) => (
<div key={group.title}>
<div className='text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider mb-2'>
{group.title}
</div>
<div className='space-y-1.5'>
{group.items.map((item, i) => (
<div
key={i}
className='flex items-center justify-between gap-3 py-1.5 px-2 rounded-lg hover:bg-gray-50 dark:hover:bg-neutral-800/50 transition-colors'
>
<span className='text-sm text-gray-700 dark:text-gray-200'>
{item.desc}
</span>
<span className='flex items-center gap-1 flex-shrink-0'>
{item.keys.map((k, j) => (
<React.Fragment key={j}>
<Key>{k}</Key>
{j < item.keys.length - 1 && (
<span className='text-gray-300 dark:text-gray-600 text-xs'>
+
</span>
)}
</React.Fragment>
))}
</span>
</div>
))}
</div>
</div>
))}
<div className='text-[11px] text-gray-400 dark:text-gray-500 pt-2 border-t border-gray-100 dark:border-neutral-800'>
{t('提示:随时按 ? 调出此面板')}
</div>
</div>
</Modal>
);
};
export default KeyboardShortcutsModal;
@@ -0,0 +1,152 @@
/*
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 React from 'react';
import { Button, Tooltip } from '@douyinfe/semi-ui';
import { RefreshCw, Copy, Trash2, UserCheck, Edit } from 'lucide-react';
import { useTranslation } from 'react-i18next';
const MessageActions = ({
message,
styleState,
onMessageReset,
onMessageCopy,
onMessageDelete,
onRoleToggle,
onMessageEdit,
isAnyMessageGenerating = false,
isEditing = false,
}) => {
const { t } = useTranslation();
const isLoading =
message.status === 'loading' || message.status === 'incomplete';
const shouldDisableActions = isAnyMessageGenerating || isEditing;
const canToggleRole =
message.role === 'assistant' || message.role === 'system';
const canEdit =
!isLoading &&
message.content &&
typeof onMessageEdit === 'function' &&
!isEditing;
return (
<div className='flex items-center gap-0.5'>
{!isLoading && (
<Tooltip
content={shouldDisableActions ? t('操作暂时被禁用') : t('重试')}
position='top'
>
<Button
theme='borderless'
type='tertiary'
size='small'
icon={<RefreshCw size={styleState.isMobile ? 12 : 14} />}
onClick={() => !shouldDisableActions && onMessageReset(message)}
disabled={shouldDisableActions}
className={`!rounded-full ${shouldDisableActions ? '!text-gray-300 !cursor-not-allowed' : '!text-gray-400 hover:!text-blue-600 hover:!bg-blue-50'} ${styleState.isMobile ? '!w-6 !h-6' : '!w-7 !h-7'} !p-0 transition-all`}
aria-label={t('重试')}
/>
</Tooltip>
)}
{message.content && (
<Tooltip content={t('复制')} position='top'>
<Button
theme='borderless'
type='tertiary'
size='small'
icon={<Copy size={styleState.isMobile ? 12 : 14} />}
onClick={() => onMessageCopy(message)}
className={`!rounded-full !text-gray-400 hover:!text-green-600 hover:!bg-green-50 ${styleState.isMobile ? '!w-6 !h-6' : '!w-7 !h-7'} !p-0 transition-all`}
aria-label={t('复制')}
/>
</Tooltip>
)}
{canEdit && (
<Tooltip
content={shouldDisableActions ? t('操作暂时被禁用') : t('编辑')}
position='top'
>
<Button
theme='borderless'
type='tertiary'
size='small'
icon={<Edit size={styleState.isMobile ? 12 : 14} />}
onClick={() => !shouldDisableActions && onMessageEdit(message)}
disabled={shouldDisableActions}
className={`!rounded-full ${shouldDisableActions ? '!text-gray-300 !cursor-not-allowed' : '!text-gray-400 hover:!text-yellow-600 hover:!bg-yellow-50'} ${styleState.isMobile ? '!w-6 !h-6' : '!w-7 !h-7'} !p-0 transition-all`}
aria-label={t('编辑')}
/>
</Tooltip>
)}
{canToggleRole && !isLoading && (
<Tooltip
content={
shouldDisableActions
? t('操作暂时被禁用')
: message.role === 'assistant'
? t('切换为System角色')
: t('切换为Assistant角色')
}
position='top'
>
<Button
theme='borderless'
type='tertiary'
size='small'
icon={<UserCheck size={styleState.isMobile ? 12 : 14} />}
onClick={() =>
!shouldDisableActions && onRoleToggle && onRoleToggle(message)
}
disabled={shouldDisableActions}
className={`!rounded-full ${shouldDisableActions ? '!text-gray-300 !cursor-not-allowed' : message.role === 'system' ? '!text-brand hover:!text-brand-deep hover:!bg-brand/5' : '!text-gray-400 hover:!text-brand-deep hover:!bg-brand/5'} ${styleState.isMobile ? '!w-6 !h-6' : '!w-7 !h-7'} !p-0 transition-all`}
aria-label={
message.role === 'assistant'
? t('切换为System角色')
: t('切换为Assistant角色')
}
/>
</Tooltip>
)}
{!isLoading && (
<Tooltip
content={shouldDisableActions ? t('操作暂时被禁用') : t('删除')}
position='top'
>
<Button
theme='borderless'
type='tertiary'
size='small'
icon={<Trash2 size={styleState.isMobile ? 12 : 14} />}
onClick={() => !shouldDisableActions && onMessageDelete(message)}
disabled={shouldDisableActions}
className={`!rounded-full ${shouldDisableActions ? '!text-gray-300 !cursor-not-allowed' : '!text-gray-400 hover:!text-red-600 hover:!bg-red-50'} ${styleState.isMobile ? '!w-6 !h-6' : '!w-7 !h-7'} !p-0 transition-all`}
aria-label={t('删除')}
/>
</Tooltip>
)}
</div>
);
};
export default MessageActions;
@@ -0,0 +1,905 @@
/*
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 React, { useRef, useEffect, useState } from 'react';
import { Typography, TextArea, Button, Tooltip } from '@douyinfe/semi-ui';
import MarkdownRenderer from '../common/markdown/MarkdownRenderer';
import ThinkingContent from './ThinkingContent';
import ImagePreviewModal from './ImagePreviewModal';
import FilePreviewModal from './FilePreviewModal';
import {
Loader2,
Check,
X,
FileText,
Globe,
ExternalLink,
Volume2,
VolumeX,
Sparkles,
FastForward,
ChevronDown,
} from 'lucide-react';
import { useTranslation } from 'react-i18next';
// 注意:不要从 helpers/utils 里 import getTextContent —— 本组件下方有同名 const,
// 同名遮蔽在 Vite/terser 生产构建里会把两者缩成同一个变量名,触发 TDZ 错误:
// "Cannot access 'Oe' before initialization"
// 本地函数签名是 (content) 而非 helpers 里的 (message),调用时记得传 message.content。
import { usePlayground } from '../../contexts/PlaygroundContext';
import { useSpeechSynthesis } from '../../hooks/playground/useSpeechSynthesis';
const MessageContent = ({
message,
className,
styleState,
onToggleReasoningExpansion,
isEditing = false,
onEditSave,
onEditCancel,
editValue,
onEditValueChange,
// 该消息是否是当前会话里最后一条 user 消息。
// 仅当 role === user && !isLatestUserMessage 时,附件 chip 会灰化 + tooltip 提示
// "已在历史上下文中读取,不会再发给模型",告诉用户:这些文件下一轮不会再次上送。
// 默认 true 是为了兼容历史调用方(如外部直接渲染 MessageContent 不传该 prop 的场景)。
isLatestUserMessage = true,
}) => {
const { t } = useTranslation();
const [previewImageUrl, setPreviewImageUrl] = useState(null);
const [previewFile, setPreviewFile] = useState(null);
// 参考来源默认折叠 —— 长会话里一条一条全展开会非常占空间,用户多数时候只想看摘要再决定是否点开
const [sourcesExpanded, setSourcesExpanded] = useState(false);
const { onSendQuickPrompt, isStreaming } = usePlayground();
const tts = useSpeechSynthesis();
const previousContentLengthRef = useRef(0);
const lastContentRef = useRef('');
const [currentDateKey, setCurrentDateKey] = useState(() =>
new Date().toDateString(),
);
const isThinkingStatus =
message.status === 'loading' || message.status === 'incomplete';
useEffect(() => {
let timerId;
const scheduleNextDateRefresh = () => {
const now = new Date();
const nextDay = new Date(now);
nextDay.setHours(24, 0, 1, 0);
timerId = window.setTimeout(() => {
setCurrentDateKey(new Date().toDateString());
scheduleNextDateRefresh();
}, Math.max(1000, nextDay.getTime() - now.getTime()));
};
scheduleNextDateRefresh();
return () => {
window.clearTimeout(timerId);
};
}, []);
const messageTime = React.useMemo(() => {
const raw =
message.createAt ||
message.createTime ||
message.created_at ||
message.timestamp;
if (!raw) return null;
const normalized =
typeof raw === 'number' && raw > 0 && raw < 1000000000000
? raw * 1000
: raw;
const dt = new Date(normalized);
return Number.isNaN(dt.getTime()) ? null : dt;
}, [
message.createAt,
message.createTime,
message.created_at,
message.timestamp,
]);
const messageTimeText = React.useMemo(() => {
if (!messageTime) return '';
const now = new Date();
const sameYear = messageTime.getFullYear() === now.getFullYear();
const sameDay =
sameYear &&
messageTime.getMonth() === now.getMonth() &&
messageTime.getDate() === now.getDate();
const time = messageTime.toLocaleTimeString([], {
hour: '2-digit',
minute: '2-digit',
});
if (sameDay) return time;
const date = messageTime.toLocaleDateString([], {
month: '2-digit',
day: '2-digit',
...(sameYear ? {} : { year: 'numeric' }),
});
return `${date} ${time}`;
}, [messageTime, currentDateKey]);
const renderMessageTime = () => {
if (message.status === 'loading' || !messageTime || !messageTimeText) {
return null;
}
const isUser = message.role === 'user';
return (
<div
className={`mt-1 text-[10px] leading-none select-none ${
isUser
? 'text-white/75 dark:text-white/70 text-right'
: 'text-gray-400/90 dark:text-gray-500'
}`}
title={messageTime.toLocaleString()}
>
{messageTimeText}
</div>
);
};
useEffect(() => {
if (!isThinkingStatus) {
previousContentLengthRef.current = 0;
lastContentRef.current = '';
}
}, [isThinkingStatus]);
if (message.status === 'error') {
let errorText;
if (Array.isArray(message.content)) {
const textContent = message.content.find((item) => item.type === 'text');
errorText =
textContent && textContent.text && typeof textContent.text === 'string'
? textContent.text
: t('请求发生错误');
} else if (typeof message.content === 'string') {
errorText = message.content;
} else {
errorText = t('请求发生错误');
}
return (
<div className={`${className}`}>
<Typography.Text className='text-white'>{errorText}</Typography.Text>
{renderMessageTime()}
</div>
);
}
let currentExtractedThinkingContent = null;
let currentDisplayableFinalContent = '';
let thinkingSource = null;
const getTextContent = (content) => {
if (Array.isArray(content)) {
const textItem = content.find((item) => item.type === 'text');
return textItem && textItem.text && typeof textItem.text === 'string'
? textItem.text
: '';
} else if (typeof content === 'string') {
return content;
}
return '';
};
currentDisplayableFinalContent = getTextContent(message.content);
if (message.role === 'assistant') {
let baseContentForDisplay = getTextContent(message.content);
let combinedThinkingContent = '';
if (message.reasoningContent) {
combinedThinkingContent = message.reasoningContent;
thinkingSource = 'reasoningContent';
}
if (baseContentForDisplay.includes('<think>')) {
const thinkTagRegex = /<think>([\s\S]*?)<\/think>/g;
let match;
let thoughtsFromPairedTags = [];
let replyParts = [];
let lastIndex = 0;
while ((match = thinkTagRegex.exec(baseContentForDisplay)) !== null) {
replyParts.push(
baseContentForDisplay.substring(lastIndex, match.index),
);
thoughtsFromPairedTags.push(match[1]);
lastIndex = match.index + match[0].length;
}
replyParts.push(baseContentForDisplay.substring(lastIndex));
if (thoughtsFromPairedTags.length > 0) {
const pairedThoughtsStr = thoughtsFromPairedTags.join('\n\n---\n\n');
if (combinedThinkingContent) {
combinedThinkingContent += '\n\n---\n\n' + pairedThoughtsStr;
} else {
combinedThinkingContent = pairedThoughtsStr;
}
thinkingSource = thinkingSource
? thinkingSource + ' & <think> tags'
: '<think> tags';
}
baseContentForDisplay = replyParts.join('');
}
if (isThinkingStatus) {
const lastOpenThinkIndex = baseContentForDisplay.lastIndexOf('<think>');
if (lastOpenThinkIndex !== -1) {
const fragmentAfterLastOpen =
baseContentForDisplay.substring(lastOpenThinkIndex);
if (!fragmentAfterLastOpen.includes('</think>')) {
const unclosedThought = fragmentAfterLastOpen
.substring('<think>'.length)
.trim();
if (unclosedThought) {
if (combinedThinkingContent) {
combinedThinkingContent += '\n\n---\n\n' + unclosedThought;
} else {
combinedThinkingContent = unclosedThought;
}
thinkingSource = thinkingSource
? thinkingSource + ' + streaming <think>'
: 'streaming <think>';
}
baseContentForDisplay = baseContentForDisplay.substring(
0,
lastOpenThinkIndex,
);
}
}
}
currentExtractedThinkingContent = combinedThinkingContent || null;
currentDisplayableFinalContent = baseContentForDisplay
.replace(/<\/?think>/g, '')
.trim();
}
const finalExtractedThinkingContent = currentExtractedThinkingContent;
const finalDisplayableFinalContent = currentDisplayableFinalContent;
if (
message.role === 'assistant' &&
isThinkingStatus &&
!finalExtractedThinkingContent &&
(!finalDisplayableFinalContent ||
finalDisplayableFinalContent.trim() === '')
) {
return (
<div
className={`${className} flex items-center gap-2 sm:gap-4 bg-gradient-to-r from-brand-from/5 to-brand-to/5 dark:from-brand-from/20 dark:to-brand-to/20`}
>
<div className='w-5 h-5 rounded-full bg-gradient-to-br from-brand-from to-brand-to flex items-center justify-center shadow-lg flex-shrink-0'>
{message.inWebSearch ? (
<Globe
className='animate-pulse text-white'
size={styleState.isMobile ? 14 : 16}
/>
) : message.processingAttachments > 0 ? (
<FileText
className='animate-pulse text-white'
size={styleState.isMobile ? 14 : 16}
/>
) : (
<Loader2
className='animate-spin text-white'
size={styleState.isMobile ? 16 : 20}
/>
)}
</div>
{/* 文案优先级:联网搜索 > 附件处理 — 两者后端都是先于模型流出执行的同步阶段,
但联网搜索通常是 5-15s 的"重"阶段,更值得专门提示;附件处理 1-5s,作为兜底标识 */}
{message.inWebSearch ? (
<span className='text-xs sm:text-sm text-brand-deep dark:text-brand-from font-medium'>
{t('正在联网搜索…')}
</span>
) : message.processingAttachments > 0 ? (
<span className='text-xs sm:text-sm text-brand-deep dark:text-brand-from font-medium'>
{t('正在处理 {{n}} 个附件,请稍候…', {
n: message.processingAttachments,
})}
</span>
) : null}
</div>
);
}
return (
<div className={className}>
{message.role === 'system' && (
<div className='mb-2 sm:mb-4'>
<div
className='flex items-center gap-2 p-2 sm:p-3 bg-gradient-to-r from-amber-50 to-orange-50 rounded-lg'
style={{ border: '1px solid var(--semi-color-border)' }}
>
<div className='w-4 h-4 sm:w-5 sm:h-5 rounded-full bg-gradient-to-br from-amber-500 to-orange-600 flex items-center justify-center shadow-sm'>
<Typography.Text className='text-white text-xs font-bold'>
S
</Typography.Text>
</div>
<Typography.Text className='text-amber-700 text-xs sm:text-sm font-medium'>
{t('系统消息')}
</Typography.Text>
</div>
</div>
)}
{message.role === 'assistant' && (
<ThinkingContent
message={message}
finalExtractedThinkingContent={finalExtractedThinkingContent}
thinkingSource={thinkingSource}
styleState={styleState}
onToggleReasoningExpansion={onToggleReasoningExpansion}
/>
)}
{isEditing ? (
<div className='space-y-3'>
{/* 编辑模式下,把消息中的附件以只读 chip 形式呈现 ——
提醒用户"附件会随保存一并保留"。否则用户只看到文本框,可能误以为附件已被删掉。
v1 不支持在编辑态删单个附件(删了再加是同样的成本);如果用户真想换附件,
建议删整条消息后重新发送。 */}
{Array.isArray(message.content) &&
message.content.some(
(p) => p?.type === 'image_url' || p?.type === 'file',
) && (
<div className='flex flex-wrap items-center gap-2 px-2 py-2 rounded-lg bg-amber-50/60 dark:bg-amber-900/15 border border-amber-200/60 dark:border-amber-800/30'>
<span className='text-[11px] text-amber-700 dark:text-amber-300 font-medium'>
{t('保存后以下附件会一并保留:')}
</span>
{message.content
.filter((p) => p?.type === 'image_url' || p?.type === 'file')
.map((p, i) => {
if (p.type === 'image_url') {
return (
<span
key={`img-${i}`}
className='inline-flex items-center gap-1 px-2 py-0.5 rounded-md bg-white/70 dark:bg-neutral-800/70 border border-amber-200/60 dark:border-amber-800/30 text-[11px] text-gray-700 dark:text-gray-200'
>
<span className='text-blue-500'>🖼</span>
{t('图片')}
</span>
);
}
const fname =
p?.file?.filename || p?.file?.file_name || t('未知文件');
return (
<span
key={`file-${i}`}
className='inline-flex items-center gap-1 px-2 py-0.5 rounded-md bg-white/70 dark:bg-neutral-800/70 border border-amber-200/60 dark:border-amber-800/30 text-[11px] text-gray-700 dark:text-gray-200'
title={fname}
>
<FileText size={11} className='text-orange-500' />
<span className='truncate max-w-[140px]'>{fname}</span>
</span>
);
})}
</div>
)}
<TextArea
value={editValue}
onChange={(value) => onEditValueChange(value)}
placeholder={t('请输入消息内容...')}
autosize={{ minRows: 3, maxRows: 12 }}
style={{
resize: 'vertical',
fontSize: styleState.isMobile ? '14px' : '15px',
lineHeight: '1.6',
}}
className='!border-blue-200 focus:!border-blue-400 !bg-blue-50/50'
/>
<div className='flex items-center gap-2 w-full'>
<Button
size='small'
type='danger'
theme='light'
icon={<X size={14} />}
onClick={onEditCancel}
className='flex-1'
>
{t('取消')}
</Button>
<Button
size='small'
type='warning'
theme='solid'
icon={<Check size={14} />}
onClick={onEditSave}
disabled={!editValue || editValue.trim() === ''}
className='flex-1'
>
{t('保存')}
</Button>
</div>
</div>
) : (
(() => {
if (Array.isArray(message.content)) {
const textContent = message.content.find(
(item) => item.type === 'text',
);
const imageContents = message.content.filter(
(item) => item.type === 'image_url',
);
const fileContents = message.content.filter(
(item) => item.type === 'file',
);
// 历史轮的附件:标灰 + tooltip 提示。仅 user 消息生效(assistant 几乎没有附件)。
// tooltip 同时说明"仍可点击预览",避免用户因灰化以为不能交互
const isHistoricalAttachment =
message.role === 'user' && !isLatestUserMessage;
const historicalTip = t(
'该附件已在历史上下文中读取,不会再发给模型(仍可点击预览原文件)',
);
return (
<div>
{imageContents.length > 0 && (
<div className='mb-3 space-y-2'>
{imageContents.map((imgItem, index) => {
// a11y:历史图片在 alt 文本里加"历史附件"标注,让屏幕阅读器
// 用户也能区分当前轮 vs 历史
const imgAlt = isHistoricalAttachment
? t(
'历史附件 用户上传的图片 {{n}}(仅作历史上下文,不会再发给模型)',
{ n: index + 1 },
)
: t('用户上传的图片 {{n}}', { n: index + 1 });
const img = (
<div
key={index}
className={`max-w-sm ${isHistoricalAttachment ? 'opacity-60 grayscale' : ''}`}
>
<img
src={imgItem.image_url.url}
alt={imgAlt}
className='rounded-lg max-w-full h-auto shadow-sm border cursor-pointer hover:opacity-90 transition-opacity'
style={{ maxHeight: '300px' }}
onClick={() =>
setPreviewImageUrl(imgItem.image_url.url)
}
onError={(e) => {
e.target.style.display = 'none';
e.target.nextSibling.style.display = 'block';
}}
/>
<div
className='text-red-500 text-sm p-2 bg-red-50 rounded-lg border border-red-200'
style={{ display: 'none' }}
>
图片加载失败: {imgItem.image_url.url}
</div>
</div>
);
return isHistoricalAttachment ? (
<Tooltip key={index} content={historicalTip}>
{img}
</Tooltip>
) : (
img
);
})}
</div>
)}
{fileContents.length > 0 && (
<div className='mb-3 flex flex-wrap gap-2'>
{fileContents.map((fileItem, index) => {
const fileName =
fileItem.file?.filename ||
fileItem.file?.file_name ||
t('未知文件');
const ext = fileName.split('.').pop().toLowerCase();
const styleMap = {
pdf: {
color: 'text-red-500',
bg: 'bg-red-50 dark:bg-red-900/20',
},
doc: {
color: 'text-blue-500',
bg: 'bg-blue-50 dark:bg-blue-900/20',
},
docx: {
color: 'text-blue-500',
bg: 'bg-blue-50 dark:bg-blue-900/20',
},
xls: {
color: 'text-green-500',
bg: 'bg-green-50 dark:bg-green-900/20',
},
xlsx: {
color: 'text-green-500',
bg: 'bg-green-50 dark:bg-green-900/20',
},
ppt: {
color: 'text-orange-500',
bg: 'bg-orange-50 dark:bg-orange-900/20',
},
pptx: {
color: 'text-orange-500',
bg: 'bg-orange-50 dark:bg-orange-900/20',
},
txt: {
color: 'text-gray-500',
bg: 'bg-gray-50 dark:bg-gray-800/50',
},
csv: {
color: 'text-green-600',
bg: 'bg-green-50 dark:bg-green-900/20',
},
json: {
color: 'text-yellow-600',
bg: 'bg-yellow-50 dark:bg-yellow-900/20',
},
xml: {
color: 'text-brand',
bg: 'bg-brand/5 dark:bg-brand-deep/20',
},
};
const s = styleMap[ext] || {
color: 'text-gray-500',
bg: 'bg-gray-50 dark:bg-gray-800/50',
};
const btn = (
<button
key={index}
type='button'
onClick={() => setPreviewFile(fileItem.file)}
className={`flex items-center gap-2 px-3 py-2 rounded-xl ${s.bg} border border-gray-200/60 dark:border-neutral-700/60 shadow-sm hover:shadow-md hover:scale-[1.02] active:scale-100 transition-all duration-200 group cursor-pointer text-left ${isHistoricalAttachment ? 'opacity-60 grayscale' : ''}`}
// 历史 chip 已用 Semi Tooltip 显示提示,不再加 native title 防止重影
title={
isHistoricalAttachment ? undefined : t('点击预览')
}
// a11y:屏幕阅读器仅看到"灰化"是没用的(视觉效果不可达),
// 用 aria-label 把"历史附件"语义+文件名说全,让无障碍用户也能区分
aria-label={
isHistoricalAttachment
? t(
'历史附件 {{name}}(仅作历史上下文,不会再发给模型)',
{
name: fileName,
},
)
: t('附件 {{name}}', { name: fileName })
}
>
<FileText
size={16}
className={`${s.color} flex-shrink-0`}
/>
<span className='text-xs text-gray-700 dark:text-gray-300 truncate max-w-[160px] group-hover:underline'>
{fileName}
</span>
{isHistoricalAttachment && (
<span className='text-[10px] px-1.5 py-0.5 rounded bg-gray-200/80 dark:bg-neutral-700/80 text-gray-600 dark:text-gray-300 flex-shrink-0'>
{t('仅历史')}
</span>
)}
</button>
);
return isHistoricalAttachment ? (
<Tooltip key={index} content={historicalTip}>
{btn}
</Tooltip>
) : (
btn
);
})}
</div>
)}
{textContent &&
textContent.text &&
typeof textContent.text === 'string' &&
textContent.text.trim() !== '' && (
<div
className={`prose prose-xs sm:prose-sm prose-gray max-w-none overflow-x-auto text-xs sm:text-sm ${message.role === 'user' ? 'user-message' : ''}`}
>
<MarkdownRenderer
content={textContent.text}
className={
message.role === 'user' ? 'user-message' : ''
}
animated={false}
previousContentLength={0}
/>
</div>
)}
</div>
);
}
if (typeof message.content === 'string') {
if (message.role === 'assistant') {
if (
finalDisplayableFinalContent &&
finalDisplayableFinalContent.trim() !== ''
) {
// 获取上一次的内容长度
let prevLength = 0;
if (isThinkingStatus && lastContentRef.current) {
// 只有当前内容包含上一次内容时,才使用上一次的长度
if (
finalDisplayableFinalContent.startsWith(
lastContentRef.current,
)
) {
prevLength = lastContentRef.current.length;
}
}
// 更新最后内容的引用
if (isThinkingStatus) {
lastContentRef.current = finalDisplayableFinalContent;
}
return (
<div className='prose prose-xs sm:prose-sm prose-gray max-w-none overflow-x-auto text-xs sm:text-sm'>
<MarkdownRenderer
content={finalDisplayableFinalContent}
className=''
animated={isThinkingStatus}
previousContentLength={prevLength}
/>
</div>
);
}
} else {
return (
<div
className={`prose prose-xs sm:prose-sm prose-gray max-w-none overflow-x-auto text-xs sm:text-sm ${message.role === 'user' ? 'user-message' : ''}`}
>
<MarkdownRenderer
content={message.content}
className={message.role === 'user' ? 'user-message' : ''}
animated={false}
previousContentLength={0}
/>
</div>
);
}
}
return null;
})()
)}
{/* 参考来源卡片:联网搜索注入的结果,由后端 X-Web-Search-Sources 头透传过来;
只在 assistant 消息上渲染,并不持久化(刷新页面会消失,这是 v1 已知限制)。
默认折叠,点击 header 切换 —— 长会话里一条全展开会占据大量空间。 */}
{message.role === 'assistant' &&
Array.isArray(message.webSearchSources) &&
message.webSearchSources.length > 0 && (
<div className='mt-3 rounded-xl border border-brand/60 dark:border-brand-deep/40 bg-brand/50 dark:bg-brand-deep/15 px-3 py-2'>
<button
type='button'
onClick={() => setSourcesExpanded((v) => !v)}
className={`flex items-center gap-1.5 w-full text-left transition-colors hover:opacity-80 ${sourcesExpanded ? 'mb-2' : ''}`}
aria-expanded={sourcesExpanded}
aria-label={
sourcesExpanded ? t('收起参考来源') : t('展开参考来源')
}
>
<Globe
size={13}
className='text-brand dark:text-brand-from flex-shrink-0'
/>
<span className='text-[11px] font-medium text-brand-deep dark:text-brand-from uppercase tracking-wide'>
{t('参考来源')} · {message.webSearchSources.length}
</span>
<ChevronDown
size={12}
className={`ml-auto text-brand-from dark:text-brand transition-transform duration-200 ${sourcesExpanded ? 'rotate-180' : ''}`}
/>
</button>
{sourcesExpanded && (
<div className='flex flex-col gap-1'>
{message.webSearchSources.map((src, i) => {
const idx = src.index || i + 1;
let host = src.url;
// 防御性 URL 校验:只允许 http / https;万一上游搜索源返回了
// javascript:、data: 之类的恶意协议,渲染成可点链接就是 XSS。
// 同时拿合法 URL 的 host 用于显示,失败时 fallback 到原串
let safeUrl = '';
try {
const parsed = new URL(src.url);
if (
parsed.protocol === 'http:' ||
parsed.protocol === 'https:'
) {
safeUrl = parsed.href;
host = parsed.host;
}
} catch (_) {
// 解析失败 → safeUrl 仍为空,下面渲染就不挂 href
}
if (!safeUrl) {
// 非法 / 不安全 URL:渲染为非交互文本块,标题还能看到,但点不动
return (
<div
key={`${idx}-${i}`}
className='flex items-start gap-2 px-2 py-1.5 rounded-lg'
title={t('链接不安全或无法解析')}
>
<span className='flex-shrink-0 inline-flex items-center justify-center w-5 h-5 rounded-md bg-gray-200/70 dark:bg-gray-700/40 text-[10px] font-mono font-semibold text-gray-500 dark:text-gray-400 mt-0.5'>
{idx}
</span>
<div className='flex-1 min-w-0'>
<div className='text-xs text-gray-500 dark:text-gray-400 line-clamp-2'>
{src.title}
</div>
<div className='text-[10px] text-gray-400 dark:text-gray-500 truncate'>
{t('链接不可用')}
</div>
</div>
</div>
);
}
// tooltip 优先用原始 src.url —— 用户 hover 时看到中文 URL 更直观;
// 但实际跳转用 safeUrl (encoded),浏览器才能正确导航
return (
<a
key={`${idx}-${safeUrl}`}
href={safeUrl}
target='_blank'
rel='noopener noreferrer'
className='group flex items-start gap-2 px-2 py-1.5 rounded-lg hover:bg-brand/50 dark:hover:bg-brand-deep/30 transition-colors'
title={src.url || safeUrl}
>
<span className='flex-shrink-0 inline-flex items-center justify-center w-5 h-5 rounded-md bg-brand/70 dark:bg-brand-deep/40 text-[10px] font-mono font-semibold text-brand-deep dark:text-brand-from mt-0.5'>
{idx}
</span>
<div className='flex-1 min-w-0'>
<div className='text-xs text-gray-800 dark:text-gray-100 line-clamp-2 group-hover:underline'>
{src.title}
</div>
<div className='text-[10px] text-gray-400 dark:text-gray-500 truncate'>
{host}
</div>
</div>
<ExternalLink
size={12}
className='flex-shrink-0 text-gray-400 dark:text-gray-500 group-hover:text-brand transition-colors mt-1'
/>
</a>
);
})}
</div>
)}
</div>
)}
{/* Token 消耗展示(仅 assistant 消息且后端返回了 token 数据时显示,体验中心调试场景关键指标) */}
{message.role === 'assistant' &&
(message.promptTokens > 0 || message.completionTokens > 0) && (
<div className='mt-1.5 flex items-center gap-2 text-[11px] text-gray-400 dark:text-gray-500 font-mono'>
{message.promptTokens > 0 && (
<span title={t('Prompt tokens (输入)')}>
↑ {message.promptTokens}
</span>
)}
{message.completionTokens > 0 && (
<span title={t('Completion tokens (输出)')}>
↓ {message.completionTokens}
</span>
)}
{message.promptTokens > 0 && message.completionTokens > 0 && (
<span className='opacity-70' title={t('总 tokens')}>
= {message.promptTokens + message.completionTokens}
</span>
)}
</div>
)}
{/* 助手消息底部"行动条":朗读 + 建议追问 ——
只在状态完成、非编辑、有内容时显示,避免流式过程里挤来挤去 */}
{message.role === 'assistant' &&
!isThinkingStatus &&
!isEditing &&
message.status !== 'error' &&
(() => {
// 本地 getTextContent 接受 content 字段而不是整个 message —— 别传错了
const plainText = getTextContent(message.content);
if (!plainText || plainText.trim() === '') return null;
const isThisSpeaking = tts.speakingId === message.id;
// 建议追问:三条通用 prompt,绝大多数对话都适用;admin 后续可以接配置
const followUps = [t('详细说说'), t('举个例子'), t('总结一下要点')];
// 响应因 token 上限被截断 → 显示"继续生成"按钮(橙色显眼),让用户一键续写
const wasTruncated = message.finishReason === 'length';
return (
<div className='mt-2 flex flex-wrap items-center gap-1.5'>
{/* "继续生成"按钮 —— 仅在响应被 length 截断时出现,醒目放在最前 */}
{wasTruncated && !isStreaming && (
<button
type='button'
onClick={() =>
onSendQuickPrompt?.(
t('请接着上面的内容继续输出,不要重复已经写过的部分'),
)
}
className='inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[11px] bg-amber-50 dark:bg-amber-900/30 hover:bg-amber-100 dark:hover:bg-amber-900/50 text-amber-700 dark:text-amber-300 border border-amber-300/70 dark:border-amber-700/50 transition-colors font-medium'
title={t('上次响应因长度限制被截断,点击让模型接着写')}
>
<FastForward size={11} />
{t('继续生成')}
</button>
)}
{/* 朗读按钮 —— 仅当浏览器支持 speechSynthesis 才显示 */}
{tts.isSupported && (
<button
type='button'
onClick={() => tts.speak(message.id, plainText)}
className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[11px] transition-colors border ${
isThisSpeaking
? 'bg-brand/10 dark:bg-brand-deep/30 text-brand-deep dark:text-brand-from border-brand-from dark:border-brand-deep animate-pulse'
: 'bg-gray-50/80 dark:bg-neutral-800/60 hover:bg-brand/5 dark:hover:bg-brand-deep/30 text-gray-500 dark:text-gray-400 hover:text-brand-deep dark:hover:text-brand-from border-gray-200/60 dark:border-neutral-700/60'
}`}
title={isThisSpeaking ? t('停止朗读') : t('朗读')}
>
{isThisSpeaking ? (
<VolumeX size={11} />
) : (
<Volume2 size={11} />
)}
{isThisSpeaking ? t('停止朗读') : t('朗读')}
</button>
)}
{/* 建议追问 chips —— 流式响应进行中时禁用避免冲突;截断状态下也不显示,避免和"继续生成"按钮抢眼 */}
{!isStreaming &&
!wasTruncated &&
followUps.map((prompt, idx) => (
<button
key={idx}
type='button'
onClick={() => onSendQuickPrompt?.(prompt)}
className='inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[11px] bg-gray-50/80 dark:bg-neutral-800/60 hover:bg-brand/5 dark:hover:bg-brand-deep/30 text-gray-500 dark:text-gray-400 hover:text-brand-deep dark:hover:text-brand-from border border-gray-200/60 dark:border-neutral-700/60 transition-colors'
title={t('一键追问')}
>
<Sparkles size={11} />
{prompt}
</button>
))}
</div>
);
})()}
{/* 时间戳:所有已完成消息都展示具体时间,hover 显示完整日期。 */}
{renderMessageTime()}
<ImagePreviewModal
visible={!!previewImageUrl}
imageUrl={previewImageUrl}
onClose={() => setPreviewImageUrl(null)}
/>
<FilePreviewModal
visible={!!previewFile}
file={previewFile}
onClose={() => setPreviewFile(null)}
/>
</div>
);
};
export default MessageContent;
@@ -0,0 +1,62 @@
/*
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
*/
// 多选导出:包在单条消息气泡内容外层的选择态容器。
//
// 为什么包在外层而不是改 OptimizedMessageContent:OptimizedComponents.js 的 React.memo
// 比较器是显式白名单(只比 message.* / isEditing / editValue / styleState),给
// OptimizedMessageContent 加 selected 这类新 prop 会被静默忽略、气泡不重渲染。包在外层后,
// selectedIds 变化只重渲染这个廉价 wrapper,memo 化的 markdown 正文自动跳过。
import React from 'react';
import { CheckCircle2, Circle } from 'lucide-react';
const MessageSelectableWrapper = ({ selected, onToggle, children }) => {
return (
<div
role='button'
tabIndex={0}
aria-pressed={selected}
onClick={onToggle}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
onToggle?.();
}
}}
className={`relative cursor-pointer rounded-2xl transition-colors duration-150 ${
selected
? 'ring-2 ring-brand-from/70 bg-brand/40 dark:bg-brand-deep/20'
: 'hover:bg-gray-50/60 dark:hover:bg-neutral-800/40'
}`}
>
<span className='absolute left-1 top-2 z-10'>
{selected ? (
<CheckCircle2 size={18} className='text-brand' />
) : (
<Circle size={18} className='text-gray-300 dark:text-neutral-600' />
)}
</span>
{/* pointer-events-none:选择态下点气泡任意处都只切换选择,不触发气泡内部交互 */}
<div className='pointer-events-none select-none pl-6'>{children}</div>
</div>
);
};
export default MessageSelectableWrapper;
@@ -0,0 +1,145 @@
/*
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
*/
// 多选导出:底部悬浮操作条。展示型组件,状态由父级(Playground/index.jsx)持有。
import React, { useState } from 'react';
import { Button, RadioGroup, Radio } from '@douyinfe/semi-ui';
import { Download, X } from 'lucide-react';
import { useTranslation } from 'react-i18next';
const MessageSelectionBar = ({
selectedCount = 0,
selectableCount = 0,
isAllSelected = false,
onSelectAll,
onClearSelection,
onExport,
onCancel,
isMobile = false,
}) => {
const { t } = useTranslation();
const [exporting, setExporting] = useState(false);
const [format, setFormat] = useState('txt');
const handleExport = async () => {
if (selectedCount === 0 || exporting) return;
setExporting(true);
try {
await onExport?.(format);
} finally {
setExporting(false);
}
};
const selectAllBtn = (
<Button
size='small'
theme='borderless'
disabled={selectableCount === 0}
onClick={isAllSelected ? onClearSelection : onSelectAll}
>
{isAllSelected ? t('取消全选') : t('全选')}
</Button>
);
const formatPicker = (
<RadioGroup
type='button'
size='small'
value={format}
onChange={(e) => setFormat(e.target.value)}
>
<Radio value='txt'>{t('文本 TXT')}</Radio>
<Radio value='word'>{t('Word 文档')}</Radio>
</RadioGroup>
);
const exportBtn = (
<Button
size='small'
theme='solid'
type='primary'
icon={<Download size={14} />}
disabled={selectedCount === 0 || exporting}
loading={exporting}
onClick={handleExport}
>
{t('导出')}
</Button>
);
const cancelBtn = (
<Button
size='small'
theme='borderless'
icon={<X size={14} />}
// 导出进行中禁用「取消」——否则 bar 被关闭但 docx 仍在 await 中,
// 最终仍会触发一次下载,对用户体感是「我已经取消了为什么还有文件」。
disabled={exporting}
onClick={onCancel}
>
{t('取消')}
</Button>
);
const countText = (
<span className='text-sm font-medium text-gray-700 dark:text-gray-200 whitespace-nowrap'>
{t('已选 {{count}} / {{total}} 条', {
count: selectedCount,
total: selectableCount,
})}
</span>
);
return (
<div
role='toolbar'
aria-label={t('消息导出工具栏')}
className='bg-white/95 dark:bg-neutral-800/95 backdrop-blur-sm border border-gray-200/80 dark:border-neutral-700/80 rounded-2xl shadow-lg'
>
{isMobile ? (
<div className='flex flex-col gap-2 px-3 py-2'>
<div className='flex items-center justify-between gap-2'>
{countText}
{formatPicker}
</div>
<div className='flex items-center justify-between gap-2'>
{selectAllBtn}
<div className='flex items-center gap-2'>
{cancelBtn}
{exportBtn}
</div>
</div>
</div>
) : (
<div className='flex items-center gap-3 px-4 py-2'>
{countText}
{selectAllBtn}
<span className='w-px h-5 bg-gray-200 dark:bg-neutral-700' />
{formatPicker}
{exportBtn}
{cancelBtn}
</div>
)}
</div>
);
};
export default MessageSelectionBar;
@@ -0,0 +1,111 @@
/*
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 React from 'react';
import MessageContent from './MessageContent';
import MessageActions from './MessageActions';
import SettingsPanel from './SettingsPanel';
import DebugPanel from './DebugPanel';
// 优化的消息内容组件
export const OptimizedMessageContent = React.memo(
MessageContent,
(prevProps, nextProps) => {
// 只有这些属性变化时才重新渲染
return (
prevProps.message.id === nextProps.message.id &&
prevProps.message.content === nextProps.message.content &&
prevProps.message.status === nextProps.message.status &&
prevProps.message.role === nextProps.message.role &&
prevProps.message.createAt === nextProps.message.createAt &&
prevProps.message.createTime === nextProps.message.createTime &&
prevProps.message.created_at === nextProps.message.created_at &&
prevProps.message.timestamp === nextProps.message.timestamp &&
prevProps.message.reasoningContent ===
nextProps.message.reasoningContent &&
prevProps.message.isReasoningExpanded ===
nextProps.message.isReasoningExpanded &&
prevProps.isEditing === nextProps.isEditing &&
prevProps.editValue === nextProps.editValue &&
// isLatestUserMessage 决定历史附件 chip 是否灰化;
// 新发消息会让前一条 user 的"最后一条"身份易主,必须参与比较,
// 否则 memo 会吃掉灰化切换(与 MessageSelectableWrapper.jsx:22-25 同源的坑)
prevProps.isLatestUserMessage === nextProps.isLatestUserMessage &&
JSON.stringify(prevProps.styleState) ===
JSON.stringify(nextProps.styleState)
);
},
);
// 优化的消息操作组件
export const OptimizedMessageActions = React.memo(
MessageActions,
(prevProps, nextProps) => {
return (
prevProps.message.id === nextProps.message.id &&
prevProps.message.role === nextProps.message.role &&
prevProps.isAnyMessageGenerating === nextProps.isAnyMessageGenerating &&
prevProps.isEditing === nextProps.isEditing &&
prevProps.onMessageReset === nextProps.onMessageReset &&
JSON.stringify(prevProps.styleState) ===
JSON.stringify(nextProps.styleState)
);
},
);
// 优化的设置面板组件
export const OptimizedSettingsPanel = React.memo(
SettingsPanel,
(prevProps, nextProps) => {
return (
JSON.stringify(prevProps.inputs) === JSON.stringify(nextProps.inputs) &&
JSON.stringify(prevProps.parameterEnabled) ===
JSON.stringify(nextProps.parameterEnabled) &&
JSON.stringify(prevProps.models) === JSON.stringify(nextProps.models) &&
JSON.stringify(prevProps.groups) === JSON.stringify(nextProps.groups) &&
prevProps.customRequestMode === nextProps.customRequestMode &&
prevProps.customRequestBody === nextProps.customRequestBody &&
prevProps.showDebugPanel === nextProps.showDebugPanel &&
prevProps.showSettings === nextProps.showSettings &&
JSON.stringify(prevProps.previewPayload) ===
JSON.stringify(nextProps.previewPayload) &&
JSON.stringify(prevProps.messages) ===
JSON.stringify(nextProps.messages) &&
JSON.stringify(prevProps.styleState) ===
JSON.stringify(nextProps.styleState)
);
},
);
// 优化的调试面板组件
export const OptimizedDebugPanel = React.memo(
DebugPanel,
(prevProps, nextProps) => {
return (
prevProps.show === nextProps.show &&
prevProps.activeTab === nextProps.activeTab &&
JSON.stringify(prevProps.debugData) ===
JSON.stringify(nextProps.debugData) &&
JSON.stringify(prevProps.previewPayload) ===
JSON.stringify(nextProps.previewPayload) &&
prevProps.customRequestMode === nextProps.customRequestMode &&
prevProps.showDebugPanel === nextProps.showDebugPanel
);
},
);
@@ -0,0 +1,297 @@
/*
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 React from 'react';
import { Input, Slider, Typography, Button, Tag } from '@douyinfe/semi-ui';
import { useTranslation } from 'react-i18next';
import {
Hash,
Thermometer,
Target,
Repeat,
Ban,
Shuffle,
Check,
X,
} from 'lucide-react';
const ParameterControl = ({
inputs,
parameterEnabled,
onInputChange,
onParameterToggle,
disabled = false,
}) => {
const { t } = useTranslation();
return (
<>
{/* Temperature */}
<div
className={`transition-opacity duration-200 mb-4 ${!parameterEnabled.temperature || disabled ? 'opacity-50' : ''}`}
>
<div className='flex items-center justify-between mb-2'>
<div className='flex items-center gap-2'>
<Thermometer size={16} className='text-gray-500' />
<Typography.Text strong className='text-sm'>
Temperature
</Typography.Text>
<Tag size='small' shape='circle'>
{inputs.temperature}
</Tag>
</div>
<Button
theme={parameterEnabled.temperature ? 'solid' : 'borderless'}
type={parameterEnabled.temperature ? 'primary' : 'tertiary'}
size='small'
icon={
parameterEnabled.temperature ? (
<Check size={10} />
) : (
<X size={10} />
)
}
onClick={() => onParameterToggle('temperature')}
className='!rounded-full !w-4 !h-4 !p-0 !min-w-0 param-toggle-hit'
disabled={disabled}
/>
</div>
<Typography.Text className='text-xs text-gray-500 mb-2'>
{t('控制输出的随机性和创造性')}
</Typography.Text>
<Slider
step={0.1}
min={0.1}
max={1}
value={inputs.temperature}
onChange={(value) => onInputChange('temperature', value)}
className='mt-2'
disabled={!parameterEnabled.temperature || disabled}
/>
</div>
{/* Top P */}
<div
className={`transition-opacity duration-200 mb-4 ${!parameterEnabled.top_p || disabled ? 'opacity-50' : ''}`}
>
<div className='flex items-center justify-between mb-2'>
<div className='flex items-center gap-2'>
<Target size={16} className='text-gray-500' />
<Typography.Text strong className='text-sm'>
Top P
</Typography.Text>
<Tag size='small' shape='circle'>
{inputs.top_p}
</Tag>
</div>
<Button
theme={parameterEnabled.top_p ? 'solid' : 'borderless'}
type={parameterEnabled.top_p ? 'primary' : 'tertiary'}
size='small'
icon={
parameterEnabled.top_p ? <Check size={10} /> : <X size={10} />
}
onClick={() => onParameterToggle('top_p')}
className='!rounded-full !w-4 !h-4 !p-0 !min-w-0 param-toggle-hit'
disabled={disabled}
/>
</div>
<Typography.Text className='text-xs text-gray-500 mb-2'>
{t('核采样,控制词汇选择的多样性')}
</Typography.Text>
<Slider
step={0.1}
min={0.1}
max={1}
value={inputs.top_p}
onChange={(value) => onInputChange('top_p', value)}
className='mt-2'
disabled={!parameterEnabled.top_p || disabled}
/>
</div>
{/* Frequency Penalty */}
<div
className={`transition-opacity duration-200 mb-4 ${!parameterEnabled.frequency_penalty || disabled ? 'opacity-50' : ''}`}
>
<div className='flex items-center justify-between mb-2'>
<div className='flex items-center gap-2'>
<Repeat size={16} className='text-gray-500' />
<Typography.Text strong className='text-sm'>
Frequency Penalty
</Typography.Text>
<Tag size='small' shape='circle'>
{inputs.frequency_penalty}
</Tag>
</div>
<Button
theme={parameterEnabled.frequency_penalty ? 'solid' : 'borderless'}
type={parameterEnabled.frequency_penalty ? 'primary' : 'tertiary'}
size='small'
icon={
parameterEnabled.frequency_penalty ? (
<Check size={10} />
) : (
<X size={10} />
)
}
onClick={() => onParameterToggle('frequency_penalty')}
className='!rounded-full !w-4 !h-4 !p-0 !min-w-0 param-toggle-hit'
disabled={disabled}
/>
</div>
<Typography.Text className='text-xs text-gray-500 mb-2'>
{t('频率惩罚,减少重复词汇的出现')}
</Typography.Text>
<Slider
step={0.1}
min={-2}
max={2}
value={inputs.frequency_penalty}
onChange={(value) => onInputChange('frequency_penalty', value)}
className='mt-2'
disabled={!parameterEnabled.frequency_penalty || disabled}
/>
</div>
{/* Presence Penalty */}
<div
className={`transition-opacity duration-200 mb-4 ${!parameterEnabled.presence_penalty || disabled ? 'opacity-50' : ''}`}
>
<div className='flex items-center justify-between mb-2'>
<div className='flex items-center gap-2'>
<Ban size={16} className='text-gray-500' />
<Typography.Text strong className='text-sm'>
Presence Penalty
</Typography.Text>
<Tag size='small' shape='circle'>
{inputs.presence_penalty}
</Tag>
</div>
<Button
theme={parameterEnabled.presence_penalty ? 'solid' : 'borderless'}
type={parameterEnabled.presence_penalty ? 'primary' : 'tertiary'}
size='small'
icon={
parameterEnabled.presence_penalty ? (
<Check size={10} />
) : (
<X size={10} />
)
}
onClick={() => onParameterToggle('presence_penalty')}
className='!rounded-full !w-4 !h-4 !p-0 !min-w-0 param-toggle-hit'
disabled={disabled}
/>
</div>
<Typography.Text className='text-xs text-gray-500 mb-2'>
{t('存在惩罚,鼓励讨论新话题')}
</Typography.Text>
<Slider
step={0.1}
min={-2}
max={2}
value={inputs.presence_penalty}
onChange={(value) => onInputChange('presence_penalty', value)}
className='mt-2'
disabled={!parameterEnabled.presence_penalty || disabled}
/>
</div>
{/* MaxTokens */}
<div
className={`transition-opacity duration-200 mb-4 ${!parameterEnabled.max_tokens || disabled ? 'opacity-50' : ''}`}
>
<div className='flex items-center justify-between mb-2'>
<div className='flex items-center gap-2'>
<Hash size={16} className='text-gray-500' />
<Typography.Text strong className='text-sm'>
Max Tokens
</Typography.Text>
</div>
<Button
theme={parameterEnabled.max_tokens ? 'solid' : 'borderless'}
type={parameterEnabled.max_tokens ? 'primary' : 'tertiary'}
size='small'
icon={
parameterEnabled.max_tokens ? (
<Check size={10} />
) : (
<X size={10} />
)
}
onClick={() => onParameterToggle('max_tokens')}
className='!rounded-full !w-4 !h-4 !p-0 !min-w-0 param-toggle-hit'
disabled={disabled}
/>
</div>
<Input
placeholder='MaxTokens'
name='max_tokens'
required
autoComplete='new-password'
defaultValue={0}
value={inputs.max_tokens}
onChange={(value) => onInputChange('max_tokens', value)}
className='!rounded-lg'
disabled={!parameterEnabled.max_tokens || disabled}
/>
</div>
{/* Seed */}
<div
className={`transition-opacity duration-200 mb-4 ${!parameterEnabled.seed || disabled ? 'opacity-50' : ''}`}
>
<div className='flex items-center justify-between mb-2'>
<div className='flex items-center gap-2'>
<Shuffle size={16} className='text-gray-500' />
<Typography.Text strong className='text-sm'>
Seed
</Typography.Text>
<Typography.Text className='text-xs text-gray-400'>
({t('可选,用于复现结果')})
</Typography.Text>
</div>
<Button
theme={parameterEnabled.seed ? 'solid' : 'borderless'}
type={parameterEnabled.seed ? 'primary' : 'tertiary'}
size='small'
icon={parameterEnabled.seed ? <Check size={10} /> : <X size={10} />}
onClick={() => onParameterToggle('seed')}
className='!rounded-full !w-4 !h-4 !p-0 !min-w-0 param-toggle-hit'
disabled={disabled}
/>
</div>
<Input
placeholder={t('随机种子 (留空为随机)')}
name='seed'
autoComplete='new-password'
value={inputs.seed || ''}
onChange={(value) =>
onInputChange('seed', value === '' ? null : value)
}
className='!rounded-lg'
disabled={!parameterEnabled.seed || disabled}
/>
</div>
</>
);
};
export default ParameterControl;
+314
View File
@@ -0,0 +1,314 @@
/*
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 React, { useState, useMemo, useCallback } from 'react';
import {
Button,
Tooltip,
Toast,
Collapse,
Badge,
Typography,
} from '@douyinfe/semi-ui';
import {
Copy,
ChevronDown,
ChevronUp,
Zap,
CheckCircle,
XCircle,
} from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { copy } from '../../helpers';
/**
* SSEViewer component for displaying Server-Sent Events in an interactive format
* @param {Object} props - Component props
* @param {Array} props.sseData - Array of SSE messages to display
* @returns {JSX.Element} Rendered SSE viewer component
*/
const SSEViewer = ({ sseData }) => {
const { t } = useTranslation();
const [expandedKeys, setExpandedKeys] = useState([]);
const [copied, setCopied] = useState(false);
const parsedSSEData = useMemo(() => {
if (!sseData || !Array.isArray(sseData)) {
return [];
}
return sseData.map((item, index) => {
let parsed = null;
let error = null;
let isDone = false;
if (item === '[DONE]') {
isDone = true;
} else {
try {
parsed = typeof item === 'string' ? JSON.parse(item) : item;
} catch (e) {
error = e.message;
}
}
return {
index,
raw: item,
parsed,
error,
isDone,
key: `sse-${index}`,
};
});
}, [sseData]);
const stats = useMemo(() => {
const total = parsedSSEData.length;
const errors = parsedSSEData.filter((item) => item.error).length;
const done = parsedSSEData.filter((item) => item.isDone).length;
const valid = total - errors - done;
return { total, errors, done, valid };
}, [parsedSSEData]);
const handleToggleAll = useCallback(() => {
setExpandedKeys((prev) => {
if (prev.length === parsedSSEData.length) {
return [];
} else {
return parsedSSEData.map((item) => item.key);
}
});
}, [parsedSSEData]);
const handleCopyAll = useCallback(async () => {
try {
const allData = parsedSSEData
.map((item) =>
item.parsed ? JSON.stringify(item.parsed, null, 2) : item.raw,
)
.join('\n\n');
await copy(allData);
setCopied(true);
Toast.success(t('已复制全部数据'));
setTimeout(() => setCopied(false), 2000);
} catch (err) {
Toast.error(t('复制失败'));
console.error('Copy failed:', err);
}
}, [parsedSSEData, t]);
const handleCopySingle = useCallback(
async (item) => {
try {
const textToCopy = item.parsed
? JSON.stringify(item.parsed, null, 2)
: item.raw;
await copy(textToCopy);
Toast.success(t('已复制'));
} catch (err) {
Toast.error(t('复制失败'));
}
},
[t],
);
const renderSSEItem = (item) => {
if (item.isDone) {
return (
<div className='flex items-center gap-2 p-3 bg-green-50 dark:bg-green-900/20 rounded-lg'>
<CheckCircle size={16} className='text-green-600' />
<Typography.Text className='text-green-600 font-medium'>
{t('流式响应完成')} [DONE]
</Typography.Text>
</div>
);
}
if (item.error) {
return (
<div className='space-y-2'>
<div className='flex items-center gap-2 p-3 bg-red-50 dark:bg-red-900/20 rounded-lg'>
<XCircle size={16} className='text-red-600' />
<Typography.Text className='text-red-600'>
{t('解析错误')}: {item.error}
</Typography.Text>
</div>
<div className='p-3 bg-gray-100 dark:bg-gray-800 rounded-lg font-mono text-xs overflow-auto'>
<pre>{item.raw}</pre>
</div>
</div>
);
}
return (
<div className='space-y-2'>
{/* JSON 格式化显示 */}
<div className='relative'>
<pre className='p-4 bg-gray-900 text-gray-100 rounded-lg overflow-auto text-xs font-mono leading-relaxed'>
{JSON.stringify(item.parsed, null, 2)}
</pre>
<Button
icon={<Copy size={12} />}
size='small'
theme='borderless'
onClick={() => handleCopySingle(item)}
className='absolute top-2 right-2 !bg-gray-800/80 !text-gray-300 hover:!bg-gray-700'
/>
</div>
{/* 关键信息摘要 */}
{item.parsed?.choices?.[0] && (
<div className='flex flex-wrap gap-2 text-xs'>
{item.parsed.choices[0].delta?.content && (
<Badge
count={`${t('内容')}: "${String(item.parsed.choices[0].delta.content).substring(0, 20)}..."`}
type='primary'
/>
)}
{item.parsed.choices[0].delta?.reasoning_content && (
<Badge count={t('有 Reasoning')} type='warning' />
)}
{item.parsed.choices[0].finish_reason && (
<Badge
count={`${t('完成')}: ${item.parsed.choices[0].finish_reason}`}
type='success'
/>
)}
{item.parsed.usage && (
<Badge
count={`${t('令牌')}: ${item.parsed.usage.prompt_tokens || 0}/${item.parsed.usage.completion_tokens || 0}`}
type='tertiary'
/>
)}
</div>
)}
</div>
);
};
if (!parsedSSEData || parsedSSEData.length === 0) {
return (
<div className='flex items-center justify-center h-full min-h-[200px] text-gray-500'>
<span>{t('暂无SSE响应数据')}</span>
</div>
);
}
return (
<div className='h-full flex flex-col bg-gray-50 dark:bg-gray-900/50 rounded-lg'>
{/* 头部工具栏 */}
<div className='flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700 flex-shrink-0'>
<div className='flex items-center gap-3'>
<Zap size={16} className='text-blue-500' />
<Typography.Text strong>{t('SSE数据流')}</Typography.Text>
<Badge count={stats.total} type='primary' />
{stats.errors > 0 && (
<Badge count={`${stats.errors} ${t('错误')}`} type='danger' />
)}
</div>
<div className='flex items-center gap-2'>
<Tooltip content={t('复制全部')}>
<Button
icon={<Copy size={14} />}
size='small'
onClick={handleCopyAll}
theme='borderless'
>
{copied ? t('已复制') : t('复制全部')}
</Button>
</Tooltip>
<Tooltip
content={
expandedKeys.length === parsedSSEData.length
? t('全部收起')
: t('全部展开')
}
>
<Button
icon={
expandedKeys.length === parsedSSEData.length ? (
<ChevronUp size={14} />
) : (
<ChevronDown size={14} />
)
}
size='small'
onClick={handleToggleAll}
theme='borderless'
>
{expandedKeys.length === parsedSSEData.length
? t('收起')
: t('展开')}
</Button>
</Tooltip>
</div>
</div>
{/* SSE 数据列表 */}
<div className='flex-1 overflow-auto p-4'>
<Collapse
activeKey={expandedKeys}
onChange={setExpandedKeys}
accordion={false}
className='bg-white dark:bg-gray-800 rounded-lg'
>
{parsedSSEData.map((item) => (
<Collapse.Panel
key={item.key}
header={
<div className='flex items-center gap-2'>
<Badge count={`#${item.index + 1}`} type='tertiary' />
{item.isDone ? (
<span className='text-green-600 font-medium'>[DONE]</span>
) : item.error ? (
<span className='text-red-600'>{t('解析错误')}</span>
) : (
<>
<span className='text-gray-600'>
{item.parsed?.id ||
item.parsed?.object ||
t('SSE 事件')}
</span>
{item.parsed?.choices?.[0]?.delta && (
<span className='text-xs text-gray-400'>
•{' '}
{Object.keys(item.parsed.choices[0].delta)
.filter((k) => item.parsed.choices[0].delta[k])
.join(', ')}
</span>
)}
</>
)}
</div>
}
>
{renderSSEItem(item)}
</Collapse.Panel>
))}
</Collapse>
</div>
</div>
);
};
export default SSEViewer;
@@ -0,0 +1,527 @@
/*
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 React, {
useMemo,
useState,
useCallback,
useRef,
useEffect,
} from 'react';
import {
Button,
List,
Modal,
Spin,
Empty,
Input,
Tooltip,
Dropdown,
} from '@douyinfe/semi-ui';
import {
Plus,
MessageSquare,
Trash2,
ChevronLeft,
ChevronRight,
Search,
X,
MoreHorizontal,
Edit3,
Sparkles,
Download,
} from 'lucide-react';
import { useTranslation } from 'react-i18next';
const formatRelativeTime = (timestamp, t) => {
if (!timestamp) return '';
try {
const dt = new Date(timestamp);
const now = new Date();
const diff = now - dt;
if (diff < 60 * 1000) return t ? t('刚刚') : '刚刚';
if (diff < 60 * 60 * 1000) {
const n = Math.floor(diff / (60 * 1000));
return t ? t('{{n}} 分钟前', { n }) : `${n} 分钟前`;
}
if (diff < 24 * 60 * 60 * 1000) {
const n = Math.floor(diff / (60 * 60 * 1000));
return t ? t('{{n}} 小时前', { n }) : `${n} 小时前`;
}
if (diff < 7 * 24 * 60 * 60 * 1000) {
const n = Math.floor(diff / (24 * 60 * 60 * 1000));
return t ? t('{{n}} 天前', { n }) : `${n} 天前`;
}
return dt.toLocaleDateString();
} catch {
return '';
}
};
const SessionSidebar = ({
sessions = [],
activeSessionId,
loading = false,
creating = false,
hasMore = false,
onCreate,
onSwitch,
onDelete,
onRename,
onExport,
onLoadMore,
onClose, // 移动端关闭回调
isMobile = false,
collapsed = false,
onToggleCollapse,
isExperienceMode = false,
}) => {
const { t } = useTranslation();
const [keyword, setKeyword] = useState('');
const [editingId, setEditingId] = useState(null);
const [editingValue, setEditingValue] = useState('');
const editInputRef = useRef(null);
// 区分单击和双击:单击延迟 220ms 触发,期间若发生双击则取消单击
const clickTimerRef = useRef(null);
useEffect(() => {
return () => {
if (clickTimerRef.current) {
clearTimeout(clickTimerRef.current);
}
};
}, []);
const shellBgClass = isExperienceMode
? 'bg-white/[0.32] dark:bg-neutral-950/[0.36]'
: 'bg-white/60 dark:bg-neutral-900/60';
const shellOverlayClass = isExperienceMode
? 'bg-white/[0.10] dark:bg-white/[0.025]'
: 'bg-white/[0.22] dark:bg-white/[0.04]';
const sessionListClass = isExperienceMode
? 'relative flex-1 overflow-y-auto mx-2 mb-2 rounded-2xl pt-2 pb-3 px-1 [scrollbar-gutter:stable] border border-white/50 dark:border-white/10 bg-sky-50/[0.45] dark:bg-slate-950/20 backdrop-blur-sm'
: 'relative flex-1 overflow-y-auto pt-1 pb-2 [scrollbar-gutter:stable]';
// 搜索过滤(前端本地过滤,配合后端分页加载)
const filteredSessions = useMemo(() => {
const kw = keyword.trim().toLowerCase();
if (!kw) return sessions;
return sessions.filter((s) => {
const title = (s.title || '').toLowerCase();
const model = (s.model || '').toLowerCase();
return title.includes(kw) || model.includes(kw);
});
}, [sessions, keyword]);
const handleDelete = useCallback(
(e, session) => {
e.stopPropagation();
Modal.confirm({
title: t('删除会话'),
content: t(
'删除会话「{{title}}」会同时清除本会话的所有聊天记录,此操作不可撤销。',
{
title: session.title || t('新对话'),
},
),
okText: t('确认删除'),
cancelText: t('取消'),
okButtonProps: { type: 'danger' },
onOk: () => onDelete?.(session.id),
});
},
[t, onDelete],
);
const startEdit = useCallback((session) => {
setEditingId(session.id);
setEditingValue(session.title || '');
setTimeout(() => {
try {
editInputRef.current?.focus();
} catch (_) {
// ignore
}
}, 30);
}, []);
const cancelEdit = useCallback(() => {
setEditingId(null);
setEditingValue('');
}, []);
const submitEdit = useCallback(
async (sessionId) => {
const newTitle = editingValue.trim();
const original = sessions.find((s) => s.id === sessionId);
const originalTitle = (original?.title || '').trim();
if (newTitle === originalTitle) {
cancelEdit();
return;
}
if (!newTitle) {
cancelEdit();
return;
}
try {
await onRename?.(sessionId, newTitle);
} finally {
cancelEdit();
}
},
[editingValue, sessions, onRename, cancelEdit],
);
// 折叠态:仅显示新建/展开按钮
if (collapsed && !isMobile) {
return (
<div
className={`relative flex flex-col h-full ${shellBgClass} backdrop-blur-[30px] backdrop-saturate-[1.7] border-r border-white/45 dark:border-white/10 shadow-[1px_0_28px_-10px_rgba(15,23,42,0.22)] dark:shadow-[1px_0_32px_-12px_rgba(0,0,0,0.5)]`}
>
<div
className={`absolute inset-0 ${shellOverlayClass} pointer-events-none`}
/>
<div className='relative flex flex-col items-center pt-4 gap-2'>
<Tooltip content={t('展开会话列表')} position='right'>
<Button
icon={<ChevronRight size={16} />}
theme='borderless'
type='tertiary'
onClick={onToggleCollapse}
className='!w-9 !h-9 !rounded-xl !bg-white/35 hover:!bg-white/60 dark:!bg-white/[0.06] dark:hover:!bg-white/[0.1]'
/>
</Tooltip>
<Tooltip content={t('新建对话')} position='right'>
<Button
icon={<Plus size={16} />}
theme='solid'
type='primary'
loading={creating}
onClick={() => onCreate?.()}
className='!w-9 !h-9 !rounded-xl'
style={{
background: 'var(--brand-primary)',
boxShadow:
'0 10px 24px color-mix(in srgb, var(--brand-primary) 30%, transparent)',
}}
/>
</Tooltip>
</div>
</div>
);
}
return (
<div
className={`
relative flex flex-col h-full
${shellBgClass} backdrop-blur-[30px] backdrop-saturate-[1.7]
border-r border-white/45 dark:border-white/10
shadow-[1px_0_34px_-10px_rgba(15,23,42,0.20)] dark:shadow-[1px_0_34px_-10px_rgba(0,0,0,0.45)]
`}
>
{/* 毛玻璃内层光泽 */}
<div
className={`absolute inset-0 ${shellOverlayClass} pointer-events-none`}
/>
<div className='absolute inset-y-0 right-0 w-px bg-white/70 dark:bg-white/10 pointer-events-none' />
{/* 顶部品牌区 + 折叠/关闭 */}
<div className='relative px-4 pt-4 pb-2 flex items-center justify-between'>
<div className='flex items-center gap-2 min-w-0'>
<div className='p-1.5 rounded-lg border border-brand/15 bg-brand/10 text-brand-deep shadow-sm shadow-brand/10 dark:border-brand/20 dark:bg-brand/15 dark:text-brand-from flex-shrink-0'>
<Sparkles size={14} />
</div>
<span className='font-semibold text-sm text-gray-900 dark:text-white truncate'>
{t('我的会话')}
</span>
</div>
{isMobile && onClose ? (
<Button
icon={<X size={16} />}
theme='borderless'
type='tertiary'
onClick={onClose}
className='!w-7 !h-7 !rounded-lg'
aria-label={t('关闭')}
/>
) : (
onToggleCollapse && (
<Tooltip content={t('收起')} position='bottom'>
<Button
icon={<ChevronLeft size={16} />}
theme='borderless'
type='tertiary'
onClick={onToggleCollapse}
className='!w-7 !h-7 !rounded-lg'
aria-label={t('收起')}
/>
</Tooltip>
)
)}
</div>
{/* 新建按钮 */}
<div className='relative px-3 pb-2'>
<Button
icon={<Plus size={16} />}
theme='solid'
type='primary'
block
loading={creating}
onClick={() => onCreate?.()}
className='!rounded-xl'
style={{
background: 'var(--brand-primary)',
boxShadow:
'0 12px 26px color-mix(in srgb, var(--brand-primary) 25%, transparent)',
}}
>
{t('新建对话')}
</Button>
</div>
{/* 搜索框 */}
<div className='relative px-3 pb-2'>
<Input
prefix={<Search size={14} className='text-gray-400' />}
placeholder={t('搜索会话')}
value={keyword}
onChange={(v) => setKeyword(v)}
showClear
className='session-search-input [&_.semi-input-wrapper]:!rounded-xl [&_.semi-input-wrapper]:!border-white/45 [&_.semi-input-wrapper]:!bg-white/30 [&_.semi-input-wrapper]:!backdrop-blur-md dark:[&_.semi-input-wrapper]:!border-white/10 dark:[&_.semi-input-wrapper]:!bg-white/[0.055] [&_.semi-input-wrapper:hover]:!border-brand/30 [&_.semi-input-wrapper:focus-within]:!border-brand'
/>
</div>
{/* 列表 */}
<div className={sessionListClass}>
{loading && sessions.length === 0 ? (
<div className='flex justify-center items-center h-32'>
<Spin />
</div>
) : filteredSessions.length === 0 ? (
<div className='flex justify-center items-center h-full p-4'>
<Empty
image={<MessageSquare size={40} className='text-gray-300' />}
title={keyword ? t('未找到匹配会话') : t('还没有对话')}
description={
keyword
? hasMore
? t('仅在已加载会话内搜索,点击下方加载更多')
: ''
: t('点击上方按钮开始你的第一次提问')
}
/>
{keyword && hasMore && (
<Button
theme='borderless'
type='primary'
size='small'
loading={loading}
onClick={() => onLoadMore?.()}
className='mt-2'
>
{t('加载更多')}
</Button>
)}
</div>
) : (
<List
dataSource={filteredSessions}
renderItem={(session) => {
const isActive = session.id === activeSessionId;
const isEditing = editingId === session.id;
const titleText = session.title || t('新对话');
const activeItemClass = isExperienceMode
? 'border-sky-300/70 bg-white/[0.72] shadow-[0_10px_24px_rgba(37,99,235,0.08)] dark:border-sky-400/25 dark:bg-white/[0.08]'
: 'border-brand/30 bg-white/45 shadow-sm shadow-brand/10 dark:bg-white/[0.075]';
const inactiveItemClass = isExperienceMode
? 'border-transparent bg-white/[0.18] hover:border-sky-200/70 hover:bg-white/[0.55] hover:shadow-[0_8px_20px_rgba(15,23,42,0.05)] dark:hover:border-sky-400/15 dark:hover:bg-white/[0.06]'
: 'border-transparent hover:border-white/45 hover:bg-white/28 dark:hover:border-white/10 dark:hover:bg-white/[0.055]';
return (
<div
className={`
group relative px-2 mx-2 my-1 rounded-xl cursor-pointer
transition-all duration-200 border
${isActive ? activeItemClass : inactiveItemClass}
`}
onClick={() => {
if (isActive || isEditing) return;
// 延迟触发切换,给双击留出窗口期
if (clickTimerRef.current)
clearTimeout(clickTimerRef.current);
clickTimerRef.current = setTimeout(() => {
clickTimerRef.current = null;
onSwitch?.(session.id);
}, 220);
}}
onDoubleClick={(e) => {
e.stopPropagation();
// 取消未触发的单击切换
if (clickTimerRef.current) {
clearTimeout(clickTimerRef.current);
clickTimerRef.current = null;
}
if (onRename) startEdit(session);
}}
>
{/* 选中色条 */}
{isActive && (
<div className='absolute left-0 top-1/2 -translate-y-1/2 w-1 h-6 rounded-r-full bg-brand shadow-[0_0_14px_color-mix(in_srgb,var(--brand-primary)_40%,transparent)]' />
)}
<div className='flex items-start gap-2 px-2 py-2'>
<MessageSquare
size={14}
className={`mt-0.5 flex-shrink-0 ${
isActive ? 'text-brand' : 'text-gray-400'
}`}
/>
<div className='flex-1 min-w-0'>
{isEditing ? (
<Input
ref={editInputRef}
size='small'
value={editingValue}
onChange={(v) => setEditingValue(v)}
onBlur={() => submitEdit(session.id)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
submitEdit(session.id);
} else if (e.key === 'Escape') {
e.preventDefault();
cancelEdit();
}
}}
onClick={(e) => e.stopPropagation()}
autoFocus
maxLength={64}
/>
) : (
<Tooltip
content={titleText}
position='top'
showArrow={false}
>
<div
className={`text-sm truncate font-medium ${
isActive
? 'text-brand-deep dark:text-brand-from'
: 'text-gray-800 dark:text-gray-200'
}`}
>
{titleText}
</div>
</Tooltip>
)}
<div className='text-xs text-gray-400 mt-0.5 truncate'>
{session.model || '-'} ·{' '}
{formatRelativeTime(session.updated_at, t)}
</div>
</div>
{/* 操作菜单 */}
{!isEditing && (
<Dropdown
trigger='click'
position='bottomRight'
clickToHide
render={
<Dropdown.Menu>
{onRename && (
<Dropdown.Item
icon={<Edit3 size={14} />}
onClick={(e) => {
e?.stopPropagation?.();
startEdit(session);
}}
>
{t('重命名')}
</Dropdown.Item>
)}
{/* 导出仅对当前活动会话可见:其它会话的 messages 还没加载到前端,
导出会得到空文档。要做"全量导出"得加后端 endpoint,目前先满足 80% 用例 */}
{onExport && session.id === activeSessionId && (
<Dropdown.Item
icon={<Download size={14} />}
onClick={(e) => {
e?.stopPropagation?.();
onExport(session);
}}
>
{t('导出 Markdown')}
</Dropdown.Item>
)}
<Dropdown.Item
icon={<Trash2 size={14} />}
type='danger'
onClick={(e) =>
handleDelete(
e || { stopPropagation: () => {} },
session,
)
}
>
{t('删除')}
</Dropdown.Item>
</Dropdown.Menu>
}
>
<button
type='button'
className='
opacity-0 group-hover:opacity-100 [@media(hover:none)]:opacity-100 transition-opacity
flex-shrink-0 p-1 rounded hover:bg-gray-200/80 dark:hover:bg-neutral-700/80
text-gray-400 hover:text-gray-700 dark:hover:text-gray-200
'
onClick={(e) => e.stopPropagation()}
aria-label={t('更多操作')}
>
<MoreHorizontal size={14} />
</button>
</Dropdown>
)}
</div>
</div>
);
}}
/>
)}
{/* 加载更多 */}
{hasMore && !keyword && (
<div className='flex justify-center py-2'>
<Button
theme='borderless'
type='tertiary'
size='small'
loading={loading}
onClick={() => onLoadMore?.()}
>
{t('加载更多')}
</Button>
</div>
)}
</div>
</div>
);
};
export default SessionSidebar;
+434
View File
@@ -0,0 +1,434 @@
/*
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 React from 'react';
import { Select, Typography, Button, Switch } from '@douyinfe/semi-ui';
import {
Users,
ToggleLeft,
X,
Settings,
Sliders,
Bot,
Zap,
} from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { renderGroupOption, renderModelOption, selectFilter } from '../../helpers';
import ParameterControl from './ParameterControl';
import ImageUrlInput from './ImageUrlInput';
import ConfigManager from './ConfigManager';
import CustomRequestEditor from './CustomRequestEditor';
const SettingsPanel = ({
inputs,
parameterEnabled,
models,
groups,
styleState,
showDebugPanel,
customRequestMode,
customRequestBody,
onInputChange,
onParameterToggle,
onCloseSettings,
onConfigImport,
onConfigReset,
onCustomRequestModeChange,
onCustomRequestBodyChange,
previewPayload,
messages,
}) => {
const { t } = useTranslation();
const currentConfig = {
inputs,
parameterEnabled,
showDebugPanel,
customRequestMode,
customRequestBody,
};
const isExperienceMode = styleState?.isExperienceMode;
// 设置项卡片组件
const SettingCard = ({ icon: Icon, title, children, disabled, gradient }) => (
<div className={`relative ${disabled ? 'opacity-50' : ''}`}>
{isExperienceMode && (
<div className='flex items-center gap-2 mb-2.5'>
<div
className={`w-6 h-6 rounded-lg bg-gradient-to-br ${gradient} flex items-center justify-center shadow-sm`}
>
<Icon size={12} className='text-white' />
</div>
<Typography.Text
strong
className='text-sm text-gray-700 dark:text-gray-200'
>
{title}
</Typography.Text>
</div>
)}
{!isExperienceMode && (
<div className='flex items-center gap-2 mb-2'>
<Icon size={16} className='text-gray-500' />
<Typography.Text strong className='text-sm'>
{title}
</Typography.Text>
{customRequestMode && disabled && (
<Typography.Text className='text-xs text-orange-600'>
({t('已在自定义模式中忽略')})
</Typography.Text>
)}
</div>
)}
{children}
</div>
);
return (
<div
className={`h-full flex flex-col ${isExperienceMode ? 'bg-gradient-to-b from-white to-gray-50/50 dark:from-neutral-900 dark:to-neutral-950/50 border-r border-gray-100 dark:border-neutral-800' : 'bg-transparent'}`}
style={{
padding: styleState.isMobile
? '16px'
: isExperienceMode
? '20px'
: '24px',
height: '100%',
display: 'flex',
flexDirection: 'column',
}}
>
{/* 标题区域 - 非体验模式显示 */}
{!isExperienceMode && (
<div className='flex items-center justify-between mb-6 flex-shrink-0'>
<div className='flex items-center'>
<div className='w-10 h-10 rounded-full bg-gradient-to-r from-brand-from to-pink-500 flex items-center justify-center mr-3'>
<Settings size={20} className='text-white' />
</div>
<Typography.Title heading={5} className='mb-0'>
{t('模型配置')}
</Typography.Title>
</div>
{styleState.isMobile && onCloseSettings && (
<Button
icon={<X size={16} />}
onClick={onCloseSettings}
theme='borderless'
type='tertiary'
size='small'
className='!rounded-lg'
/>
)}
</div>
)}
{/* 体验模式下的美化标题 */}
{isExperienceMode && !styleState.isMobile && (
<div className='mb-6 flex-shrink-0'>
<div className='flex items-center gap-3 mb-2'>
<div className='w-10 h-10 rounded-xl bg-gradient-to-br from-brand-from to-brand-to flex items-center justify-center shadow-lg shadow-brand/20'>
<Sliders size={18} className='text-white' />
</div>
<div>
<Typography.Title
heading={5}
style={{ fontWeight: 600, marginBottom: 0 }}
>
{t('模型配置')}
</Typography.Title>
<Typography.Text className='text-xs text-gray-400 dark:text-gray-500'>
{t('自定义对话参数')}
</Typography.Text>
</div>
</div>
{/* 装饰性分隔线 */}
<div className='h-px bg-gradient-to-r from-brand-from/30 via-brand-via/20 to-transparent mt-4' />
</div>
)}
{/* 移动端配置管理 */}
{styleState.isMobile && (
<div className='mb-4 flex-shrink-0'>
<ConfigManager
currentConfig={currentConfig}
onConfigImport={onConfigImport}
onConfigReset={onConfigReset}
styleState={{ ...styleState, isMobile: false }}
messages={messages}
/>
</div>
)}
<div
className={`space-y-4 overflow-y-auto flex-1 pr-2 model-settings-scroll ${isExperienceMode ? 'px-1' : ''}`}
>
{/* 自定义请求体编辑器 - 体验模式隐藏 */}
{!isExperienceMode && (
<CustomRequestEditor
customRequestMode={customRequestMode}
customRequestBody={customRequestBody}
onCustomRequestModeChange={onCustomRequestModeChange}
onCustomRequestBodyChange={onCustomRequestBodyChange}
defaultPayload={previewPayload}
/>
)}
{/* 分组选择 - 体验模式隐藏 */}
{!isExperienceMode && (
<SettingCard
icon={Users}
title={t('分组')}
disabled={customRequestMode}
gradient='from-blue-500 to-cyan-500'
>
<Select
placeholder={t('请选择分组')}
name='group'
required
selection
filter={selectFilter}
autoClearSearchValue={false}
onChange={(value) => onInputChange('group', value)}
value={inputs.group}
autoComplete='new-password'
optionList={groups}
renderOptionItem={renderGroupOption}
style={{ width: '100%' }}
dropdownStyle={{ width: '100%', maxWidth: '100%' }}
className='!rounded-xl'
disabled={customRequestMode}
/>
</SettingCard>
)}
{/* 模型选择 - 体验模式下使用增强样式 */}
{isExperienceMode ? (
<div className='group relative'>
{/* 外发光效果 */}
<div className='absolute -inset-0.5 bg-gradient-to-r from-brand-from/30 via-brand-via/30 to-brand-to/30 rounded-2xl blur-md opacity-0 group-hover:opacity-100 transition-all duration-500' />
<div className='relative p-4 rounded-xl bg-gradient-to-br from-white/80 to-gray-50/80 dark:from-neutral-800/80 dark:to-neutral-900/80 backdrop-blur-sm border border-white/50 dark:border-neutral-700/50 shadow-lg shadow-brand/5 hover:shadow-brand/10 transition-all duration-300'>
{/* 顶部装饰条 */}
<div className='absolute top-0 left-4 right-4 h-[2px] bg-gradient-to-r from-transparent via-brand-via/50 to-transparent rounded-full' />
<div className='flex items-center gap-3 mb-3'>
<div className='relative'>
<div className='absolute -inset-1 bg-gradient-to-br from-brand-from to-brand-to rounded-xl blur-sm opacity-60' />
<div className='relative w-8 h-8 rounded-lg bg-gradient-to-br from-brand-from to-brand-to flex items-center justify-center shadow-lg'>
<Bot size={16} className='text-white' />
</div>
</div>
<div>
<Typography.Text
strong
className='text-sm text-gray-800 dark:text-gray-100'
>
{t('模型')}
</Typography.Text>
<Typography.Text className='text-xs text-gray-400 dark:text-gray-500 block'>
{t('选择 AI 模型')}
</Typography.Text>
</div>
</div>
<Select
placeholder={t('请选择模型')}
name='model'
required
selection
filter={selectFilter}
autoClearSearchValue={false}
onChange={(value) => onInputChange('model', value)}
value={inputs.model}
autoComplete='new-password'
optionList={models}
renderOptionItem={renderModelOption}
style={{ width: '100%' }}
dropdownStyle={{ width: '100%', maxWidth: '100%' }}
className='!rounded-xl !border-brand/50 dark:!border-brand-deep/30 hover:!border-brand-from transition-colors'
disabled={customRequestMode}
/>
</div>
</div>
) : (
<SettingCard
icon={Bot}
title={t('模型')}
disabled={customRequestMode}
gradient='from-brand-from to-brand-to'
>
<div className='relative'>
<Select
placeholder={t('请选择模型')}
name='model'
required
selection
filter={selectFilter}
autoClearSearchValue={false}
onChange={(value) => onInputChange('model', value)}
value={inputs.model}
autoComplete='new-password'
optionList={models}
renderOptionItem={renderModelOption}
style={{ width: '100%' }}
dropdownStyle={{ width: '100%', maxWidth: '100%' }}
className='!rounded-xl'
disabled={customRequestMode}
/>
</div>
</SettingCard>
)}
{/* 图片URL输入 - 体验模式下使用增强样式 */}
<div
className={`${customRequestMode ? 'opacity-50' : ''} ${isExperienceMode ? 'group relative' : ''}`}
>
{isExperienceMode && (
<div className='absolute -inset-0.5 bg-gradient-to-r from-pink-500/20 via-rose-500/20 to-orange-500/20 rounded-2xl blur-md opacity-0 group-hover:opacity-100 transition-all duration-500' />
)}
<div
className={
isExperienceMode
? 'relative p-4 rounded-xl bg-gradient-to-br from-white/80 to-gray-50/80 dark:from-neutral-800/80 dark:to-neutral-900/80 backdrop-blur-sm border border-white/50 dark:border-neutral-700/50 shadow-lg shadow-pink-500/5 hover:shadow-pink-500/10 transition-all duration-300'
: ''
}
>
{isExperienceMode && (
<div className='absolute top-0 left-4 right-4 h-[2px] bg-gradient-to-r from-transparent via-pink-500/50 to-transparent rounded-full' />
)}
<ImageUrlInput
imageUrls={inputs.imageUrls}
imageEnabled={inputs.imageEnabled}
onImageUrlsChange={(urls) => onInputChange('imageUrls', urls)}
onImageEnabledChange={(enabled) =>
onInputChange('imageEnabled', enabled)
}
disabled={customRequestMode}
/>
</div>
</div>
{/* 参数控制组件 - 体验模式下使用增强样式 */}
<div
className={`${customRequestMode ? 'opacity-50' : ''} ${isExperienceMode ? 'group relative' : ''}`}
>
{isExperienceMode && (
<div className='absolute -inset-0.5 bg-gradient-to-r from-blue-500/20 via-cyan-500/20 to-teal-500/20 rounded-2xl blur-md opacity-0 group-hover:opacity-100 transition-all duration-500' />
)}
<div
className={
isExperienceMode
? 'relative p-4 rounded-xl bg-gradient-to-br from-white/80 to-gray-50/80 dark:from-neutral-800/80 dark:to-neutral-900/80 backdrop-blur-sm border border-white/50 dark:border-neutral-700/50 shadow-lg shadow-blue-500/5 hover:shadow-blue-500/10 transition-all duration-300'
: ''
}
>
{isExperienceMode && (
<div className='absolute top-0 left-4 right-4 h-[2px] bg-gradient-to-r from-transparent via-blue-500/50 to-transparent rounded-full' />
)}
<ParameterControl
inputs={inputs}
parameterEnabled={parameterEnabled}
onInputChange={onInputChange}
onParameterToggle={onParameterToggle}
disabled={customRequestMode}
/>
</div>
</div>
{/* 流式输出开关 - 体验模式下使用增强样式 */}
<div
className={`${customRequestMode ? 'opacity-50' : ''} ${isExperienceMode ? 'group relative' : ''}`}
>
{isExperienceMode && (
<div className='absolute -inset-0.5 bg-gradient-to-r from-emerald-500/20 via-teal-500/20 to-cyan-500/20 rounded-2xl blur-md opacity-0 group-hover:opacity-100 transition-all duration-500' />
)}
<div
className={
isExperienceMode
? 'relative p-4 rounded-xl bg-gradient-to-br from-white/80 to-gray-50/80 dark:from-neutral-800/80 dark:to-neutral-900/80 backdrop-blur-sm border border-white/50 dark:border-neutral-700/50 shadow-lg shadow-emerald-500/5 hover:shadow-emerald-500/10 transition-all duration-300'
: ''
}
>
{isExperienceMode && (
<div className='absolute top-0 left-4 right-4 h-[2px] bg-gradient-to-r from-transparent via-emerald-500/50 to-transparent rounded-full' />
)}
<div className='flex items-center justify-between'>
<div className='flex items-center gap-2'>
{isExperienceMode ? (
<div className='relative'>
<div className='absolute -inset-0.5 bg-gradient-to-br from-emerald-500 to-teal-600 rounded-lg blur-sm opacity-60' />
<div className='relative w-7 h-7 rounded-lg bg-gradient-to-br from-emerald-500 to-teal-600 flex items-center justify-center shadow-md'>
<Zap size={14} className='text-white' />
</div>
</div>
) : (
<ToggleLeft size={16} className='text-gray-500' />
)}
<div>
<Typography.Text strong className='text-sm'>
{t('流式输出')}
</Typography.Text>
{isExperienceMode && (
<Typography.Text className='text-xs text-gray-400 dark:text-gray-500 block'>
{t('实时显示AI回复内容')}
</Typography.Text>
)}
</div>
{customRequestMode && !isExperienceMode && (
<Typography.Text className='text-xs text-orange-600'>
({t('已在自定义模式中忽略')})
</Typography.Text>
)}
</div>
<Switch
checked={inputs.stream}
onChange={(checked) => onInputChange('stream', checked)}
checkedText={t('开')}
uncheckedText={t('关')}
size='small'
disabled={customRequestMode}
/>
</div>
</div>
</div>
</div>
{/* 桌面端的配置管理放在底部 */}
{!styleState.isMobile && (
<div className='flex-shrink-0 pt-4'>
{isExperienceMode && (
<div className='h-px bg-gradient-to-r from-transparent via-gray-200 dark:via-neutral-700 to-transparent mb-4' />
)}
<ConfigManager
currentConfig={currentConfig}
onConfigImport={onConfigImport}
onConfigReset={onConfigReset}
styleState={styleState}
messages={messages}
/>
</div>
)}
</div>
);
};
export default SettingsPanel;
@@ -0,0 +1,178 @@
/*
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 React, { useEffect, useRef } from 'react';
import { Typography } from '@douyinfe/semi-ui';
import MarkdownRenderer from '../common/markdown/MarkdownRenderer';
import { ChevronRight, ChevronUp, Brain, Loader2 } from 'lucide-react';
import { useTranslation } from 'react-i18next';
const ThinkingContent = ({
message,
finalExtractedThinkingContent,
thinkingSource,
styleState,
onToggleReasoningExpansion,
}) => {
const { t } = useTranslation();
const scrollRef = useRef(null);
const lastContentRef = useRef('');
const isThinkingStatus =
message.status === 'loading' || message.status === 'incomplete';
const headerText =
isThinkingStatus && !message.isThinkingComplete
? t('思考中...')
: t('思考过程');
useEffect(() => {
if (
scrollRef.current &&
finalExtractedThinkingContent &&
message.isReasoningExpanded
) {
scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
}
}, [finalExtractedThinkingContent, message.isReasoningExpanded]);
useEffect(() => {
if (!isThinkingStatus) {
lastContentRef.current = '';
}
}, [isThinkingStatus]);
if (!finalExtractedThinkingContent) return null;
let prevLength = 0;
if (isThinkingStatus && lastContentRef.current) {
if (finalExtractedThinkingContent.startsWith(lastContentRef.current)) {
prevLength = lastContentRef.current.length;
}
}
if (isThinkingStatus) {
lastContentRef.current = finalExtractedThinkingContent;
}
return (
<div className='rounded-xl sm:rounded-2xl mb-2 sm:mb-4 overflow-hidden shadow-sm backdrop-blur-sm'>
<div
className='flex items-center justify-between p-3 cursor-pointer hover:bg-gradient-to-r hover:from-white/20 hover:to-brand-to/30 transition-all'
style={{
background:
'linear-gradient(135deg, color-mix(in srgb, var(--brand-gradient-via) 35%, #000) 0%, color-mix(in srgb, var(--brand-primary) 45%, #000) 50%, var(--brand-primary-hover) 100%)',
position: 'relative',
}}
onClick={() => onToggleReasoningExpansion(message.id)}
>
<div className='absolute inset-0 overflow-hidden'>
<div className='absolute -top-10 -right-10 w-40 h-40 bg-white opacity-5 rounded-full'></div>
<div className='absolute -bottom-8 -left-8 w-24 h-24 bg-white opacity-10 rounded-full'></div>
</div>
<div className='flex items-center gap-2 sm:gap-4 relative'>
<div className='w-6 h-6 sm:w-8 sm:h-8 rounded-full bg-white/20 flex items-center justify-center shadow-lg'>
<Brain
style={{ color: 'white' }}
size={styleState.isMobile ? 12 : 16}
/>
</div>
<div className='flex flex-col'>
<Typography.Text
strong
style={{ color: 'white' }}
className='text-sm sm:text-base'
>
{headerText}
</Typography.Text>
{thinkingSource && (
<Typography.Text
style={{ color: 'white' }}
className='text-xs mt-0.5 opacity-80 hidden sm:block'
>
来源: {thinkingSource}
</Typography.Text>
)}
</div>
</div>
<div className='flex items-center gap-2 sm:gap-3 relative'>
{isThinkingStatus && !message.isThinkingComplete && (
<div className='flex items-center gap-1 sm:gap-2'>
<Loader2
style={{ color: 'white' }}
className='animate-spin'
size={styleState.isMobile ? 14 : 18}
/>
<Typography.Text
style={{ color: 'white' }}
className='text-xs sm:text-sm font-medium opacity-90'
>{t('思考中')}</Typography.Text>
</div>
)}
{(!isThinkingStatus || message.isThinkingComplete) && (
<div className='w-5 h-5 sm:w-6 sm:h-6 rounded-full bg-white/20 flex items-center justify-center'>
{message.isReasoningExpanded ? (
<ChevronUp
size={styleState.isMobile ? 12 : 16}
style={{ color: 'white' }}
/>
) : (
<ChevronRight
size={styleState.isMobile ? 12 : 16}
style={{ color: 'white' }}
/>
)}
</div>
)}
</div>
</div>
<div
className={`transition-all duration-500 ease-out ${
message.isReasoningExpanded
? 'max-h-96 opacity-100'
: 'max-h-0 opacity-0'
} overflow-hidden bg-gradient-to-br from-brand-from/5 via-brand-via/5 to-brand-to/5`}
>
{message.isReasoningExpanded && (
<div className='p-3 sm:p-5 pt-2 sm:pt-4'>
<div
ref={scrollRef}
className='bg-white/70 backdrop-blur-sm rounded-lg sm:rounded-xl p-2 shadow-inner overflow-x-auto overflow-y-auto thinking-content-scroll'
style={{
maxHeight: '200px',
scrollbarWidth: 'thin',
scrollbarColor: 'var(--brand-scroll) transparent',
}}
>
<div className='prose prose-xs sm:prose-sm prose-purple max-w-none text-xs sm:text-sm'>
<MarkdownRenderer
content={finalExtractedThinkingContent}
className=''
animated={isThinkingStatus}
previousContentLength={prevLength}
/>
</div>
</div>
</div>
)}
</div>
</div>
);
};
export default ThinkingContent;
+328
View File
@@ -0,0 +1,328 @@
/*
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 { DEFAULT_CONFIG } from '../../constants/playground.constants';
// 存储键前缀
const STORAGE_KEY_PREFIX = 'playground';
/**
* 获取当前用户ID
* @returns {number|string} 用户ID,未登录返回 'guest'
*/
const getCurrentUserId = () => {
try {
const userStr = localStorage.getItem('user');
if (userStr) {
const user = JSON.parse(userStr);
return user.id || 'guest';
}
} catch (error) {
console.error('获取用户ID失败:', error);
}
return 'guest';
};
/**
* 生成带用户ID的存储键
* @param {string} type - 存储类型 ('config' 或 'messages')
* @param {number|string} userId - 用户ID(可选,默认获取当前用户)
* @returns {string} 存储键名
*/
const getStorageKey = (type, userId = null) => {
const uid = userId ?? getCurrentUserId();
return `${STORAGE_KEY_PREFIX}_${type}_user_${uid}`;
};
/**
* 保存配置到 localStorage
* @param {Object} config - 要保存的配置对象
* @param {number|string} userId - 用户ID(可选)
*/
export const saveConfig = (config, userId = null) => {
try {
const configToSave = {
...config,
timestamp: new Date().toISOString(),
};
localStorage.setItem(
getStorageKey('config', userId),
JSON.stringify(configToSave),
);
} catch (error) {
console.error('保存配置失败:', error);
}
};
/**
* 保存消息到 localStorage
* @param {Array} messages - 要保存的消息数组
* @param {number|string} userId - 用户ID(可选)
*/
export const saveMessages = (messages, userId = null) => {
try {
const messagesToSave = {
messages,
timestamp: new Date().toISOString(),
};
localStorage.setItem(
getStorageKey('messages', userId),
JSON.stringify(messagesToSave),
);
} catch (error) {
console.error('保存消息失败:', error);
}
};
/**
* 从 localStorage 加载配置
* @param {number|string} userId - 用户ID(可选)
* @returns {Object} 配置对象,如果不存在则返回默认配置
*/
export const loadConfig = (userId = null) => {
try {
const savedConfig = localStorage.getItem(getStorageKey('config', userId));
if (savedConfig) {
const parsedConfig = JSON.parse(savedConfig);
const mergedConfig = {
inputs: {
...DEFAULT_CONFIG.inputs,
...parsedConfig.inputs,
},
parameterEnabled: {
...DEFAULT_CONFIG.parameterEnabled,
...parsedConfig.parameterEnabled,
},
showDebugPanel:
parsedConfig.showDebugPanel || DEFAULT_CONFIG.showDebugPanel,
customRequestMode:
parsedConfig.customRequestMode || DEFAULT_CONFIG.customRequestMode,
customRequestBody:
parsedConfig.customRequestBody || DEFAULT_CONFIG.customRequestBody,
};
return mergedConfig;
}
} catch (error) {
console.error('加载配置失败:', error);
}
return DEFAULT_CONFIG;
};
/**
* 从 localStorage 加载消息
* @param {number|string} userId - 用户ID(可选)
* @returns {Array} 消息数组,如果不存在则返回 null
*/
export const loadMessages = (userId = null) => {
try {
const savedMessages = localStorage.getItem(
getStorageKey('messages', userId),
);
if (savedMessages) {
const parsedMessages = JSON.parse(savedMessages);
return parsedMessages.messages || null;
}
} catch (error) {
console.error('加载消息失败:', error);
}
return null;
};
/**
* 清除保存的配置
* @param {number|string} userId - 用户ID(可选)
*/
export const clearConfig = (userId = null) => {
try {
localStorage.removeItem(getStorageKey('config', userId));
localStorage.removeItem(getStorageKey('messages', userId));
} catch (error) {
console.error('清除配置失败:', error);
}
};
/**
* 清除保存的消息
* @param {number|string} userId - 用户ID(可选)
*/
export const clearMessages = (userId = null) => {
try {
localStorage.removeItem(getStorageKey('messages', userId));
} catch (error) {
console.error('清除消息失败:', error);
}
};
/**
* 检查是否有保存的配置
* @param {number|string} userId - 用户ID(可选)
* @returns {boolean} 是否存在保存的配置
*/
export const hasStoredConfig = (userId = null) => {
try {
return localStorage.getItem(getStorageKey('config', userId)) !== null;
} catch (error) {
console.error('检查配置失败:', error);
return false;
}
};
/**
* 获取配置的最后保存时间
* @param {number|string} userId - 用户ID(可选)
* @returns {string|null} 最后保存时间的 ISO 字符串
*/
export const getConfigTimestamp = (userId = null) => {
try {
const savedConfig = localStorage.getItem(getStorageKey('config', userId));
if (savedConfig) {
const parsedConfig = JSON.parse(savedConfig);
return parsedConfig.timestamp || null;
}
} catch (error) {
console.error('获取配置时间戳失败:', error);
}
return null;
};
/**
* 导出配置为 JSON 文件(包含消息)
* @param {Object} config - 要导出的配置
* @param {Array} messages - 要导出的消息
*/
export const exportConfig = (config, messages = null) => {
try {
const configToExport = {
...config,
messages: messages || loadMessages(),
exportTime: new Date().toISOString(),
version: '1.0',
};
const dataStr = JSON.stringify(configToExport, null, 2);
const dataBlob = new Blob([dataStr], { type: 'application/json' });
const link = document.createElement('a');
link.href = URL.createObjectURL(dataBlob);
link.download = `playground-config-${new Date().toISOString().split('T')[0]}.json`;
link.click();
URL.revokeObjectURL(link.href);
} catch (error) {
console.error('导出配置失败:', error);
}
};
/**
* 从文件导入配置(包含消息)
* @param {File} file - 包含配置的 JSON 文件
* @returns {Promise<Object>} 导入的配置对象
*/
export const importConfig = (file) => {
return new Promise((resolve, reject) => {
try {
const reader = new FileReader();
reader.onload = (e) => {
try {
const importedConfig = JSON.parse(e.target.result);
if (importedConfig.inputs && importedConfig.parameterEnabled) {
// 如果导入的配置包含消息,也一起导入
if (
importedConfig.messages &&
Array.isArray(importedConfig.messages)
) {
saveMessages(importedConfig.messages);
}
resolve(importedConfig);
} else {
reject(new Error('配置文件格式无效'));
}
} catch (parseError) {
reject(new Error('解析配置文件失败: ' + parseError.message));
}
};
reader.onerror = () => reject(new Error('读取文件失败'));
reader.readAsText(file);
} catch (error) {
reject(new Error('导入配置失败: ' + error.message));
}
});
};
/**
* 清理旧的非用户隔离的存储数据
* 注意:不进行数据迁移,因为无法确定旧数据属于哪个用户
* 直接删除旧数据以避免跨用户数据泄露
*/
export const migrateOldStorage = () => {
try {
const oldConfigKey = 'playground_config';
const oldMessagesKey = 'playground_messages';
// 直接清除旧的非用户隔离数据,避免数据泄露
localStorage.removeItem(oldConfigKey);
localStorage.removeItem(oldMessagesKey);
} catch (error) {
console.error('清理旧存储失败:', error);
}
};
// ====================================================================
// 多会话相关:activeSessionId 持久化(仅记住"上次打开哪个会话")
// ====================================================================
/**
* 保存当前活跃会话 ID
* @param {number|string|null} sessionId
*/
export const saveActiveSessionId = (sessionId) => {
try {
const key = `${STORAGE_KEY_PREFIX}_active_session_user_${getCurrentUserId()}`;
if (sessionId === null || sessionId === undefined) {
localStorage.removeItem(key);
} else {
localStorage.setItem(key, String(sessionId));
}
} catch (error) {
console.error('保存 activeSessionId 失败:', error);
}
};
/**
* 加载当前活跃会话 ID
* @returns {number|null}
*/
export const loadActiveSessionId = () => {
try {
const key = `${STORAGE_KEY_PREFIX}_active_session_user_${getCurrentUserId()}`;
const v = localStorage.getItem(key);
if (!v) return null;
const n = parseInt(v, 10);
return Number.isNaN(n) ? null : n;
} catch (error) {
console.error('加载 activeSessionId 失败:', error);
return null;
}
};
+40
View File
@@ -0,0 +1,40 @@
/*
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 { default as SettingsPanel } from './SettingsPanel';
export { default as ChatArea } from './ChatArea';
export { default as DebugPanel } from './DebugPanel';
export { default as MessageContent } from './MessageContent';
export { default as MessageActions } from './MessageActions';
export { default as CustomInputRender } from './CustomInputRender';
export { default as SSEViewer } from './SSEViewer';
export { default as ParameterControl } from './ParameterControl';
export { default as ImageUrlInput } from './ImageUrlInput';
export { default as FloatingButtons } from './FloatingButtons';
export { default as ConfigManager } from './ConfigManager';
export {
saveConfig,
loadConfig,
clearConfig,
hasStoredConfig,
getConfigTimestamp,
exportConfig,
importConfig,
} from './configStorage';