/* 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 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 '../../context/Playground'; 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 (
{messageTimeText}
); }; 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 (
{errorText} {renderMessageTime()}
); } 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('')) { const thinkTagRegex = /([\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 + ' & tags' : ' tags'; } baseContentForDisplay = replyParts.join(''); } if (isThinkingStatus) { const lastOpenThinkIndex = baseContentForDisplay.lastIndexOf(''); if (lastOpenThinkIndex !== -1) { const fragmentAfterLastOpen = baseContentForDisplay.substring(lastOpenThinkIndex); if (!fragmentAfterLastOpen.includes('')) { const unclosedThought = fragmentAfterLastOpen .substring(''.length) .trim(); if (unclosedThought) { if (combinedThinkingContent) { combinedThinkingContent += '\n\n---\n\n' + unclosedThought; } else { combinedThinkingContent = unclosedThought; } thinkingSource = thinkingSource ? thinkingSource + ' + streaming ' : 'streaming '; } 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 (
{message.inWebSearch ? ( ) : message.processingAttachments > 0 ? ( ) : ( )}
{/* 文案优先级:联网搜索 > 附件处理 — 两者后端都是先于模型流出执行的同步阶段, 但联网搜索通常是 5-15s 的"重"阶段,更值得专门提示;附件处理 1-5s,作为兜底标识 */} {message.inWebSearch ? ( {t('正在联网搜索…')} ) : message.processingAttachments > 0 ? ( {t('正在处理 {{n}} 个附件,请稍候…', { n: message.processingAttachments, })} ) : null}
); } return (
{message.role === 'system' && (
S
{t('系统消息')}
)} {message.role === 'assistant' && ( )} {isEditing ? (
{/* 编辑模式下,把消息中的附件以只读 chip 形式呈现 —— 提醒用户"附件会随保存一并保留"。否则用户只看到文本框,可能误以为附件已被删掉。 v1 不支持在编辑态删单个附件(删了再加是同样的成本);如果用户真想换附件, 建议删整条消息后重新发送。 */} {Array.isArray(message.content) && message.content.some( (p) => p?.type === 'image_url' || p?.type === 'file', ) && (
{t('保存后以下附件会一并保留:')} {message.content .filter((p) => p?.type === 'image_url' || p?.type === 'file') .map((p, i) => { if (p.type === 'image_url') { return ( 🖼 {t('图片')} ); } const fname = p?.file?.filename || p?.file?.file_name || t('未知文件'); return ( {fname} ); })}
)}