Add hot-reloadable transports and log streaming

Enable runtime config reload and dynamic endpoint management across transports, and add server-side log streaming + UI.

- Transport hot-reload: HttpTransport, HttpPostTransport and WsTransport now maintain endpoint lists and start/stop individual endpoints (servers/clients) dynamically; servers/clients use keys/Maps to identify instances; added reloadConfig methods and helper key functions.
- OneBot control: OneBotInstance.reloadConfig delegating to transports; OneBotManager.reloadConfig(uin) to load and apply new config; added getPids helper.
- Logger & streaming: added in-memory recent log buffer, subscriber API (getRecentLogs, subscribeLogs) and LogEntry shape; web UI exposes /api/logs and /api/logs/stream (SSE) and improved token/query handling.
- Web UI: added LogsPage, integrated into layout and sidebar, EventSource client to show live logs; config save now attempts hot-reload and returns reloaded status.
- Misc: refactors to use Maps for server lists, cleanup on stop, and various small helpers and safety checks.
This commit is contained in:
手瓜一十雪 committed 2026-05-02 20:19:37 +08:00
1 parent ac1ddee54e
commit bd40af2517
11 files changed
+391 -60

No files matched your search

+5 -1
View File
@@ -4,6 +4,7 @@ import { MainLayout } from './components/layout/MainLayout';
import { LoginPage } from './components/pages/LoginPage';
import { OverviewPage } from './components/pages/OverviewPage';
import { ConfigPage } from './components/pages/ConfigPage';
import { LogsPage } from './components/pages/LogsPage';
import type { QQInfo, OneBotConfig, HookProcessInfo } from './types';
const fetchApi = async (url: string, options: RequestInit = {}) => {
@@ -18,7 +19,7 @@ function App() {
const [isAuthenticated, setIsAuthenticated] = useState<boolean | null>(
import.meta.env.VITE_SKIP_AUTH === 'true' ? true : null
);
const [activePage, setActivePage] = useState<'总览' | '配置'>('总览');
const [activePage, setActivePage] = useState<'总览' | '配置' | '日志'>('总览');
const [qqList, setQqList] = useState<QQInfo[]>([]);
const [processList, setProcessList] = useState<HookProcessInfo[]>([]);
const [processLoadingPid, setProcessLoadingPid] = useState<number | null>(null);
@@ -219,6 +220,9 @@ function App() {
onConfigChange={setConfig}
/>
)}
{activePage === '日志' && (
<LogsPage fetchApi={fetchApi} />
)}
</MainLayout>
</ThemeProvider>
);
+3 -2
View File
@@ -1,10 +1,10 @@
import type { ReactNode } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Activity, LayoutDashboard, Settings, Sparkles } from 'lucide-react';
import { Activity, LayoutDashboard, Settings, Sparkles, Terminal } from 'lucide-react';
import { Sidebar } from './Sidebar';
import { useTheme } from '../../contexts/ThemeContext';
type Page = '总览' | '配置';
type Page = '总览' | '配置' | '日志';
interface MainLayoutProps {
activePage: Page;
@@ -17,6 +17,7 @@ interface MainLayoutProps {
const pageMeta: Record<Page, { title: string; subtitle: string; badge: string; icon: typeof LayoutDashboard }> = {
'总览': { title: '总览', subtitle: '查看当前接入的 QQ 账号及服务运行状态', badge: '控制台视图', icon: LayoutDashboard },
'配置': { title: '节点配置', subtitle: '管理 OneBot 协议端点与通信参数', badge: '协议编排', icon: Settings },
'日志': { title: '日志', subtitle: '查看后端运行日志与实时事件流', badge: 'SSE 实时流', icon: Terminal },
};
export function MainLayout({ activePage, onNavigate, status, onLogout, children }: MainLayoutProps) {
+3 -2
View File
@@ -1,10 +1,10 @@
import { LayoutDashboard, Settings, LogOut, Sun, Moon, Monitor } from 'lucide-react';
import { LayoutDashboard, Settings, LogOut, Sun, Moon, Monitor, Terminal } from 'lucide-react';
import { Avatar } from '@heroui/react';
import { StatusBadge } from '../ui/StatusBadge';
import { motion } from 'framer-motion';
import { useTheme, type ThemeMode } from '../../contexts/ThemeContext';
type Page = '总览' | '配置';
type Page = '总览' | '配置' | '日志';
interface SidebarProps {
activePage: Page;
@@ -16,6 +16,7 @@ interface SidebarProps {
const navItems: { page: Page; label: string; icon: typeof LayoutDashboard }[] = [
{ page: '总览', label: '总览', icon: LayoutDashboard },
{ page: '配置', label: '配置', icon: Settings },
{ page: '日志', label: '日志', icon: Terminal },
];
const THEME_OPTIONS: { mode: ThemeMode; icon: typeof Sun; label: string }[] = [
+132
View File
@@ -0,0 +1,132 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { RefreshCw, Terminal } from 'lucide-react';
import { motion } from 'framer-motion';
import { useTheme } from '../../contexts/ThemeContext';
interface LogEntry {
id: number;
time: string;
level: 'debug' | 'info' | 'success' | 'warn' | 'error';
scope: string;
message: string;
line: string;
}
interface LogsPageProps {
fetchApi: (url: string, options?: RequestInit) => Promise<Response>;
}
const levelColor: Record<LogEntry['level'], string> = {
debug: 'var(--text-tertiary)',
info: 'var(--accent)',
success: 'var(--color-success)',
warn: '#f59e0b',
error: 'var(--color-danger)',
};
export function LogsPage({ fetchApi }: LogsPageProps) {
const { resolved } = useTheme();
const dark = resolved === 'dark';
const [logs, setLogs] = useState<LogEntry[]>([]);
const [streamStatus, setStreamStatus] = useState('连接中');
const endRef = useRef<HTMLDivElement | null>(null);
const token = useMemo(() => localStorage.getItem('snowluma_token') || '', []);
async function loadLogs() {
const res = await fetchApi('/api/logs?limit=500');
if (!res.ok) return;
const data = await res.json();
setLogs(data.list || []);
}
useEffect(() => {
loadLogs().catch(console.error);
}, []);
useEffect(() => {
if (!token) return;
const url = `/api/logs/stream?token=${encodeURIComponent(token)}`;
const source = new EventSource(url);
source.onopen = () => setStreamStatus('实时连接');
source.onerror = () => setStreamStatus('重连中');
source.onmessage = event => {
try {
const entry = JSON.parse(event.data) as LogEntry | { type: string };
if ('type' in entry) return;
setLogs(prev => [...prev.filter(item => item.id !== entry.id), entry].slice(-500));
} catch {
}
};
return () => source.close();
}, [token]);
useEffect(() => {
endRef.current?.scrollIntoView({ block: 'end' });
}, [logs]);
return (
<div className="flex min-h-0 flex-1 flex-col gap-4">
<motion.div
initial={{ opacity: 0, y: 12 }}
animate={{ opacity: 1, y: 0 }}
className="rounded-xl p-4"
style={{
background: dark ? 'rgba(8,12,19,0.4)' : 'rgba(255,255,255,0.4)',
border: '1px solid',
borderColor: dark ? 'rgba(255,255,255,0.06)' : 'rgba(255,255,255,0.8)',
backdropFilter: 'blur(32px) saturate(1.2)',
WebkitBackdropFilter: 'blur(32px) saturate(1.2)',
}}
>
<div className="mb-4 flex items-center justify-between gap-3">
<div className="flex items-center gap-2">
<div
className="flex size-9 items-center justify-center rounded-lg"
style={{ background: 'var(--accent-subtle)', color: 'var(--accent)' }}
>
<Terminal size={17} strokeWidth={2} />
</div>
<div>
<h2 className="text-sm font-semibold" style={{ color: 'var(--text-primary)' }}>运行日志</h2>
<p className="mt-0.5 text-xs" style={{ color: 'var(--text-secondary)' }}>{streamStatus} · 最近 {logs.length} 条</p>
</div>
</div>
<button
onClick={() => loadLogs().catch(console.error)}
className="inline-flex h-8 cursor-pointer items-center gap-1.5 rounded-lg px-3 text-xs font-medium"
style={{
color: 'var(--text-secondary)',
border: '1px solid var(--border-subtle)',
background: 'transparent',
}}
>
<RefreshCw size={13} />
刷新
</button>
</div>
<div
className="h-[58vh] overflow-auto rounded-xl p-3 text-xs"
style={{
background: dark ? 'rgba(0,0,0,0.22)' : 'rgba(255,255,255,0.42)',
border: '1px solid var(--border-subtle)',
fontFamily: 'var(--font-mono)',
}}
>
{logs.length === 0 ? (
<div className="flex h-full items-center justify-center" style={{ color: 'var(--text-tertiary)' }}>暂无日志</div>
) : logs.map(log => (
<div key={log.id} className="flex gap-2 whitespace-pre-wrap py-0.5 leading-5">
<span className="shrink-0" style={{ color: 'var(--text-tertiary)' }}>{new Date(log.time).toLocaleTimeString()}</span>
<span className="w-14 shrink-0 font-semibold" style={{ color: levelColor[log.level] }}>{log.level.toUpperCase()}</span>
<span className="w-24 shrink-0 truncate" style={{ color: 'var(--text-secondary)' }}>[{log.scope}]</span>
<span style={{ color: 'var(--text-primary)' }}>{log.message}</span>
</div>
))}
<div ref={endRef} />
</div>
</motion.div>
</div>
);
}