refactor: clarify async state and subscription ownership

This commit is contained in:
手瓜一十雪 committed 2026-10-18 12:42:54 +08:00
1 parent f6ca9d5f65
commit c54aeffc77
20 files changed
+698 -316

No files matched your search

@@ -139,9 +139,7 @@ export function FileSource({
onChange={(e) => onChange(e.target.value)}
placeholder="/path/on/server/file.jpg"
/>
<span className="text-xs text-muted-foreground">
这是 <strong>运行 bot 的服务器</strong> 上的路径,不是你本机的。
</span>
<span className="text-xs text-muted-foreground">使用服务器上的文件路径</span>
</div>
)}
@@ -188,7 +186,7 @@ export function FileSource({
</>
) : (
<>
<FileUp className="h-4 w-4" /> 选择或拖入文件上传到服务器
<FileUp className="h-4 w-4" /> 选择或拖入文件
</>
)}
</label>
@@ -1,8 +1,3 @@
// 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';
@@ -37,7 +32,7 @@ function Row({ task, onDismiss }: { task: DebugTask; onDismiss: () => void }) {
>
<X className="h-3.5 w-3.5" />
</button>
) : (
) : task.status !== 'running' ? (
<button
type="button"
onClick={onDismiss}
@@ -46,7 +41,7 @@ function Row({ task, onDismiss }: { task: DebugTask; onDismiss: () => void }) {
>
<X className="h-3.5 w-3.5" />
</button>
)}
) : null}
</div>
{task.status === 'running' && (
<div className="h-1 overflow-hidden rounded-full bg-muted">
@@ -129,7 +124,7 @@ export function TaskBadge() {
)}
{count > 0 ? (
<span>
{count} 个任务进行中{ringPct !== null ? ` · ${ringPct}%` : ''}
{count} 个任务{ringPct !== null ? ` · ${ringPct}%` : ''}
</span>
) : (
<span className="text-muted-foreground">任务完成</span>
@@ -1,40 +1,28 @@
// 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,
useReducer,
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;
}
import {
debugTasksReducer,
type DebugTask,
type DebugTaskStatus,
type DebugTaskUpdate,
} from '@/lib/debug-tasks';
export type { DebugTask, DebugTaskStatus, DebugTaskKind } from '@/lib/debug-tasks';
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;
start: (
task: Omit<DebugTask, 'id' | 'status' | 'startedAt' | 'endedAt'> & { id?: string },
) => string;
update: (id: string, patch: DebugTaskUpdate) => void;
/** Mark terminal (done/failed/canceled) and stamp endedAt. */
finish: (id: string, status: Exclude<DebugTaskStatus, 'running'>, detail?: string) => void;
remove: (id: string) => void;
@@ -47,60 +35,32 @@ 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 [tasks, dispatch] = useReducer(debugTasksReducer, []);
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));
});
dispatch({ type: 'start', task: { ...t, id, status: 'running', startedAt: Date.now() } });
return id;
}, []);
const update = useCallback<DebugTaskContextValue['update']>((id, patch) => {
setTasks((prev) => prev.map((t) => (t.id === id ? { ...t, ...patch } : t)));
dispatch({ type: 'update', id, patch });
}, []);
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,
),
);
dispatch({ type: 'finish', id, status, detail, endedAt: Date.now() });
}, []);
const remove = useCallback<DebugTaskContextValue['remove']>((id) => {
setTasks((prev) => prev.filter((t) => t.id !== id));
dispatch({ type: 'remove', id });
}, []);
const clearFinished = useCallback(() => {
setTasks((prev) => prev.filter((t) => t.status === 'running'));
dispatch({ type: 'clearFinished' });
}, []);
// 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).
const anyRunning = tasks.some((task) => task.status === 'running');
useEffect(() => {
const anyRunning = tasks.some((t) => t.status === 'running');
if (!anyRunning) {
return;
}
@@ -112,7 +72,7 @@ export function DebugTaskProvider({ children }: { children: ReactNode }) {
window.addEventListener('beforeunload', handler);
return () => window.removeEventListener('beforeunload', handler);
}, [tasks]);
}, [anyRunning]);
const value = useMemo<DebugTaskContextValue>(
() => ({ tasks, start, update, finish, remove, clearFinished }),
@@ -135,16 +95,23 @@ export function useDebugTasks(): DebugTaskContextValue {
export function useRunningTaskSummary(): { count: number; progress: number | null } {
const { tasks } = useDebugTasks();
return useMemo(() => {
const running = tasks.filter((t) => t.status === 'running');
let count = 0;
let determinate = 0;
let total = 0;
if (running.length === 0) {
return { count: 0, progress: null };
for (const task of tasks) {
if (task.status !== 'running') {
continue;
}
count++;
if (task.progress !== undefined) {
determinate++;
total += task.progress;
}
}
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 };
return { count, progress: determinate ? total / determinate : null };
}, [tasks]);
}
+65
View File
@@ -0,0 +1,65 @@
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; undefined means indeterminate. */
progress?: number;
detail?: string;
startedAt: number;
endedAt?: number;
cancel?: () => void;
}
export type DebugTaskUpdate = Partial<Pick<DebugTask, 'progress' | 'detail' | 'label'>>;
export type DebugTaskAction =
| { type: 'start'; task: DebugTask }
| { type: 'update'; id: string; patch: DebugTaskUpdate }
| {
type: 'finish';
id: string;
status: Exclude<DebugTaskStatus, 'running'>;
detail?: string;
endedAt: number;
}
| { type: 'remove'; id: string }
| { type: 'clearFinished' };
function trimFinished(tasks: DebugTask[]): DebugTask[] {
let remaining = Math.max(0, 50 - tasks.filter((task) => task.status === 'running').length);
return tasks.filter((task) => task.status === 'running' || remaining-- > 0);
}
export function debugTasksReducer(tasks: DebugTask[], action: DebugTaskAction): DebugTask[] {
switch (action.type) {
case 'start':
return trimFinished([action.task, ...tasks]);
case 'update':
return tasks.map((task) =>
task.id === action.id && task.status === 'running'
? { ...task, ...action.patch }
: task,
);
case 'finish':
return trimFinished(
tasks.map((task) =>
task.id === action.id && task.status === 'running'
? {
...task,
status: action.status,
detail: action.detail ?? task.detail,
endedAt: action.endedAt,
cancel: undefined,
}
: task,
),
);
case 'remove':
return tasks.filter((task) => task.id !== action.id || task.status === 'running');
case 'clearFinished':
return tasks.filter((task) => task.status === 'running');
}
}