import { useEffect, useMemo, useState, type ReactNode } from 'react'; import { motion } from 'motion/react'; import { Link } from '@tanstack/react-router'; import { Activity, ArrowRight, Bell, Cable, Check, Cpu, MemoryStick, MonitorCog, Pencil, PlugZap, RefreshCw, RotateCcw, Server, Users, } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import { Progress } from '@/components/ui/progress'; import { ScrollArea } from '@/components/ui/scroll-area'; import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'; import { Skeleton } from '@/components/ui/skeleton'; import { cn, formatBytes, formatUptime } from '@/lib/utils'; import type { AppPath } from '@/router'; import type { AdapterStatus, AdapterStatusLevel, LogEntry, LogLevel, UiLayoutItem } from '@/types'; import { useApi } from '@/lib/api'; import { useAppState } from '@/contexts/AppStateContext'; import { useSession } from '@/contexts/SessionContext'; import { useTheme } from '@/contexts/ThemeContext'; import { useLayout } from '@/contexts/LayoutContext'; import { useMediaQuery } from '@/hooks/use-media-query'; import { CONFIGURABLE_WIDGETS, GRID_COLS, parseAlertsConfig, parseSessionsConfig, widgetLabel, type AlertsConfig, type SessionsConfig, } from '@/lib/dashboard-layout'; import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'; import { DashboardGrid, type GridCoord } from '@/components/pages/dashboard-grid'; import { AlertsConfigForm, SessionsConfigForm } from '@/components/pages/widget-config-forms'; function qqAvatarUrl(uin: string) { return `/avatar/${encodeURIComponent(uin)}`; } function renderWidget(block: UiLayoutItem): ReactNode { if (block.id.startsWith('stat:')) return ; switch (block.id) { case 'connections': return ; case 'alerts': return ; case 'host': return ; case 'sessions': return ; default: return null; } } export function OverviewPage() { const { qqList, processList } = useAppState(); const { overviewBlocks, setOverviewBlocks, resetLayout, editing: editingCtx, setEditing } = useLayout(); const off = useTheme().appearance.disableMotion; const isWide = useMediaQuery('(min-width: 768px)'); // Free-grid editing is desktop-only (no room to drag/resize on a phone). const editing = isWide && editingCtx; const [configId, setConfigId] = useState(null); const visibleBlocks = useMemo(() => overviewBlocks.filter((b) => b.visible), [overviewBlocks]); // In edit mode show ALL blocks (hidden ones as re-enableable ghosts); else visible-only. const gridBlocks = editing ? overviewBlocks : visibleBlocks; const onGridChange = (coords: GridCoord[]) => { const cmap = new Map(coords.map((c) => [c.id, c])); setOverviewBlocks( overviewBlocks.map((b) => { const c = cmap.get(b.id); return c ? { ...b, x: c.x, y: c.y, w: c.w, h: c.h } : b; }), ); }; const toggleBlock = (id: string) => setOverviewBlocks(overviewBlocks.map((b) => (b.id === id ? { ...b, visible: !b.visible } : b))); const setBlockConfig = (id: string, config: Record) => setOverviewBlocks(overviewBlocks.map((b) => (b.id === id ? { ...b, config: { ...b.config, ...config } } : b))); const loadableProcs = processList.filter((p) => !p.injected).length; const configBlock = configId ? overviewBlocks.find((b) => b.id === configId) : null; return (
{/* Toolbar: edit toggle is desktop-only. In edit mode the cards carry their own floating drag/hide/settings overlays, and the sidebar nav becomes drag-sortable — no separate editor panel. */} {isWide && (
{editing && ( )}
)} {editing && (

拖动卡片顶部的「拖动」手柄移动位置、拖右下角缩放;眼睛图标显隐、齿轮改设置。左侧导航也可在编辑态拖动排序。

)} {/* First-run nudge — always shown (not a grid widget) so it can't be hidden. */} {qqList.length === 0 && (

{loadableProcs > 0 ? `检测到 ${loadableProcs} 个可加载 QQ 进程` : '尚未接入任何账号'}

前往「进程注入」加载 QQ,登录后会自动接入 OneBot 流程。

)} {visibleBlocks.length === 0 && !editing ? ( ) : ( )} { if (!o) setConfigId(null); }}> {configBlock ? `${widgetLabel(configBlock.id)} · 设置` : '设置'} {configBlock?.id === 'alerts' && setBlockConfig('alerts', c)} />} {configBlock?.id === 'sessions' && setBlockConfig('sessions', c)} />}
); } function EmptyLayout({ onReset }: { onReset: () => void }) { return (

所有总览卡片都已隐藏

); } // ─────────────── stat tiles (one widget each) ─────────────── function StatTile({ icon, label, value, subtext, accent = false, to, }: { icon: ReactNode; label: string; value: ReactNode; subtext?: ReactNode; accent?: boolean; to?: AppPath; }) { const body = (
{icon}

