{value}
+
+ dump: nodes fold, values are colour-typed, the
+// root offers copy, and a string that looks like an image URL gets an inline
+// preview toggle. Read-only; no external deps.
+import { useState, type ReactNode } from 'react';
+import { Check, ChevronRight, Copy, Image as ImageIcon } from 'lucide-react';
+import { cn } from '@/lib/utils';
+
+const IMAGE_URL_RE = /^https?:\/\/[^\s]+?\.(?:png|jpe?g|gif|webp|bmp)(?:[?#][^\s]*)?$/i;
+// QQ multimedia rkey image URLs don't end in an extension but carry these hints.
+const IMAGE_HINT_RE = /^https?:\/\/[^\s]*(?:rkey=|gchatpic|multimedia|c2cpicdw|offpic|gchat\.qpic)/i;
+
+function isImageUrl(s: string): boolean {
+ return IMAGE_URL_RE.test(s) || IMAGE_HINT_RE.test(s);
+}
+
+function Punct({ children }: { children: ReactNode }) {
+ return {children};
+}
+
+function Leaf({ value }: { value: string | number | boolean | null }) {
+ const [showImg, setShowImg] = useState(false);
+ if (value === null) return null;
+ if (typeof value === 'number') return {value};
+ if (typeof value === 'boolean') return {String(value)};
+ // string
+ const img = isImageUrl(value);
+ return (
+
+ "{value}"
+ {img && (
+ <>
+
+ {showImg && (
+
+
+
+ )}
+ >
+ )}
+
+ );
+}
+
+const NODE_CAP = 100; // render at most this many children before "show more"
+
+function Node({ k, value, depth, defaultOpen }: { k?: string; value: unknown; depth: number; defaultOpen: boolean }) {
+ const isObj = typeof value === 'object' && value !== null;
+ const [open, setOpen] = useState(defaultOpen);
+ const [limit, setLimit] = useState(NODE_CAP);
+
+ const keyLabel = k != null ? <>{k}: > : null;
+
+ if (!isObj) {
+ return (
+
+ {keyLabel}
+
+
+ );
+ }
+
+ const entries = Array.isArray(value)
+ ? value.map((v, i) => [String(i), v] as const)
+ : Object.entries(value as Record);
+ const openB = Array.isArray(value) ? '[' : '{';
+ const closeB = Array.isArray(value) ? ']' : '}';
+ const shown = open ? Math.min(entries.length, limit) : 0;
+
+ return (
+
+
+ {open && (
+ <>
+ {entries.slice(0, shown).map(([ck, cv]) => (
+
+ ))}
+ {entries.length > shown && (
+
+ )}
+ {closeB}
+ >
+ )}
+
+ );
+}
+
+export function JsonTree({ data, className, maxHeight = '20rem' }: { data: unknown; className?: string; maxHeight?: string }) {
+ const [copied, setCopied] = useState(false);
+ const text = (() => { try { return JSON.stringify(data, null, 2); } catch { return String(data); } })();
+
+ const copy = async () => {
+ try {
+ if (navigator.clipboard?.writeText) {
+ await navigator.clipboard.writeText(text);
+ } else {
+ // navigator.clipboard is undefined on http LAN deployments — fall back
+ // to the legacy execCommand path so copy still works (and shows feedback).
+ const ta = document.createElement('textarea');
+ ta.value = text;
+ ta.style.position = 'fixed';
+ ta.style.opacity = '0';
+ document.body.appendChild(ta);
+ ta.select();
+ document.execCommand('copy');
+ document.body.removeChild(ta);
+ }
+ setCopied(true);
+ setTimeout(() => setCopied(false), 1200);
+ } catch { /* clipboard blocked */ }
+ };
+
+ return (
+
+
+
+
+
+
+ );
+}
diff --git a/packages/webui/src/components/ui/picker.tsx b/packages/webui/src/components/ui/picker.tsx
new file mode 100644
index 00000000..18c0e83e
--- /dev/null
+++ b/packages/webui/src/components/ui/picker.tsx
@@ -0,0 +1,227 @@
+// Picker — a searchable, windowed combobox for choosing from large lists
+// (group members can be thousands). Apple-HIG flavour built on the same idiom
+// as DropdownSelect: calm trigger matching Input height, a soft floating panel
+// with a search field, virtualised rows (avatar + name + sub), keyboard nav,
+// and an always-present escape hatch — if what you typed isn't in the list you
+// can still commit it as a raw value. Loading / error / empty states degrade to
+// the raw-value input so the picker never traps you.
+import { useEffect, useMemo, useRef, useState } from 'react';
+import { AnimatePresence, motion } from 'motion/react';
+import { ChevronDown, Loader2, RefreshCw, Search } from 'lucide-react';
+import { cn } from '@/lib/utils';
+
+export interface PickerOption {
+ value: string;
+ label: string;
+ /** Secondary line (e.g. the uin under a nickname). */
+ sub?: string;
+ /** Avatar URL. */
+ avatar?: string;
+}
+
+interface PickerProps {
+ value: string;
+ onChange: (v: string) => void;
+ options: ReadonlyArray;
+ loading?: boolean;
+ error?: string | null;
+ onRefresh?: () => void;
+ placeholder?: string;
+ /** Validates a typed raw value before it can be committed via the escape
+ * hatch. Defaults to "non-empty". */
+ validateRaw?: (raw: string) => boolean;
+ ariaLabel: string;
+ className?: string;
+ disabled?: boolean;
+}
+
+const ROW_H = 44; // px — fixed row height drives the windowing math
+const OVERSCAN = 6;
+const PANEL_MAX = 264; // px of scroll viewport
+
+export function Picker({
+ value, onChange, options, loading, error, onRefresh,
+ placeholder = '选择…', validateRaw, ariaLabel, className, disabled,
+}: PickerProps) {
+ const [open, setOpen] = useState(false);
+ const [query, setQuery] = useState('');
+ const [scrollTop, setScrollTop] = useState(0);
+ const [active, setActive] = useState(0);
+ const rootRef = useRef(null);
+ const listRef = useRef(null);
+ const searchRef = useRef(null);
+
+ const selected = options.find((o) => o.value === value);
+
+ const filtered = useMemo(() => {
+ const q = query.trim().toLowerCase();
+ if (!q) return options;
+ return options.filter((o) => o.label.toLowerCase().includes(q) || o.value.includes(q) || (o.sub?.toLowerCase().includes(q) ?? false));
+ }, [options, query]);
+
+ // The escape-hatch row: show when the query is a committable raw value that
+ // isn't already an exact option.
+ const canRaw = query.trim() !== '' && (validateRaw ? validateRaw(query.trim()) : true)
+ && !options.some((o) => o.value === query.trim());
+ const rawRow = canRaw ? query.trim() : null;
+
+ useEffect(() => {
+ if (!open) return;
+ setScrollTop(0);
+ setActive(0);
+ const t = setTimeout(() => searchRef.current?.focus(), 10);
+ const onPointer = (e: PointerEvent) => {
+ if (rootRef.current && !rootRef.current.contains(e.target as Node)) setOpen(false);
+ };
+ document.addEventListener('pointerdown', onPointer);
+ return () => { clearTimeout(t); document.removeEventListener('pointerdown', onPointer); };
+ }, [open]);
+
+ const totalRows = filtered.length + (rawRow ? 1 : 0);
+ // Keep the keyboard cursor in range when the list shrinks (refresh / typing)
+ // without a keystroke that would have reset it.
+ useEffect(() => {
+ setActive((a) => Math.min(a, Math.max(0, totalRows - 1)));
+ }, [totalRows]);
+ const viewH = Math.min(PANEL_MAX, totalRows * ROW_H);
+ const start = Math.max(0, Math.floor(scrollTop / ROW_H) - OVERSCAN);
+ const end = Math.min(totalRows, Math.ceil((scrollTop + viewH) / ROW_H) + OVERSCAN);
+
+ const commit = (v: string) => { onChange(v); setOpen(false); setQuery(''); };
+
+ const choose = (idx: number) => {
+ if (rawRow && idx === filtered.length) commit(rawRow);
+ else { const o = filtered[idx]; if (o) commit(o.value); }
+ };
+
+ const onKeyDown = (e: React.KeyboardEvent) => {
+ if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); setOpen(false); return; }
+ if (e.key === 'ArrowDown') { e.preventDefault(); setActive((a) => Math.min(totalRows - 1, a + 1)); }
+ else if (e.key === 'ArrowUp') { e.preventDefault(); setActive((a) => Math.max(0, a - 1)); }
+ else if (e.key === 'Enter') { e.preventDefault(); choose(active); }
+ };
+
+ // Keep the active row scrolled into view.
+ useEffect(() => {
+ if (!open || !listRef.current) return;
+ const top = active * ROW_H;
+ const el = listRef.current;
+ if (top < el.scrollTop) el.scrollTop = top;
+ else if (top + ROW_H > el.scrollTop + el.clientHeight) el.scrollTop = top + ROW_H - el.clientHeight;
+ }, [active, open]);
+
+ const rows: { idx: number; opt: PickerOption | null }[] = [];
+ for (let i = start; i < end; i++) {
+ if (rawRow && i === filtered.length) rows.push({ idx: i, opt: null });
+ else rows.push({ idx: i, opt: filtered[i] ?? null });
+ }
+
+ return (
+
+
+
+
+ {open && (
+
+
+
+ {
+ setQuery(e.target.value);
+ setActive(0);
+ setScrollTop(0);
+ if (listRef.current) listRef.current.scrollTop = 0;
+ }}
+ placeholder="搜索名称 / 号码…"
+ className="min-w-0 flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground"
+ />
+ {onRefresh && (
+
+ )}
+
+
+ {loading && options.length === 0 ? (
+
+ 加载中…
+
+ ) : error ? (
+
+ {error}
+ 可直接在上方输入号码后回车使用
+
+ ) : totalRows === 0 ? (
+ 无匹配项{query && ';输入完整号码可直接使用'}
+ ) : (
+ setScrollTop((e.target as HTMLDivElement).scrollTop)}
+ className="overflow-auto"
+ style={{ height: viewH }}
+ >
+
+ {rows.map(({ idx, opt }) => (
+ setActive(idx)}
+ onClick={() => choose(idx)}
+ className={cn(
+ 'absolute left-0 right-0 flex cursor-pointer items-center gap-2.5 px-3',
+ idx === active ? 'bg-accent text-accent-foreground' : 'hover:bg-accent/50',
+ )}
+ style={{ top: idx * ROW_H, height: ROW_H }}
+ >
+ {opt ? (
+ <>
+ {opt.avatar
+ ?
+ : }
+ {opt.label}
+ {opt.sub && {opt.sub}}
+ >
+ ) : (
+ 使用 {rawRow}
+ )}
+
+ ))}
+
+
+ )}
+
+ )}
+
+
+ );
+}
diff --git a/packages/webui/src/components/ui/tabs.tsx b/packages/webui/src/components/ui/tabs.tsx
new file mode 100644
index 00000000..3ffba350
--- /dev/null
+++ b/packages/webui/src/components/ui/tabs.tsx
@@ -0,0 +1,89 @@
+// Tabs — a horizontal tab bar with an Apple-HIG sliding indicator. Shares the
+// spring-pill idiom of the debug page's segmented control but scaled up for
+// top-level section switching, with full roving-tabindex keyboard support
+// (←/→/Home/End). Generic over a string union of tab ids.
+import { useId, useRef, type ReactNode } from 'react';
+import { motion } from 'motion/react';
+import { cn } from '@/lib/utils';
+
+export interface TabItem {
+ value: T;
+ label: ReactNode;
+ /** Optional leading icon (already sized by the caller, ~16px). */
+ icon?: ReactNode;
+ /** Optional trailing count / badge. */
+ badge?: ReactNode;
+}
+
+interface TabsProps {
+ value: T;
+ onChange: (v: T) => void;
+ items: ReadonlyArray>;
+ className?: string;
+ 'aria-label'?: string;
+}
+
+export function Tabs({ value, onChange, items, className, ...rest }: TabsProps) {
+ const layoutId = useId();
+ const refs = useRef<(HTMLButtonElement | null)[]>([]);
+
+ const move = (from: number, dir: 1 | -1 | 'home' | 'end') => {
+ const n = items.length;
+ let to: number;
+ if (dir === 'home') to = 0;
+ else if (dir === 'end') to = n - 1;
+ else to = (from + dir + n) % n;
+ const next = items[to];
+ if (next) { onChange(next.value); refs.current[to]?.focus(); }
+ };
+
+ return (
+
+ {items.map((it, i) => {
+ const active = it.value === value;
+ return (
+
+ );
+ })}
+
+ );
+}
diff --git a/packages/webui/src/contexts/DebugTaskContext.tsx b/packages/webui/src/contexts/DebugTaskContext.tsx
new file mode 100644
index 00000000..3597d817
--- /dev/null
+++ b/packages/webui/src/contexts/DebugTaskContext.tsx
@@ -0,0 +1,110 @@
+// DebugTaskContext — an app-level registry of in-flight debug-console tasks
+// (file uploads, streaming invocations) so they survive tab/page switches
+// WITHIN the app (their state lives above the page, not in the unmounting tab).
+// A full page unload (refresh / close) can't be survived, so a beforeunload
+// guard warns while any task runs. Finished tasks linger briefly for history.
+import { createContext, useCallback, useContext, useEffect, useMemo, useState, type ReactNode } from 'react';
+
+export type DebugTaskStatus = 'running' | 'done' | 'failed' | 'canceled';
+export type DebugTaskKind = 'upload' | 'stream' | 'invoke';
+
+export interface DebugTask {
+ id: string;
+ kind: DebugTaskKind;
+ label: string;
+ status: DebugTaskStatus;
+ /** 0..1 when determinate; undefined = indeterminate. */
+ progress?: number;
+ detail?: string;
+ startedAt: number;
+ endedAt?: number;
+ /** Cancel the underlying work (abort the fetch / xhr). */
+ cancel?: () => void;
+}
+
+interface DebugTaskContextValue {
+ tasks: DebugTask[];
+ /** Register a task; returns its id. */
+ start: (task: Omit & { id?: string }) => string;
+ update: (id: string, patch: Partial>) => void;
+ /** Mark terminal (done/failed/canceled) and stamp endedAt. */
+ finish: (id: string, status: Exclude, detail?: string) => void;
+ remove: (id: string) => void;
+ clearFinished: () => void;
+}
+
+const Ctx = createContext(null);
+
+let seq = 0;
+const nextId = () => `dt-${Date.now().toString(36)}-${(seq++).toString(36)}`;
+
+export function DebugTaskProvider({ children }: { children: ReactNode }) {
+ const [tasks, setTasks] = useState([]);
+
+ const start = useCallback((t) => {
+ const id = t.id ?? nextId();
+ setTasks((prev) => {
+ const next = [{ ...t, id, status: 'running' as const, startedAt: Date.now() }, ...prev];
+ if (next.length <= 50) return next;
+ // Over cap: evict the OLDEST finished tasks only — never drop a running
+ // task (that would orphan its finish()/cancel handle while it keeps going).
+ const running = next.filter((x) => x.status === 'running').length;
+ const finished = next.filter((x) => x.status !== 'running');
+ const drop = new Set(finished.slice(Math.max(0, 50 - running)).map((x) => x.id));
+ return next.filter((x) => !drop.has(x.id));
+ });
+ return id;
+ }, []);
+
+ const update = useCallback((id, patch) => {
+ setTasks((prev) => prev.map((t) => (t.id === id ? { ...t, ...patch } : t)));
+ }, []);
+
+ const finish = useCallback((id, status, detail) => {
+ setTasks((prev) => prev.map((t) => (t.id === id ? { ...t, status, detail: detail ?? t.detail, endedAt: Date.now(), cancel: undefined } : t)));
+ }, []);
+
+ const remove = useCallback((id) => {
+ setTasks((prev) => prev.filter((t) => t.id !== id));
+ }, []);
+
+ const clearFinished = useCallback(() => {
+ setTasks((prev) => prev.filter((t) => t.status === 'running'));
+ }, []);
+
+ // beforeunload guard: a real page unload kills in-flight tasks, so warn while
+ // any task is still running (within-app navigation is safe — state is here).
+ useEffect(() => {
+ const anyRunning = tasks.some((t) => t.status === 'running');
+ if (!anyRunning) return;
+ const handler = (e: BeforeUnloadEvent) => { e.preventDefault(); e.returnValue = ''; };
+ window.addEventListener('beforeunload', handler);
+ return () => window.removeEventListener('beforeunload', handler);
+ }, [tasks]);
+
+ const value = useMemo(
+ () => ({ tasks, start, update, finish, remove, clearFinished }),
+ [tasks, start, update, finish, remove, clearFinished],
+ );
+ return {children} ;
+}
+
+export function useDebugTasks(): DebugTaskContextValue {
+ const v = useContext(Ctx);
+ if (!v) throw new Error('useDebugTasks must be used within DebugTaskProvider');
+ return v;
+}
+
+/** Convenience: count + aggregate progress of running tasks, for the badge. */
+export function useRunningTaskSummary(): { count: number; progress: number | null } {
+ const { tasks } = useDebugTasks();
+ return useMemo(() => {
+ const running = tasks.filter((t) => t.status === 'running');
+ if (running.length === 0) return { count: 0, progress: null };
+ const determinate = running.filter((t) => typeof t.progress === 'number');
+ const progress = determinate.length
+ ? determinate.reduce((s, t) => s + (t.progress ?? 0), 0) / determinate.length
+ : null;
+ return { count: running.length, progress };
+ }, [tasks]);
+}
diff --git a/packages/webui/src/hooks/use-debug-contacts.ts b/packages/webui/src/hooks/use-debug-contacts.ts
new file mode 100644
index 00000000..3ca00232
--- /dev/null
+++ b/packages/webui/src/hooks/use-debug-contacts.ts
@@ -0,0 +1,174 @@
+// Debug contacts data layer — lazy-loads friend / group / member lists for the
+// debug console's pickers via the read-only OneBot actions, with a shared
+// module-level cache persisted to localStorage (version-stamped) and a short
+// TTL. Every loader degrades gracefully: on error the hook returns the error so
+// the Picker can fall back to raw input. One cache is shared across every
+// picker instance (tester form, message builder, etc.).
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { useApi } from '@/lib/api';
+import type { PickerOption } from '@/components/ui/picker';
+
+const CACHE_VERSION = 1; // bump to invalidate all persisted entries
+const TTL_MS = 5 * 60_000;
+const LS_KEY = `snowluma.debug.contacts.v${CACHE_VERSION}`;
+
+export function userAvatar(uin: string | number): string {
+ return `https://q1.qlogo.cn/g?b=qq&nk=${uin}&s=100`;
+}
+export function groupAvatar(gid: string | number): string {
+ return `https://p.qlogo.cn/gh/${gid}/${gid}/100`;
+}
+
+interface Entry { at: number; items: PickerOption[] }
+
+// Avatars are derivable from the id + the list kind (encoded in the cache-key
+// prefix), so they're stripped before persisting (a big member list × long
+// avatar URLs would otherwise blow the ~5MB localStorage quota and silently
+// kill persistence for ALL entries) and regenerated on hydrate.
+function avatarFor(key: string, value: string): string | undefined {
+ if (key.startsWith('groups:')) return groupAvatar(value);
+ if (key.startsWith('friends:') || key.startsWith('members:')) return userAvatar(value);
+ return undefined;
+}
+
+// ── shared cache (module-level, hydrated from localStorage once) ──
+const mem = new Map();
+let hydrated = false;
+function hydrate(): void {
+ if (hydrated) return;
+ hydrated = true;
+ try {
+ const raw = localStorage.getItem(LS_KEY);
+ if (raw) {
+ const obj = JSON.parse(raw) as Record;
+ for (const [k, v] of Object.entries(obj)) {
+ if (v && Array.isArray(v.items)) {
+ mem.set(k, { at: v.at, items: v.items.map((it) => ({ ...it, avatar: it.avatar ?? avatarFor(k, it.value) })) });
+ }
+ }
+ }
+ } catch { /* corrupt / unavailable — start empty */ }
+}
+function persist(): void {
+ try {
+ const obj: Record = {};
+ // Strip the derivable avatar to keep the serialized blob small.
+ for (const [k, v] of mem) obj[k] = { at: v.at, items: v.items.map((it) => ({ value: it.value, label: it.label, sub: it.sub })) };
+ localStorage.setItem(LS_KEY, JSON.stringify(obj));
+ } catch { /* quota / unavailable — memory cache still works */ }
+}
+
+/** Drop every cached contact list (the data layer's "清缓存" button). */
+export function clearDebugContactsCache(): void {
+ mem.clear();
+ try { localStorage.removeItem(LS_KEY); } catch { /* ignore */ }
+}
+
+type ParseRow = (row: Record) => PickerOption | null;
+
+interface ListState {
+ items: PickerOption[];
+ loading: boolean;
+ error: string | null;
+ refresh: () => void;
+}
+
+function useContactList(cacheKey: string | null, action: string, uin: string, params: Record, parse: ParseRow): ListState {
+ const api = useApi();
+ hydrate();
+ const [items, setItems] = useState(() => (cacheKey && mem.get(cacheKey)?.items) || []);
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState(null);
+ const reqId = useRef(0);
+
+ const load = useCallback(async (force: boolean) => {
+ if (!cacheKey || !uin) return;
+ const cached = mem.get(cacheKey);
+ if (!force && cached && Date.now() - cached.at < TTL_MS) {
+ setItems(cached.items);
+ return;
+ }
+ const myId = ++reqId.current;
+ setLoading(true);
+ setError(null);
+ try {
+ const res = await api.debug.invoke(uin, action, params);
+ if (myId !== reqId.current) return; // superseded
+ if (res.status !== 'ok') throw new Error(res.message || res.wording || '加载失败');
+ const arr = Array.isArray(res.data) ? (res.data as Record[]) : [];
+ const mapped = arr.map(parse).filter((x): x is PickerOption => x !== null);
+ mem.set(cacheKey, { at: Date.now(), items: mapped });
+ persist();
+ setItems(mapped);
+ } catch (e) {
+ if (myId !== reqId.current) return;
+ setError(e instanceof Error ? e.message : '加载失败');
+ // keep any stale items visible as a fallback
+ } finally {
+ if (myId === reqId.current) setLoading(false);
+ }
+ // params + parse are stable per call-site (their identity is captured by
+ // cacheKey, which already varies on uin/group), so excluding them is
+ // deliberate — including the fresh object/closure would reload every render.
+ }, [api, cacheKey, uin, action]); // eslint-disable-line react-hooks/exhaustive-deps
+
+ useEffect(() => {
+ if (!cacheKey || !uin) { setItems([]); return; }
+ const cached = mem.get(cacheKey);
+ // Clear stale items when switching to an uncached key — otherwise the picker
+ // would show the previous account/group's contacts as valid until the fetch
+ // returns (a member-selection hazard).
+ setItems(cached ? cached.items : []);
+ void load(false);
+ }, [cacheKey, uin, load]);
+
+ return { items, loading, error, refresh: () => void load(true) };
+}
+
+export function useFriends(uin: string): ListState {
+ return useContactList(
+ uin ? `friends:${uin}` : null,
+ 'get_friend_list',
+ uin,
+ {},
+ (r) => {
+ const id = r.user_id;
+ if (id == null) return null;
+ const v = String(id);
+ const nick = (r.remark as string) || (r.nickname as string) || v;
+ return { value: v, label: nick, sub: v, avatar: userAvatar(v) };
+ },
+ );
+}
+
+export function useGroups(uin: string): ListState {
+ return useContactList(
+ uin ? `groups:${uin}` : null,
+ 'get_group_list',
+ uin,
+ {},
+ (r) => {
+ const id = r.group_id;
+ if (id == null) return null;
+ const v = String(id);
+ return { value: v, label: (r.group_name as string) || v, sub: v, avatar: groupAvatar(v) };
+ },
+ );
+}
+
+export function useGroupMembers(uin: string, groupId: string): ListState {
+ const gid = groupId.trim();
+ return useContactList(
+ uin && gid ? `members:${uin}:${gid}` : null,
+ 'get_group_member_list',
+ uin,
+ { group_id: gid },
+ (r) => {
+ const id = r.user_id;
+ if (id == null) return null;
+ const v = String(id);
+ const name = (r.card as string) || (r.nickname as string) || v;
+ return { value: v, label: name, sub: v, avatar: userAvatar(v) };
+ },
+ );
+}
diff --git a/packages/webui/src/lib/api/client.ts b/packages/webui/src/lib/api/client.ts
index 980d3c43..b334c157 100644
--- a/packages/webui/src/lib/api/client.ts
+++ b/packages/webui/src/lib/api/client.ts
@@ -128,6 +128,9 @@ class HttpApiClient implements ApiClient {
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 }),
+ invokeStream: (uin, action, params, onFrame, signal) =>
+ this.openDebugInvokeStream(uin, action, params, onFrame, signal),
+ upload: (file, opts) => this.uploadDebugFile(file, opts),
stream: (onMessage, onStatus) => this.openDebugStream(onMessage, onStatus),
};
@@ -405,6 +408,88 @@ class HttpApiClient implements ApiClient {
};
}
+ // Invoke a (stream) action and relay each `data: \n\n` SSE frame. Uses
+ // fetch + a body reader (not EventSource) so the bearer token rides in the
+ // header and the request can be a POST. Resolves when the stream ends.
+ private async openDebugInvokeStream(
+ uin: string,
+ action: string,
+ params: Record,
+ onFrame: (frame: import('@/types').DebugStreamFrame) => void,
+ signal?: AbortSignal,
+ ): Promise {
+ const headers: Record = { 'Content-Type': 'application/json' };
+ if (this.currentToken) headers['Authorization'] = `Bearer ${this.currentToken}`;
+ const res = await fetch('/api/debug/invoke-stream', {
+ method: 'POST',
+ headers,
+ body: JSON.stringify({ uin, action, params }),
+ signal,
+ });
+ if (res.status === 401) {
+ this.setToken(null);
+ this.onUnauthorized?.();
+ throw new ApiError(401, '未授权');
+ }
+ if (!res.ok || !res.body) {
+ const payload = await readJson(res).catch(() => ({}) as ErrorPayload);
+ throw new ApiError(res.status, extractErrorMessage(payload, '流式调用失败'), payload.code);
+ }
+ const reader = res.body.getReader();
+ const decoder = new TextDecoder();
+ let buf = '';
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ buf += decoder.decode(value, { stream: true });
+ let sep: number;
+ while ((sep = buf.indexOf('\n\n')) >= 0) {
+ const block = buf.slice(0, sep);
+ buf = buf.slice(sep + 2);
+ const line = block.startsWith('data: ') ? block.slice(6) : block;
+ if (!line.trim()) continue;
+ try { onFrame(JSON.parse(line) as import('@/types').DebugStreamFrame); } catch { /* skip malformed */ }
+ }
+ }
+ }
+
+ // Upload a browser file to a server temp path. Uses XHR (not fetch) so the
+ // upload progress callback can fire — fetch can't observe request-body
+ // progress. Returns the parsed { path, size }.
+ private uploadDebugFile(
+ file: File,
+ opts?: { filename?: string; onProgress?: (fraction: number) => void; signal?: AbortSignal },
+ ): Promise {
+ return new Promise((resolve, reject) => {
+ const name = opts?.filename ?? file.name;
+ const xhr = new XMLHttpRequest();
+ xhr.open('POST', `/api/debug/upload?filename=${encodeURIComponent(name)}`);
+ if (this.currentToken) xhr.setRequestHeader('Authorization', `Bearer ${this.currentToken}`);
+ xhr.responseType = 'json';
+ xhr.upload.onprogress = (e) => {
+ if (e.lengthComputable) opts?.onProgress?.(e.loaded / e.total);
+ };
+ xhr.onload = () => {
+ if (xhr.status === 401) {
+ this.setToken(null);
+ this.onUnauthorized?.();
+ reject(new ApiError(401, '未授权'));
+ return;
+ }
+ const body = (xhr.response ?? {}) as import('@/types').DebugUploadResult;
+ if (xhr.status >= 200 && xhr.status < 300 && body.path) resolve(body);
+ else reject(new ApiError(xhr.status, body.message || '上传失败'));
+ };
+ xhr.onerror = () => reject(new ApiError(0, '上传网络错误'));
+ xhr.onabort = () => reject(new ApiError(0, '上传已取消'));
+ if (opts?.signal) {
+ if (opts.signal.aborted) { xhr.abort(); return; }
+ opts.signal.addEventListener('abort', () => xhr.abort(), { once: true });
+ }
+ xhr.send(file);
+ });
+ }
+
private openDebugStream(
onMessage: (m: DebugStreamMessage) => void,
onStatus?: (s: import('./types').StreamStatus) => void,
diff --git a/packages/webui/src/lib/api/types.ts b/packages/webui/src/lib/api/types.ts
index 699fd53f..cb80c92e 100644
--- a/packages/webui/src/lib/api/types.ts
+++ b/packages/webui/src/lib/api/types.ts
@@ -4,7 +4,9 @@ import type {
BackupImportResult,
DebugActionDoc,
DebugInvokeResult,
+ DebugStreamFrame,
DebugStreamMessage,
+ DebugUploadResult,
GlobalSettings,
HookProcessInfo,
LogEntry,
@@ -152,6 +154,21 @@ export interface ApiClient {
debug: {
actions(): Promise<{ actions: DebugActionDoc[]; categories: { category: string; count: number }[] }>;
invoke(uin: string, action: string, params: Record): Promise;
+ /** Invoke a Stream API action (or any action) and receive every frame.
+ * Resolves when the stream ends; pass a signal to cancel. */
+ invokeStream(
+ uin: string,
+ action: string,
+ params: Record,
+ onFrame: (frame: DebugStreamFrame) => void,
+ signal?: AbortSignal,
+ ): Promise;
+ /** Stream a browser file to a temp path on the server; returns the path to
+ * feed a send action. `onProgress` reports 0..1 of bytes uploaded. */
+ upload(
+ file: File,
+ opts?: { filename?: string; onProgress?: (fraction: number) => void; signal?: AbortSignal },
+ ): Promise;
/** Live merged SSE; returns an unsubscribe. */
stream(onMessage: (m: DebugStreamMessage) => void, onStatus?: (s: StreamStatus) => void): () => void;
};
diff --git a/packages/webui/src/types.ts b/packages/webui/src/types.ts
index 45dc202c..e0ee9406 100644
--- a/packages/webui/src/types.ts
+++ b/packages/webui/src/types.ts
@@ -171,7 +171,25 @@ export interface SystemSettingsResponse {
restartRequiredToApply: boolean;
}
-// Debug tools (Wave A3).
+// Debug tools (Wave A3; roles + streaming added in the console expansion).
+
+/** Semantic role of a param, mirrored from the backend's `FieldRole`. Drives
+ * which smart widget the tester renders. Unknown values degrade to the plain
+ * typed control, so this list can lag the backend without breaking. */
+export type FieldRole =
+ | 'group_id'
+ | 'user_id'
+ | 'member_id'
+ | 'message_id'
+ | 'file_id'
+ | 'file'
+ | 'image'
+ | 'record'
+ | 'video'
+ | 'duration'
+ | 'timestamp'
+ | 'face_id';
+
export interface DebugActionParam {
name: string;
type: string;
@@ -179,6 +197,8 @@ export interface DebugActionParam {
default?: unknown;
desc?: string;
values?: (string | number)[];
+ /** Semantic role (group_id / user_id / image / …) for widget selection. */
+ role?: FieldRole;
}
export interface DebugActionDoc {
name: string;
@@ -187,8 +207,33 @@ export interface DebugActionDoc {
summary?: string;
returns?: string;
readOnly: boolean;
+ /** True for Stream API actions — invoke via the streaming transport. */
+ stream?: boolean;
+ /** Cross-field constraints, for display in the tester / API browser. */
+ invariants?: string[];
params: DebugActionParam[];
}
+
+/** One frame relayed from /api/debug/invoke-stream — an OB11 envelope carrying
+ * the stream marker. Intermediate frames have `data.type` of stream/error;
+ * the terminal frame mirrors the action's final response. */
+export interface DebugStreamFrame {
+ status: string;
+ retcode?: number;
+ data?: unknown;
+ message?: string;
+ wording?: string;
+ stream?: string;
+ echo?: unknown;
+}
+
+/** Result of POST /api/debug/upload — a path on the SERVER for a send action. */
+export interface DebugUploadResult {
+ status: string;
+ path?: string;
+ size?: number;
+ message?: string;
+}
export interface DebugInvokeResult {
status: string;
retcode?: number;