diff --git a/packages/webui/src/App.tsx b/packages/webui/src/App.tsx index 8d663603..14e8b49c 100644 --- a/packages/webui/src/App.tsx +++ b/packages/webui/src/App.tsx @@ -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([]); const [systemInfo, setSystemInfo] = useState(null); - const [processLoadingPid, setProcessLoadingPid] = useState(null); - const [processUnloadingPid, setProcessUnloadingPid] = useState(null); - const [processRefreshingPid, setProcessRefreshingPid] = useState(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()); - 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 ( <> @@ -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' && } @@ -273,7 +195,7 @@ function AppInner({ status, onLogoutComplete }: AppInnerProps) { !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} /> ); diff --git a/packages/webui/src/components/pages/overview-page.tsx b/packages/webui/src/components/pages/overview-page.tsx index 339c219e..1b6dd661 100644 --- a/packages/webui/src/components/pages/overview-page.tsx +++ b/packages/webui/src/components/pages/overview-page.tsx @@ -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; - onUnloadProcess: (pid: number) => Promise | void; - onRefreshProcess: (pid: number) => Promise | void; + processOps: HookProcessOps; } const processStatusLabel: Record = { @@ -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({ ) : (
{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); }} />
diff --git a/packages/webui/src/hooks/use-hook-process-ops.ts b/packages/webui/src/hooks/use-hook-process-ops.ts new file mode 100644 index 00000000..1dc1efda --- /dev/null +++ b/packages/webui/src/hooks/use-hook-process-ops.ts @@ -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; + unload(pid: number): Promise; + refresh(pid: number): Promise; +} + +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 = { + 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 } = {}, +): UseHookProcessOpsResult { + const api = useApi(); + const [byPid, setByPid] = useState>(() => new Map()); + const [banner, setBanner] = useState(''); + const [unloadFailedAlert, setUnloadFailedAlert] = useState(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>(new Set()); + const bannerTimerRef = useRef(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, + ) => { + 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( + () => ({ statusOf, banner, load, unload, refresh }), + [statusOf, banner, load, unload, refresh], + ); + + return { ops, unloadFailedAlert, dismissUnloadFailedAlert }; +}