/*
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 .
For commercial licensing, please contact support@quantumnous.com
*/
import {
EyeOff as ActionEyeOff,
Eye as ActionEye,
X as ActionX,
ArrowDown as ActionArrowDown,
} from '@/components/common/icons/ActionIcons';
import React, { useContext } from 'react';
import {
Card,
Chat,
Typography,
Button,
Select,
Toast,
Tooltip,
Popover,
} from '@/components/ui';
import {
MessageSquare,
Eye,
Sparkles,
Brain,
Code2,
Lightbulb,
Zap,
Bot,
Wand2,
ChevronDown,
MessageCircle,
Layers,
Paintbrush,
Upload,
ListChecks,
} from 'lucide-react';
import { useChatScroll } from '../../hooks/playground/useChatScroll';
import { useTranslation } from 'react-i18next';
import CustomInputRender from './CustomInputRender';
import MessageSelectionBar from './MessageSelectionBar';
import {
getExperienceCenterBool,
getExperienceCenterPositiveInt,
getExperienceCenterValue,
isModelFilesCapable,
isModelVisionAllowed,
selectFilter,
countRounds,
} from '../../helpers';
import { usePlayground } from '../../context/Playground';
import { StatusContext } from '../../context/Status';
const ChatArea = ({
chatRef,
message,
activeSessionId,
inputs,
styleState,
showDebugPanel,
roleInfo,
onMessageSend,
onMessageCopy,
onMessageReset,
onMessageDelete,
onStopGenerator,
onClearMessages,
onToggleDebugPanel,
renderCustomChatContent,
renderChatBoxAction,
models = [],
groups = [],
onInputChange,
onCreateSession,
sessionCreating = false,
onOpenSessionDrawer,
// 多选导出
selectionMode = false,
selectedCount = 0,
selectableCount = 0,
isAllSelected = false,
onEnterSelectionMode,
onExitSelectionMode,
onSelectAll,
onClearSelection,
onExportSelected,
// 长会话摘要管理
conversationSummary = '',
onRegenerateSummary,
onClearSummary,
}) => {
const { t } = useTranslation();
const {
imageGenMode,
imageGenModel,
imageGenSize,
onImageGenModelChange,
onImageGenSizeChange,
onUploadFiles,
currentModel,
isVisionAllowed,
} = usePlayground();
// 滚动到底部跟随 —— 流式时如果用户已经滚上去看历史,显示悬浮"回到最新"按钮
const chatWrapperRef = React.useRef(null);
const { isAtBottom, scrollToBottom } = useChatScroll(chatWrapperRef, [
message.length,
activeSessionId,
]);
// 多选模式下底部悬浮条占据同一位置,隐藏「回到最新」避免视觉重叠
const showScrollToBottom =
!isAtBottom && message.length > 0 && !selectionMode;
const [statusState] = useContext(StatusContext);
const status = statusState?.status;
const [isDragOver, setIsDragOver] = React.useState(false);
// 摘要 chip 的本地 loading:调用 onRegenerateSummary / onClearSummary(Promise)期间 disable 按钮
const [summaryActionLoading, setSummaryActionLoading] = React.useState(null); // 'regen' | 'clear' | null
// Feature C:长会话引导 + 摘要状态指示,使用同一条悬浮条。
// 行为:
// - 有摘要 → 持续显示「📝 已压缩较早对话」chip,含 查看/重新摘要/清空 actions
// - 无摘要 + 轮数到阈值 → 显示「建议新建对话」可关闭横幅
// - 两者互斥;摘要存在时,新建对话的劝阻让位给摘要管理
const [longConvHintDismissed, setLongConvHintDismissed] =
React.useState(false);
React.useEffect(() => {
// 切换会话时重置「已忽略」状态
setLongConvHintDismissed(false);
}, [activeSessionId]);
const ecSummaryThreshold = getExperienceCenterPositiveInt(
status,
'experience_center_summary_threshold',
'experience_center_summary_threshold',
0,
);
const longConvHintThreshold =
ecSummaryThreshold > 0 ? ecSummaryThreshold : 20;
const conversationRounds = countRounds(message);
const hasSummary = !!(conversationSummary && conversationSummary.trim());
// 摘要 chip:摘要存在就常驻显示,不可关闭(信息性指示)
const showSummaryChip =
styleState.isExperienceMode &&
!!activeSessionId &&
!imageGenMode &&
hasSummary;
// 长对话提示:摘要存在时不再劝新建对话(互斥),未启用摘要时按阈值显示
const showLongConversationHint =
styleState.isExperienceMode &&
!!activeSessionId &&
!imageGenMode &&
!hasSummary &&
!longConvHintDismissed &&
conversationRounds >= longConvHintThreshold;
const ecEnableDragUpload =
styleState.isExperienceMode &&
getExperienceCenterBool(
status,
'experience_center_enable_drag_upload',
'experience_center_enable_drag_upload',
true,
) &&
getExperienceCenterBool(
status,
'experience_center_enable_file_upload',
'experience_center_enable_file_upload',
false,
);
// 绘图模式根本不读 uploadedFiles,所以拖拽 overlay 直接屏蔽,避免误操作。
// 注意:dragUploadAvailable 必须在 ecEnableDragUpload 声明之后,否则 production
// minify 后会触发 const TDZ —— "Cannot access X before initialization"
const dragUploadAvailable = ecEnableDragUpload && !imageGenMode;
const ecUploadMaxSizeMB = getExperienceCenterPositiveInt(
status,
'experience_center_upload_max_size',
'experience_center_upload_max_size',
10,
);
// 视觉模型白名单:用于在模型下拉选项里给视觉模型挂一枚 👁️ 徽标,
// 让用户在「选模型」环节就能预判哪个能传图片
const ecVisionModels = getExperienceCenterValue(
status,
'experience_center_vision_models',
'experience_center_vision_models',
'',
);
// 判断给定模型在当前配置下是否「可接收图片」:
// - 视觉白名单非空:仅白名单内为 true
// - 视觉白名单留空(默认):用反向黑名单(isModelFilesCapable)做启发式判断,
// gpt-3.5 / o1-mini / davinci 等老式纯文本模型会被排除
const isModelVisionCapable = React.useCallback(
(modelName) =>
isModelFilesCapable(modelName) &&
isModelVisionAllowed(modelName, ecVisionModels),
[ecVisionModels],
);
const handleDragOver = React.useCallback(
(e) => {
if (!dragUploadAvailable) return;
// 仅当拖拽里确实带文件才进入 drop 高亮,避免选中文本拖拽时也亮起
const hasFiles = Array.from(e.dataTransfer?.types || []).includes(
'Files',
);
if (!hasFiles) return;
e.preventDefault();
e.stopPropagation();
setIsDragOver(true);
},
[dragUploadAvailable],
);
const handleDragLeave = React.useCallback((e) => {
e.preventDefault();
e.stopPropagation();
if (e.currentTarget.contains(e.relatedTarget)) return;
setIsDragOver(false);
}, []);
// 拖拽和点击上传共用 useFileUpload Hook — 进度、并行、失败重试、5xx 回退逻辑一致。
// 模型能力 gate:当前模型若已知不支持文件,拖拽也要拒绝,给出与按钮 Tooltip 一致的提示。
const handleDrop = React.useCallback(
(e) => {
e.preventDefault();
e.stopPropagation();
setIsDragOver(false);
if (!dragUploadAvailable) return;
const files = e.dataTransfer?.files;
if (!files || files.length === 0) return;
if (!isModelFilesCapable(currentModel)) {
Toast.warning({
content: t(
'当前模型 {{model}} 不支持文件输入,请切换到 GPT-4o / Claude / Gemini 等多模态模型',
{ model: currentModel },
),
duration: 3,
});
return;
}
// 视觉模型白名单:当前模型未在白名单内时,过滤掉拖入的 image/* 文件,
// 非图片文件(PDF / Word / 文本)正常上传 —— 视觉白名单只限制图片输入
let accepted = Array.from(files);
if (!isVisionAllowed) {
const rejected = accepted.filter((f) => f.type?.startsWith('image/'));
accepted = accepted.filter((f) => !f.type?.startsWith('image/'));
if (rejected.length > 0) {
Toast.warning({
content: t(
'当前模型 {{model}} 未启用图片输入,已忽略 {{count}} 个图片文件',
{ model: currentModel, count: rejected.length },
),
duration: 3,
});
}
}
if (accepted.length > 0 && typeof onUploadFiles === 'function') {
onUploadFiles(accepted);
}
},
[dragUploadAvailable, onUploadFiles, currentModel, isVisionAllowed, t],
);
const ecImageGenModels = React.useMemo(
() =>
(localStorage.getItem('experience_center_image_gen_models') || 'dall-e-3')
.split(',')
.map((m) => m.trim())
.filter(Boolean)
.map((m) => ({ label: m, value: m })),
[],
);
React.useEffect(() => {
if (!styleState.isExperienceMode || ecImageGenModels.length === 0) {
return;
}
if (!ecImageGenModels.some((option) => option.value === imageGenModel)) {
onImageGenModelChange(ecImageGenModels[0].value);
}
}, [
ecImageGenModels,
imageGenModel,
onImageGenModelChange,
styleState.isExperienceMode,
]);
const imageSizeOptions = React.useMemo(
() => [
{ label: '1024x1024', value: '1024x1024' },
{ label: '1024x1792', value: '1024x1792' },
{ label: '1792x1024', value: '1792x1024' },
],
[],
);
const hasActiveSession = !styleState.isExperienceMode || !!activeSessionId;
const chatPlaceholder = hasActiveSession
? t('请输入您的问题...')
: t('请先新建或选择会话');
const renderInputArea = React.useCallback((props) => {
return ;
}, []);
// 功能卡片数据
const featureCards = [
{
icon: Lightbulb,
title: t('智能问答'),
description: t('快速获取准确答案'),
gradient: 'from-amber-400 to-orange-500',
bgLight: 'bg-amber-50',
textColor: 'text-amber-600',
},
{
icon: Wand2,
title: t('创意写作'),
description: t('激发灵感辅助创作'),
gradient: 'from-pink-400 to-rose-500',
bgLight: 'bg-pink-50',
textColor: 'text-pink-600',
},
{
icon: Code2,
title: t('代码辅助'),
description: t('生成优化代码片段'),
gradient: 'from-emerald-400 to-teal-500',
bgLight: 'bg-emerald-50',
textColor: 'text-emerald-600',
},
{
icon: Brain,
title: t('深度分析'),
description: t('复杂问题深入解读'),
gradient: 'from-brand-from to-brand-to',
bgLight: 'bg-brand/5',
textColor: 'text-brand-deep',
},
];
// 快速提问建议
const quickPrompts = [
t('帮我写一篇关于人工智能的文章'),
t('解释一下量子计算的原理'),
t('用Python写一个排序算法'),
t('给我一些提高工作效率的建议'),
];
return (
{/* 拖拽上传遮罩 — 体验中心唯一拖拽入口;点选上传走 CustomInputRender */}
{isDragOver && dragUploadAvailable && (
{t('释放上传文件')}
{t('单文件最大 {{size}}MB,支持图片 / PDF / Office 文档', {
size: ecUploadMaxSizeMB,
})}
)}
{/* 聊天头部 */}
{styleState.isMobile ? (
// 手机端头部:分组 / 模型选择器。
// 此前这里只是一个 pt-4 空占位——分组与模型 Select 全在 !isMobile 分支里,
// 而体验模式下设置面板被 !isExperienceMode 关掉、设置浮button 也被
// hideSettingsButton 隐藏,导致手机上根本没有任何入口切换模型,锁死在默认值。
{groups.length > 0 &&
getExperienceCenterBool(
status,
'experience_center_enable_group_select',
'experience_center_enable_group_select',
true,
) && (
) : styleState.isExperienceMode ? (
// 体验模式下的简化头部 - 与下方聊天区域融为一体
{/* 左对齐:分组选择器 + 模型选择器 */}
{/* 分组选择器 - 受管理员配置控制 */}
{groups.length > 0 &&
getExperienceCenterBool(
status,
'experience_center_enable_group_select',
'experience_center_enable_group_select',
true,
) && (
<>
{t('分组')}
onInputChange && onInputChange('group', value)
}
optionList={groups}
filter={selectFilter}
autoClearSearchValue={false}
style={{ width: 'auto' }}
className='model-select-experience'
dropdownClassName='model-select-dropdown'
dropdownStyle={{ minWidth: 200 }}
triggerRender={() => (
{inputs.group
? groups.find((g) => g.value === inputs.group)
?.label || inputs.group
: t('选择分组')}
)}
/>
>
)}
{t('当前模型')}
onInputChange && onInputChange('model', value)
}
optionList={models}
filter={selectFilter}
autoClearSearchValue={false}
style={{ width: 'auto' }}
className='model-select-experience'
dropdownClassName='model-select-dropdown'
dropdownStyle={{ minWidth: 340 }}
renderOptionItem={(renderProps) => {
const { value, label, focused, selected, onClick } =
renderProps;
const visionCapable = isModelVisionCapable(value);
return (
{label || value}
{visionCapable && (
)}
);
}}
triggerRender={() => (
{inputs.model
? inputs.model.split('/').pop()
: t('选择模型')}
)}
/>
{/* 多选导出入口:仿模型选择 pill 的玻璃拟态风格,仅在非多选态且会话非空时显示 */}
{!selectionMode && message.length > 0 && onEnterSelectionMode && (
)}
) : (
{t('AI 对话')}
{inputs.model || t('选择模型开始对话')}
) : (
)
}
onClick={onToggleDebugPanel}
theme='borderless'
type='primary'
size='small'
className='!rounded-lg !text-white/80 hover:!text-white hover:!bg-white/10'
>
{showDebugPanel ? t('隐藏调试') : t('显示调试')}
)}
{/* 聊天内容区域 */}
{/* 体验模式背景:页面级背景(TextModel.jsx 的渐变 + 光球)已铺满整屏,
这里不再叠不透明的 from-slate-50/90 via-white/80 主背景,否则会把
页面蓝色渐变整体盖住、显得发白。仅保留极轻的装饰网格/点纹增加质感。
聊天可读性由内层 max-w-4xl 容器的 bg-white/60 毛玻璃单独保证。 */}
{styleState.isExperienceMode && (
{/* 装饰性网格 */}
{/* 细腻的点状纹理 */}
)}
{styleState.isExperienceMode && message.length === 0 && (
{/* 动态背景 - 欢迎页面专用 */}
{/* Logo 和标题 */}
{/* 外层光环 */}
{/* 主图标 */}
{/* 闪烁装饰 */}
{t('AI 智能对话')}
{t('探索无限可能,开启智能对话之旅')}
{/* 功能卡片 */}
{featureCards.map((card, index) => (
{card.title}
{card.description}
))}
{hasActiveSession ? (
{t('试试这些问题')}
{quickPrompts.map((prompt, index) => (
))}
) : (
{t('先创建一个会话,再开始你的提问。')}
{styleState.isMobile && (
)}
)}
)}
{/* 体验模式下的聊天容器毛玻璃效果 */}
{styleState.isExperienceMode && message.length > 0 && (
)}
{/* 图片生成模式设置栏 */}
{styleState.isExperienceMode && imageGenMode && (
onImageGenModelChange(val)}
optionList={ecImageGenModels}
size='small'
style={{ width: 160 }}
/>
onImageGenSizeChange(val)}
optionList={imageSizeOptions}
size='small'
style={{ width: 130 }}
/>
)}
{/* 摘要 chip:摘要激活时持续显示,让用户能感知「历史已被压缩」并提供管理入口。
与下面的长对话提示互斥(hasSummary 时已抑制 showLongConversationHint)。 */}
{showSummaryChip && (
{t('对话历史摘要')}
{t(
'发送给模型的请求会用本段摘要代替较早的历史,节省 token 消耗。重新生成或清空会产生相应的计费变化。',
)}
{conversationSummary}
}
>
)}
{/* Feature C:长会话「新建对话」引导 —— 悬浮在聊天区顶部,可关闭。
与摘要 chip 互斥:摘要激活后这条不再出现(产品语义上摘要已经替你压缩了上下文)。 */}
{showLongConversationHint && (
{ecSummaryThreshold > 0
? t(
'当前对话已 {{rounds}} 轮,即将触发自动摘要;如希望话题更聚焦也可新建对话',
{ rounds: conversationRounds },
)
: t(
'当前对话已 {{rounds}} 轮,较长的上下文会增加消耗,建议新建对话',
{ rounds: conversationRounds },
)}
)}
null,
}}
renderInputArea={renderInputArea}
roleConfig={roleInfo}
style={{
height: '100%',
width: '100%',
maxWidth: '100%',
position: 'relative',
zIndex: 1,
}}
chats={message}
onMessageSend={onMessageSend}
onMessageCopy={onMessageCopy}
onMessageReset={onMessageReset}
onMessageDelete={onMessageDelete}
showClearContext
showStopGenerate
onStopGenerator={onStopGenerator}
onClear={onClearMessages}
className={`h-full ${styleState.isExperienceMode ? 'experience-chat-container' : ''}`}
placeholder={chatPlaceholder}
/>
{/* 回到最新悬浮按钮 —— 用户上滚看历史时显示,避免错过流式输出
放在最外层 wrapper,定位用 absolute;底部偏移留出 CustomInputRender 的高度 */}
{showScrollToBottom && (
)}
{/* 多选导出底部悬浮条:定位仿"回到最新"pill;手机端拉满宽显示两行。
底部偏移不能写死 —— 手机端输入区是「输入行 + 工具行」双行结构,比桌面高一截,
写死的 bottom-32/sm:bottom-28 会落在工具按钮上并挡住点击。
改读 CustomInputRender 实测发布的 --composer-height。 */}
{selectionMode && (
)}
);
};
export default ChatArea;