diff --git a/packages/webui/src/components/debug/action-tester.tsx b/packages/webui/src/components/debug/action-tester.tsx new file mode 100644 index 00000000..2a23c0eb --- /dev/null +++ b/packages/webui/src/components/debug/action-tester.tsx @@ -0,0 +1,378 @@ +// ActionTester — the debug console's centrepiece. Pick an account + action and +// invoke it; params render as role-driven smart controls (pickers, switches, +// file sources) with a raw-JSON escape hatch. Read-only actions are badged +// green, side-effecting ones amber; destructive ones confirm first. Stream API +// actions invoke over the streaming transport and render frames live (tracked +// in the app-level task registry). Every call lands in localStorage history +// with one-click replay. Responses render in a collapsible JsonTree. +import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'; +import { motion } from 'motion/react'; +import { AlertTriangle, FlaskConical, History, Loader2, Play, RotateCcw, ShieldCheck, Trash2, Zap } from 'lucide-react'; +import { Select } from '@/components/ui/select'; +import { Textarea } from '@/components/ui/textarea'; +import { Picker } from '@/components/ui/picker'; +import { JsonTree } from '@/components/ui/json-tree'; +import { ParamField } from '@/components/debug/param-field'; +import { Segmented } from '@/components/debug/segmented'; +import { useApi } from '@/lib/api'; +import { useDebugTasks } from '@/contexts/DebugTaskContext'; +import { clearHistory, loadHistory, pushHistory, type InvokeRecord } from '@/lib/debug-history'; +import { cn } from '@/lib/utils'; +import type { DebugActionDoc, DebugStreamFrame, QQInfo } from '@/types'; + +const cardCls = 'rounded-2xl border border-border/60 bg-card/80 shadow-[0_1px_2px_rgb(0_0_0/0.04),0_8px_24px_-12px_rgb(0_0_0/0.10)] backdrop-blur-sm'; + +// Name patterns for genuinely destructive actions → require a confirm. False +// positives just add one extra click; false negatives skip a confirm — both low +// stakes (the amber banner already warns that any write is real). +const DESTRUCTIVE_RE = /(kick|ban|mute|recall|withdraw|delete|del_|dismiss|disband|leave|quit|remove|revoke)/i; + +function coerceParam(type: string, raw: string): unknown { + if (raw === '') return undefined; + if (/int|uint|number|messageId/i.test(type)) { + const n = Number(raw); + return Number.isFinite(n) ? n : raw; + } + if (type === 'bool' || type === 'boolean') return raw === 'true' || raw === '1'; + if (type === 'message') { + const t = raw.trim(); + if ((t.startsWith('[') && t.endsWith(']')) || (t.startsWith('{') && t.endsWith('}'))) { + try { return JSON.parse(t); } catch { /* fall through to literal */ } + } + return raw; + } + return raw; +} + +function Field({ label, children }: { label: ReactNode; children: ReactNode }) { + return ( + + ); +} + +export function ActionTester({ accounts, docs }: { accounts: QQInfo[]; docs: DebugActionDoc[] }) { + const api = useApi(); + const tasks = useDebugTasks(); + + const [uin, setUin] = useState(''); + const [actionName, setActionName] = useState(''); + const [fields, setFields] = useState>({}); + const [paramMode, setParamMode] = useState<'form' | 'json'>('form'); + const [rawJson, setRawJson] = useState('{}'); + const [invoking, setInvoking] = useState(false); + const [result, setResult] = useState(null); + const [frames, setFrames] = useState([]); + const [confirmOpen, setConfirmOpen] = useState(false); + const [history, setHistory] = useState([]); + const [showHistory, setShowHistory] = useState(false); + const streamAbort = useRef(null); + + useEffect(() => { setHistory(loadHistory()); }, []); + useEffect(() => { if (accounts[0] && !uin) setUin(accounts[0].uin); }, [accounts, uin]); + + const doc = useMemo(() => docs.find((d) => d.name === actionName), [docs, actionName]); + const effectiveMode = paramMode === 'json' || !doc ? 'json' : 'form'; + const isStream = !!doc?.stream; + const isDestructive = DESTRUCTIVE_RE.test(actionName); + + const actionOptions = useMemo( + () => docs.map((d) => ({ value: d.name, label: d.name, sub: d.summary })), + [docs], + ); + + const buildParams = (): Record | { __error: string } => { + if (effectiveMode === 'json') { + let parsed: unknown; + try { parsed = JSON.parse(rawJson || '{}'); } catch { return { __error: 'params JSON 无效' }; } + if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return { __error: 'params 必须是对象' }; + return parsed as Record; + } + const out: Record = {}; + if (doc) for (const p of doc.params) { + const v = coerceParam(p.type, fields[p.name] ?? ''); + if (v !== undefined) out[p.name] = v; + } + return out; + }; + + const runInvoke = async () => { + if (!uin) { setResult({ error: '请选择账号' }); return; } + if (!actionName.trim()) { setResult({ error: '请填写 action' }); return; } + const params = buildParams(); + if ('__error' in params) { setResult({ error: params.__error as string }); return; } + + setInvoking(true); + setResult(null); + setFrames([]); + const startedAt = Date.now(); + + if (isStream) { + const ac = new AbortController(); + streamAbort.current = ac; + const taskId = tasks.start({ kind: 'stream', label: `${actionName} @ ${uin}`, progress: undefined, cancel: () => ac.abort() }); + let last: DebugStreamFrame | null = null; + try { + await api.debug.invokeStream(uin, actionName.trim(), params, (frame) => { + last = frame; + setFrames((prev) => [...prev, frame]); + const d = frame.data as { type?: string; progress?: number; transferred?: number; total?: number } | undefined; + if (d && typeof d.progress === 'number') tasks.update(taskId, { progress: d.progress }); + else if (d && typeof d.transferred === 'number' && typeof d.total === 'number' && d.total > 0) tasks.update(taskId, { progress: d.transferred / d.total }); + }, ac.signal); + // A clean success requires the terminal frame (status ok AND the + // NapCat terminal marker data.type==='response') — a stream that closed + // without emitting its terminator must not read as success. + const term = last as DebugStreamFrame | null; + const ok = !!term && term.status === 'ok' && (term.data as { type?: string } | undefined)?.type === 'response'; + setResult(last); + tasks.finish(taskId, ok ? 'done' : 'failed'); + setHistory(pushHistory({ at: startedAt, uin, action: actionName.trim(), params, ok, ms: Date.now() - startedAt, stream: true })); + } catch (e) { + const aborted = ac.signal.aborted; + const msg = e instanceof Error ? e.message : '流式调用失败'; + if (!aborted) setResult({ error: msg }); + tasks.finish(taskId, aborted ? 'canceled' : 'failed', msg); + setHistory(pushHistory({ at: startedAt, uin, action: actionName.trim(), params, ok: false, ms: Date.now() - startedAt, stream: true })); + } finally { + streamAbort.current = null; + setInvoking(false); + } + return; + } + + try { + const res = await api.debug.invoke(uin, actionName.trim(), params); + setResult(res); + setHistory(pushHistory({ at: startedAt, uin, action: actionName.trim(), params, ok: res.status === 'ok', ms: Date.now() - startedAt })); + } catch (e) { + setResult({ error: e instanceof Error ? e.message : '调用失败' }); + setHistory(pushHistory({ at: startedAt, uin, action: actionName.trim(), params, ok: false, ms: Date.now() - startedAt })); + } finally { + setInvoking(false); + } + }; + + const onExecute = () => { + if (isDestructive) { setConfirmOpen(true); return; } + void runInvoke(); + }; + + const replay = (rec: InvokeRecord) => { + setUin(rec.uin); + setActionName(rec.action); + setParamMode('json'); + setRawJson(JSON.stringify(rec.params, null, 2)); + setResult(null); + setFrames([]); + setShowHistory(false); + }; + + const resultFailed = !!result && ('error' in result || result.status === 'failed'); + + return ( +
+ {/* tester */} + +
+
+ +

Action 测试台

+
+ +
+ +
+ + 调用会真实生效(真发消息 / 真踢人等),请谨慎。 +
+ +
+ + + + + { setActionName(v); setResult(null); setFrames([]); }} + options={actionOptions} + placeholder="search action…" + validateRaw={(s) => s.trim().length > 0} + /> + +
+ + {doc && ( +
+ {doc.readOnly + ? 只读·安全 + : 有副作用} + {isStream && 流式} + {doc.summary}{doc.returns ? <> · 返回 {doc.returns} : null} +
+ )} + +
+ 参数 + +
+ + {effectiveMode === 'json' ? ( +