From fae2f7552546e47392082f764e5497cf819b0b4c Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Thu, 18 Jun 2026 15:25:34 +0800 Subject: [PATCH] =?UTF-8?q?feat(webui):=20debug=20panel=20=E2=80=94=20acti?= =?UTF-8?q?on=20tester=20+=20live=20stream=20(Wave=20A3)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit New Settings → 调试 tab (DebugPanel): an action tester (account picker + schema-driven form from /api/debug/actions, with a raw-JSON escape hatch for legacy actions, real-side-effect warning) and a live merged SSE view of OneBot events + action calls (pause / clear / kind filter, expandable JSON, drop marker). Typed debug API client domain (actions/invoke/stream over EventSource with ?token=). View layer — verified by tsc + vite build. --- .../src/components/pages/settings-page.tsx | 3 + .../src/components/settings/debug-panel.tsx | 254 ++++++++++++++++++ packages/webui/src/lib/api/client.ts | 25 +- packages/webui/src/lib/api/types.ts | 11 + packages/webui/src/router/index.tsx | 2 +- packages/webui/src/types.ts | 31 +++ 6 files changed, 324 insertions(+), 2 deletions(-) create mode 100644 packages/webui/src/components/settings/debug-panel.tsx diff --git a/packages/webui/src/components/pages/settings-page.tsx b/packages/webui/src/components/pages/settings-page.tsx index f0ff89b2..7f2fe148 100644 --- a/packages/webui/src/components/pages/settings-page.tsx +++ b/packages/webui/src/components/pages/settings-page.tsx @@ -43,6 +43,7 @@ import { cn } from '@/lib/utils'; import { settingsRoute, type SettingsTab } from '@/router'; import { NotificationsPanel } from '@/components/settings/notifications-panel'; import { SystemPanel } from '@/components/settings/system-panel'; +import { DebugPanel } from '@/components/settings/debug-panel'; const TABS: { key: SettingsTab; label: string; icon: typeof Sun }[] = [ { key: 'appearance', label: '外观', icon: Palette }, @@ -50,6 +51,7 @@ const TABS: { key: SettingsTab; label: string; icon: typeof Sun }[] = [ { key: 'advanced', label: '高级', icon: Code2 }, { key: 'account', label: '账号安全', icon: ShieldCheck }, { key: 'system', label: '服务', icon: Server }, + { key: 'debug', label: '调试', icon: Bug }, { key: 'notifications', label: '通知', icon: Bell }, { key: 'about', label: '关于', icon: Info }, ]; @@ -82,6 +84,7 @@ export function SettingsPage() { {tab === 'advanced' && } {tab === 'account' && } {tab === 'system' && } + {tab === 'debug' && } {tab === 'notifications' && } {tab === 'about' && } diff --git a/packages/webui/src/components/settings/debug-panel.tsx b/packages/webui/src/components/settings/debug-panel.tsx new file mode 100644 index 00000000..7350e96a --- /dev/null +++ b/packages/webui/src/components/settings/debug-panel.tsx @@ -0,0 +1,254 @@ +// Settings → 调试 tab (Wave A3). Two tools over /api/debug/*: +// 1) Action 测试台 — pick an account, pick an action (schema-driven form, or a +// raw-JSON escape hatch for legacy/freeform), invoke, see the response. +// Invocations are REAL (send messages, kick, etc.) — flagged in red. +// 2) 实时流 — merged live SSE of OneBot events + action calls across accounts, +// with pause / clear / kind filter. +import { useEffect, useMemo, useRef, useState } from 'react'; +import { Bug, ChevronRight, Loader2, Pause, Play, Trash2 } from 'lucide-react'; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; +import { Badge } from '@/components/ui/badge'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { Select } from '@/components/ui/select'; +import { Textarea } from '@/components/ui/textarea'; +import { useApi } from '@/lib/api'; +import { cn } from '@/lib/utils'; +import type { DebugActionDoc, DebugInvokeResult, DebugStreamMessage, QQInfo } from '@/types'; + +const STREAM_CAP = 300; + +interface StreamRow { id: number; at: number; msg: Extract } + +function coerceParam(type: string, raw: string): unknown { + if (raw === '') return undefined; + if (type.includes('int') || type === 'number' || type === 'uint') { + const n = Number(raw); + return Number.isFinite(n) ? n : raw; + } + if (type === 'bool' || type === 'boolean') return raw === 'true' || raw === '1'; + return raw; +} + +export function DebugPanel() { + const api = useApi(); + + // ── action tester ── + const [accounts, setAccounts] = useState([]); + const [docs, setDocs] = useState([]); + const [uin, setUin] = useState(''); + const [actionName, setActionName] = useState(''); + const [fields, setFields] = useState>({}); + const [rawMode, setRawMode] = useState(false); + const [rawJson, setRawJson] = useState('{}'); + const [invoking, setInvoking] = useState(false); + const [result, setResult] = useState(null); + + const doc = useMemo(() => docs.find((d) => d.name === actionName), [docs, actionName]); + + useEffect(() => { + void (async () => { + try { + const [qq, acts] = await Promise.all([api.qqList(), api.debug.actions()]); + setAccounts(qq); + setDocs(acts.actions); + if (qq[0]) setUin(qq[0].uin); + } catch { /* surfaced lazily */ } + })(); + }, []); // eslint-disable-line react-hooks/exhaustive-deps + + const invoke = async () => { + if (!uin) { setResult({ error: '请选择账号' }); return; } + if (!actionName.trim()) { setResult({ error: '请填写 action' }); return; } + let params: Record = {}; + if (rawMode || !doc) { + try { params = JSON.parse(rawJson || '{}'); } catch { setResult({ error: 'params JSON 无效' }); return; } + if (typeof params !== 'object' || params === null || Array.isArray(params)) { setResult({ error: 'params 必须是对象' }); return; } + } else { + for (const p of doc.params) { + const v = coerceParam(p.type, fields[p.name] ?? ''); + if (v !== undefined) params[p.name] = v; + } + } + setInvoking(true); + setResult(null); + try { + setResult(await api.debug.invoke(uin, actionName.trim(), params)); + } catch (e) { + setResult({ error: e instanceof Error ? e.message : '调用失败' }); + } finally { + setInvoking(false); + } + }; + + // ── live stream ── + const [rows, setRows] = useState([]); + const [paused, setPaused] = useState(false); + const [status, setStatus] = useState<'open' | 'reconnecting' | 'closed'>('closed'); + const [kindFilter, setKindFilter] = useState<'all' | 'event' | 'action'>('all'); + const pausedRef = useRef(paused); + pausedRef.current = paused; + const idRef = useRef(0); + + useEffect(() => { + const off = api.debug.stream( + (m) => { + if (m.kind === 'ready') return; + if (pausedRef.current) return; + setRows((prev) => { + const next = [{ id: idRef.current++, at: Date.now(), msg: m }, ...prev]; + return next.length > STREAM_CAP ? next.slice(0, STREAM_CAP) : next; + }); + }, + (s) => setStatus(s), + ); + return off; + }, []); // eslint-disable-line react-hooks/exhaustive-deps + + const visible = rows.filter((r) => kindFilter === 'all' || r.msg.kind === kindFilter); + + return ( + + + + 测试台调用会真实生效(真发消息 / 真踢人等),请谨慎操作。 + + + {/* Action tester */} + + + Action 测试台 + 选择账号与接口,填参数后调用并查看响应。 + + + + + 账号 + setUin(e.target.value)}> + {accounts.length === 0 && (无在线账号)} + {accounts.map((a) => {a.nickname || a.uin}({a.uin}))} + + + + Action + { setActionName(e.target.value); setResult(null); }} + placeholder="如 send_group_msg" + /> + + {docs.map((d) => {d.summary})} + + + + + {doc && {doc.summary}{doc.returns ? ` · 返回 ${doc.returns}` : ''}} + + + 原始 JSON 参数(覆盖表单;legacy 接口必用) + setRawMode((v) => !v)}>{rawMode ? '用表单' : '用 JSON'} + + + {rawMode || !doc ? ( + setRawJson(e.target.value)} placeholder='{"group_id": 12345, "message": "hi"}' /> + ) : ( + + {doc.params.length === 0 && 无参数。} + {doc.params.map((p) => ( + + + {p.name}({p.type}{p.required ? ' *' : ''}) + + setFields((f) => ({ ...f, [p.name]: e.target.value }))} + placeholder={p.desc || (p.default !== undefined ? `默认 ${JSON.stringify(p.default)}` : '')} + /> + + ))} + + )} + + + + {invoking ? : } 执行 + + + + {result && ( + + {JSON.stringify(result, null, 2)} + + )} + + + + {/* Live stream */} + + + + 实时流 + + + 所有账号的 OneBot 事件与 action 调用(实时)。 + + + + setPaused((v) => !v)} className="gap-1.5"> + {paused ? : } {paused ? '继续' : '暂停'} + + setRows([])} className="gap-1.5"> 清空 + + setKindFilter(e.target.value as 'all' | 'event' | 'action')}> + 全部 + 事件 + 调用 + + + {visible.length} 条{paused ? ' · 已暂停' : ''} + + + + {visible.length === 0 && 暂无数据…} + {visible.map((r) => )} + + + + + ); +} + +function StreamRowItem({ row }: { row: StreamRow }) { + const [open, setOpen] = useState(false); + const { msg } = row; + const time = new Date(row.at).toLocaleTimeString(); + let label: string; + let detail: unknown; + if (msg.kind === 'dropped') { + return ⚠ 因客户端过慢丢弃了 {msg.count} 条; + } else if (msg.kind === 'event') { + const e = msg.event; + label = `${e.post_type ?? 'event'}${e.message_type ? `.${e.message_type}` : e.notice_type ? `.${e.notice_type}` : ''}`; + detail = e; + } else { + const ok = (msg.response as { status?: string }).status === 'ok'; + label = `${msg.action} → ${ok ? 'ok' : 'failed'} (${msg.ms}ms)`; + detail = { params: msg.params, response: msg.response }; + } + return ( + + setOpen((v) => !v)}> + + {time} + {msg.kind === 'action' ? '调用' : '事件'} + {msg.uin} + {label} + + {open && {JSON.stringify(detail, null, 2)}} + + ); +} diff --git a/packages/webui/src/lib/api/client.ts b/packages/webui/src/lib/api/client.ts index faf7aea5..e3c7afaf 100644 --- a/packages/webui/src/lib/api/client.ts +++ b/packages/webui/src/lib/api/client.ts @@ -1,4 +1,4 @@ -import type { AccountConnections, BackupBundle, BackupImportResult, HookProcessInfo, LogEntry, LogLevel, NotificationDeliveryRecord, NotificationsConfig, QQInfo, SystemInfo, SystemSettingsPatch, SystemSettingsResponse, UiAppearance, UiConfig, UpdateInfo } from '@/types'; +import type { AccountConnections, BackupBundle, BackupImportResult, DebugActionDoc, DebugInvokeResult, DebugStreamMessage, HookProcessInfo, LogEntry, LogLevel, NotificationDeliveryRecord, NotificationsConfig, QQInfo, SystemInfo, SystemSettingsPatch, SystemSettingsResponse, UiAppearance, UiConfig, UpdateInfo } from '@/types'; import type { PasswordRule } from '@/components/pages/change-password-page'; import { normalizeOneBotConfig } from '@/lib/onebot-config'; import { @@ -46,6 +46,7 @@ class HttpApiClient implements ApiClient { readonly ui: ApiClient['ui']; readonly notifications: ApiClient['notifications']; readonly systemSettings: ApiClient['systemSettings']; + readonly debug: ApiClient['debug']; constructor(opts: CreateApiClientOptions = {}) { this.tokenStore = opts.tokenStore ?? localStorageTokenStore(DEFAULT_TOKEN_KEY); @@ -118,6 +119,13 @@ class HttpApiClient implements ApiClient { this.postJson('/api/system/backup/import', { backup, restoreCredentials }), }; + this.debug = { + actions: () => this.getJson<{ actions: DebugActionDoc[]; categories: { category: string; count: number }[] }>('/api/debug/actions'), + invoke: (uin: string, action: string, params: Record) => + this.postJson('/api/debug/invoke', { uin, action, params }), + stream: (onMessage, onStatus) => this.openDebugStream(onMessage, onStatus), + }; + this.ui = { get: () => this.getJson<{ config: UiConfig }>('/api/ui').then((d) => d.config), save: async (config) => { @@ -339,6 +347,21 @@ class HttpApiClient implements ApiClient { options.onStatus?.('closed'); }; } + + private openDebugStream( + onMessage: (m: DebugStreamMessage) => void, + onStatus?: (s: import('./types').StreamStatus) => void, + ): () => void { + if (!this.currentToken) { onStatus?.('closed'); return () => {}; } + const url = `/api/debug/stream?token=${encodeURIComponent(this.currentToken)}`; + const source = new EventSource(url); + source.onopen = () => onStatus?.('open'); + source.onerror = () => onStatus?.('reconnecting'); + source.onmessage = (event) => { + try { onMessage(JSON.parse(event.data) as DebugStreamMessage); } catch { /* skip malformed */ } + }; + return () => { source.close(); onStatus?.('closed'); }; + } } export function createApiClient(options: CreateApiClientOptions = {}): ApiClient { diff --git a/packages/webui/src/lib/api/types.ts b/packages/webui/src/lib/api/types.ts index b8b34686..45e6369c 100644 --- a/packages/webui/src/lib/api/types.ts +++ b/packages/webui/src/lib/api/types.ts @@ -2,6 +2,9 @@ import type { AccountConnections, BackupBundle, BackupImportResult, + DebugActionDoc, + DebugInvokeResult, + DebugStreamMessage, HookProcessInfo, LogEntry, LogLevel, @@ -92,6 +95,14 @@ export interface ApiClient { importBackup(backup: BackupBundle, restoreCredentials: boolean): Promise; }; + // ---- debug tools (action tester + live event/action stream) ---- + debug: { + actions(): Promise<{ actions: DebugActionDoc[]; categories: { category: string; count: number }[] }>; + invoke(uin: string, action: string, params: Record): Promise; + /** Live merged SSE; returns an unsubscribe. */ + stream(onMessage: (m: DebugStreamMessage) => void, onStatus?: (s: StreamStatus) => void): () => void; + }; + // ---- notifications (account up/down webhooks) ---- notifications: { /** Global channel store (channels + debounce). Bearer-gated. */ diff --git a/packages/webui/src/router/index.tsx b/packages/webui/src/router/index.tsx index b26204ff..c991232c 100644 --- a/packages/webui/src/router/index.tsx +++ b/packages/webui/src/router/index.tsx @@ -65,7 +65,7 @@ const logsRoute = createRoute({ }); /** Settings sub-tabs — also the contract for the `?tab=` deep link. */ -export const SETTINGS_TABS = ['appearance', 'data', 'advanced', 'account', 'system', 'notifications', 'about'] as const; +export const SETTINGS_TABS = ['appearance', 'data', 'advanced', 'account', 'system', 'debug', 'notifications', 'about'] as const; export type SettingsTab = (typeof SETTINGS_TABS)[number]; export const settingsRoute = createRoute({ diff --git a/packages/webui/src/types.ts b/packages/webui/src/types.ts index c0aa34da..07d327c8 100644 --- a/packages/webui/src/types.ts +++ b/packages/webui/src/types.ts @@ -158,6 +158,37 @@ export interface SystemSettingsResponse { restartRequiredToApply: boolean; } +// Debug tools (Wave A3). +export interface DebugActionParam { + name: string; + type: string; + required: boolean; + default?: unknown; + desc?: string; + values?: (string | number)[]; +} +export interface DebugActionDoc { + name: string; + aliases: string[]; + category?: string; + summary?: string; + returns?: string; + readOnly: boolean; + params: DebugActionParam[]; +} +export interface DebugInvokeResult { + status: string; + retcode?: number; + data?: unknown; + message?: string; + wording?: string; +} +export type DebugStreamMessage = + | { kind: 'ready' } + | { kind: 'dropped'; count: number } + | { kind: 'event'; uin: string; event: Record } + | { kind: 'action'; uin: string; action: string; params: Record; response: Record; ms: number }; + // Config backup/restore (Wave A2). The bundle is an opaque JSON object the // server validates; the client never inspects its internals. export type BackupBundle = Record;
{doc.summary}{doc.returns ? ` · 返回 ${doc.returns}` : ''}
无参数。
+ {JSON.stringify(result, null, 2)} +
暂无数据…
{JSON.stringify(detail, null, 2)}