feat(webui): add live connection status for OneBot adapters in dashboard

This commit is contained in:
DrSmoothl committed 2026-05-30 18:02:01 +08:00
1 parent 90f26ca4f4
commit 0e4b881f76
18 files changed
+351 -13

No files matched your search

+6
View File
@@ -355,6 +355,12 @@ export async function initWebUI(
return c.json({ list });
});
// Live OneBot adapter health per account (listening / connected / client
// counts / last-delivery), powering the dashboard's connection card.
app.get('/api/connections', (c) => {
return c.json({ list: oneBotManager.getConnectionStatuses() });
});
app.get('/api/logs', (c) => {
const limit = Number(c.req.query('limit') ?? 300);
return c.json({ list: getRecentLogs(limit) });
+6
View File
@@ -18,6 +18,7 @@ import {
OneBotNetworkManager,
WsClientAdapter,
WsServerAdapter,
type AdapterStatus,
type NetworkAdapterContext,
} from './network';
import { ReactionStore } from './reaction-store';
@@ -46,6 +47,11 @@ export class OneBotInstance {
get nickname(): string { return this.bridge.identity.nickname; }
/** Live status of this account's OneBot network adapters. */
getConnectionStatuses(): AdapterStatus[] {
return this.networkManager.describeStatuses();
}
constructor(uin: string, bridge: BridgeInterface, config: OneBotConfig) {
this.uin = uin;
this.bridge = bridge;
+17
View File
@@ -3,10 +3,18 @@ import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import type { BridgeManager } from '@snowluma/core/manager';
import { loadOneBotConfig } from './config';
import { OneBotInstance } from './instance';
import type { AdapterStatus } from './network';
const log = createLogger('OneBot');
const VERBOSE_WARMUP = process.env.SNOWLUMA_VERBOSE_WARMUP === '1';
/** Per-account OneBot connection health, surfaced to the WebUI dashboard. */
export interface AccountConnections {
uin: string;
nickname: string;
adapters: AdapterStatus[];
}
export class OneBotManager {
private readonly instances = new Map<string, OneBotInstance>();
@@ -28,6 +36,15 @@ export class OneBotManager {
return [...this.instances.values()];
}
/** Live OneBot adapter status for every account, for the WebUI dashboard. */
getConnectionStatuses(): AccountConnections[] {
return this.getInstances().map((i) => ({
uin: i.uin,
nickname: i.nickname,
adapters: i.getConnectionStatuses(),
}));
}
reloadConfig(uin: string): boolean {
const instance = this.instances.get(uin);
if (!instance) return false;
+16
View File
@@ -16,6 +16,19 @@ export enum NetworkReloadType {
Opened = 3,
}
export type AdapterStatusLevel = 'ok' | 'warn' | 'down' | 'disabled';
/** Live runtime status of a single network adapter, surfaced to the WebUI
* dashboard (and the per-node config cards) so the gateway's own
* connection health is visible. `detail` is a short human string, e.g.
* "3 个客户端" / "重连中" / "上次推送失败 14:53:01". */
export interface AdapterStatus {
name: string;
kind: 'httpServer' | 'httpClient' | 'wsServer' | 'wsClient';
status: AdapterStatusLevel;
detail: string;
}
export abstract class IOneBotNetworkAdapter<C extends NetworkBase> {
readonly name: string;
protected config: C;
@@ -37,4 +50,7 @@ export abstract class IOneBotNetworkAdapter<C extends NetworkBase> {
abstract reload(config: C): NetworkReloadType | Promise<NetworkReloadType>;
abstract onEvent(event: JsonObject, payload: DispatchPayload): void | Promise<void>;
/** Report live connection health for the WebUI dashboard. */
abstract describeStatus(): AdapterStatus;
}
@@ -6,7 +6,7 @@ import {
type EventReportOptions,
} from '../event-filter';
import type { HttpClientNetwork, JsonObject } from '../types';
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
import { IOneBotNetworkAdapter, NetworkReloadType, type AdapterStatus, type NetworkAdapterContext } from './adapter';
import { executeQuickOperation } from './quick-operation';
const moduleLog = createLogger('OneBot.POST');
@@ -15,6 +15,7 @@ const DEFAULT_TIMEOUT_MS = 5000;
export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
private options: EventReportOptions;
private signature_: string;
private lastDelivery: { at: number; ok: boolean } | null = null;
private readonly log: Logger;
constructor(name: string, config: HttpClientNetwork, ctx: NetworkAdapterContext) {
@@ -39,6 +40,15 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
this.isEnabled = false;
}
override describeStatus(): AdapterStatus {
if (!this.isEnabled) return { name: this.name, kind: 'httpClient', status: 'disabled', detail: '未启用' };
if (!this.lastDelivery) return { name: this.name, kind: 'httpClient', status: 'ok', detail: '已启用' };
const at = new Date(this.lastDelivery.at).toTimeString().slice(0, 8);
return this.lastDelivery.ok
? { name: this.name, kind: 'httpClient', status: 'ok', detail: `上次推送成功 ${at}` }
: { name: this.name, kind: 'httpClient', status: 'warn', detail: `上次推送失败 ${at}` };
}
async reload(next: HttpClientNetwork): Promise<NetworkReloadType> {
const wasEnabled = this.isEnabled;
const willEnable = next.enabled !== false && !!next.url;
@@ -98,6 +108,7 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
signal: AbortSignal.timeout(timeoutMs),
});
if (response.ok) {
this.lastDelivery = { at: Date.now(), ok: true };
const contentType = response.headers.get('content-type') ?? '';
if (contentType.includes('application/json')) {
const body = await response.text();
@@ -106,9 +117,11 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
}
}
} else {
this.lastDelivery = { at: Date.now(), ok: false };
this.log.warn('[%s] POST %s returned %d', this.name, this.config.url, response.status);
}
} catch (error) {
this.lastDelivery = { at: Date.now(), ok: false };
if (this.isEnabled) {
this.log.warn('[%s] POST %s failed: %s', this.name, this.config.url, error instanceof Error ? error.message : String(error));
}
@@ -7,13 +7,14 @@ import {
} from 'http';
import type { DispatchPayload } from '../event-filter';
import type { HttpServerNetwork, JsonObject, JsonValue } from '../types';
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
import { IOneBotNetworkAdapter, NetworkReloadType, type AdapterStatus, type NetworkAdapterContext } from './adapter';
import { isAuthorized, normalizePath } from './utils';
const moduleLog = createLogger('OneBot.HTTP');
export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork> {
private server: Server | null = null;
private listening = false;
private readonly log: Logger;
constructor(name: string, config: HttpServerNetwork, ctx: NetworkAdapterContext) {
@@ -36,10 +37,17 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
close(): void {
if (!this.isEnabled && !this.server) return;
this.isEnabled = false;
this.listening = false;
this.server?.close();
this.server = null;
}
override describeStatus(): AdapterStatus {
if (!this.isEnabled) return { name: this.name, kind: 'httpServer', status: 'disabled', detail: '未启用' };
if (!this.listening) return { name: this.name, kind: 'httpServer', status: 'down', detail: '未监听(端口被占用?)' };
return { name: this.name, kind: 'httpServer', status: 'ok', detail: '监听中' };
}
async reload(next: HttpServerNetwork): Promise<NetworkReloadType> {
const prevSig = bindingSignature(this.config);
const wasEnabled = this.isEnabled;
@@ -76,6 +84,7 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
this.server = server;
server.on('listening', () => {
this.listening = true;
this.log.success(
'[%s] listening %s:%d%s',
this.name,
@@ -85,6 +94,7 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
);
});
server.on('error', (err) => {
this.listening = false;
this.log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err));
});
+7 -1
View File
@@ -1,4 +1,10 @@
export { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
export {
IOneBotNetworkAdapter,
NetworkReloadType,
type AdapterStatus,
type AdapterStatusLevel,
type NetworkAdapterContext,
} from './adapter';
export { HttpPostAdapter } from './http-post-adapter';
export { HttpServerAdapter } from './http-server-adapter';
export { OneBotNetworkManager } from './network-manager';
@@ -1,7 +1,7 @@
import { createLogger } from '@snowluma/common/logger';
import { buildDispatchPayload } from '../event-filter';
import type { JsonObject, NetworkBase } from '../types';
import { IOneBotNetworkAdapter } from './adapter';
import { IOneBotNetworkAdapter, type AdapterStatus } from './adapter';
const log = createLogger('OneBot.Network');
@@ -30,6 +30,11 @@ export class OneBotNetworkManager {
list(): AnyAdapter[] { return [...this.adapters.values()]; }
/** Live status of every registered adapter, for the WebUI dashboard. */
describeStatuses(): AdapterStatus[] {
return this.list().map((a) => a.describeStatus());
}
hasActiveAdapters(): boolean {
for (const a of this.adapters.values()) if (a.isActive) return true;
return false;
@@ -8,7 +8,7 @@ import {
type EventReportOptions,
} from '../event-filter';
import type { JsonObject, WsClientNetwork, WsRole } from '../types';
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
import { IOneBotNetworkAdapter, NetworkReloadType, type AdapterStatus, type NetworkAdapterContext } from './adapter';
import { rawDataToString, safeClose, safeSend } from './utils';
const moduleLog = createLogger('OneBot.WS-Client');
@@ -16,6 +16,7 @@ const DEFAULT_RECONNECT_INTERVAL_MS = 5000;
export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
private socket: WebSocket | null = null;
private connected = false;
private reconnectTimer: NodeJS.Timeout | null = null;
private options: EventReportOptions;
private role: WsRole;
@@ -46,6 +47,7 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
close(): void {
this.explicitlyClosed = true;
this.isEnabled = false;
this.connected = false;
this.cancelReconnect();
if (this.socket) {
safeClose(this.socket);
@@ -53,6 +55,12 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
}
}
override describeStatus(): AdapterStatus {
if (!this.isEnabled) return { name: this.name, kind: 'wsClient', status: 'disabled', detail: '未启用' };
if (this.connected) return { name: this.name, kind: 'wsClient', status: 'ok', detail: '已连接' };
return { name: this.name, kind: 'wsClient', status: 'warn', detail: this.reconnectTimer ? '重连中' : '连接中' };
}
async reload(next: WsClientNetwork): Promise<NetworkReloadType> {
const prevSig = bindingSignature(this.config);
const wasEnabled = this.isEnabled;
@@ -108,6 +116,7 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
this.socket = socket;
socket.on('open', () => {
this.connected = true;
this.log.info('[%s] connected %s', this.name, this.config.url);
this.sendBootstrapMetaEvents(socket);
});
@@ -120,6 +129,7 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
socket.on('close', () => {
this.socket = null;
this.connected = false;
if (this.explicitlyClosed || !this.isEnabled) return;
this.scheduleReconnect();
});
@@ -9,7 +9,7 @@ import {
type EventReportOptions,
} from '../event-filter';
import type { JsonObject, WsRole, WsServerNetwork } from '../types';
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
import { IOneBotNetworkAdapter, NetworkReloadType, type AdapterStatus, type NetworkAdapterContext } from './adapter';
import { isAuthorized, normalizePath, parseRequestPath, rawDataToString, safeClose, safeSend } from './utils';
const moduleLog = createLogger('OneBot.WS-Server');
@@ -22,6 +22,7 @@ interface ForwardConn {
export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
private wss: WebSocketServer | null = null;
private listening = false;
private connections = new Map<WebSocket, ForwardConn>();
private options: EventReportOptions;
private readonly log: Logger;
@@ -57,12 +58,19 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
}
this.isEnabled = false;
this.listening = false;
for (const ws of [...this.connections.keys()]) safeClose(ws);
this.connections.clear();
this.wss?.close();
this.wss = null;
}
override describeStatus(): AdapterStatus {
if (!this.isEnabled) return { name: this.name, kind: 'wsServer', status: 'disabled', detail: '未启用' };
if (!this.listening) return { name: this.name, kind: 'wsServer', status: 'down', detail: '未监听(端口被占用?)' };
return { name: this.name, kind: 'wsServer', status: 'ok', detail: `${this.connections.size} 个客户端` };
}
async reload(next: WsServerNetwork): Promise<NetworkReloadType> {
const prevSig = bindingSignature(this.config);
const wasEnabled = this.isEnabled;
@@ -111,6 +119,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
this.wss = wss;
wss.on('listening', () => {
this.listening = true;
this.log.success(
'[%s] listening %s:%d%s',
this.name,
@@ -121,6 +130,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
});
wss.on('error', (err: Error) => {
this.listening = false;
this.log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err));
});
@@ -9,11 +9,27 @@ import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { cn } from '@/lib/utils';
import type { AdapterCommon } from './defaults';
import type { AdapterStatus } from '@/types';
const LIVE_STYLE: Record<AdapterStatus['status'], string> = {
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 LIVE_LABEL: Record<AdapterStatus['status'], string> = {
ok: '正常',
warn: '注意',
down: '异常',
disabled: '未启用',
};
interface NodeSummaryCardProps<T extends AdapterCommon> {
item: T;
summary: string;
duplicateName: boolean;
/** Live runtime status from the OneBot manager, matched by adapter name. */
liveStatus?: AdapterStatus;
onToggleEnabled: (next: boolean) => void;
onEdit: () => void;
onDelete: () => void;
@@ -23,6 +39,7 @@ export function NodeSummaryCard<T extends AdapterCommon>({
item,
summary,
duplicateName,
liveStatus,
onToggleEnabled,
onEdit,
onDelete,
@@ -51,6 +68,14 @@ export function NodeSummaryCard<T extends AdapterCommon>({
{!enabled && (
<Badge variant="secondary" className="font-normal">已停用</Badge>
)}
{liveStatus && (
<span
className={cn('rounded px-1.5 py-0.5 text-[10px] font-medium', LIVE_STYLE[liveStatus.status])}
title={liveStatus.detail}
>
{LIVE_LABEL[liveStatus.status]} · {liveStatus.detail}
</span>
)}
</div>
<div className="mt-0.5 truncate font-mono text-xs text-muted-foreground tabular-nums">{summary}</div>
<div className="mt-1.5 flex flex-wrap items-center gap-1.5">
@@ -16,6 +16,7 @@ import { Badge } from '@/components/ui/badge';
import { ConfirmDialog } from '@/components/confirm-dialog';
import { cn } from '@/lib/utils';
import type {
AdapterStatus,
NetworkKind,
OneBotConfig,
OneBotNetworks,
@@ -39,7 +40,7 @@ type DialogState =
// index: null → create with `seed`, otherwise edit the item at that position.
export function ConfigPage() {
const { qqList, selectedUin, setSelectedUin } = useAppState();
const { qqList, connections, selectedUin, setSelectedUin } = useAppState();
const {
config,
setConfig,
@@ -72,6 +73,15 @@ export function ConfigPage() {
[pendingSwitchUin, qqList],
);
// Live adapter status for the selected account, keyed by adapter name so
// each summary card can light up its real connection state.
const liveStatusByName = useMemo(() => {
const acc = connections.find((c) => c.uin === selectedUin);
const map = new Map<string, AdapterStatus>();
for (const a of acc?.adapters ?? []) map.set(a.name, a);
return map;
}, [connections, selectedUin]);
// A discrete node mutation (create / edit / delete / enable-toggle) is
// persisted the moment it happens — clicking 保存 inside the editor dialog
// (or flipping the enable switch) IS the save. This removes the old
@@ -170,6 +180,7 @@ export function ConfigPage() {
<NetworkTabView
kind={activeTab}
config={config}
statusByName={liveStatusByName}
onCreateClick={() => openCreate(activeTab)}
onEdit={(idx) => openEdit(activeTab, idx)}
onDelete={(idx) => handleDelete(activeTab, idx)}
@@ -344,6 +355,7 @@ function countMap(networks: OneBotNetworks): Record<NetworkKind, number> {
interface NetworkTabViewProps {
kind: NetworkKind;
config: OneBotConfig;
statusByName: Map<string, AdapterStatus>;
onCreateClick: () => void;
onEdit: (index: number) => void;
onDelete: (index: number) => void;
@@ -353,6 +365,7 @@ interface NetworkTabViewProps {
function NetworkTabView({
kind,
config,
statusByName,
onCreateClick,
onEdit,
onDelete,
@@ -401,6 +414,7 @@ function NetworkTabView({
item={item}
summary={summarize(item)}
duplicateName={duplicate}
liveStatus={statusByName.get(item.name)}
onToggleEnabled={(v) => onToggleEnabled(idx, v)}
onEdit={() => onEdit(idx)}
onDelete={() => onDelete(idx)}
@@ -4,6 +4,8 @@ import { Link } from '@tanstack/react-router';
import {
Activity,
ArrowRight,
Bell,
Cable,
Cpu,
MemoryStick,
MonitorCog,
@@ -20,6 +22,8 @@ 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 { AccountConnections, AdapterStatus, AdapterStatusLevel, LogEntry } from '@/types';
import { useApi } from '@/lib/api';
import { useAppState } from '@/contexts/AppStateContext';
import { useSession } from '@/contexts/SessionContext';
@@ -73,7 +77,7 @@ function StatTile({
}
export function OverviewPage() {
const { qqList, processList, systemInfo, refreshSystem } = useAppState();
const { qqList, processList, systemInfo, connections, refreshSystem } = useAppState();
const { status } = useSession();
// Lightweight tick to refresh "uptime" pretty-print every 30s
@@ -149,6 +153,12 @@ export function OverviewPage() {
</motion.div>
)}
{/* Operational health — connection status + recent alerts (side by side on wide screens) */}
<div className="grid gap-6 xl:grid-cols-2">
<ConnectionsCard connections={connections} />
<RecentAlertsCard />
</div>
{/* System metrics */}
<Card>
<CardHeader className="flex flex-row items-center justify-between gap-3 space-y-0">
@@ -297,3 +307,157 @@ export function OverviewPage() {
</div>
);
}
// ─────────────── connection health ───────────────
const CONN_STATUS_STYLE: Record<AdapterStatusLevel, string> = {
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<AdapterStatusLevel, string> = {
ok: '正常',
warn: '注意',
down: '异常',
disabled: '未启用',
};
const ADAPTER_KIND_LABEL: Record<AdapterStatus['kind'], string> = {
httpServer: 'HTTP 服务端',
httpClient: 'HTTP 上报',
wsServer: 'WS 服务端',
wsClient: 'WS 客户端',
};
function ConnectionsCard({ connections }: { connections: AccountConnections[] }) {
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Cable className="size-4 text-primary" /> OneBot 连接
</CardTitle>
<CardDescription>各账号协议端点的实时连接状态</CardDescription>
</CardHeader>
<CardContent>
{connections.length === 0 ? (
<div className="flex flex-col items-center justify-center gap-2 rounded-lg border border-dashed py-10 text-muted-foreground">
<Cable className="size-7" strokeWidth={1.5} />
<p className="text-sm">暂无已接入的账号实例</p>
</div>
) : (
<div className="flex flex-col gap-4">
{connections.map((acc) => (
<div key={acc.uin} className="flex flex-col gap-2">
<div className="flex items-baseline gap-2">
<span className="text-sm font-semibold">{acc.nickname || acc.uin}</span>
<span className="font-mono text-[11px] text-muted-foreground tabular-nums">{acc.uin}</span>
</div>
{acc.adapters.length === 0 ? (
<p className="rounded-md border border-dashed px-3 py-2 text-[11px] text-muted-foreground">
未配置任何协议端点
</p>
) : (
<div className="flex flex-col gap-1.5">
{acc.adapters.map((a) => (
<div key={a.name} className="flex items-center gap-2 rounded-lg border bg-card/40 px-3 py-2">
<span
className={cn(
'shrink-0 rounded px-1.5 py-0.5 text-[10px] font-medium',
CONN_STATUS_STYLE[a.status],
)}
>
{CONN_STATUS_LABEL[a.status]}
</span>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-1.5">
<span className="truncate text-sm font-medium">{a.name}</span>
<span className="shrink-0 text-[10px] text-muted-foreground">{ADAPTER_KIND_LABEL[a.kind]}</span>
</div>
<div className="truncate text-[11px] text-muted-foreground">{a.detail}</div>
</div>
</div>
))}
</div>
)}
</div>
))}
</div>
)}
</CardContent>
</Card>
);
}
// ─────────────── recent alerts ───────────────
function alertClock(t: string): string {
const d = new Date(t);
return Number.isNaN(d.getTime()) ? t : d.toLocaleTimeString();
}
function RecentAlertsCard() {
const api = useApi();
const [alerts, setAlerts] = useState<LogEntry[]>([]);
useEffect(() => {
let active = true;
api.logs
.list(200)
.then((list) => {
if (!active) return;
setAlerts(list.filter((l) => l.level === 'warn' || l.level === 'error').slice(-5));
})
.catch(() => { /* ignore */ });
const stop = api.logs.stream({
onLine: (entry) => {
if (entry.level !== 'warn' && entry.level !== 'error') return;
setAlerts((prev) => [...prev.filter((a) => a.id !== entry.id), entry].slice(-5));
},
});
return () => {
active = false;
stop();
};
}, [api]);
return (
<Card>
<CardHeader className="flex flex-row items-center justify-between gap-3 space-y-0">
<div>
<CardTitle className="flex items-center gap-2">
<Bell className="size-4 text-primary" /> 最近告警
</CardTitle>
<CardDescription>最近的 warn / error 级别日志</CardDescription>
</div>
<Link
to="/logs"
className="inline-flex shrink-0 items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground"
>
查看日志 <ArrowRight className="size-3" />
</Link>
</CardHeader>
<CardContent>
{alerts.length === 0 ? (
<div className="flex flex-col items-center justify-center gap-2 rounded-lg border border-dashed py-10 text-muted-foreground">
<Bell className="size-7" strokeWidth={1.5} />
<p className="text-sm">暂无告警</p>
</div>
) : (
<div className="flex flex-col gap-1 font-mono text-[11px]">
{alerts.map((a) => (
<div key={a.id} className="flex gap-2 rounded px-2 py-1 hover:bg-accent/30">
<span className="shrink-0 text-muted-foreground tabular-nums">{alertClock(a.time)}</span>
<span className={cn('shrink-0 font-semibold', a.level === 'error' ? 'text-destructive' : 'text-warning')}>
{a.level.toUpperCase()}
</span>
<span className="min-w-0 flex-1 truncate" title={a.message}>
[{a.scope}] {a.message}
</span>
</div>
))}
</div>
)}
</CardContent>
</Card>
);
}
@@ -1,5 +1,5 @@
import { createContext, useContext, type ReactNode } from 'react';
import type { HookProcessInfo, QQInfo, SystemInfo } from '@/types';
import type { AccountConnections, HookProcessInfo, QQInfo, SystemInfo } from '@/types';
import type { HookProcessOps } from '@/hooks/use-hook-process-ops';
/**
@@ -12,11 +12,13 @@ export interface AppStateValue {
qqList: QQInfo[];
processList: HookProcessInfo[];
systemInfo: SystemInfo | null;
connections: AccountConnections[];
selectedUin: string | null;
setSelectedUin: (uin: string | null) => void;
processOps: HookProcessOps;
refreshProcesses: () => void;
refreshSystem: () => void;
refreshConnections: () => void;
/** Triggered from the topbar logout button. */
onLogout: () => void;
}
+5 -1
View File
@@ -1,4 +1,4 @@
import type { HookProcessInfo, LogEntry, LogLevel, QQInfo, SystemInfo } from '@/types';
import type { AccountConnections, HookProcessInfo, LogEntry, LogLevel, QQInfo, SystemInfo } from '@/types';
import type { PasswordRule } from '@/components/pages/change-password-page';
import { normalizeOneBotConfig } from '@/lib/onebot-config';
import {
@@ -222,6 +222,10 @@ class HttpApiClient implements ApiClient {
return this.getJson<SystemInfo>('/api/system');
}
connections(): Promise<AccountConnections[]> {
return this.getJson<{ list: AccountConnections[] }>('/api/connections').then((d) => d.list ?? []);
}
// ---------- SSE ----------
private openLogStream(options: LogsStreamOptions): () => void {
+3
View File
@@ -1,4 +1,5 @@
import type {
AccountConnections,
HookProcessInfo,
LogEntry,
LogLevel,
@@ -50,6 +51,8 @@ export interface ApiClient {
// ---- system ----
qqList(): Promise<QQInfo[]>;
system(): Promise<SystemInfo>;
/** Live OneBot adapter health per account. */
connections(): Promise<AccountConnections[]>;
// ---- hook processes ----
processes: {
+15 -3
View File
@@ -8,7 +8,7 @@ import { ConfirmDialog } from '@/components/confirm-dialog';
import { Skeleton } from '@/components/ui/skeleton';
import { AppStateProvider } from '@/contexts/AppStateContext';
import { useSession } from '@/contexts/SessionContext';
import type { HookProcessInfo, QQInfo, SystemInfo } from '@/types';
import type { AccountConnections, HookProcessInfo, QQInfo, SystemInfo } from '@/types';
/**
* The layout route. Owns the live state shared across the four pages
@@ -24,6 +24,7 @@ export function AppLayout() {
const [qqList, setQqList] = useState<QQInfo[]>([]);
const [processList, setProcessList] = useState<HookProcessInfo[]>([]);
const [systemInfo, setSystemInfo] = useState<SystemInfo | null>(null);
const [connections, setConnections] = useState<AccountConnections[]>([]);
const [selectedUin, setSelectedUin] = useState<string | null>(null);
const refreshQqList = useCallback(async () => {
@@ -50,6 +51,14 @@ export function AppLayout() {
}
}, [api]);
const refreshConnections = useCallback(async () => {
try {
setConnections(await api.connections());
} catch (e) {
console.error('connections', e);
}
}, [api]);
const { ops: processOps, unloadFailedAlert, dismissUnloadFailedAlert } = useHookProcessOps({
onAfterOp: refreshProcesses,
});
@@ -59,7 +68,7 @@ export function AppLayout() {
let cancelled = false;
const tick = async () => {
if (cancelled) return;
await Promise.all([refreshQqList(), refreshProcesses(), refreshSystem()]);
await Promise.all([refreshQqList(), refreshProcesses(), refreshSystem(), refreshConnections()]);
};
tick();
const interval = setInterval(tick, pollInterval);
@@ -67,13 +76,14 @@ export function AppLayout() {
cancelled = true;
clearInterval(interval);
};
}, [pollInterval, refreshQqList, refreshProcesses, refreshSystem]);
}, [pollInterval, refreshQqList, refreshProcesses, refreshSystem, refreshConnections]);
const handleLogout = useCallback(async () => {
await api.logout();
setQqList([]);
setProcessList([]);
setSystemInfo(null);
setConnections([]);
setSelectedUin(null);
session.onLogoutComplete();
}, [api, session]);
@@ -84,11 +94,13 @@ export function AppLayout() {
qqList,
processList,
systemInfo,
connections,
selectedUin,
setSelectedUin,
processOps,
refreshProcesses,
refreshSystem,
refreshConnections,
onLogout: handleLogout,
}}
>
+15
View File
@@ -7,6 +7,21 @@ export interface QQInfo {
nickname: string;
}
export type AdapterStatusLevel = 'ok' | 'warn' | 'down' | 'disabled';
export interface AdapterStatus {
name: string;
kind: 'httpServer' | 'httpClient' | 'wsServer' | 'wsClient';
status: AdapterStatusLevel;
detail: string;
}
export interface AccountConnections {
uin: string;
nickname: string;
adapters: AdapterStatus[];
}
export interface HookProcessInfo {
pid: number;
name: string;