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
@@ -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>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user