refactor(webui): deepen Hook process ops behind a single seam

App.tsx held three copy-pasted handlers (load / unload / refresh) and
three parallel processXxxPid state slots that were mutually exclusive
but unenforced by the type system. The unload-failed alert was a
separate path, and OverviewPage needed 11 props to drive the table.

Extract useHookProcessOps: one inflight Set for dedup, one Map<pid,
OpKind> for view state, one run() that branches on kind via a
message table, and ownership of the unload-failed alert. OverviewPage
takes a single HookProcessOps prop and queries statusOf(pid).

App.tsx 270 → 216 LOC; OverviewPage props 11 → 7.
This commit is contained in:
DrSmoothl committed 2026-05-16 02:13:09 +08:00
1 parent b89d51d984
commit 7cef104f93
3 files changed
+177 -108

No files matched your search

+9 -87
View File
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { TooltipProvider } from '@/components/ui/tooltip';
import { ThemeProvider, useTheme } from '@/contexts/ThemeContext';
import { LoginPage } from '@/components/pages/login-page';
@@ -12,6 +12,7 @@ import { ConfirmDialog } from '@/components/confirm-dialog';
import type { Page } from '@/components/layout/sidebar';
import type { HookProcessInfo, QQInfo, SystemInfo } from '@/types';
import { ApiProvider, createApiClient, useApi, type ApiClient } from '@/lib/api';
import { useHookProcessOps } from '@/hooks/use-hook-process-ops';
export default function App() {
return (
@@ -122,15 +123,6 @@ function AppInner({ status, onLogoutComplete }: AppInnerProps) {
const [processList, setProcessList] = useState<HookProcessInfo[]>([]);
const [systemInfo, setSystemInfo] = useState<SystemInfo | null>(null);
const [processLoadingPid, setProcessLoadingPid] = useState<number | null>(null);
const [processUnloadingPid, setProcessUnloadingPid] = useState<number | null>(null);
const [processRefreshingPid, setProcessRefreshingPid] = useState<number | null>(null);
const [processActionStatus, setProcessActionStatus] = useState('');
const [unloadFailedAlert, setUnloadFailedAlert] = useState<{ pid: number; error: string } | null>(null);
// Tracks PIDs with an in-flight load/unload/refresh request so the UI can
// collapse spam-clicks instead of firing a second concurrent request.
const inflightProcessOps = useRef(new Set<number>());
const refreshQqList = useCallback(async () => {
try {
setQqList(await api.qqList());
@@ -155,6 +147,10 @@ function AppInner({ status, onLogoutComplete }: AppInnerProps) {
}
}, [api]);
const { ops: processOps, unloadFailedAlert, dismissUnloadFailedAlert } = useHookProcessOps({
onAfterOp: refreshProcesses,
});
useEffect(() => {
if (pollInterval <= 0) return;
let cancelled = false;
@@ -178,74 +174,6 @@ function AppInner({ status, onLogoutComplete }: AppInnerProps) {
onLogoutComplete();
}, [api, onLogoutComplete]);
const handleLoadProcess = useCallback(
async (pid: number) => {
if (inflightProcessOps.current.has(pid)) return;
inflightProcessOps.current.add(pid);
setProcessLoadingPid(pid);
setProcessActionStatus(`正在向进程 ${pid} 加载 SnowLuma…`);
try {
await api.processes.load(pid);
setProcessActionStatus(`已向进程 ${pid} 注入 SnowLuma,等待管道连接…`);
await refreshProcesses();
} catch (e) {
setProcessActionStatus(`加载失败:${e instanceof Error ? e.message : '未知错误'}`);
} finally {
inflightProcessOps.current.delete(pid);
setProcessLoadingPid(null);
setTimeout(() => setProcessActionStatus(''), 4000);
}
},
[api, refreshProcesses],
);
const handleUnloadProcess = useCallback(
async (pid: number) => {
if (inflightProcessOps.current.has(pid)) return;
inflightProcessOps.current.add(pid);
setProcessUnloadingPid(pid);
setProcessActionStatus(`正在从进程 ${pid} 卸载…`);
try {
const result = await api.processes.unload(pid);
if (result.process?.status === 'connecting' && result.process.error) {
setUnloadFailedAlert({ pid, error: result.process.error });
setProcessActionStatus(`进程 ${pid} 卸载失败`);
} else {
setProcessActionStatus(`已从进程 ${pid} 卸载`);
}
await refreshProcesses();
} catch (e) {
setProcessActionStatus(`卸载失败:${e instanceof Error ? e.message : '未知错误'}`);
} finally {
inflightProcessOps.current.delete(pid);
setProcessUnloadingPid(null);
setTimeout(() => setProcessActionStatus(''), 4000);
}
},
[api, refreshProcesses],
);
const handleRefreshProcess = useCallback(
async (pid: number) => {
if (inflightProcessOps.current.has(pid)) return;
inflightProcessOps.current.add(pid);
setProcessRefreshingPid(pid);
setProcessActionStatus(`正在刷新进程 ${pid} 的管道状态…`);
try {
await api.processes.refresh(pid);
setProcessActionStatus(`已刷新进程 ${pid} 的管道状态`);
await refreshProcesses();
} catch (e) {
setProcessActionStatus(`刷新失败:${e instanceof Error ? e.message : '未知错误'}`);
} finally {
inflightProcessOps.current.delete(pid);
setProcessRefreshingPid(null);
setTimeout(() => setProcessActionStatus(''), 4000);
}
},
[api, refreshProcesses],
);
return (
<>
<MainLayout active={active} onNavigate={setActive} status={status} onLogout={handleLogout}>
@@ -254,16 +182,10 @@ function AppInner({ status, onLogoutComplete }: AppInnerProps) {
qqList={qqList}
status={status}
processList={processList}
processLoadingPid={processLoadingPid}
processUnloadingPid={processUnloadingPid}
processRefreshingPid={processRefreshingPid}
processActionStatus={processActionStatus}
systemInfo={systemInfo}
onRefreshProcesses={refreshProcesses}
onRefreshSystem={refreshSystem}
onLoadProcess={handleLoadProcess}
onUnloadProcess={handleUnloadProcess}
onRefreshProcess={handleRefreshProcess}
processOps={processOps}
/>
)}
{active === 'config' && <ConfigPage qqList={qqList} />}
@@ -273,7 +195,7 @@ function AppInner({ status, onLogoutComplete }: AppInnerProps) {
<ConfirmDialog
open={!!unloadFailedAlert}
onOpenChange={(open) => !open && setUnloadFailedAlert(null)}
onOpenChange={(open) => !open && dismissUnloadFailedAlert()}
title="卸载失败"
description={
unloadFailedAlert ? (
@@ -287,7 +209,7 @@ function AppInner({ status, onLogoutComplete }: AppInnerProps) {
) : null
}
confirmText="知道了"
onConfirm={() => setUnloadFailedAlert(null)}
onConfirm={dismissUnloadFailedAlert}
/>
</>
);
@@ -23,21 +23,16 @@ import { Skeleton } from '@/components/ui/skeleton';
import { ConfirmDialog } from '@/components/confirm-dialog';
import { cn, formatBytes, formatUptime } from '@/lib/utils';
import type { HookProcessInfo, QQInfo, SystemInfo } from '@/types';
import type { HookProcessOps } from '@/hooks/use-hook-process-ops';
interface OverviewPageProps {
qqList: QQInfo[];
status: string;
processList: HookProcessInfo[];
processLoadingPid: number | null;
processUnloadingPid: number | null;
processRefreshingPid: number | null;
processActionStatus: string;
systemInfo: SystemInfo | null;
onRefreshProcesses: () => void;
onRefreshSystem: () => void;
onLoadProcess: (pid: number) => Promise<void> | void;
onUnloadProcess: (pid: number) => Promise<void> | void;
onRefreshProcess: (pid: number) => Promise<void> | void;
processOps: HookProcessOps;
}
const processStatusLabel: Record<HookProcessInfo['status'], string> = {
@@ -100,17 +95,12 @@ export function OverviewPage({
qqList,
status,
processList,
processLoadingPid,
processUnloadingPid,
processRefreshingPid,
processActionStatus,
systemInfo,
onRefreshProcesses,
onRefreshSystem,
onLoadProcess,
onUnloadProcess,
onRefreshProcess,
processOps,
}: OverviewPageProps) {
const { statusOf, banner: processActionStatus, load, unload, refresh } = processOps;
const [confirm, setConfirm] = useState<
| { kind: 'load' | 'unload'; pid: number; name: string }
| null
@@ -292,10 +282,11 @@ export function OverviewPage({
) : (
<div className="grid grid-cols-1 gap-3 xl:grid-cols-2">
{processList.map((proc, idx) => {
const loading = processLoadingPid === proc.pid || proc.status === 'loading';
const unloading = processUnloadingPid === proc.pid;
const refreshing = processRefreshingPid === proc.pid;
const busy = loading || unloading || refreshing;
const op = statusOf(proc.pid);
const loading = op === 'load' || proc.status === 'loading';
const unloading = op === 'unload';
const refreshing = op === 'refresh';
const busy = op != null || proc.status === 'loading';
const isOnline = proc.status === 'online';
const canUnload = proc.injected;
// Refresh is meaningful whenever a hook may exist (so the user
@@ -355,7 +346,7 @@ export function OverviewPage({
disabled={busy}
aria-label={`刷新进程 ${proc.pid} 管道状态`}
title="刷新管道状态 / 重连"
onClick={() => onRefreshProcess(proc.pid)}
onClick={() => refresh(proc.pid)}
className="size-8 text-muted-foreground hover:text-foreground"
>
{refreshing ? (
@@ -449,8 +440,8 @@ export function OverviewPage({
destructive={confirm?.kind === 'unload'}
onConfirm={async () => {
if (!confirm) return;
if (confirm.kind === 'unload') await onUnloadProcess(confirm.pid);
else await onLoadProcess(confirm.pid);
if (confirm.kind === 'unload') await unload(confirm.pid);
else await load(confirm.pid);
}}
/>
</div>
@@ -0,0 +1,156 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useApi, type ProcessActionResult } from '@/lib/api';
export type HookProcessOpKind = 'load' | 'unload' | 'refresh';
export interface HookProcessOps {
/** Returns the in-flight op kind for a pid, or null if idle. */
statusOf(pid: number): HookProcessOpKind | null;
/** Latest user-facing status; auto-clears a few seconds after the last update. */
banner: string;
load(pid: number): Promise<void>;
unload(pid: number): Promise<void>;
refresh(pid: number): Promise<void>;
}
export interface UnloadFailedAlert {
pid: number;
error: string;
}
export interface UseHookProcessOpsResult {
ops: HookProcessOps;
unloadFailedAlert: UnloadFailedAlert | null;
dismissUnloadFailedAlert: () => void;
}
interface KindMessages {
start(pid: number): string;
ok(pid: number): string;
fail(message: string): string;
}
const KIND_MESSAGES: Record<HookProcessOpKind, KindMessages> = {
load: {
start: (pid) => `正在向进程 ${pid} 加载 SnowLuma…`,
ok: (pid) => `已向进程 ${pid} 注入 SnowLuma,等待管道连接…`,
fail: (m) => `加载失败:${m}`,
},
unload: {
start: (pid) => `正在从进程 ${pid} 卸载…`,
ok: (pid) => `已从进程 ${pid} 卸载`,
fail: (m) => `卸载失败:${m}`,
},
refresh: {
start: (pid) => `正在刷新进程 ${pid} 的管道状态…`,
ok: (pid) => `已刷新进程 ${pid} 的管道状态`,
fail: (m) => `刷新失败:${m}`,
},
};
const BANNER_CLEAR_MS = 4000;
/**
* Drives load/unload/refresh actions on Hook-target processes. Owns the
* per-pid inflight dedup, the per-kind status indicator, the banner message
* lifecycle, and the "unload silently failed" alert that surfaces when the
* backend reports the named pipe is still alive after an unload attempt.
*/
export function useHookProcessOps(
opts: { onAfterOp?: () => Promise<void> | void } = {},
): UseHookProcessOpsResult {
const api = useApi();
const [byPid, setByPid] = useState<Map<number, HookProcessOpKind>>(() => new Map());
const [banner, setBanner] = useState('');
const [unloadFailedAlert, setUnloadFailedAlert] = useState<UnloadFailedAlert | null>(null);
// Synchronous inflight guard — protects against rapid double-clicks that
// would race the byPid setter (state updates are batched, refs are not).
const inflightRef = useRef<Set<number>>(new Set());
const bannerTimerRef = useRef<number | null>(null);
const onAfterOpRef = useRef(opts.onAfterOp);
onAfterOpRef.current = opts.onAfterOp;
useEffect(
() => () => {
if (bannerTimerRef.current != null) window.clearTimeout(bannerTimerRef.current);
},
[],
);
const scheduleBannerClear = useCallback(() => {
if (bannerTimerRef.current != null) window.clearTimeout(bannerTimerRef.current);
bannerTimerRef.current = window.setTimeout(() => {
setBanner('');
bannerTimerRef.current = null;
}, BANNER_CLEAR_MS);
}, []);
const setKind = useCallback((pid: number, kind: HookProcessOpKind | null) => {
setByPid((prev) => {
const next = new Map(prev);
if (kind == null) next.delete(pid);
else next.set(pid, kind);
return next;
});
}, []);
const run = useCallback(
async (
pid: number,
kind: HookProcessOpKind,
action: () => Promise<ProcessActionResult>,
) => {
if (inflightRef.current.has(pid)) return;
inflightRef.current.add(pid);
setKind(pid, kind);
const messages = KIND_MESSAGES[kind];
setBanner(messages.start(pid));
try {
const result = await action();
if (kind === 'unload' && result.process?.status === 'connecting' && result.process.error) {
setUnloadFailedAlert({ pid, error: result.process.error });
setBanner(`进程 ${pid} 卸载失败`);
} else {
setBanner(messages.ok(pid));
}
await onAfterOpRef.current?.();
} catch (e) {
const msg = e instanceof Error ? e.message : '未知错误';
setBanner(messages.fail(msg));
} finally {
inflightRef.current.delete(pid);
setKind(pid, null);
scheduleBannerClear();
}
},
[setKind, scheduleBannerClear],
);
const load = useCallback(
(pid: number) => run(pid, 'load', () => api.processes.load(pid)),
[api, run],
);
const unload = useCallback(
(pid: number) => run(pid, 'unload', () => api.processes.unload(pid)),
[api, run],
);
const refresh = useCallback(
(pid: number) => run(pid, 'refresh', () => api.processes.refresh(pid)),
[api, run],
);
const statusOf = useCallback(
(pid: number): HookProcessOpKind | null => byPid.get(pid) ?? null,
[byPid],
);
const dismissUnloadFailedAlert = useCallback(() => setUnloadFailedAlert(null), []);
const ops = useMemo<HookProcessOps>(
() => ({ statusOf, banner, load, unload, refresh }),
[statusOf, banner, load, unload, refresh],
);
return { ops, unloadFailedAlert, dismissUnloadFailedAlert };
}