feat(webui): debug-console shared primitives, data layer, task manager
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:<json> 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).
This commit is contained in:
12 files changed
+1188
-2
No files matched your search
@@ -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 (
|
||||
<ApiProvider client={client}>
|
||||
<TooltipProvider delayDuration={150}>{view}</TooltipProvider>
|
||||
<DebugTaskProvider>
|
||||
<TooltipProvider delayDuration={150}>{view}</TooltipProvider>
|
||||
<TaskBadge />
|
||||
</DebugTaskProvider>
|
||||
</ApiProvider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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<Record<FieldRole, string>> = {
|
||||
image: 'image/*',
|
||||
record: 'audio/*',
|
||||
video: 'video/*',
|
||||
};
|
||||
|
||||
function Seg({ active, onClick, icon, label }: { active: boolean; onClick: () => void; icon: React.ReactNode; label: string }) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
className={cn('inline-flex items-center gap-1.5 rounded-lg px-2.5 py-1 text-xs font-medium transition-colors',
|
||||
active ? 'bg-card text-foreground shadow-sm ring-1 ring-border/60' : 'text-muted-foreground hover:text-foreground')}
|
||||
>
|
||||
{icon}{label}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
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<Mode>('url');
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [uploadName, setUploadName] = useState<string | null>(null);
|
||||
const [uploadErr, setUploadErr] = useState<string | null>(null);
|
||||
const inputRef = useRef<HTMLInputElement>(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 (
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="inline-flex w-fit gap-0.5 rounded-xl bg-muted/70 p-0.5">
|
||||
<Seg active={mode === 'url'} onClick={() => setMode('url')} icon={<Link2 className="h-3.5 w-3.5" />} label="URL" />
|
||||
<Seg active={mode === 'server'} onClick={() => setMode('server')} icon={<ServerCog className="h-3.5 w-3.5" />} label="服务器路径" />
|
||||
<Seg active={mode === 'upload'} onClick={() => setMode('upload')} icon={<FileUp className="h-3.5 w-3.5" />} label="上传" />
|
||||
</div>
|
||||
|
||||
{mode === 'url' && (
|
||||
<Input value={value} onChange={(e) => onChange(e.target.value)} placeholder={placeholder || 'https://…'} />
|
||||
)}
|
||||
|
||||
{mode === 'server' && (
|
||||
<div className="flex flex-col gap-1">
|
||||
<Input value={value} onChange={(e) => onChange(e.target.value)} placeholder="/path/on/server/file.jpg" />
|
||||
<span className="text-[11px] text-muted-foreground">这是 <strong>运行 bot 的服务器</strong> 上的路径,不是你本机的。</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{mode === 'upload' && (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="file"
|
||||
accept={accept}
|
||||
className="hidden"
|
||||
onChange={(e) => { const f = e.target.files?.[0]; if (f) void doUpload(f); e.target.value = ''; }}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
disabled={uploading}
|
||||
onClick={() => inputRef.current?.click()}
|
||||
className={cn('flex items-center justify-center gap-2 rounded-xl border border-dashed border-border/70 px-3 py-3 text-sm text-muted-foreground transition-colors hover:border-primary/50 hover:text-foreground disabled:opacity-60')}
|
||||
>
|
||||
{uploading ? <><Loader2 className="h-4 w-4 animate-spin" /> 上传中…</> : <><FileUp className="h-4 w-4" /> 选择文件上传到服务器</>}
|
||||
</button>
|
||||
{value && uploadName && !uploading && (
|
||||
<div className="flex items-center gap-2 rounded-lg bg-muted/40 px-2.5 py-1.5 text-[11px]">
|
||||
<span className="truncate text-muted-foreground">已上传:{uploadName}</span>
|
||||
<code className="ml-auto max-w-[55%] truncate font-mono text-muted-foreground/80" title={value}>{value}</code>
|
||||
<button type="button" onClick={() => { onChange(''); setUploadName(null); }} className="shrink-0 text-muted-foreground hover:text-destructive"><X className="h-3.5 w-3.5" /></button>
|
||||
</div>
|
||||
)}
|
||||
{uploadErr && <span className="text-[11px] text-destructive">{uploadErr}</span>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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 <Loader2 className="h-3.5 w-3.5 animate-spin text-primary" />;
|
||||
if (status === 'done') return <CheckCircle2 className="h-3.5 w-3.5 text-success" />;
|
||||
return <XCircle className="h-3.5 w-3.5 text-destructive" />;
|
||||
}
|
||||
|
||||
function Row({ task, onDismiss }: { task: DebugTask; onDismiss: () => void }) {
|
||||
const pct = typeof task.progress === 'number' ? Math.round(task.progress * 100) : null;
|
||||
return (
|
||||
<div className="flex flex-col gap-1 rounded-lg px-2.5 py-2 hover:bg-muted/50">
|
||||
<div className="flex items-center gap-2 text-xs">
|
||||
<StatusIcon status={task.status} />
|
||||
<span className="min-w-0 flex-1 truncate text-foreground/90">{task.label}</span>
|
||||
{task.status === 'running' && task.cancel
|
||||
? <button type="button" onClick={task.cancel} className="text-muted-foreground hover:text-destructive" title="取消"><X className="h-3.5 w-3.5" /></button>
|
||||
: <button type="button" onClick={onDismiss} className="text-muted-foreground hover:text-foreground" title="移除"><X className="h-3.5 w-3.5" /></button>}
|
||||
</div>
|
||||
{task.status === 'running' && (
|
||||
<div className="h-1 overflow-hidden rounded-full bg-muted">
|
||||
<div
|
||||
className={cn('h-full rounded-full bg-primary transition-all', pct === null && 'animate-pulse')}
|
||||
style={{ width: pct === null ? '40%' : `${pct}%` }}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{task.detail && task.status !== 'running' && (
|
||||
<span className="truncate text-[10px] text-muted-foreground" title={task.detail}>{task.detail}</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<div className="fixed bottom-4 right-4 z-[60] flex flex-col items-end gap-2">
|
||||
<AnimatePresence>
|
||||
{open && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 8, scale: 0.97 }}
|
||||
animate={{ opacity: 1, y: 0, scale: 1 }}
|
||||
exit={{ opacity: 0, y: 8, scale: 0.97 }}
|
||||
transition={{ type: 'spring', stiffness: 480, damping: 36 }}
|
||||
className="w-72 overflow-hidden rounded-2xl border border-border/60 bg-popover shadow-xl ring-1 ring-black/5"
|
||||
>
|
||||
<div className="flex items-center justify-between border-b border-border/60 px-3 py-2">
|
||||
<span className="text-xs font-semibold">调试任务</span>
|
||||
{tasks.some((t) => t.status !== 'running') && (
|
||||
<button type="button" onClick={clearFinished} className="text-[11px] text-muted-foreground hover:text-foreground">清除已完成</button>
|
||||
)}
|
||||
</div>
|
||||
<div className="max-h-72 overflow-auto p-1.5">
|
||||
{tasks.map((t) => <Row key={t.id} task={t} onDismiss={() => remove(t.id)} />)}
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
className="flex items-center gap-2 rounded-full border border-border/60 bg-card/90 px-3 py-2 text-xs font-medium shadow-lg ring-1 ring-black/5 backdrop-blur transition-colors hover:bg-card"
|
||||
>
|
||||
{count > 0 ? <Loader2 className="h-4 w-4 animate-spin text-primary" /> : <CheckCircle2 className="h-4 w-4 text-success" />}
|
||||
{count > 0
|
||||
? <span>{count} 个任务进行中{ringPct !== null ? ` · ${ringPct}%` : ''}</span>
|
||||
: <span className="text-muted-foreground">任务完成</span>}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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<Set<number>>(() => 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 (
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Input value={q} onChange={(e) => setQ(e.target.value)} placeholder="按 id 过滤…" className="h-8 flex-1" />
|
||||
<Input
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value.replace(/[^\d]/g, ''))}
|
||||
placeholder="id"
|
||||
inputMode="numeric"
|
||||
className="h-8 w-20 text-center font-mono"
|
||||
aria-label="表情 id"
|
||||
/>
|
||||
</div>
|
||||
<div className="grid max-h-48 grid-cols-8 gap-1 overflow-auto rounded-xl border border-border/60 bg-muted/30 p-2 sm:grid-cols-10">
|
||||
{ids.map((id) => (
|
||||
<button
|
||||
key={id}
|
||||
type="button"
|
||||
title={`face ${id}`}
|
||||
onClick={() => onChange(String(id))}
|
||||
className={cn('flex aspect-square items-center justify-center rounded-lg p-1 transition-colors hover:bg-accent',
|
||||
selected === String(id) && 'bg-primary/15 ring-1 ring-primary/50')}
|
||||
>
|
||||
<img
|
||||
src={faceUrl(id)}
|
||||
alt={`face ${id}`}
|
||||
className="h-full w-full object-contain"
|
||||
loading="lazy"
|
||||
onError={() => setBroken((prev) => { const n = new Set(prev); n.add(id); return n; })}
|
||||
/>
|
||||
</button>
|
||||
))}
|
||||
{ids.length === 0 && <span className="col-span-full py-4 text-center text-xs text-muted-foreground">无匹配表情</span>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
// JsonTree — a calm, collapsible JSON viewer for action responses / event
|
||||
// payloads. Replaces a raw <pre> 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 <span className="text-muted-foreground/60">{children}</span>;
|
||||
}
|
||||
|
||||
function Leaf({ value }: { value: string | number | boolean | null }) {
|
||||
const [showImg, setShowImg] = useState(false);
|
||||
if (value === null) return <span className="text-muted-foreground/70">null</span>;
|
||||
if (typeof value === 'number') return <span className="text-sky-600 dark:text-sky-400 tabular-nums">{value}</span>;
|
||||
if (typeof value === 'boolean') return <span className="text-violet-600 dark:text-violet-400">{String(value)}</span>;
|
||||
// string
|
||||
const img = isImageUrl(value);
|
||||
return (
|
||||
<span className="break-all">
|
||||
<span className="text-emerald-700 dark:text-emerald-400">"{value}"</span>
|
||||
{img && (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowImg((v) => !v)}
|
||||
className="ml-1.5 inline-flex items-center gap-0.5 rounded-md bg-muted/70 px-1 py-0.5 align-middle text-[10px] text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<ImageIcon className="h-3 w-3" /> {showImg ? '隐藏' : '预览'}
|
||||
</button>
|
||||
{showImg && (
|
||||
<span className="mt-1.5 block">
|
||||
<img src={value} alt="预览" className="max-h-48 rounded-lg border border-border/60" loading="lazy" />
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
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 ? <><span className="text-foreground/80">{k}</span><Punct>: </Punct></> : null;
|
||||
|
||||
if (!isObj) {
|
||||
return (
|
||||
<div className="flex gap-1 py-px pl-[1.1rem]" style={{ paddingLeft: `${depth * 0.9 + 1.1}rem` }}>
|
||||
{keyLabel}
|
||||
<Leaf value={value as string | number | boolean | null} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const entries = Array.isArray(value)
|
||||
? value.map((v, i) => [String(i), v] as const)
|
||||
: Object.entries(value as Record<string, unknown>);
|
||||
const openB = Array.isArray(value) ? '[' : '{';
|
||||
const closeB = Array.isArray(value) ? ']' : '}';
|
||||
const shown = open ? Math.min(entries.length, limit) : 0;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
className="flex w-full items-center gap-1 py-px text-left hover:bg-muted/40"
|
||||
style={{ paddingLeft: `${depth * 0.9}rem` }}
|
||||
>
|
||||
<ChevronRight className={cn('h-3 w-3 shrink-0 text-muted-foreground/60 transition-transform', open && 'rotate-90')} />
|
||||
{keyLabel}
|
||||
<Punct>{openB}</Punct>
|
||||
{!open && <span className="text-muted-foreground/50">{entries.length}{Array.isArray(value) ? '' : ' keys'}<Punct>{closeB}</Punct></span>}
|
||||
</button>
|
||||
{open && (
|
||||
<>
|
||||
{entries.slice(0, shown).map(([ck, cv]) => (
|
||||
<Node key={ck} k={Array.isArray(value) ? undefined : ck} value={cv} depth={depth + 1} defaultOpen={depth < 1} />
|
||||
))}
|
||||
{entries.length > shown && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setLimit((l) => l + 500)}
|
||||
className="py-0.5 text-[11px] text-primary hover:underline"
|
||||
style={{ paddingLeft: `${depth * 0.9 + 1.1}rem` }}
|
||||
>
|
||||
还有 {entries.length - shown} 项,点击展开…
|
||||
</button>
|
||||
)}
|
||||
<div style={{ paddingLeft: `${depth * 0.9 + 0.9}rem` }}><Punct>{closeB}</Punct></div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<div className={cn('relative rounded-xl border border-border/60 bg-muted/30', className)}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={copy}
|
||||
title="复制 JSON"
|
||||
className="absolute right-2 top-2 z-10 inline-flex items-center gap-1 rounded-md bg-card/80 px-1.5 py-1 text-[11px] text-muted-foreground shadow-sm ring-1 ring-border/50 backdrop-blur hover:text-foreground"
|
||||
>
|
||||
{copied ? <Check className="h-3 w-3 text-success" /> : <Copy className="h-3 w-3" />}
|
||||
{copied ? '已复制' : '复制'}
|
||||
</button>
|
||||
<div className="overflow-auto p-3 font-mono text-[11.5px] leading-relaxed" style={{ maxHeight }}>
|
||||
<Node value={data} depth={0} defaultOpen />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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<PickerOption>;
|
||||
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<HTMLDivElement>(null);
|
||||
const listRef = useRef<HTMLDivElement>(null);
|
||||
const searchRef = useRef<HTMLInputElement>(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 (
|
||||
<div ref={rootRef} className={cn('relative', className)} onKeyDown={onKeyDown}>
|
||||
<button
|
||||
type="button"
|
||||
disabled={disabled}
|
||||
aria-label={ariaLabel}
|
||||
aria-haspopup="listbox"
|
||||
aria-expanded={open}
|
||||
onClick={() => !disabled && setOpen((v) => !v)}
|
||||
className={cn(
|
||||
'flex h-9 w-full items-center gap-2 rounded-md border border-border bg-transparent px-3 text-sm outline-none transition-colors',
|
||||
'focus-visible:ring-[3px] focus-visible:ring-ring/40 focus-visible:border-ring disabled:opacity-50',
|
||||
!selected && !value && 'text-muted-foreground',
|
||||
)}
|
||||
>
|
||||
{selected?.avatar && <img src={selected.avatar} alt="" className="h-5 w-5 shrink-0 rounded-full" />}
|
||||
<span className="min-w-0 flex-1 truncate text-left">
|
||||
{selected ? selected.label : value || placeholder}
|
||||
{selected?.sub && <span className="ml-1.5 text-xs text-muted-foreground tabular-nums">{selected.sub}</span>}
|
||||
</span>
|
||||
<ChevronDown className={cn('h-4 w-4 shrink-0 text-muted-foreground transition-transform', open && 'rotate-180')} />
|
||||
</button>
|
||||
|
||||
<AnimatePresence>
|
||||
{open && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: -4, scale: 0.98 }}
|
||||
animate={{ opacity: 1, y: 0, scale: 1 }}
|
||||
exit={{ opacity: 0, y: -4, scale: 0.98 }}
|
||||
transition={{ type: 'spring', stiffness: 500, damping: 38 }}
|
||||
className="absolute z-50 mt-1.5 w-full overflow-hidden rounded-xl border border-border/60 bg-popover shadow-lg ring-1 ring-black/5"
|
||||
>
|
||||
<div className="flex items-center gap-2 border-b border-border/60 px-2.5 py-2">
|
||||
<Search className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
|
||||
<input
|
||||
ref={searchRef}
|
||||
value={query}
|
||||
onChange={(e) => {
|
||||
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 && (
|
||||
<button type="button" title="刷新" onClick={onRefresh}
|
||||
className="shrink-0 text-muted-foreground hover:text-foreground">
|
||||
<RefreshCw className={cn('h-3.5 w-3.5', loading && 'animate-spin')} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{loading && options.length === 0 ? (
|
||||
<div className="flex items-center justify-center gap-2 py-8 text-sm text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 animate-spin" /> 加载中…
|
||||
</div>
|
||||
) : error ? (
|
||||
<div className="px-3 py-6 text-center text-xs text-muted-foreground">
|
||||
<p className="text-destructive">{error}</p>
|
||||
<p className="mt-1">可直接在上方输入号码后回车使用</p>
|
||||
</div>
|
||||
) : totalRows === 0 ? (
|
||||
<div className="px-3 py-6 text-center text-xs text-muted-foreground">无匹配项{query && ';输入完整号码可直接使用'}</div>
|
||||
) : (
|
||||
<div
|
||||
ref={listRef}
|
||||
role="listbox"
|
||||
onScroll={(e) => setScrollTop((e.target as HTMLDivElement).scrollTop)}
|
||||
className="overflow-auto"
|
||||
style={{ height: viewH }}
|
||||
>
|
||||
<div style={{ height: totalRows * ROW_H, position: 'relative' }}>
|
||||
{rows.map(({ idx, opt }) => (
|
||||
<div
|
||||
key={opt ? opt.value : `__raw-${idx}`}
|
||||
role="option"
|
||||
aria-selected={idx === active}
|
||||
onMouseEnter={() => 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
|
||||
? <img src={opt.avatar} alt="" className="h-7 w-7 shrink-0 rounded-full" />
|
||||
: <span className="h-7 w-7 shrink-0 rounded-full bg-muted" />}
|
||||
<span className="min-w-0 flex-1 truncate text-sm">{opt.label}</span>
|
||||
{opt.sub && <span className="shrink-0 font-mono text-[11px] text-muted-foreground tabular-nums">{opt.sub}</span>}
|
||||
</>
|
||||
) : (
|
||||
<span className="text-sm">使用 <span className="font-mono text-primary">{rawRow}</span></span>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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<T extends string> {
|
||||
value: T;
|
||||
label: ReactNode;
|
||||
/** Optional leading icon (already sized by the caller, ~16px). */
|
||||
icon?: ReactNode;
|
||||
/** Optional trailing count / badge. */
|
||||
badge?: ReactNode;
|
||||
}
|
||||
|
||||
interface TabsProps<T extends string> {
|
||||
value: T;
|
||||
onChange: (v: T) => void;
|
||||
items: ReadonlyArray<TabItem<T>>;
|
||||
className?: string;
|
||||
'aria-label'?: string;
|
||||
}
|
||||
|
||||
export function Tabs<T extends string>({ value, onChange, items, className, ...rest }: TabsProps<T>) {
|
||||
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 (
|
||||
<div
|
||||
role="tablist"
|
||||
aria-label={rest['aria-label']}
|
||||
className={cn('relative flex items-center gap-1 overflow-x-auto', className)}
|
||||
>
|
||||
{items.map((it, i) => {
|
||||
const active = it.value === value;
|
||||
return (
|
||||
<button
|
||||
key={it.value}
|
||||
ref={(el) => { refs.current[i] = el; }}
|
||||
role="tab"
|
||||
type="button"
|
||||
aria-selected={active}
|
||||
tabIndex={active ? 0 : -1}
|
||||
onClick={() => onChange(it.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'ArrowRight') { e.preventDefault(); move(i, 1); }
|
||||
else if (e.key === 'ArrowLeft') { e.preventDefault(); move(i, -1); }
|
||||
else if (e.key === 'Home') { e.preventDefault(); move(i, 'home'); }
|
||||
else if (e.key === 'End') { e.preventDefault(); move(i, 'end'); }
|
||||
}}
|
||||
className={cn(
|
||||
'relative z-10 inline-flex shrink-0 items-center gap-2 rounded-xl px-3.5 py-2 text-sm font-medium outline-none transition-colors',
|
||||
'focus-visible:ring-[3px] focus-visible:ring-ring/40',
|
||||
active ? 'text-foreground' : 'text-muted-foreground hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
{active && (
|
||||
<motion.span
|
||||
layoutId={`tabs-${layoutId}`}
|
||||
transition={{ type: 'spring', stiffness: 500, damping: 40 }}
|
||||
className="absolute inset-0 -z-10 rounded-xl bg-card shadow-sm ring-1 ring-border/60"
|
||||
/>
|
||||
)}
|
||||
{it.icon}
|
||||
<span>{it.label}</span>
|
||||
{it.badge != null && (
|
||||
<span className={cn('rounded-full px-1.5 text-[11px] tabular-nums',
|
||||
active ? 'bg-primary/12 text-primary' : 'bg-muted text-muted-foreground')}>
|
||||
{it.badge}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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<DebugTask, 'id' | 'status' | 'startedAt'> & { id?: string }) => string;
|
||||
update: (id: string, patch: Partial<Omit<DebugTask, 'id'>>) => void;
|
||||
/** Mark terminal (done/failed/canceled) and stamp endedAt. */
|
||||
finish: (id: string, status: Exclude<DebugTaskStatus, 'running'>, detail?: string) => void;
|
||||
remove: (id: string) => void;
|
||||
clearFinished: () => void;
|
||||
}
|
||||
|
||||
const Ctx = createContext<DebugTaskContextValue | null>(null);
|
||||
|
||||
let seq = 0;
|
||||
const nextId = () => `dt-${Date.now().toString(36)}-${(seq++).toString(36)}`;
|
||||
|
||||
export function DebugTaskProvider({ children }: { children: ReactNode }) {
|
||||
const [tasks, setTasks] = useState<DebugTask[]>([]);
|
||||
|
||||
const start = useCallback<DebugTaskContextValue['start']>((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<DebugTaskContextValue['update']>((id, patch) => {
|
||||
setTasks((prev) => prev.map((t) => (t.id === id ? { ...t, ...patch } : t)));
|
||||
}, []);
|
||||
|
||||
const finish = useCallback<DebugTaskContextValue['finish']>((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<DebugTaskContextValue['remove']>((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<DebugTaskContextValue>(
|
||||
() => ({ tasks, start, update, finish, remove, clearFinished }),
|
||||
[tasks, start, update, finish, remove, clearFinished],
|
||||
);
|
||||
return <Ctx.Provider value={value}>{children}</Ctx.Provider>;
|
||||
}
|
||||
|
||||
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]);
|
||||
}
|
||||
@@ -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<string, Entry>();
|
||||
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<string, Entry>;
|
||||
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<string, Entry> = {};
|
||||
// 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<string, unknown>) => PickerOption | null;
|
||||
|
||||
interface ListState {
|
||||
items: PickerOption[];
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
refresh: () => void;
|
||||
}
|
||||
|
||||
function useContactList(cacheKey: string | null, action: string, uin: string, params: Record<string, unknown>, parse: ParseRow): ListState {
|
||||
const api = useApi();
|
||||
hydrate();
|
||||
const [items, setItems] = useState<PickerOption[]>(() => (cacheKey && mem.get(cacheKey)?.items) || []);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(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<string, unknown>[]) : [];
|
||||
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) };
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -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<string, unknown>) =>
|
||||
this.postJson<DebugInvokeResult>('/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: <json>\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<string, unknown>,
|
||||
onFrame: (frame: import('@/types').DebugStreamFrame) => void,
|
||||
signal?: AbortSignal,
|
||||
): Promise<void> {
|
||||
const headers: Record<string, string> = { '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<ErrorPayload>(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<import('@/types').DebugUploadResult> {
|
||||
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,
|
||||
|
||||
@@ -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<string, unknown>): Promise<DebugInvokeResult>;
|
||||
/** 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<string, unknown>,
|
||||
onFrame: (frame: DebugStreamFrame) => void,
|
||||
signal?: AbortSignal,
|
||||
): Promise<void>;
|
||||
/** 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<DebugUploadResult>;
|
||||
/** Live merged SSE; returns an unsubscribe. */
|
||||
stream(onMessage: (m: DebugStreamMessage) => void, onStatus?: (s: StreamStatus) => void): () => void;
|
||||
};
|
||||
|
||||
@@ -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;
|
||||
|
||||
Reference in new issue
Block a user