{label}

{value}
{subtext &&

{subtext}

}
{to && }
); if (to) { return ( {body} ); } return {body}; } function StatTileWidget({ id }: { id: string }) { const { qqList, processList, systemInfo } = useAppState(); const { status } = useSession(); const online = status === '已连接'; switch (id) { case 'stat:status': return ( } label="服务状态" value={online ? '运行中' : status} subtext={online ? '已连接到后端' : '请检查后端进程'} accent={online} /> ); case 'stat:accounts': return ( } label="在线账号" value={qqList.length} subtext={`已接入 ${qqList.length} 个会话`} /> ); case 'stat:processes': { const onlineProcs = processList.filter((p) => p.status === 'online').length; const loadableProcs = processList.filter((p) => !p.injected).length; return ( } label="进程注入" value={`${onlineProcs} 在线`} subtext={`${processList.length} 进程 · ${loadableProcs} 可注入`} to="/processes" /> ); } case 'stat:host': return ( } label="主机名" value={systemInfo?.hostname ?? '—'} subtext={systemInfo ? `${systemInfo.platform} · ${systemInfo.arch}` : '加载中'} /> ); case 'stat:uptime': return ( } label="系统运行" value={systemInfo ? formatUptime(systemInfo.uptime) : '—'} subtext={systemInfo ? `进程 ${formatUptime(systemInfo.processUptime)}` : undefined} /> ); default: return null; } } // ─────────────── host resources ─────────────── function HostBlock() { const { systemInfo, refreshSystem } = useAppState(); return (
主机资源 {systemInfo ? `${systemInfo.cpu.model.trim()} · ${systemInfo.cpu.cores} 核 · Node ${systemInfo.nodeVersion}` : '正在采集主机信息…'}
{/* CPU */}
CPU 使用率
{systemInfo ? `${systemInfo.cpu.average.toFixed(1)}%` : '—'}

负载: {systemInfo ? systemInfo.cpu.loadAvg.map((v) => v.toFixed(2)).join(' / ') : '—'}

