Initial import of weiyuan frontend
This commit is contained in:
@@ -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;
|
||||
Reference in New Issue
Block a user