Files
monkey-ai-web/src/pages/ServiceDashboard/GroupMonitor.jsx
T
zhanjunhao 3dc2624e00 fix(market): 修复模型名称模糊搜索并统一三中心表格操作列
统一用户中心、企业中心和控制台的操作列标题、宽度与右侧固定规则,并按表格宽度固定末列,保留横向滚动。
2026-11-17 10:10:28 +08:00

736 lines
24 KiB
React

/*
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 {
Zap as ActionZap,
ChevronRight as ActionChevronRight,
RefreshCw as ActionRefreshCw,
} from '@/components/common/icons/ActionIcons';
import React, { useState, useEffect, useCallback, useMemo } from 'react';
import Table from '../../components/ui/CenterActionTable';
import { Empty, Spin, Button, Modal, Tooltip, Statistic, theme } from 'antd';
import { Server, ChevronRight, Clock } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { API, showError } from '../../helpers';
import { isAdmin } from '../../helpers/utils';
// 条形码状态组件 - 美化版
const StatusBars = ({ dataPoints = [], loading = false, t }) => {
const { token } = theme.useToken();
// 补全或截取数据以适应展示 (展示最近60个点)
// 注意:useMemo 必须在任何 early return 之前调用,保证 hook 调用顺序稳定。
const displayCount = 60;
const normalizedData = useMemo(() => {
if (!dataPoints || dataPoints.length === 0) {
return Array(displayCount).fill(null);
}
// 如果数据点过多,取最后 displayCount 个
if (dataPoints.length > displayCount) {
return dataPoints.slice(-displayCount);
}
// 如果不足,前面补 null
const pad = Array(displayCount - dataPoints.length).fill(null);
return [...pad, ...dataPoints];
}, [dataPoints]);
if (loading) {
return (
<div className='flex gap-[2px] items-center h-8 opacity-50 animate-pulse'>
{Array.from({ length: 60 }).map((_, i) => (
<div
key={i}
className='service-history-loading w-[6px] h-4 rounded-sm'
/>
))}
</div>
);
}
return (
<div className='flex flex-col w-fit'>
<div className='flex gap-[2px] items-end h-8'>
{normalizedData.map((point, i) => {
if (!point) {
return (
<div
key={i}
className='service-history-pending w-[6px] h-2 rounded-sm'
/>
);
}
const isHealthy = point.uptime_percent >= 90;
const isWarning =
point.uptime_percent >= 50 && point.uptime_percent < 90;
let bgColor = token.colorError;
if (isHealthy) {
bgColor = token.colorPrimary;
} else if (isWarning) {
bgColor = token.colorWarning;
}
const height = isHealthy ? '20px' : '16px';
return (
<Tooltip
key={i}
title={
<div className='text-xs p-1'>
<div style={{ color: bgColor }} className='font-semibold'>
{isHealthy ? t('正常') : t('异常')} (
{point.uptime_percent?.toFixed(1)}%)
</div>
<div className='text-gray-400 mt-1'>
{point.timestamp
? new Date(point.timestamp * 1000).toLocaleString()
: '-'}
</div>
</div>
}
>
<div
className={`w-[6px] rounded-sm hover:opacity-80 cursor-pointer ${isHealthy ? 'service-history-healthy' : ''}`}
style={{
backgroundColor: bgColor,
height: height,
}}
/>
</Tooltip>
);
})}
</div>
<div className='flex justify-between w-full text-[10px] text-gray-400 dark:text-gray-500 mt-1.5 font-medium'>
<span>1h</span>
<span>{t('现在')}</span>
</div>
</div>
);
};
// 模型测试单元格组件
const TestModelCell = ({ modelName, groupName, t }) => {
const { token } = theme.useToken();
const [testing, setTesting] = useState(false);
const [result, setResult] = useState(null);
const handleTest = async (e) => {
e.stopPropagation();
setTesting(true);
setResult(null);
try {
const res = await API.post(
'/api/monitor/test/model',
{
model: modelName,
group: groupName,
},
{
timeout: 60000,
skipErrorHandler: true,
},
);
const { success, message, time } = res.data;
const timeMs = Math.round((time || 0) * 1000);
if (success) {
setResult({ success: true, time: timeMs });
} else {
setResult({
success: false,
time: timeMs,
error: message || t('测试失败'),
});
}
} catch (error) {
const errorMsg =
error.response?.data?.message || error.message || t('测试失败');
setResult({ success: false, time: 0, error: errorMsg });
} finally {
setTesting(false);
}
};
return (
<div className='flex items-center gap-3'>
<Button size='small' loading={testing} onClick={handleTest}>
<ActionZap size={12} className='mr-1' />
{testing ? t('测试中') : t('测试')}
</Button>
{result && (
<span
className='text-xs font-medium'
style={{
color: result.success ? token.colorPrimary : token.colorError,
}}
>
{result.success ? (
<span
className='flex items-center gap-1 px-2 py-0.5 rounded-full'
style={{ background: token.colorPrimaryBg }}
>
<span>✓</span>
<span>{result.time}ms</span>
</span>
) : (
<Tooltip title={result.error}>
<span
className='flex items-center gap-1 px-2 py-0.5 rounded-full cursor-help'
style={{ background: token.colorErrorBg }}
>
<span>✗</span>
{result.time > 0 && <span>{result.time}ms</span>}
</span>
</Tooltip>
)}
</span>
)}
</div>
);
};
const GroupMonitor = () => {
const { t } = useTranslation();
const { token } = theme.useToken();
const [groups, setGroups] = useState([]);
const [loading, setLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
const [selectedGroup, setSelectedGroup] = useState(null);
const [modalVisible, setModalVisible] = useState(false);
const [lastUpdateTime, setLastUpdateTime] = useState(null);
const [nextRefreshTime, setNextRefreshTime] = useState(null);
const [timeRemaining, setTimeRemaining] = useState(0);
const [listHistoryData, setListHistoryData] = useState({});
const adminUser = isAdmin();
const formatDateTime = (date) => {
if (!date) return '';
const pad = (n) => n.toString().padStart(2, '0');
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
};
const fetchGroupData = useCallback(
async (showRefreshIndicator = false) => {
if (showRefreshIndicator) {
setRefreshing(true);
} else {
setLoading(true);
}
try {
const res = await API.get('/api/monitor/groups');
if (res.data.success) {
const newGroups = res.data.data || [];
setGroups(newGroups);
const now = new Date();
setLastUpdateTime(now);
const next = new Date(now.getTime() + 60000);
setNextRefreshTime(next);
setTimeRemaining(60);
const newHistoryData = {};
newGroups.forEach((group) => {
if (group.data_points) {
newHistoryData[group.name] = { data_points: group.data_points };
}
});
setListHistoryData(newHistoryData);
} else {
showError(res.data.message || t('获取数据失败'));
}
} catch (error) {
showError(error.message || t('网络请求失败'));
} finally {
setLoading(false);
setRefreshing(false);
}
},
[t],
);
useEffect(() => {
fetchGroupData();
const interval = setInterval(() => {
fetchGroupData(true);
}, 60000);
return () => clearInterval(interval);
}, [fetchGroupData]);
useEffect(() => {
if (!nextRefreshTime) return;
const timer = setInterval(() => {
const now = new Date();
const diff = Math.max(0, Math.ceil((nextRefreshTime - now) / 1000));
setTimeRemaining(diff);
}, 1000);
return () => clearInterval(timer);
}, [nextRefreshTime]);
const handleGroupClick = (group) => {
if (!adminUser) return;
setSelectedGroup(group);
setModalVisible(true);
};
const handleCloseModal = () => {
setModalVisible(false);
};
const handleAfterClose = () => {
setSelectedGroup(null);
};
const getUptimeColor = useCallback(
(uptime) => {
const val = Number(uptime) || 0;
if (val >= 95) return token.colorPrimary;
if (val >= 80) return token.colorWarning;
return token.colorError;
},
[token.colorPrimary, token.colorWarning, token.colorError],
);
const getUptimeClass = (uptime) => {
const val = Number(uptime) || 0;
if (val >= 95) return 'service-status-normal';
if (val >= 80) return 'service-status-warning';
return 'service-status-error';
};
const modelColumns = useMemo(
() => [
{
title: t('模型'),
dataIndex: 'model',
key: 'model',
render: (text) => (
<div className='font-medium text-gray-700 dark:text-gray-200 flex items-center gap-2'>
<div
className='w-2 h-2 rounded-full'
style={{ background: token.colorPrimary }}
/>
{text}
</div>
),
},
{
title: t('可用率'),
dataIndex: 'uptime_percent',
key: 'uptime_percent',
render: (value) => (
<div className='flex items-center gap-2'>
<div className='w-16 h-1.5 bg-gray-100 dark:bg-gray-700 rounded-full overflow-hidden'>
<div
className='h-full rounded-full'
style={{
width: `${Math.min(100, value || 0)}%`,
backgroundColor: getUptimeColor(value),
}}
/>
</div>
<span
className='text-sm font-medium'
style={{ color: getUptimeColor(value) }}
>
{(value || 0).toFixed(1)}%
</span>
</div>
),
sorter: (a, b) => (a.uptime_percent || 0) - (b.uptime_percent || 0),
},
{
title: t('可用/总数'),
key: 'count',
render: (_, record) => (
<span className='text-gray-600 dark:text-gray-300 font-medium'>
<span style={{ color: token.colorPrimary }}>
{record.available_count}
</span>
<span className='text-gray-300 dark:text-gray-600 mx-1'>/</span>
<span>{record.total_count}</span>
</span>
),
},
{
title: t('平均响应'),
dataIndex: 'avg_response_time',
key: 'avg_response_time',
render: (value) =>
value > 0 ? (
<div className='flex items-center gap-1.5'>
<Clock size={12} className='text-gray-400' />
<span
className={`font-medium ${value > 2000 ? 'text-orange-500' : 'text-gray-600 dark:text-gray-300'}`}
>
{value}ms
</span>
</div>
) : (
<span className='text-gray-300 dark:text-gray-600'>-</span>
),
sorter: (a, b) => a.avg_response_time - b.avg_response_time,
},
{
title: t('操作'),
key: 'action',
width: 200,
render: (_, record) => (
<TestModelCell
modelName={record.model}
groupName={selectedGroup?.name || ''}
t={t}
/>
),
},
],
[t, selectedGroup, getUptimeColor, token.colorPrimary],
);
const modalDataSource = useMemo(() => {
if (!selectedGroup?.model_stats) return [];
return selectedGroup.model_stats.filter(
(item) => item && typeof item === 'object',
);
}, [selectedGroup?.model_stats]);
const modalPagination = useMemo(
() => ({
pageSize: 10,
size: 'small',
showSizeChanger: false,
hideOnSinglePage: true,
}),
[],
);
if (loading) {
return (
<div className='flex flex-col items-center justify-center py-20'>
<div className='relative'>
<Spin size='large' />
</div>
<p className='mt-4 text-gray-500 dark:text-gray-400'>
{t('加载中...')}
</p>
</div>
);
}
if (groups.length === 0) {
return (
<div className='py-16'>
<Empty description={t('暂无分组数据')} />
</div>
);
}
return (
<div className='group-monitor'>
{/* 分组列表 */}
<div className='space-y-3'>
{groups.map((group, index) => {
const history = listHistoryData[group.name];
const availableModelCount =
group.model_stats?.filter((m) => m.available_count > 0).length || 0;
const totalModelCount = group.model_stats?.length || 0;
const uptimePercent = group.uptime_percent || 0;
return (
<div
key={group.name}
className={`service-group-row group relative rounded-xl border overflow-hidden ${adminUser ? 'service-group-interactive cursor-pointer' : ''}`}
onClick={adminUser ? () => handleGroupClick(group) : undefined}
>
{/* 左侧状态指示条 */}
<div
className={`service-group-marker absolute left-0 top-0 bottom-0 w-1 ${getUptimeClass(uptimePercent)}`}
/>
{/* 桌面端布局 */}
<div className='hidden md:flex items-center px-6 py-5 pl-8'>
{/* 分组名称 */}
<div className='w-[180px] shrink-0 pr-4'>
<div className='flex items-center gap-3'>
<div
className={`service-status-icon w-10 h-10 rounded-xl ${getUptimeClass(uptimePercent)} flex items-center justify-center`}
>
<Server className='w-5 h-5' />
</div>
<div className='min-w-0'>
<div
className='text-base font-bold text-gray-800 dark:text-gray-100 truncate'
title={group.name}
>
{group.name}
</div>
<div className='text-xs text-gray-400 dark:text-gray-500 mt-0.5'>
{t('服务分组')}
</div>
</div>
</div>
</div>
{/* 可用率 */}
<div className='w-[120px] shrink-0 flex justify-center'>
<div className='relative'>
<div
className={`service-uptime-badge px-4 py-2 rounded-xl text-sm font-bold ${getUptimeClass(uptimePercent)}`}
>
{uptimePercent.toFixed(2)}%
</div>
</div>
</div>
{/* 模型数量 */}
<div className='w-[120px] shrink-0 flex flex-col items-center justify-center'>
<div className='flex items-baseline gap-1'>
<span
className={`text-xl font-bold ${availableModelCount > 0 ? 'text-gray-800 dark:text-gray-100' : 'text-red-500'}`}
>
{availableModelCount}
</span>
<span className='text-gray-300 dark:text-gray-600 text-sm'>
/
</span>
<span className='text-gray-500 dark:text-gray-400 text-sm font-medium'>
{totalModelCount}
</span>
</div>
<div className='text-xs text-gray-400 dark:text-gray-500 mt-0.5'>
{t('模型')}
</div>
</div>
{/* 趋势图 */}
<div className='flex-1 flex justify-center px-6'>
<StatusBars
dataPoints={history?.data_points}
loading={!history}
t={t}
/>
</div>
{/* 查看按钮 - 仅管理员可见 */}
{adminUser && (
<div className='w-[100px] shrink-0 flex justify-end'>
<Button
className='service-group-details'
onClick={(e) => {
e.stopPropagation();
handleGroupClick(group);
}}
>
{t('详情')}
<ActionChevronRight
size={16}
className='transition-transform group-hover:translate-x-0.5'
/>
</Button>
</div>
)}
</div>
{/* 移动端布局 */}
<div className='flex md:hidden flex-col px-4 py-4 pl-6 gap-3'>
<div className='flex items-center justify-between'>
<div className='flex items-center gap-3 min-w-0 flex-1'>
<div
className={`service-status-icon w-9 h-9 shrink-0 rounded-lg ${getUptimeClass(uptimePercent)} flex items-center justify-center`}
>
<Server className='w-4 h-4' />
</div>
<div className='min-w-0'>
<div
className='text-sm font-bold text-gray-800 dark:text-gray-100 truncate'
title={group.name}
>
{group.name}
</div>
<div className='text-[11px] text-gray-400 dark:text-gray-500'>
{t('服务分组')}
</div>
</div>
</div>
<div className='flex items-center gap-3 shrink-0'>
<div className='relative'>
<div
className={`service-uptime-badge px-3 py-1.5 rounded-lg text-xs font-bold ${getUptimeClass(uptimePercent)}`}
>
{uptimePercent.toFixed(2)}%
</div>
</div>
<div className='text-center'>
<div className='flex items-baseline gap-0.5'>
<span
className={`text-sm font-bold ${availableModelCount > 0 ? 'text-gray-800 dark:text-gray-100' : 'text-red-500'}`}
>
{availableModelCount}
</span>
<span className='text-gray-300 dark:text-gray-600 text-xs'>
/
</span>
<span className='text-gray-500 dark:text-gray-400 text-xs'>
{totalModelCount}
</span>
</div>
<div className='text-[10px] text-gray-400 dark:text-gray-500'>
{t('模型')}
</div>
</div>
{adminUser && (
<ChevronRight size={16} className='text-gray-400' />
)}
</div>
</div>
{/* 移动端趋势图 */}
<div className='overflow-x-auto -mx-2 px-2'>
<StatusBars
dataPoints={history?.data_points}
loading={!history}
t={t}
/>
</div>
</div>
</div>
);
})}
</div>
{/* 刷新信息 */}
{lastUpdateTime && (
<div className='mt-8 flex flex-col items-center justify-center gap-3'>
<div className='service-refresh-info flex items-center gap-4 px-6 py-3 bg-white/50 dark:bg-gray-800/50 backdrop-blur-sm rounded-full border border-gray-100 dark:border-gray-700/50'>
<div className='flex items-center gap-2 text-gray-500 dark:text-gray-400 text-sm'>
<Clock size={14} />
<span>
{t('更新时间')}: {formatDateTime(lastUpdateTime)}
</span>
</div>
<div className='w-px h-4 bg-gray-200 dark:bg-gray-700' />
<div className='service-refresh-countdown flex items-center gap-2 text-sm font-medium'>
<div className='relative'>
<svg
className='w-5 h-5 transform -rotate-90'
viewBox='0 0 24 24'
>
<circle
cx='12'
cy='12'
r='10'
fill='none'
stroke='currentColor'
strokeWidth='2'
opacity='0.2'
/>
<circle
cx='12'
cy='12'
r='10'
fill='none'
stroke='currentColor'
strokeWidth='2'
strokeDasharray={62.83}
strokeDashoffset={62.83 * (1 - timeRemaining / 60)}
strokeLinecap='round'
className='transition-all duration-1000'
/>
</svg>
</div>
<span>
{Math.floor(timeRemaining / 60)
.toString()
.padStart(2, '0')}
:
{Math.floor(timeRemaining % 60)
.toString()
.padStart(2, '0')}
</span>
</div>
</div>
<Button
icon={
<ActionRefreshCw
className={`w-4 h-4 ${refreshing ? 'animate-spin' : ''}`}
/>
}
onClick={() => fetchGroupData(true)}
loading={refreshing}
type='text'
className='service-refresh-button'
>
{t('立即刷新')}
</Button>
</div>
)}
{/* 详情弹窗 */}
<Modal
open={modalVisible}
onCancel={handleCloseModal}
afterClose={handleAfterClose}
footer={null}
width={950}
title={selectedGroup?.name}
centered
className='group-monitor-modal'
mask={{ closable: true }}
>
{selectedGroup && (
<>
<div className='service-monitor-details'>
<Statistic
title={t('可用率')}
value={selectedGroup.uptime_percent || 0}
precision={2}
suffix='%'
/>
<Statistic
title={t('模型数量')}
value={selectedGroup.models?.length || 0}
/>
</div>
<Table
columns={modelColumns}
dataSource={modalDataSource}
pagination={modalPagination}
size='middle'
rowKey='model'
scroll={{ x: 680 }}
locale={{
emptyText: <Empty description={t('暂无模型数据')} />,
}}
/>
</>
)}
</Modal>
</div>
);
};
export default GroupMonitor;