From c5611ed622564905f778950d13f3c57c2758136a Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 30 Jun 2026 16:53:43 +0800 Subject: [PATCH] feat(webui): debug-console shared primitives, data layer, task manager MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Phase 3 of the debug-console expansion — the Apple-HIG foundation the new tabs build on (reusing the existing ui kit; new controls match its idiom, no browser-native widgets). API client + types: - debug.invokeStream() reads /api/debug/invoke-stream via fetch + a body reader, parsing data: SSE frames (header auth, cancellable). - debug.upload() streams a file via XHR for real upload progress. - DebugActionParam.role, DebugActionDoc.stream/invariants, FieldRole, DebugStreamFrame, DebugUploadResult. Primitives: - Tabs (sliding indicator + roving tabindex), Picker (searchable, windowed combobox with a raw-value escape hatch), JsonTree (collapsible response viewer, image-url preview, copy w/ http fallback, node cap), FileSource (URL / server-path / browser-upload tri-state), FaceGrid. Infra: - DebugTaskProvider + TaskBadge: app-level registry of in-flight upload/ stream tasks so they survive in-app tab switches, with a global progress chip and a beforeunload guard; eviction never drops a running task. Wired into App. - use-debug-contacts: lazy friend/group/member data layer, shared module cache + localStorage (version-stamped, avatars stripped to dodge quota) + TTL + request-id race guard, degrading to raw input on error. Adversarially reviewed (no automated component tests): virtualization math and SSE framing verified correct; fixed the stale-contacts-on-switch member-selection hazard, the quota-kills-persistence issue, and several low UX edges (active-row clamp, filter scroll reset, copy fallback). --- packages/webui/src/App.tsx | 7 +- .../src/components/debug/file-source.tsx | 122 ++++++++++ .../webui/src/components/debug/task-badge.tsx | 89 +++++++ .../webui/src/components/ui/face-grid.tsx | 71 ++++++ .../webui/src/components/ui/json-tree.tsx | 152 ++++++++++++ packages/webui/src/components/ui/picker.tsx | 227 ++++++++++++++++++ packages/webui/src/components/ui/tabs.tsx | 89 +++++++ .../webui/src/contexts/DebugTaskContext.tsx | 110 +++++++++ .../webui/src/hooks/use-debug-contacts.ts | 174 ++++++++++++++ packages/webui/src/lib/api/client.ts | 85 +++++++ packages/webui/src/lib/api/types.ts | 17 ++ packages/webui/src/types.ts | 47 +++- 12 files changed, 1188 insertions(+), 2 deletions(-) create mode 100644 packages/webui/src/components/debug/file-source.tsx create mode 100644 packages/webui/src/components/debug/task-badge.tsx create mode 100644 packages/webui/src/components/ui/face-grid.tsx create mode 100644 packages/webui/src/components/ui/json-tree.tsx create mode 100644 packages/webui/src/components/ui/picker.tsx create mode 100644 packages/webui/src/components/ui/tabs.tsx create mode 100644 packages/webui/src/contexts/DebugTaskContext.tsx create mode 100644 packages/webui/src/hooks/use-debug-contacts.ts diff --git a/packages/webui/src/App.tsx b/packages/webui/src/App.tsx index 7e3ade0b..f1a380b3 100644 --- a/packages/webui/src/App.tsx +++ b/packages/webui/src/App.tsx @@ -7,6 +7,8 @@ import { LoginPage } from '@/components/pages/login-page'; import { ChangePasswordPage } from '@/components/pages/change-password-page'; import { ConsentPage } from '@/components/pages/consent-page'; import { ApiProvider, createApiClient, useApi, type ApiClient } from '@/lib/api'; +import { DebugTaskProvider } from '@/contexts/DebugTaskContext'; +import { TaskBadge } from '@/components/debug/task-badge'; import type { AgreementsPayload } from '@/lib/api/types'; import { appRouter } from '@/router'; @@ -132,7 +134,10 @@ function AuthBoundary() { return ( - {view} + + {view} + + ); } diff --git a/packages/webui/src/components/debug/file-source.tsx b/packages/webui/src/components/debug/file-source.tsx new file mode 100644 index 00000000..a6a7b18b --- /dev/null +++ b/packages/webui/src/components/debug/file-source.tsx @@ -0,0 +1,122 @@ +// FileSource — the control behind a file/image/record/video param. The bot runs +// on the SERVER, so a browser-local path is meaningless to it; this offers three +// honest sources: a URL the bot fetches, a path that already exists on the +// server, or a browser upload that we stream to a server temp path (and then +// feed that path to the action). Upload progress flows through the app-level +// task registry so it survives tab switches. +import { useRef, useState } from 'react'; +import { FileUp, Link2, Loader2, ServerCog, X } from 'lucide-react'; +import { Input } from '@/components/ui/input'; +import { useApi } from '@/lib/api'; +import { useDebugTasks } from '@/contexts/DebugTaskContext'; +import { cn } from '@/lib/utils'; +import type { FieldRole } from '@/types'; + +type Mode = 'url' | 'server' | 'upload'; + +const ACCEPT: Partial> = { + image: 'image/*', + record: 'audio/*', + video: 'video/*', +}; + +function Seg({ active, onClick, icon, label }: { active: boolean; onClick: () => void; icon: React.ReactNode; label: string }) { + return ( + + ); +} + +export function FileSource({ value, onChange, role, placeholder }: { + value: string; + onChange: (v: string) => void; + role?: FieldRole; + placeholder?: string; +}) { + const api = useApi(); + const { start, update, finish } = useDebugTasks(); + const [mode, setMode] = useState('url'); + const [uploading, setUploading] = useState(false); + const [uploadName, setUploadName] = useState(null); + const [uploadErr, setUploadErr] = useState(null); + const inputRef = useRef(null); + const accept = role ? ACCEPT[role] : undefined; + + const doUpload = async (file: File) => { + setUploadErr(null); + setUploadName(file.name); + setUploading(true); + const ac = new AbortController(); + const taskId = start({ kind: 'upload', label: `上传 ${file.name}`, progress: 0, cancel: () => ac.abort() }); + try { + const res = await api.debug.upload(file, { + signal: ac.signal, + onProgress: (f) => update(taskId, { progress: f }), + }); + if (!res.path) throw new Error(res.message || '上传失败'); + onChange(res.path); + finish(taskId, 'done', res.path); + } catch (e) { + const msg = e instanceof Error ? e.message : '上传失败'; + setUploadErr(msg); + finish(taskId, ac.signal.aborted ? 'canceled' : 'failed', msg); + } finally { + setUploading(false); + } + }; + + return ( +
+
+ setMode('url')} icon={} label="URL" /> + setMode('server')} icon={} label="服务器路径" /> + setMode('upload')} icon={} label="上传" /> +
+ + {mode === 'url' && ( + onChange(e.target.value)} placeholder={placeholder || 'https://…'} /> + )} + + {mode === 'server' && ( +
+ onChange(e.target.value)} placeholder="/path/on/server/file.jpg" /> + 这是 运行 bot 的服务器 上的路径,不是你本机的。 +
+ )} + + {mode === 'upload' && ( +
+ { const f = e.target.files?.[0]; if (f) void doUpload(f); e.target.value = ''; }} + /> + + {value && uploadName && !uploading && ( +
+ 已上传:{uploadName} + {value} + +
+ )} + {uploadErr && {uploadErr}} +
+ )} +
+ ); +} diff --git a/packages/webui/src/components/debug/task-badge.tsx b/packages/webui/src/components/debug/task-badge.tsx new file mode 100644 index 00000000..481a88eb --- /dev/null +++ b/packages/webui/src/components/debug/task-badge.tsx @@ -0,0 +1,89 @@ +// TaskBadge — the app-wide floating indicator for in-flight debug tasks. Sits +// bottom-right on every page so a streaming upload/download stays visible after +// you switch tabs. Collapsed: a chip with a ring-progress + count. Expanded: a +// list with per-task progress, cancel (running) / dismiss (finished). Renders +// nothing when there are no tasks at all. +import { useState } from 'react'; +import { AnimatePresence, motion } from 'motion/react'; +import { CheckCircle2, Loader2, X, XCircle } from 'lucide-react'; +import { useDebugTasks, useRunningTaskSummary, type DebugTask } from '@/contexts/DebugTaskContext'; +import { cn } from '@/lib/utils'; + +function StatusIcon({ status }: { status: DebugTask['status'] }) { + if (status === 'running') return ; + if (status === 'done') return ; + return ; +} + +function Row({ task, onDismiss }: { task: DebugTask; onDismiss: () => void }) { + const pct = typeof task.progress === 'number' ? Math.round(task.progress * 100) : null; + return ( +
+
+ + {task.label} + {task.status === 'running' && task.cancel + ? + : } +
+ {task.status === 'running' && ( +
+
+
+ )} + {task.detail && task.status !== 'running' && ( + {task.detail} + )} +
+ ); +} + +export function TaskBadge() { + const { tasks, remove, clearFinished } = useDebugTasks(); + const { count, progress } = useRunningTaskSummary(); + const [open, setOpen] = useState(false); + + if (tasks.length === 0) return null; + + const ringPct = progress === null ? null : Math.round(progress * 100); + + return ( +
+ + {open && ( + +
+ 调试任务 + {tasks.some((t) => t.status !== 'running') && ( + + )} +
+
+ {tasks.map((t) => remove(t.id)} />)} +
+
+ )} +
+ + +
+ ); +} diff --git a/packages/webui/src/components/ui/face-grid.tsx b/packages/webui/src/components/ui/face-grid.tsx new file mode 100644 index 00000000..38c07636 --- /dev/null +++ b/packages/webui/src/components/ui/face-grid.tsx @@ -0,0 +1,71 @@ +// FaceGrid — pick a QQ classic face id. Renders the classic face sprites from +// QQ's long-standing public CDN; any id whose image 404s hides itself, so a +// curated-but-imperfect id list still looks clean. A manual id box is the +// escape hatch for faces outside the classic range. +import { useMemo, useState } from 'react'; +import { Input } from '@/components/ui/input'; +import { cn } from '@/lib/utils'; + +// Classic QQ face ids that resolve on the gtimg CDN. Curated to avoid the gaps +// in the 0..170 range (deprecated / never-existed ids) that would 404. +const CLASSIC_FACE_IDS: number[] = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 19, 20, 21, 22, + 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 41, 42, + 43, 46, 49, 53, 60, 63, 64, 66, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, + 85, 86, 87, 88, 89, 96, 97, 98, 99, 100, 101, 102, 103, 104, 106, 109, 111, + 116, 118, 120, 122, 123, 124, 125, 129, 144, 147, 171, 173, 174, 175, 176, + 179, 180, 181, 182, 183, 201, 203, 212, 214, 219, 222, 227, +]; + +const faceUrl = (id: number) => `https://qzonestyle.gtimg.cn/qzone/em/e${id}.png`; + +export function FaceGrid({ value, onChange }: { value: string; onChange: (v: string) => void }) { + const [q, setQ] = useState(''); + const [broken, setBroken] = useState>(() => new Set()); + + const ids = useMemo(() => { + const qq = q.trim(); + const base = CLASSIC_FACE_IDS.filter((id) => !broken.has(id)); + if (!qq) return base; + return base.filter((id) => String(id).includes(qq)); + }, [q, broken]); + + const selected = value.trim(); + + return ( +
+
+ setQ(e.target.value)} placeholder="按 id 过滤…" className="h-8 flex-1" /> + onChange(e.target.value.replace(/[^\d]/g, ''))} + placeholder="id" + inputMode="numeric" + className="h-8 w-20 text-center font-mono" + aria-label="表情 id" + /> +
+
+ {ids.map((id) => ( + + ))} + {ids.length === 0 && 无匹配表情} +
+
+ ); +} diff --git a/packages/webui/src/components/ui/json-tree.tsx b/packages/webui/src/components/ui/json-tree.tsx new file mode 100644 index 00000000..36a671f2 --- /dev/null +++ b/packages/webui/src/components/ui/json-tree.tsx @@ -0,0 +1,152 @@ +// JsonTree — a calm, collapsible JSON viewer for action responses / event +// payloads. Replaces a raw
 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;