{systemInfo && systemInfo.cpu.perCore.length > 0 && (
{systemInfo.cpu.perCore.map((p, i) => (
))}
)}
{/* Memory */}
内存使用
{systemInfo ? `${systemInfo.memory.usagePercent.toFixed(1)}%` : '—'}
已用 {systemInfo ? formatBytes(systemInfo.memory.used) : '—'} 共 {systemInfo ? formatBytes(systemInfo.memory.total) : '—'}
{/* Runtime */}
运行进程
{systemInfo ? `PID ${systemInfo.runtime.pid}` : '—'}
{!systemInfo ? (
) : (
RSS {formatBytes(systemInfo.runtime.rss)}
堆内存 {formatBytes(systemInfo.runtime.heapUsed)} / {formatBytes(systemInfo.runtime.heapTotal)}
外部内存 {formatBytes(systemInfo.runtime.external)}
)}
); } // ─────────────── online sessions ─────────────── function SessionsBlock({ config }: { config: SessionsConfig }) { const { qqList } = useAppState(); const off = useTheme().appearance.disableMotion; const list = useMemo(() => { const f = config.filter.trim().toLowerCase(); let arr = f ? qqList.filter((q) => (q.nickname ?? '').toLowerCase().includes(f) || q.uin.includes(f)) : qqList; if (config.sort === 'uin') arr = [...arr].sort((a, b) => a.uin.localeCompare(b.uin, undefined, { numeric: true })); else if (config.sort === 'nickname') arr = [...arr].sort((a, b) => (a.nickname ?? '').localeCompare(b.nickname ?? '')); // 'recent' keeps the server/insertion order. return arr; }, [qqList, config.sort, config.filter]); return ( 在线会话 当前已接入并完成登录的 QQ 账号{config.filter.trim() ? `(筛选:${config.filter.trim()})` : ''} {list.length === 0 ? (

{qqList.length === 0 ? '暂无在线会话' : '无匹配的会话'}

) : (
{list.map((q, idx) => ( {(q.nickname || q.uin).slice(0, 2)}
{q.nickname}
{q.uin}
))}
)}
); } // ─────────────── connection health ─────────────── const CONN_STATUS_STYLE: Record = { ok: 'bg-success/10 text-success', warn: 'bg-warning/10 text-warning', down: 'bg-destructive/10 text-destructive', disabled: 'bg-muted text-muted-foreground', }; const CONN_STATUS_LABEL: Record = { ok: '正常', warn: '注意', down: '异常', disabled: '未启用', }; const ADAPTER_KIND_LABEL: Record = { httpServer: 'HTTP 服务端', httpClient: 'HTTP 上报', wsServer: 'WS 服务端', wsClient: 'WS 客户端', }; function ConnectionsBlock() { const { connections } = useAppState(); return ( OneBot 连接 各账号协议端点的实时连接状态 {connections.length === 0 ? (

暂无已接入的账号实例

) : (
{connections.map((acc) => (
{acc.nickname || acc.uin} {acc.uin}
{acc.adapters.length === 0 ? (

未配置任何协议端点

) : (
{acc.adapters.map((adp) => (
{CONN_STATUS_LABEL[adp.status]}
{adp.name} {ADAPTER_KIND_LABEL[adp.kind]}
{adp.detail}
))}
)}
))}
)}
); } // ─────────────── recent alerts ─────────────── const ALERT_LEVEL_CLASS: Record = { trace: 'text-muted-foreground/60', debug: 'text-muted-foreground', info: 'text-primary', success: 'text-success', warn: 'text-warning', error: 'text-destructive', }; function RecentAlertsCard({ config }: { config: AlertsConfig }) { const api = useApi(); const { formatClock } = useTheme(); const [alerts, setAlerts] = useState([]); const { count } = config; const levelsKey = config.levels.join(','); useEffect(() => { const levels = new Set(levelsKey.split(',') as LogLevel[]); let active = true; api.logs .list(Math.max(200, count * 4)) .then((list) => { if (!active) return; setAlerts(list.filter((l) => levels.has(l.level)).slice(-count)); }) .catch(() => { /* ignore */ }); const stop = api.logs.stream({ onLine: (entry) => { if (!levels.has(entry.level)) return; setAlerts((prev) => [...prev.filter((a) => a.id !== entry.id), entry].slice(-count)); }, }); return () => { active = false; stop(); }; }, [api, count, levelsKey]); return (
最近告警 最近 {count} 条 · {config.levels.map((l) => l.toUpperCase()).join(' / ')}
查看日志
{alerts.length === 0 ? (

暂无告警

) : (
{alerts.map((a) => (
{formatClock(a.time)} {a.level.toUpperCase()} [{a.scope}] {a.message}
))}
)}
); }