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:
1 parent
2e340f58a8
commit
4b02367a5f
6 files changed
+435
-138
No files matched your search
@@ -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));
|
||||
}
|
||||
@@ -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> {
|
||||
|
||||
@@ -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);
|
||||
|
||||
Reference in new issue
Block a user