Add pipe-watcher and manual refresh for hooks

Introduce a background pipe-watcher and per-PID operation serialization in HookManager to reliably detect and reconnect to SnowLuma pipes, reduce races, and remove the previous connect retry loop. Add new status 'connecting' and a refreshProcess API endpoint to force a probe/reconcile for a PID. Implement QqHookClient.listLivePipes() (and isClosed/probePipe updates) to enumerate live mojo pipes efficiently. Simplify client teardown logic and improve state transitions/logging. Update web UI: add a Refresh button, track inflight process ops, show connecting status and updated action messages. Update shared types to include the new 'connecting' status.
This commit is contained in:
手瓜一十雪 committed 2026-05-06 16:10:14 +08:00
1 parent 2e340f58a8
commit 4b02367a5f
6 files changed
+435 -138

No files matched your search

+307 -103
View File
@@ -6,10 +6,17 @@ import { injectHookProcess, listHookProcesses, unloadHookProcess, type HookInjec
import { QqHookClient, type QqHookLoginState, type QqHookPacket } from './qq-hook-client';
const log = createLogger('Hook');
const CONNECT_RETRY_COUNT = 30;
const CONNECT_RETRY_INTERVAL_MS = 1000;
const DEFAULT_WATCHER_INTERVAL_MS = 1500;
const MIN_WATCHER_INTERVAL_MS = 250;
export type HookProcessStatus = 'available' | 'loading' | 'loaded' | 'online' | 'error' | 'disconnected';
export type HookProcessStatus =
| 'available'
| 'loading'
| 'connecting'
| 'loaded'
| 'online'
| 'error'
| 'disconnected';
export interface HookProcessInfo extends HookProcessBaseInfo {
injected: boolean;
@@ -25,96 +32,141 @@ interface HookProcessState extends HookProcessInfo {
client: QqHookClient | null;
sender: HookPacketClient | null;
injectResult: HookInjectResult | null;
connectTask: Promise<void> | null;
bound: boolean;
}
export interface HookManagerOptions {
/** Background pipe-watcher polling interval. Lower = faster reconnect but
* more frequent named-pipe directory listings. Defaults to 1500 ms. */
watcherIntervalMs?: number;
}
/**
* Manages SnowLuma hook injection and bridge connectivity for QQ.exe processes.
*
* Lifecycle: load -> inject DLL only (returns fast) -> background watcher
* detects the named pipe coming up and connects -> on QQ login the bridge is
* notified. The watcher also handles reconnect after a pipe drop and detects
* hooks that survived a previous SnowLuma restart.
*
* Concurrency: every per-PID mutation (load / unload / refresh / connect /
* close-handler / watcher reconcile) goes through a per-PID promise chain so
* users can spam buttons without races.
*/
export class HookManager {
private readonly states = new Map<number, HookProcessState>();
private readonly loadTasks = new Map<number, Promise<HookProcessInfo>>();
private readonly unloadTasks = new Map<number, Promise<HookProcessInfo>>();
private readonly opsByPid = new Map<number, Promise<unknown>>();
private readonly watcherIntervalMs: number;
private watcherTimer: NodeJS.Timeout | null = null;
private watcherTicking = false;
private disposed = false;
constructor(
private readonly ntqq: NtqqHandler,
private readonly bridgeManager: BridgeManager,
) {}
options: HookManagerOptions = {},
) {
this.watcherIntervalMs = Math.max(
MIN_WATCHER_INTERVAL_MS,
options.watcherIntervalMs ?? DEFAULT_WATCHER_INTERVAL_MS,
);
// Boot the watcher on the next tick so callers can attach listeners first.
this.scheduleWatcher(0);
}
async listProcesses(): Promise<HookProcessInfo[]> {
const processes = await listHookProcesses();
const processes = listHookProcesses();
const seen = new Set<number>();
for (const proc of processes) {
seen.add(proc.pid);
const state = this.ensureState(proc.pid);
state.name = proc.name;
state.path = proc.path;
state.name = proc.name || state.name;
state.path = proc.path || state.path;
}
const seen = new Set(processes.map(proc => proc.pid));
const result: HookProcessInfo[] = [];
for (const proc of processes) {
result.push(this.toPublicInfo(this.ensureState(proc.pid)));
}
for (const state of this.states.values()) {
if (!seen.has(state.pid) && state.injected) {
if (!seen.has(state.pid) && (state.injected || state.client)) {
result.push(this.toPublicInfo(state));
}
}
return result.sort((a, b) => a.pid - b.pid);
}
async loadProcess(pid: number): Promise<HookProcessInfo> {
if (!Number.isInteger(pid) || pid <= 0) {
throw new Error('invalid pid');
}
const runningTask = this.loadTasks.get(pid);
if (runningTask) return runningTask;
const task = this.loadProcessInternal(pid);
this.loadTasks.set(pid, task);
try {
return await task;
} finally {
this.loadTasks.delete(pid);
}
loadProcess(pid: number): Promise<HookProcessInfo> {
if (!Number.isInteger(pid) || pid <= 0) throw new Error('invalid pid');
return this.serialize(pid, () => this.loadProcessInternal(pid));
}
async unloadProcess(pid: number): Promise<HookProcessInfo> {
if (!Number.isInteger(pid) || pid <= 0) {
throw new Error('invalid pid');
}
const runningTask = this.unloadTasks.get(pid);
if (runningTask) return runningTask;
unloadProcess(pid: number): Promise<HookProcessInfo> {
if (!Number.isInteger(pid) || pid <= 0) throw new Error('invalid pid');
return this.serialize(pid, () => this.unloadProcessInternal(pid));
}
const task = this.unloadProcessInternal(pid);
this.unloadTasks.set(pid, task);
try {
return await task;
} finally {
this.unloadTasks.delete(pid);
}
/**
* Re-probe the named pipe for `pid`, reconnect if it became available,
* or tear down a stale connection if it disappeared. Safe to call at any
* time; serialised against load/unload/watcher actions on the same PID.
*/
refreshProcess(pid: number): Promise<HookProcessInfo> {
if (!Number.isInteger(pid) || pid <= 0) throw new Error('invalid pid');
return this.serialize(pid, () => this.refreshProcessInternal(pid));
}
dispose(): void {
this.disposed = true;
if (this.watcherTimer) {
clearTimeout(this.watcherTimer);
this.watcherTimer = null;
}
for (const state of this.states.values()) {
state.client?.close();
state.client = null;
state.connected = false;
state.loggedIn = false;
this.tearDownClient(state);
state.status = state.injected ? 'disconnected' : 'available';
}
}
// ───────────────────────── per-PID serialization ─────────────────────────
/**
* Serialise an operation against a per-PID promise chain. Guarantees that
* load / unload / refresh / watcher-driven connects for the same PID never
* interleave even if the user mashes buttons.
*/
private async serialize<T>(pid: number, op: () => Promise<T>): Promise<T> {
const previous = this.opsByPid.get(pid) ?? Promise.resolve();
let release!: () => void;
const completion = new Promise<void>(resolve => { release = resolve; });
const chained = previous.then(() => completion);
this.opsByPid.set(pid, chained);
try {
await previous.catch(() => undefined);
return await op();
} finally {
release();
// Drop the chain entry once nothing else is waiting on it.
if (this.opsByPid.get(pid) === chained) this.opsByPid.delete(pid);
}
}
// ──────────────────────────── load / unload ──────────────────────────────
private async loadProcessInternal(pid: number): Promise<HookProcessInfo> {
const state = this.ensureState(pid);
state.status = 'loading';
state.error = '';
state.status = 'loading';
try {
if (!state.injected) {
// Fast path: if QQ.exe still hosts a hook DLL from a previous SnowLuma
// run, the control pipe is already listed. Skip re-injection on a hit.
if (await QqHookClient.probePipe(pid)) {
// Fast path: a previous SnowLuma run may have left the hook DLL
// resident in QQ.exe. If the control pipe is already listed we skip
// re-injection and let the watcher reconnect instead.
const livePipes = await QqHookClient.listLivePipes();
if (livePipes.has(pid)) {
state.injected = true;
state.method = 'reconnect';
log.info('SnowLuma reconnected to existing hook in PID=%d', pid);
log.info('PID=%d already has SnowLuma pipe; will reconnect via watcher', pid);
} else {
state.injectResult = injectHookProcess(pid);
state.injected = true;
@@ -122,14 +174,18 @@ export class HookManager {
log.info('SnowLuma loaded into PID=%d via %s', pid, state.method);
}
}
state.status = state.connected ? (state.loggedIn ? 'online' : 'loaded') : 'loaded';
this.startClient(state);
state.status = state.connected
? (state.loggedIn ? 'online' : 'loaded')
: 'connecting';
} catch (error) {
state.status = 'error';
state.error = error instanceof Error ? error.message : String(error);
log.error('load failed: PID=%d err=%s', pid, state.error);
}
// Wake the watcher so it can pick up the freshly-injected pipe asap
// instead of waiting up to one full interval.
this.scheduleWatcher(0);
return this.toPublicInfo(state);
}
@@ -138,14 +194,9 @@ export class HookManager {
state.error = '';
try {
state.client?.close();
state.client = null;
state.sender = null;
state.connectTask = null;
state.bound = false;
state.connected = false;
state.loggedIn = false;
this.bridgeManager.onPidDisconnected(pid);
const wasLoggedIn = state.loggedIn;
this.tearDownClient(state);
if (wasLoggedIn) this.bridgeManager.onPidDisconnected(pid);
const handle = state.injectResult?.handle;
if (state.injected && handle) {
@@ -167,6 +218,44 @@ export class HookManager {
return this.toPublicInfo(state);
}
private async refreshProcessInternal(pid: number): Promise<HookProcessInfo> {
const state = this.ensureState(pid);
state.error = '';
try {
const livePipes = await QqHookClient.listLivePipes();
const pipeUp = livePipes.has(pid);
if (pipeUp) {
// A live pipe means a SnowLuma DLL is resident — even if we did not
// inject it ourselves (e.g. left over from a prior run).
if (!state.injected) {
state.injected = true;
state.method = state.method || 'reconnect';
}
if (state.client?.isClosed) this.tearDownClient(state);
if (!state.connected) {
await this.attemptConnect(state);
} else {
state.status = state.loggedIn ? 'online' : 'loaded';
}
} else {
// Pipe is gone; if we still hold a client, drop it and surface the
// appropriate disconnected/available state to the UI.
const wasLoggedIn = state.loggedIn;
this.tearDownClient(state);
if (wasLoggedIn) this.bridgeManager.onPidDisconnected(pid);
state.status = state.injected ? 'disconnected' : 'available';
}
} catch (error) {
state.error = error instanceof Error ? error.message : String(error);
state.status = state.injected ? 'disconnected' : 'error';
log.warn('refresh failed: PID=%d err=%s', pid, state.error);
}
return this.toPublicInfo(state);
}
private ensureState(pid: number): HookProcessState {
let state = this.states.get(pid);
if (!state) {
@@ -184,7 +273,6 @@ export class HookManager {
client: null,
sender: null,
injectResult: null,
connectTask: null,
bound: false,
};
this.states.set(pid, state);
@@ -192,20 +280,139 @@ export class HookManager {
return state;
}
private startClient(state: HookProcessState): void {
// ───────────────────────────── pipe watcher ──────────────────────────────
private scheduleWatcher(delayMs: number): void {
if (this.disposed) return;
if (this.watcherTimer) {
clearTimeout(this.watcherTimer);
this.watcherTimer = null;
}
this.watcherTimer = setTimeout(() => {
this.watcherTimer = null;
void this.tickWatcher();
}, Math.max(0, delayMs));
}
private async tickWatcher(): Promise<void> {
if (this.disposed) return;
if (this.watcherTicking) {
this.scheduleWatcher(this.watcherIntervalMs);
return;
}
this.watcherTicking = true;
try {
const livePipes = await QqHookClient.listLivePipes();
const processes = listHookProcesses();
// Refresh metadata + ensure a state entry exists for each known PID.
for (const proc of processes) {
const state = this.ensureState(proc.pid);
state.name = proc.name || state.name;
state.path = proc.path || state.path;
}
// Auto-detect hooks that survived a SnowLuma restart.
for (const pid of livePipes) {
const state = this.ensureState(pid);
if (!state.injected) {
state.injected = true;
state.method = state.method || 'reconnect';
if (state.status === 'available') state.status = 'connecting';
log.info('Detected pre-existing SnowLuma pipe in PID=%d', pid);
}
}
const runningSet = new Set(processes.map(p => p.pid));
const tasks: Promise<unknown>[] = [];
for (const state of [...this.states.values()]) {
const alivePipe = livePipes.has(state.pid);
const aliveProc = runningSet.has(state.pid);
// Reap stale state entries that have nothing left to do.
if (!aliveProc && !alivePipe && !state.injected && !state.client) {
this.states.delete(state.pid);
continue;
}
// Pipe vanished but we still hold a client → schedule a teardown.
if (state.connected && !alivePipe) {
tasks.push(this.serialize(state.pid, async () => this.reconcileLostPipe(state.pid))
.catch(err => log.warn('watcher teardown failed: PID=%d err=%s', state.pid, this.errMsg(err))));
continue;
}
// Injected & pipe up but not connected → schedule a connect.
if (state.injected && !state.connected && alivePipe) {
tasks.push(this.serialize(state.pid, async () => this.reconcileConnect(state.pid))
.catch(err => log.warn('watcher connect failed: PID=%d err=%s', state.pid, this.errMsg(err))));
continue;
}
// Injected but pipe still pending → keep status visible to the UI.
if (state.injected && !state.connected && !alivePipe) {
if (state.status !== 'error' && state.status !== 'disconnected' && state.status !== 'loading') {
state.status = 'connecting';
}
}
}
await Promise.all(tasks);
} finally {
this.watcherTicking = false;
this.scheduleWatcher(this.watcherIntervalMs);
}
}
/** Re-check pipe and connect under the per-PID lock. */
private async reconcileConnect(pid: number): Promise<void> {
const state = this.states.get(pid);
if (!state || !state.injected || state.connected) return;
if (state.client?.isClosed) this.tearDownClient(state);
const live = await QqHookClient.listLivePipes();
if (!live.has(pid)) return;
await this.attemptConnect(state);
}
/** Tear down a client whose pipe disappeared. */
private async reconcileLostPipe(pid: number): Promise<void> {
const state = this.states.get(pid);
if (!state || !state.connected) return;
const live = await QqHookClient.listLivePipes();
if (live.has(pid)) return;
const wasLoggedIn = state.loggedIn;
this.tearDownClient(state);
state.status = state.injected ? (wasLoggedIn ? 'disconnected' : 'connecting') : 'available';
if (wasLoggedIn) this.bridgeManager.onPidDisconnected(pid);
}
// ───────────────────────────── client plumbing ───────────────────────────
private async attemptConnect(state: HookProcessState): Promise<void> {
if (state.connected) return;
if (state.client?.isClosed) this.tearDownClient(state);
if (!state.client) {
state.client = new QqHookClient(state.pid);
state.sender = new HookPacketClient(state.client);
state.bound = false;
}
if (!state.bound) {
this.bindClient(state, state.client);
state.bound = true;
}
if (!state.connectTask) {
state.connectTask = this.connectClient(state).finally(() => {
state.connectTask = null;
});
void state.connectTask;
const client = state.client;
try {
await client.connectAll({ recv: true });
state.connected = true;
state.status = client.isLoggedIn ? 'online' : 'loaded';
state.error = '';
const loginState = client.getLoginState();
if (loginState.loggedIn) this.handleLoginState(state, loginState);
log.info('pipe connected: PID=%d', state.pid);
} catch (error) {
state.error = this.errMsg(error);
// Drop the client so the next attempt builds a fresh socket pair.
this.tearDownClient(state);
state.status = state.injected ? 'connecting' : 'available';
}
}
@@ -213,46 +420,43 @@ export class HookManager {
client.on('packet', packet => this.handlePacket(state, packet));
client.on('loginState', loginState => this.handleLoginState(state, loginState));
client.on('error', error => {
state.error = error instanceof Error ? error.message : String(error);
if (!state.connected) state.status = 'error';
log.warn('pipe error: PID=%d err=%s', state.pid, state.error);
const msg = this.errMsg(error);
state.error = msg;
log.warn('pipe error: PID=%d err=%s', state.pid, msg);
});
client.on('close', () => {
state.connected = false;
if (state.loggedIn) {
state.loggedIn = false;
state.status = 'disconnected';
this.bridgeManager.onPidDisconnected(state.pid);
}
if (this.disposed) return;
// Only the client that is currently registered should drive a reconcile;
// listeners may fire for an already-replaced client.
if (state.client !== client) return;
void this.serialize(state.pid, async () => {
if (state.client !== client) return;
const wasLoggedIn = state.loggedIn;
this.tearDownClient(state);
if (!state.injected) {
state.status = 'available';
} else if (wasLoggedIn) {
state.status = 'disconnected';
this.bridgeManager.onPidDisconnected(state.pid);
} else {
state.status = 'connecting';
}
}).catch(err => log.warn('close reconcile failed: PID=%d err=%s', state.pid, this.errMsg(err)));
});
}
private async connectClient(state: HookProcessState): Promise<void> {
/** Detach + close the current client and reset its associated fields. */
private tearDownClient(state: HookProcessState): void {
const client = state.client;
if (!client) return;
for (let attempt = 1; attempt <= CONNECT_RETRY_COUNT; attempt++) {
try {
await client.connectAll({ recv: true });
state.connected = true;
state.status = client.isLoggedIn ? 'online' : 'loaded';
state.error = '';
const loginState = client.getLoginState();
if (loginState.loggedIn) {
this.handleLoginState(state, loginState);
}
log.info('pipe connected: PID=%d', state.pid);
return;
} catch (error) {
state.error = error instanceof Error ? error.message : String(error);
if (attempt >= CONNECT_RETRY_COUNT) {
state.status = 'error';
log.error('pipe connect failed: PID=%d err=%s', state.pid, state.error);
return;
}
await delay(CONNECT_RETRY_INTERVAL_MS);
}
if (client) {
client.removeAllListeners();
try { client.close(); } catch { /* ignore */ }
}
state.client = null;
state.sender = null;
state.bound = false;
state.connected = false;
state.loggedIn = false;
}
private handleLoginState(state: HookProcessState, loginState: QqHookLoginState): void {
@@ -290,13 +494,13 @@ export class HookManager {
method: state.method,
};
}
private errMsg(value: unknown): string {
return value instanceof Error ? value.message : String(value);
}
}
function isRealUin(uin: string): boolean {
if (!uin || uin === '0') return false;
return /^\d+$/.test(uin) && uin.length >= 5;
}
function delay(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
+27 -7
View File
@@ -253,6 +253,10 @@ export class QqHookClient extends EventEmitter {
return this.loginState.loggedIn;
}
get isClosed(): boolean {
return this.closed;
}
get currentUin(): string {
return this.loginState.uin;
}
@@ -289,19 +293,35 @@ export class QqHookClient extends EventEmitter {
* opening the pipe, so probing cannot disturb the first real client connect.
*/
static async probePipe(pid: number): Promise<boolean> {
const live = await QqHookClient.listLivePipes();
return live.has(pid);
}
/**
* Enumerate every PID currently hosting a SnowLuma `mojo.<pid>.control` pipe
* in a single filesystem listing. The HookManager's pipe-watcher uses this
* to drive connect/reconnect decisions without per-PID stat calls.
*/
static async listLivePipes(): Promise<Set<number>> {
const result = new Set<number>();
try {
const pipeFileName = process.platform === 'win32'
? `mojo.${pid}.control`
: `mojo.${pid}.control.sock`;
if (process.platform === 'win32') {
const names = await fs.readdir('\\\\.\\pipe\\');
return names.some(name => name.toLowerCase() === pipeFileName.toLowerCase());
for (const name of names) {
const m = /^mojo\.(\d+)\.control$/i.exec(name);
if (m) result.add(Number(m[1]));
}
} else {
const names = await fs.readdir(linuxRuntimeDir());
for (const name of names) {
const m = /^mojo\.(\d+)\.control\.sock$/.exec(name);
if (m) result.add(Number(m[1]));
}
}
const names = await fs.readdir(linuxRuntimeDir());
return names.includes(pipeFileName);
} catch {
return false;
/* directory missing or inaccessible — treat as no live pipes */
}
return result;
}
async connect(): Promise<QqHookHello> {
+14
View File
@@ -436,6 +436,20 @@ export async function initWebUI(
}
});
app.post('/api/processes/:pid/refresh', async (c) => {
if (!hookManager) return c.json({ success: false, message: 'hook manager is not available' }, 503);
const pid = Number(c.req.param('pid'));
if (!Number.isInteger(pid) || pid <= 0 || pid > 4_194_304) {
return c.json({ success: false, message: 'invalid pid' }, 400);
}
try {
const processInfo = await hookManager.refreshProcess(pid);
return c.json({ success: processInfo.status !== 'error', process: processInfo });
} catch (err) {
return c.json({ success: false, message: err instanceof Error ? err.message : String(err) }, 500);
}
});
app.get('/api/config/:uin', (c) => {
const uin = c.req.param('uin');
if (!UIN_REGEX.test(uin)) return c.json({ message: 'invalid uin' }, 400);
+35 -3
View File
@@ -39,7 +39,11 @@ function AppInner() {
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('');
// 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 [selectedUin, setSelectedUin] = useState<string | null>(null);
const [config, setConfig] = useState<OneBotConfig | null>(null);
@@ -224,39 +228,65 @@ function AppInner() {
}, [fetchApi]);
const handleLoadProcess = useCallback(async (pid: number) => {
if (inflightProcessOps.current.has(pid)) return;
inflightProcessOps.current.add(pid);
setProcessLoadingPid(pid);
setProcessActionStatus(`正在向进程 ${pid} 加载 SnowLuma…`);
try {
const res = await fetchApi(`/api/processes/${pid}/load`, { method: 'POST' });
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || '加载失败');
setProcessActionStatus(`已向进程 ${pid} 注入 SnowLuma`);
if (!res.ok) throw new Error(data.message || data.error || '加载失败');
setProcessActionStatus(`已向进程 ${pid} 注入 SnowLuma,等待管道连接…`);
await refreshProcesses();
} catch (e) {
setProcessActionStatus(`加载失败:${(e as Error).message}`);
} finally {
inflightProcessOps.current.delete(pid);
setProcessLoadingPid(null);
setTimeout(() => setProcessActionStatus(''), 4000);
}
}, [fetchApi, refreshProcesses]);
const handleUnloadProcess = useCallback(async (pid: number) => {
if (inflightProcessOps.current.has(pid)) return;
inflightProcessOps.current.add(pid);
setProcessUnloadingPid(pid);
setProcessActionStatus(`正在从进程 ${pid} 卸载…`);
try {
const res = await fetchApi(`/api/processes/${pid}/unload`, { method: 'POST' });
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || '卸载失败');
if (!res.ok) throw new Error(data.message || data.error || '卸载失败');
setProcessActionStatus(`已从进程 ${pid} 卸载`);
await refreshProcesses();
} catch (e) {
setProcessActionStatus(`卸载失败:${(e as Error).message}`);
} finally {
inflightProcessOps.current.delete(pid);
setProcessUnloadingPid(null);
setTimeout(() => setProcessActionStatus(''), 4000);
}
}, [fetchApi, refreshProcesses]);
const handleRefreshProcess = useCallback(async (pid: number) => {
if (inflightProcessOps.current.has(pid)) return;
inflightProcessOps.current.add(pid);
setProcessRefreshingPid(pid);
setProcessActionStatus(`正在刷新进程 ${pid} 的管道状态…`);
try {
const res = await fetchApi(`/api/processes/${pid}/refresh`, { method: 'POST' });
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.message || data.error || '刷新失败');
setProcessActionStatus(`已刷新进程 ${pid} 的管道状态`);
await refreshProcesses();
} catch (e) {
setProcessActionStatus(`刷新失败:${(e as Error).message}`);
} finally {
inflightProcessOps.current.delete(pid);
setProcessRefreshingPid(null);
setTimeout(() => setProcessActionStatus(''), 4000);
}
}, [fetchApi, refreshProcesses]);
const handleSaveConfig = useCallback(async () => {
if (!selectedUin || !config) return;
setSaveStatus('保存中...');
@@ -321,12 +351,14 @@ function AppInner() {
processList={processList}
processLoadingPid={processLoadingPid}
processUnloadingPid={processUnloadingPid}
processRefreshingPid={processRefreshingPid}
processActionStatus={processActionStatus}
systemInfo={systemInfo}
onRefreshProcesses={refreshProcesses}
onRefreshSystem={refreshSystem}
onLoadProcess={handleLoadProcess}
onUnloadProcess={handleUnloadProcess}
onRefreshProcess={handleRefreshProcess}
/>
)}
{active === 'config' && (
@@ -31,17 +31,20 @@ interface OverviewPageProps {
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;
}
const processStatusLabel: Record<HookProcessInfo['status'], string> = {
available: '可加载',
loading: '加载中',
connecting: '等待连接',
loaded: '等待登录',
online: '已在线',
error: '错误',
@@ -50,8 +53,9 @@ const processStatusLabel: Record<HookProcessInfo['status'], string> = {
function processBadgeVariant(status: HookProcessInfo['status']) {
if (status === 'online') return 'success' as const;
if (status === 'error' || status === 'disconnected') return 'destructive' as const;
if (status === 'loading' || status === 'loaded') return 'default' as const;
if (status === 'error') return 'destructive' as const;
if (status === 'disconnected') return 'destructive' as const;
if (status === 'loading' || status === 'connecting' || status === 'loaded') return 'default' as const;
return 'secondary' as const;
}
@@ -99,12 +103,14 @@ export function OverviewPage({
processList,
processLoadingPid,
processUnloadingPid,
processRefreshingPid,
processActionStatus,
systemInfo,
onRefreshProcesses,
onRefreshSystem,
onLoadProcess,
onUnloadProcess,
onRefreshProcess,
}: OverviewPageProps) {
const [confirm, setConfirm] = useState<
| { kind: 'load' | 'unload'; pid: number; name: string }
@@ -278,10 +284,13 @@ export function OverviewPage({
{processList.map((proc, idx) => {
const loading = processLoadingPid === proc.pid || proc.status === 'loading';
const unloading = processUnloadingPid === proc.pid;
const busy = loading || unloading;
const refreshing = processRefreshingPid === proc.pid;
const busy = loading || unloading || refreshing;
const isOnline = proc.status === 'online';
const canUnload =
proc.injected || proc.status === 'loaded' || isOnline || proc.status === 'disconnected';
const canUnload = proc.injected;
// Refresh is meaningful whenever a hook may exist (so the user
// can re-check the pipe and trigger a reconnect on demand).
const showRefresh = proc.injected || proc.status === 'connecting' || proc.status === 'disconnected';
return (
<motion.div
key={proc.pid}
@@ -328,26 +337,44 @@ export function OverviewPage({
</div>
)}
</div>
<Button
size="sm"
variant={canUnload ? 'outline' : 'default'}
disabled={busy}
onClick={() =>
setConfirm({
kind: canUnload ? 'unload' : 'load',
pid: proc.pid,
name: proc.name || `PID ${proc.pid}`,
})
}
className={cn(
'shrink-0',
canUnload && 'text-destructive hover:bg-destructive/10 hover:text-destructive'
<div className="flex shrink-0 items-center gap-1.5">
{showRefresh && (
<Button
size="icon"
variant="ghost"
disabled={busy}
aria-label={`刷新进程 ${proc.pid} 管道状态`}
title="刷新管道状态 / 重连"
onClick={() => onRefreshProcess(proc.pid)}
className="size-8 text-muted-foreground hover:text-foreground"
>
{refreshing ? (
<Loader2 className="size-3.5 animate-spin" />
) : (
<RefreshCw className="size-3.5" />
)}
</Button>
)}
>
{busy && <Loader2 className="size-3.5 animate-spin" />}
{!busy && canUnload && <Unplug className="size-3.5" />}
{canUnload ? (unloading ? '卸载中' : '卸载') : loading ? '加载中' : '加载'}
</Button>
<Button
size="sm"
variant={canUnload ? 'outline' : 'default'}
disabled={busy}
onClick={() =>
setConfirm({
kind: canUnload ? 'unload' : 'load',
pid: proc.pid,
name: proc.name || `PID ${proc.pid}`,
})
}
className={cn(
canUnload && 'text-destructive hover:bg-destructive/10 hover:text-destructive'
)}
>
{(loading || unloading) && <Loader2 className="size-3.5 animate-spin" />}
{!loading && !unloading && canUnload && <Unplug className="size-3.5" />}
{canUnload ? (unloading ? '卸载中' : '卸载') : loading ? '加载中' : '加载'}
</Button>
</div>
</motion.div>
);
})}
+1 -1
View File
@@ -14,7 +14,7 @@ export interface HookProcessInfo {
connected: boolean;
loggedIn: boolean;
uin: string;
status: 'available' | 'loading' | 'loaded' | 'online' | 'error' | 'disconnected';
status: 'available' | 'loading' | 'connecting' | 'loaded' | 'online' | 'error' | 'disconnected';
error: string;
method: string;
}