From 4fc52578a5091bc3db3b1bd41ce80e92b5ac214f Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 12 May 2026 14:41:42 +0800 Subject: [PATCH] refactor(core): split HookManager into PipeWatcher + HookSession MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit HookManager was a 515-line god class with four tangled responsibilities (state machine, watcher loop, per-PID serialization, lifecycle plumbing) and no tests — every code path needed a real QQ.exe to exercise. Split into three modules: - PipeWatcher: the only module that polls the OS for QQ.exe processes and live SnowLuma named pipes. Emits diff events (process-discovered, process-gone, pipe-up, pipe-down, tick). Native list functions are constructor deps so tests can drive ticks with in-memory fakes. - HookSession: per-PID lifecycle. Owns its own state machine, its own promise chain (serializes load/unload/refresh/onPipeUp/onPipeDown so rapid user clicks don't race), and its own QqHookClient. Emits high-level events (login, disconnected, status-changed, disposed) that the manager forwards instead of reaching into BridgeManager directly. Injector and pipe-client factory are deps for testability. - HookManager: shrinks to a thin orchestrator (227 lines, was 515). Routes user commands and watcher events to sessions, forwards session events to BridgeManager, retries stuck-in-connecting sessions on every watcher tick (preserves the original tickWatcher reconcile pass). Public API (listProcesses/loadProcess/unloadProcess/refreshProcess) unchanged for WebUI callers; only the constructor moves to a deps object: new HookManager({ ntqq, bridgeManager }). Behavior preserved including all the edge cases the original code handles: re-using a SnowLuma DLL that survived a process restart (fast-path via pipeWatcher.isPipeLive), stale close events from a replaced client, DLL-unload-failed fallback to "watcher will reconnect", QQ.exe killed with a live pipe (pipe-down emitted before process-gone so disconnect runs before dispose). Adds 27 unit tests across two new vitest suites (hook-session.test.ts and pipe-watcher.test.ts) covering load fast-path, login emission, duplicate-login suppression, connect retry on failure, pipe up/down cycles, unload while logged in, unload verification failure, user command serialization, and process-gone handling — none of which previously had test coverage. --- packages/core/src/hook/hook-manager.ts | 647 +++++++---------------- packages/core/src/hook/hook-session.ts | 416 +++++++++++++++ packages/core/src/hook/pipe-watcher.ts | 208 ++++++++ packages/core/src/hook/types.ts | 27 + packages/core/src/index.ts | 2 +- packages/core/tests/hook-session.test.ts | 309 +++++++++++ packages/core/tests/pipe-watcher.test.ts | 197 +++++++ 7 files changed, 1338 insertions(+), 468 deletions(-) create mode 100644 packages/core/src/hook/hook-session.ts create mode 100644 packages/core/src/hook/pipe-watcher.ts create mode 100644 packages/core/src/hook/types.ts create mode 100644 packages/core/tests/hook-session.test.ts create mode 100644 packages/core/tests/pipe-watcher.test.ts diff --git a/packages/core/src/hook/hook-manager.ts b/packages/core/src/hook/hook-manager.ts index 0933babb..f34fca7a 100644 --- a/packages/core/src/hook/hook-manager.ts +++ b/packages/core/src/hook/hook-manager.ts @@ -1,514 +1,227 @@ import type { BridgeManager } from '../bridge/manager'; import type { NtqqHandler } from '../protocol/ntqq-handler'; -import { createLogger } from '../utils/logger'; -import { HookPacketClient } from './hook-packet-client'; -import { injectHookProcess, listHookProcesses, unloadHookProcess, type HookInjectResult, type HookProcessBaseInfo } from './injector'; -import { QqHookClient, type QqHookLoginState, type QqHookPacket } from './qq-hook-client'; +import { createLogger, type Logger } from '../utils/logger'; +import { + injectHookProcess, + listHookProcesses, + unloadHookProcess, + type HookProcessBaseInfo, +} from './injector'; +import { HookSession, type HookSessionDeps } from './hook-session'; +import { PipeWatcher } from './pipe-watcher'; +import { QqHookClient } from './qq-hook-client'; +import type { HookProcessInfo } from './types'; -const log = createLogger('Hook'); -const DEFAULT_WATCHER_INTERVAL_MS = 1500; -const MIN_WATCHER_INTERVAL_MS = 250; +export type { HookProcessInfo, HookProcessStatus } from './types'; +export type { HookProcessBaseInfo } from './injector'; -export type HookProcessStatus = - | 'available' - | 'loading' - | 'connecting' - | 'loaded' - | 'online' - | 'error' - | 'disconnected'; - -export interface HookProcessInfo extends HookProcessBaseInfo { - injected: boolean; - connected: boolean; - loggedIn: boolean; - uin: string; - status: HookProcessStatus; - error: string; - method: string; -} - -interface HookProcessState extends HookProcessInfo { - client: QqHookClient | null; - sender: HookPacketClient | null; - injectResult: HookInjectResult | 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. */ +export type HookManagerDeps = { + ntqq: NtqqHandler; + bridgeManager: BridgeManager; + /** Native injector entrypoints. Defaults to the real native addon. */ + injector?: HookSessionDeps['injector']; + /** Hook pipe-client factory. Defaults to `new QqHookClient(pid)`. */ + makeClient?: HookSessionDeps['makeClient']; + /** Pre-built watcher. Defaults to a PipeWatcher wrapping the native listings. */ + pipeWatcher?: PipeWatcher; + /** Polling interval for the default watcher. Ignored if `pipeWatcher` is provided. */ watcherIntervalMs?: number; -} + /** Native process lister used by `listProcesses()`. Defaults to the native addon. */ + listProcesses?: () => HookProcessBaseInfo[]; + log?: Logger; +}; /** - * Manages SnowLuma hook injection and bridge connectivity for QQ.exe processes. + * HookManager — thin orchestrator over a per-PID HookSession map and a + * singleton PipeWatcher. * - * 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. + * Responsibilities: + * - Route user commands (load/unload/refresh) to the matching session. + * - Route watcher diff events to the matching session. + * - Forward session events ('login' / 'disconnected') to BridgeManager. + * - Retry stuck-in-connecting sessions on every watcher tick (so a + * failed connect eventually recovers without a manual refresh). * - * 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. + * The native injector, native pipe-client, and native process/pipe + * listings are all swappable dependencies so tests can run without a + * real QQ.exe or a native addon. */ export class HookManager { - private readonly states = new Map(); - private readonly opsByPid = new Map>(); - private readonly watcherIntervalMs: number; - private watcherTimer: NodeJS.Timeout | null = null; - private watcherTicking = false; + private readonly ntqq: NtqqHandler; + private readonly bridgeManager: BridgeManager; + private readonly injector: HookSessionDeps['injector']; + private readonly makeClient: HookSessionDeps['makeClient']; + private readonly pipeWatcher: PipeWatcher; + private readonly ownsPipeWatcher: boolean; + private readonly listProcessesNative: () => HookProcessBaseInfo[]; + private readonly log: Logger; + private readonly sessions = new Map(); + private readonly startPromise: Promise; + 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); + constructor(deps: HookManagerDeps) { + this.ntqq = deps.ntqq; + this.bridgeManager = deps.bridgeManager; + this.log = deps.log ?? createLogger('Hook'); + + this.injector = deps.injector ?? { + inject: injectHookProcess, + unload: (pid, handle) => { + if (!handle) return; + unloadHookProcess(pid, handle); + }, + }; + this.makeClient = deps.makeClient ?? ((pid: number) => new QqHookClient(pid)); + this.listProcessesNative = deps.listProcesses ?? listHookProcesses; + + if (deps.pipeWatcher) { + this.pipeWatcher = deps.pipeWatcher; + this.ownsPipeWatcher = false; + } else { + this.pipeWatcher = new PipeWatcher({ + listProcesses: this.listProcessesNative, + listLivePipes: () => QqHookClient.listLivePipes(), + intervalMs: deps.watcherIntervalMs, + log: this.log, + }); + this.ownsPipeWatcher = true; + } + + this.bindWatcher(); + this.startPromise = this.pipeWatcher.start(); } + // ─────────────── public API (unchanged from prior HookManager) ─────────────── + async listProcesses(): Promise { - const processes = listHookProcesses(); - for (const proc of processes) { - const state = this.ensureState(proc.pid); - state.name = proc.name || state.name; - state.path = proc.path || state.path; + await this.startPromise; + let processes: HookProcessBaseInfo[]; + try { + processes = this.listProcessesNative(); + } catch (error) { + this.log.warn('listProcesses failed: %s', errMsg(error)); + processes = []; } const result: HookProcessInfo[] = []; for (const proc of processes) { - result.push(this.toPublicInfo(this.ensureState(proc.pid))); + const session = this.ensureSession(proc.pid); + session.attachProcessInfo(proc); + result.push(session.toInfo()); } return result.sort((a, b) => a.pid - b.pid); } - loadProcess(pid: number): Promise { - if (!Number.isInteger(pid) || pid <= 0) throw new Error('invalid pid'); - return this.serialize(pid, () => this.loadProcessInternal(pid)); + async loadProcess(pid: number): Promise { + this.assertValidPid(pid); + await this.startPromise; + const session = this.ensureSession(pid); + const info = await session.load(); + // Pull the next tick forward so a freshly-injected pipe gets noticed + // within the next event-loop turn instead of after the full interval. + this.pipeWatcher.wake(); + return info; } - unloadProcess(pid: number): Promise { - if (!Number.isInteger(pid) || pid <= 0) throw new Error('invalid pid'); - return this.serialize(pid, () => this.unloadProcessInternal(pid)); + async unloadProcess(pid: number): Promise { + this.assertValidPid(pid); + await this.startPromise; + const session = this.ensureSession(pid); + return session.unload(); } - /** - * 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 { - if (!Number.isInteger(pid) || pid <= 0) throw new Error('invalid pid'); - return this.serialize(pid, () => this.refreshProcessInternal(pid)); + async refreshProcess(pid: number): Promise { + this.assertValidPid(pid); + await this.startPromise; + const session = this.ensureSession(pid); + return session.refresh(); } dispose(): void { + if (this.disposed) return; this.disposed = true; - if (this.watcherTimer) { - clearTimeout(this.watcherTimer); - this.watcherTimer = null; + for (const session of this.sessions.values()) { + session.dispose(); } - for (const state of this.states.values()) { - this.tearDownClient(state); - state.status = state.injected ? 'disconnected' : 'available'; + this.sessions.clear(); + if (this.ownsPipeWatcher) { + this.pipeWatcher.dispose(); } } - // ───────────────────────── per-PID serialization ───────────────────────── + // ─────────────── wiring ─────────────── - /** - * 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(pid: number, op: () => Promise): Promise { - const previous = this.opsByPid.get(pid) ?? Promise.resolve(); - let release!: () => void; - const completion = new Promise(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 { - const state = this.ensureState(pid); - state.error = ''; - state.status = 'loading'; - - try { - if (!state.injected) { - // 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 = state.method || 'reconnect'; - log.info('PID=%d already has SnowLuma pipe; will reconnect via watcher', pid); - } else { - state.injectResult = injectHookProcess(pid); - state.injected = true; - state.method = state.injectResult.method; - } - } - 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); - } - - private async unloadProcessInternal(pid: number): Promise { - const state = this.ensureState(pid); - state.error = ''; - - try { - const wasLoggedIn = state.loggedIn; - this.tearDownClient(state); - if (wasLoggedIn) this.bridgeManager.onPidDisconnected(pid); - - const handle = state.injectResult?.handle; - if (state.injected && handle) { - unloadHookProcess(pid, handle); - log.info('SnowLuma unloaded from PID=%d via unloadModuleManual', pid); - } - - // Clear injection state first - state.injected = false; - state.injectResult = null; - state.method = ''; - state.uin = '0'; - - // Verify unload succeeded by checking if pipe still exists - const livePipes = await QqHookClient.listLivePipes(); - if (livePipes.has(pid)) { - // Pipe still exists - unload failed, but let watcher handle reconnection - state.error = 'DLL卸载失败:命名管道仍然存在,watcher将自动重连'; - state.status = 'connecting'; // Let watcher pick it up and reconnect - log.warn('unload verification failed: PID=%d pipe still exists after unloadModuleManual, watcher will reconnect', pid); - } else { - // Successfully unloaded - state.status = 'available'; - state.error = ''; - } - } catch (error) { - state.status = 'error'; - state.error = error instanceof Error ? error.message : String(error); - log.error('unload failed: PID=%d err=%s', pid, state.error); - } - - return this.toPublicInfo(state); - } - - private async refreshProcessInternal(pid: number): Promise { - 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) { - state = { - pid, - name: 'QQ.exe', - path: '', - injected: false, - connected: false, - loggedIn: false, - uin: '0', - status: 'available', - error: '', - method: '', - client: null, - sender: null, - injectResult: null, - bound: false, - }; - this.states.set(pid, state); - } - return state; - } - - // ───────────────────────────── 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 { - if (this.disposed) return; - if (this.watcherTicking) { - this.scheduleWatcher(this.watcherIntervalMs); - return; - } - this.watcherTicking = true; - try { - const livePipes = await QqHookClient.listLivePipes(); - const processes = listHookProcesses(); - const runningSet = new Set(processes.map(p => p.pid)); - - // 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 or failed unload. - for (const pid of livePipes) { - if (!runningSet.has(pid)) continue; - 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 tasks: Promise[] = []; - for (const state of [...this.states.values()]) { - const alivePipe = livePipes.has(state.pid); - const aliveProc = runningSet.has(state.pid); - - if (!aliveProc) { - const wasLoggedIn = state.loggedIn; - this.tearDownClient(state); - if (wasLoggedIn) this.bridgeManager.onPidDisconnected(state.pid); - 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 { - 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 { - 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 { - 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; - } - - 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'; - } - } - - private bindClient(state: HookProcessState, client: QqHookClient): void { - client.on('packet', packet => this.handlePacket(state, packet)); - client.on('loginState', loginState => this.handleLoginState(state, loginState)); - client.on('error', error => { - const msg = this.errMsg(error); - state.error = msg; - log.warn('pipe error: PID=%d err=%s', state.pid, msg); - }); - client.on('close', () => { + private bindWatcher(): void { + this.pipeWatcher.on('process-discovered', (info: HookProcessBaseInfo) => { 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'; + const session = this.ensureSession(info.pid); + session.attachProcessInfo(info); + }); + this.pipeWatcher.on('process-gone', (pid: number) => { + if (this.disposed) return; + const session = this.sessions.get(pid); + if (session) session.notifyProcessGone(); + }); + this.pipeWatcher.on('pipe-up', (pid: number) => { + if (this.disposed) return; + const session = this.sessions.get(pid); + if (session) session.onPipeUp(); + }); + this.pipeWatcher.on('pipe-down', (pid: number) => { + if (this.disposed) return; + const session = this.sessions.get(pid); + if (session) session.onPipeDown(); + }); + // After every tick, retry sessions that are stuck in 'connecting' + // while the pipe is up. Mirrors the original tickWatcher's per-tick + // reconcileConnect pass; onPipeUp is idempotent so calling it for an + // already-connected session is harmless. + this.pipeWatcher.on('tick', () => { + if (this.disposed) return; + for (const session of this.sessions.values()) { + if (session.status === 'connecting' && this.pipeWatcher.isPipeLive(session.pid)) { + session.onPipeUp(); } - }).catch(err => log.warn('close reconcile failed: PID=%d err=%s', state.pid, this.errMsg(err))); + } }); } - /** Detach + close the current client and reset its associated fields. */ - private tearDownClient(state: HookProcessState): void { - const client = state.client; - 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 ensureSession(pid: number): HookSession { + let session = this.sessions.get(pid); + if (session) return session; + + session = new HookSession(pid, { + injector: this.injector, + makeClient: this.makeClient, + pipeWatcher: this.pipeWatcher, + ntqq: this.ntqq, + log: this.log, + }); + session.attachProcessInfo({ name: defaultProcessName() }); + + session.on('login', (uin: string, sender) => { + this.bridgeManager.onHookLogin(pid, uin, sender); + }); + session.on('disconnected', (wasLoggedIn: boolean) => { + if (wasLoggedIn) this.bridgeManager.onPidDisconnected(pid); + }); + session.on('disposed', () => { + this.sessions.delete(pid); + }); + + this.sessions.set(pid, session); + return session; } - private handleLoginState(state: HookProcessState, loginState: QqHookLoginState): void { - const wasLoggedIn = state.loggedIn; - const previousUin = state.uin; - state.uin = loginState.uin || loginState.uinNumber.toString(); - state.loggedIn = loginState.loggedIn && isRealUin(state.uin); - state.status = state.loggedIn ? 'online' : (state.connected ? 'loaded' : state.status); - - if (!state.loggedIn || !state.sender) return; - if (wasLoggedIn && previousUin === state.uin) return; - - this.bridgeManager.onHookLogin(state.pid, state.uin, state.sender); - log.success('login detected: PID=%d UIN=%s', state.pid, state.uin); - } - - private handlePacket(state: HookProcessState, packet: QqHookPacket): void { - if (!state.loggedIn) return; - const uin = packet.uin || state.uin; - if (!isRealUin(uin)) return; - this.ntqq.onHookPacket(state.pid, { ...packet, uin }); - } - - private toPublicInfo(state: HookProcessState): HookProcessInfo { - return { - pid: state.pid, - name: state.name, - path: state.path, - injected: state.injected, - connected: state.connected, - loggedIn: state.loggedIn, - uin: state.uin, - status: state.status, - error: state.error, - method: state.method, - }; - } - - private errMsg(value: unknown): string { - return value instanceof Error ? value.message : String(value); + private assertValidPid(pid: number): void { + if (!Number.isInteger(pid) || pid <= 0) throw new Error('invalid pid'); } } -function isRealUin(uin: string): boolean { - if (!uin || uin === '0') return false; - return /^\d+$/.test(uin) && uin.length >= 5; +function defaultProcessName(): string { + return process.platform === 'win32' ? 'QQ.exe' : 'qq'; +} + +function errMsg(value: unknown): string { + return value instanceof Error ? value.message : String(value); } diff --git a/packages/core/src/hook/hook-session.ts b/packages/core/src/hook/hook-session.ts new file mode 100644 index 00000000..82398ac7 --- /dev/null +++ b/packages/core/src/hook/hook-session.ts @@ -0,0 +1,416 @@ +import { EventEmitter } from 'events'; +import type { NtqqHandler } from '../protocol/ntqq-handler'; +import type { PacketSender } from '../protocol/packet-sender'; +import { createLogger, type Logger } from '../utils/logger'; +import { HookPacketClient } from './hook-packet-client'; +import type { HookInjectResult } from './injector'; +import type { QqHookClient, QqHookLoginState, QqHookPacket } from './qq-hook-client'; +import type { HookProcessInfo, HookProcessStatus } from './types'; + +export type HookSessionDeps = { + injector: { + inject: (pid: number) => HookInjectResult; + unload: (pid: number, handle: HookInjectResult['handle']) => void; + }; + makeClient: (pid: number) => QqHookClient; + /** Sync fast-path check used by load() to skip re-injection when a + * prior SnowLuma run left a working pipe behind. */ + pipeWatcher: { isPipeLive: (pid: number) => boolean }; + /** Optional packet sink. If provided, parsed packets are forwarded here. */ + ntqq?: NtqqHandler; + log?: Logger; +}; + +/** + * HookSession — owns the lifecycle of one QQ.exe process: injection, + * pipe client, login state, and the public status field. + * + * Concurrency: every state-mutating method goes through a per-session + * promise chain so user clicks (load/unload/refresh) and watcher-driven + * events (onPipeUp/onPipeDown) never interleave. + * + * Communication: emits high-level events instead of calling BridgeManager + * directly, so HookManager forwards them and tests can attach spies. + * + * Emitted events: + * 'login' (uin, packetSender) — real-UIN login detected + * 'disconnected' (wasLoggedIn) — connection dropped or torn down + * 'status-changed' (status, error) — status field mutated + * 'disposed' () — session stopped tracking this PID + */ +export class HookSession extends EventEmitter { + readonly pid: number; + + private readonly injector: HookSessionDeps['injector']; + private readonly makeClient: HookSessionDeps['makeClient']; + private readonly pipeWatcher: HookSessionDeps['pipeWatcher']; + private readonly ntqq: NtqqHandler | null; + private readonly log: Logger; + + private _status: HookProcessStatus = 'available'; + private _error = ''; + private _uin = '0'; + private _method = ''; + private _name = ''; + private _path = ''; + + private injected = false; + private connected = false; + private loggedIn = false; + private injectResult: HookInjectResult | null = null; + private client: QqHookClient | null = null; + private sender: HookPacketClient | null = null; + private bound = false; + private opChain: Promise = Promise.resolve(); + private disposed = false; + + constructor(pid: number, deps: HookSessionDeps) { + super(); + this.pid = pid; + this.injector = deps.injector; + this.makeClient = deps.makeClient; + this.pipeWatcher = deps.pipeWatcher; + this.ntqq = deps.ntqq ?? null; + this.log = deps.log ?? createLogger('HookSession'); + } + + // ─────────────── readonly public surface ─────────────── + + get status(): HookProcessStatus { return this._status; } + get error(): string { return this._error; } + get uin(): string { return this._uin; } + get method(): string { return this._method; } + get isDisposed(): boolean { return this.disposed; } + + attachProcessInfo(info: { name?: string; path?: string }): void { + if (info.name) this._name = info.name; + if (info.path) this._path = info.path; + } + + toInfo(): HookProcessInfo { + return { + pid: this.pid, + name: this._name, + path: this._path, + injected: this.injected, + connected: this.connected, + loggedIn: this.loggedIn, + uin: this._uin, + status: this._status, + error: this._error, + method: this._method, + }; + } + + // ─────────────── user-facing commands ─────────────── + + load(): Promise { + return this.serialize(() => this.loadInternal()); + } + + unload(): Promise { + return this.serialize(() => this.unloadInternal()); + } + + refresh(): Promise { + return this.serialize(() => this.refreshInternal()); + } + + // ─────────────── watcher-driven events (called by manager) ─────────────── + + /** Pipe came up (or stayed up across a SnowLuma restart). Drives connect + * attempts and adopts pre-existing hooks. Idempotent; safe to call on + * every watcher tick where the pipe is live. */ + onPipeUp(): void { + if (this.disposed) return; + void this.serialize(async () => { + if (this.disposed) return; + // Adopt a DLL that survived a SnowLuma restart. + if (!this.injected) { + this.injected = true; + if (!this._method) this._method = 'reconnect'; + } + if (this.client?.isClosed) this.tearDownClient(); + if (!this.connected) { + await this.attemptConnect(); + } else { + this.setStatus(this.loggedIn ? 'online' : 'loaded', ''); + } + }).catch(err => this.log.warn('onPipeUp failed: PID=%d err=%s', this.pid, errMsg(err))); + } + + onPipeDown(): void { + if (this.disposed) return; + void this.serialize(async () => { + if (this.disposed) return; + if (!this.connected) { + // Nothing to tear down; just keep status visible. + if (this.injected) this.setStatus('connecting', this._error); + return; + } + const wasLoggedIn = this.loggedIn; + this.tearDownClient(); + this.setStatus( + this.injected ? (wasLoggedIn ? 'disconnected' : 'connecting') : 'available', + '', + ); + if (wasLoggedIn) this.emit('disconnected', true); + }).catch(err => this.log.warn('onPipeDown failed: PID=%d err=%s', this.pid, errMsg(err))); + } + + /** Called by the manager when the watcher reports the QQ.exe process is + * gone. Cleans up and signals the manager to remove this session. */ + notifyProcessGone(): void { + if (this.disposed) return; + void this.serialize(async () => { + if (this.disposed) return; + const wasLoggedIn = this.loggedIn; + this.tearDownClient(); + this.injected = false; + this.injectResult = null; + this._method = ''; + this.setStatus('available', ''); + if (wasLoggedIn) this.emit('disconnected', true); + this.disposed = true; + this.emit('disposed'); + this.removeAllListeners(); + }).catch(err => this.log.warn('notifyProcessGone failed: PID=%d err=%s', this.pid, errMsg(err))); + } + + dispose(): void { + if (this.disposed) return; + this.disposed = true; + this.tearDownClient(); + this.removeAllListeners(); + } + + // ─────────────── per-session serialization ─────────────── + + private serialize(op: () => Promise): Promise { + const previous = this.opChain; + let release!: () => void; + const completion = new Promise(resolve => { release = resolve; }); + this.opChain = previous.then(() => completion); + return (async () => { + try { + await previous.catch(() => undefined); + return await op(); + } finally { + release(); + } + })(); + } + + // ─────────────── internal transitions ─────────────── + + private async loadInternal(): Promise { + this._error = ''; + this.setStatus('loading', ''); + try { + if (!this.injected) { + // Fast path: a previous SnowLuma run may have left the hook DLL + // resident in QQ.exe. If the watcher already sees a live pipe, + // skip re-injection and let onPipeUp drive the reconnect. + if (this.pipeWatcher.isPipeLive(this.pid)) { + this.injected = true; + this._method = this._method || 'reconnect'; + this.log.info('PID=%d already has SnowLuma pipe; will reconnect', this.pid); + } else { + this.injectResult = this.injector.inject(this.pid); + this.injected = true; + this._method = this.injectResult.method; + } + } + this.setStatus( + this.connected ? (this.loggedIn ? 'online' : 'loaded') : 'connecting', + '', + ); + } catch (error) { + this._error = errMsg(error); + this.setStatus('error', this._error); + this.log.error('load failed: PID=%d err=%s', this.pid, this._error); + } + return this.toInfo(); + } + + private async unloadInternal(): Promise { + this._error = ''; + try { + const wasLoggedIn = this.loggedIn; + this.tearDownClient(); + if (wasLoggedIn) this.emit('disconnected', true); + + const handle = this.injectResult?.handle; + if (this.injected && handle) { + this.injector.unload(this.pid, handle); + this.log.info('SnowLuma unloaded from PID=%d', this.pid); + } + + this.injected = false; + this.injectResult = null; + this._method = ''; + this._uin = '0'; + + // Verify the unload took: if the pipe is still up the DLL is still + // resident. Drop back to 'connecting' and let the watcher reconnect. + if (this.pipeWatcher.isPipeLive(this.pid)) { + this._error = 'DLL卸载失败:命名管道仍然存在,watcher将自动重连'; + this.setStatus('connecting', this._error); + this.log.warn('unload verification failed: PID=%d pipe still up', this.pid); + } else { + this.setStatus('available', ''); + } + } catch (error) { + this._error = errMsg(error); + this.setStatus('error', this._error); + this.log.error('unload failed: PID=%d err=%s', this.pid, this._error); + } + return this.toInfo(); + } + + private async refreshInternal(): Promise { + this._error = ''; + try { + const pipeUp = this.pipeWatcher.isPipeLive(this.pid); + if (pipeUp) { + // Adopt an unknown DLL the same way onPipeUp would. + if (!this.injected) { + this.injected = true; + this._method = this._method || 'reconnect'; + } + if (this.client?.isClosed) this.tearDownClient(); + if (!this.connected) { + await this.attemptConnect(); + } else { + this.setStatus(this.loggedIn ? 'online' : 'loaded', ''); + } + } else { + const wasLoggedIn = this.loggedIn; + this.tearDownClient(); + this.setStatus(this.injected ? 'disconnected' : 'available', ''); + if (wasLoggedIn) this.emit('disconnected', true); + } + } catch (error) { + this._error = errMsg(error); + this.setStatus(this.injected ? 'disconnected' : 'error', this._error); + this.log.warn('refresh failed: PID=%d err=%s', this.pid, this._error); + } + return this.toInfo(); + } + + // ─────────────── client plumbing ─────────────── + + private async attemptConnect(): Promise { + if (this.connected) return; + if (this.client?.isClosed) this.tearDownClient(); + if (!this.client) { + this.client = this.makeClient(this.pid); + this.sender = new HookPacketClient(this.client); + this.bound = false; + } + if (!this.bound) { + this.bindClient(this.client); + this.bound = true; + } + + const client = this.client; + try { + await client.connectAll({ recv: true }); + this.connected = true; + this.setStatus(client.isLoggedIn ? 'online' : 'loaded', ''); + const loginState = client.getLoginState(); + if (loginState.loggedIn) this.handleLoginState(loginState); + this.log.info('pipe connected: PID=%d', this.pid); + } catch (error) { + this._error = errMsg(error); + // Drop the client so the next attempt builds a fresh socket pair. + this.tearDownClient(); + this.setStatus(this.injected ? 'connecting' : 'available', this._error); + } + } + + private bindClient(client: QqHookClient): void { + client.on('packet', packet => this.handlePacket(packet)); + client.on('loginState', state => this.handleLoginState(state)); + client.on('error', error => { + const msg = errMsg(error); + this._error = msg; + this.log.warn('pipe error: PID=%d err=%s', this.pid, msg); + }); + client.on('close', () => { + if (this.disposed) return; + // Only the currently-registered client should drive a reconcile; + // listeners may fire for an already-replaced client. + if (this.client !== client) return; + void this.serialize(async () => { + if (this.disposed) return; + if (this.client !== client) return; + const wasLoggedIn = this.loggedIn; + this.tearDownClient(); + if (!this.injected) { + this.setStatus('available', ''); + } else if (wasLoggedIn) { + this.setStatus('disconnected', ''); + } else { + this.setStatus('connecting', ''); + } + if (wasLoggedIn) this.emit('disconnected', true); + }).catch(err => this.log.warn('close reconcile failed: PID=%d err=%s', this.pid, errMsg(err))); + }); + } + + private tearDownClient(): void { + const client = this.client; + if (client) { + client.removeAllListeners(); + try { client.close(); } catch { /* ignore */ } + } + this.client = null; + this.sender = null; + this.bound = false; + this.connected = false; + this.loggedIn = false; + } + + private handleLoginState(state: QqHookLoginState): void { + const wasLoggedIn = this.loggedIn; + const previousUin = this._uin; + this._uin = state.uin || state.uinNumber.toString(); + this.loggedIn = state.loggedIn && isRealUin(this._uin); + + if (this.loggedIn) { + this.setStatus('online', ''); + } else if (this.connected) { + this.setStatus('loaded', this._error); + } + + if (!this.loggedIn || !this.sender) return; + if (wasLoggedIn && previousUin === this._uin) return; + + this.emit('login', this._uin, this.sender); + this.log.success('login detected: PID=%d UIN=%s', this.pid, this._uin); + } + + private handlePacket(packet: QqHookPacket): void { + if (!this.loggedIn) return; + const uin = packet.uin || this._uin; + if (!isRealUin(uin)) return; + this.ntqq?.onHookPacket(this.pid, { ...packet, uin }); + } + + private setStatus(status: HookProcessStatus, error: string): void { + if (this._status === status && this._error === error) return; + this._status = status; + this._error = error; + this.emit('status-changed', status, error); + } +} + +function isRealUin(uin: string): boolean { + if (!uin || uin === '0') return false; + return /^\d+$/.test(uin) && uin.length >= 5; +} + +function errMsg(value: unknown): string { + return value instanceof Error ? value.message : String(value); +} diff --git a/packages/core/src/hook/pipe-watcher.ts b/packages/core/src/hook/pipe-watcher.ts new file mode 100644 index 00000000..b69bb34e --- /dev/null +++ b/packages/core/src/hook/pipe-watcher.ts @@ -0,0 +1,208 @@ +import { EventEmitter } from 'events'; +import { createLogger, type Logger } from '../utils/logger'; +import type { HookProcessBaseInfo } from './injector'; + +const DEFAULT_INTERVAL_MS = 1500; +const MIN_INTERVAL_MS = 250; + +export type PipeWatcherDeps = { + /** Native: list QQ.exe processes currently running. */ + listProcesses: () => HookProcessBaseInfo[]; + /** Native: PIDs that currently have a live SnowLuma named pipe. */ + listLivePipes: () => Promise>; + /** Polling interval in ms. Defaults to 1500, floored to 250. */ + intervalMs?: number; + log?: Logger; +}; + +/** + * PipeWatcher — the only module that polls the OS for QQ.exe processes + * and live SnowLuma named pipes. Subscribers consume diffs as events. + * + * Lifecycle: start() runs one tick synchronously, then schedules a poll + * every `intervalMs`. tickNow() drains a single tick on demand. wake() + * pulls the next scheduled tick forward to the next event-loop turn. + * + * Emitted events: + * 'process-discovered' (info: HookProcessBaseInfo) — a QQ.exe appeared + * 'process-gone' (pid: number) — a QQ.exe disappeared + * 'pipe-up' (pid: number) — named pipe came up + * 'pipe-down' (pid: number) — named pipe dropped + * 'tick' () — fired after every poll + * + * Within a single tick the order is: process-discovered, pipe-up, + * pipe-down, process-gone, tick. That ordering lets HookManager create + * a session before it gets a pipe event and run disconnect logic before + * dispose logic when QQ.exe is killed with a live pipe. + */ +export class PipeWatcher extends EventEmitter { + private readonly listProcesses: PipeWatcherDeps['listProcesses']; + private readonly listLivePipes: PipeWatcherDeps['listLivePipes']; + private readonly intervalMs: number; + private readonly log: Logger; + + private livePipes = new Set(); + private knownPids = new Set(); + private timer: NodeJS.Timeout | null = null; + private ticking = false; + private pendingWake = false; + private startPromise: Promise | null = null; + private stopped = false; + + constructor(deps: PipeWatcherDeps) { + super(); + this.listProcesses = deps.listProcesses; + this.listLivePipes = deps.listLivePipes; + this.intervalMs = Math.max(MIN_INTERVAL_MS, deps.intervalMs ?? DEFAULT_INTERVAL_MS); + this.log = deps.log ?? createLogger('PipeWatcher'); + } + + /** Was this PID's pipe live as of the last completed tick? */ + isPipeLive(pid: number): boolean { + return this.livePipes.has(pid); + } + + /** Was this PID alive as of the last completed tick? */ + isProcessAlive(pid: number): boolean { + return this.knownPids.has(pid); + } + + /** + * Run an initial tick (so isPipeLive/isProcessAlive return real data) + * and begin the polling loop. Idempotent. + */ + start(): Promise { + if (this.startPromise) return this.startPromise; + this.startPromise = (async () => { + try { + await this.tickOnce(); + } finally { + this.scheduleNext(this.intervalMs); + } + })(); + return this.startPromise; + } + + /** Pull the next scheduled tick forward to the next event-loop turn. */ + wake(): void { + if (this.stopped) return; + this.scheduleNext(0); + } + + /** Force a single tick now. Resolves after diff events have been emitted. */ + tickNow(): Promise { + return this.tickOnce(); + } + + stop(): void { + this.stopped = true; + if (this.timer) { + clearTimeout(this.timer); + this.timer = null; + } + } + + dispose(): void { + this.stop(); + this.removeAllListeners(); + } + + private scheduleNext(delayMs: number): void { + if (this.stopped) return; + if (this.timer) { + clearTimeout(this.timer); + this.timer = null; + } + this.timer = setTimeout(() => { + this.timer = null; + void this.tickAndReschedule(); + }, Math.max(0, delayMs)); + } + + private async tickAndReschedule(): Promise { + try { + await this.tickOnce(); + } finally { + this.scheduleNext(this.intervalMs); + } + } + + /** + * Read processes + live pipes, emit diff events. If another tick is + * already running, mark a follow-up tick so we don't lose a wake(). + */ + private async tickOnce(): Promise { + if (this.ticking) { + this.pendingWake = true; + return; + } + this.ticking = true; + try { + let processes: HookProcessBaseInfo[]; + try { + processes = this.listProcesses(); + } catch (error) { + this.log.warn('listProcesses failed: %s', errMsg(error)); + processes = []; + } + let livePipes: Set; + try { + livePipes = await this.listLivePipes(); + } catch (error) { + this.log.warn('listLivePipes failed: %s', errMsg(error)); + livePipes = new Set(); + } + + const newKnownPids = new Set(); + for (const proc of processes) newKnownPids.add(proc.pid); + + // 1. Newly discovered processes. + for (const proc of processes) { + if (!this.knownPids.has(proc.pid)) { + this.emit('process-discovered', proc); + } + } + + // 2. Pipes that came up. Ignore pipes for processes we don't know + // about (would race against an out-of-order tick). + const newLivePipes = new Set(); + for (const pid of livePipes) { + if (!newKnownPids.has(pid)) continue; + newLivePipes.add(pid); + if (!this.livePipes.has(pid)) { + this.emit('pipe-up', pid); + } + } + + // 3. Pipes that dropped. Emit pipe-down BEFORE process-gone so + // subscribers can run disconnect logic before dispose logic. + for (const pid of this.livePipes) { + if (!newLivePipes.has(pid)) { + this.emit('pipe-down', pid); + } + } + + // 4. Processes that disappeared. + for (const pid of this.knownPids) { + if (!newKnownPids.has(pid)) { + this.emit('process-gone', pid); + } + } + + this.knownPids = newKnownPids; + this.livePipes = newLivePipes; + this.emit('tick'); + } finally { + this.ticking = false; + if (this.pendingWake) { + this.pendingWake = false; + // Defer to break sync recursion if a listener calls wake(). + setImmediate(() => { void this.tickOnce(); }); + } + } + } +} + +function errMsg(value: unknown): string { + return value instanceof Error ? value.message : String(value); +} diff --git a/packages/core/src/hook/types.ts b/packages/core/src/hook/types.ts new file mode 100644 index 00000000..352b00bc --- /dev/null +++ b/packages/core/src/hook/types.ts @@ -0,0 +1,27 @@ +import type { HookProcessBaseInfo } from './injector'; + +/** + * Lifecycle status of a single per-PID HookSession. + * + * Transitions live inside HookSession; this union only enumerates the + * states visible to API callers (WebUI, manager.listProcesses()). + */ +export type HookProcessStatus = + | 'available' + | 'loading' + | 'connecting' + | 'loaded' + | 'online' + | 'error' + | 'disconnected'; + +/** Public-facing snapshot of a per-PID HookSession. */ +export interface HookProcessInfo extends HookProcessBaseInfo { + injected: boolean; + connected: boolean; + loggedIn: boolean; + uin: string; + status: HookProcessStatus; + error: string; + method: string; +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index e3ddd4fe..48a7046f 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -14,7 +14,7 @@ async function main() { const ntqq = new NtqqHandler(); const bridgeManager = new BridgeManager(); const oneBotManager = new OneBotManager(); - const hookManager = new HookManager(ntqq, bridgeManager); + const hookManager = new HookManager({ ntqq, bridgeManager }); // Bind bridge manager to NTQQ handler (receives all parsed packets) bridgeManager.bind(ntqq); diff --git a/packages/core/tests/hook-session.test.ts b/packages/core/tests/hook-session.test.ts new file mode 100644 index 00000000..6220d750 --- /dev/null +++ b/packages/core/tests/hook-session.test.ts @@ -0,0 +1,309 @@ +import { describe, it, expect, vi } from 'vitest'; +import { EventEmitter } from 'events'; +import { HookSession } from '../src/hook/hook-session'; +import type { ManualMapHandle } from '../src/hook/injector'; +import type { QqHookClient } from '../src/hook/qq-hook-client'; + +const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 }; + +/** Minimal stand-in for QqHookClient. Tests drive login/packet/error/close + * events directly via fire* helpers. connectAll succeeds unless told otherwise. */ +class FakeClient extends EventEmitter { + isClosed = false; + isLoggedIn = false; + shouldFailConnect = false; + private loginState = { loggedIn: false, uin: '0', uinNumber: 0n }; + + async connectAll(_opts: { recv: boolean }): Promise { + if (this.shouldFailConnect) throw new Error('connect failed'); + if (this.isClosed) throw new Error('client is closed'); + } + getLoginState() { return { ...this.loginState }; } + close(): void { + if (this.isClosed) return; + this.isClosed = true; + this.emit('close'); + } + + fireLogin(uin: string): void { + this.isLoggedIn = true; + this.loginState = { loggedIn: true, uin, uinNumber: BigInt(uin) }; + this.emit('loginState', { ...this.loginState }); + } +} + +function makeSession(opts: { pid?: number; pipeLive?: boolean; clientFailsConnect?: boolean } = {}) { + const pid = opts.pid ?? 1234; + let pipeLive = opts.pipeLive ?? false; + const clients: FakeClient[] = []; + const injector = { + inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })), + unload: vi.fn(), + }; + + const session = new HookSession(pid, { + injector, + makeClient: () => { + const c = new FakeClient(); + if (opts.clientFailsConnect) c.shouldFailConnect = true; + clients.push(c); + // Cast: FakeClient mirrors only the surface HookSession touches. + return c as unknown as QqHookClient; + }, + pipeWatcher: { isPipeLive: () => pipeLive }, + }); + + return { + session, + injector, + clients, + currentClient: () => clients[clients.length - 1], + setPipeLive: (v: boolean) => { pipeLive = v; }, + }; +} + +const flush = () => new Promise(r => setImmediate(r)); + +describe('HookSession — load', () => { + it('with no live pipe: injects, status → connecting, method from inject result', async () => { + const { session, injector } = makeSession({ pipeLive: false }); + const info = await session.load(); + + expect(injector.inject).toHaveBeenCalledOnce(); + expect(info.status).toBe('connecting'); + expect(info.method).toBe('loadModuleManual'); + expect(info.injected).toBe(true); + }); + + it('fast-path: pipe already live → skip inject, method → "reconnect"', async () => { + const { session, injector } = makeSession({ pipeLive: true }); + const info = await session.load(); + + expect(injector.inject).not.toHaveBeenCalled(); + expect(info.method).toBe('reconnect'); + expect(info.injected).toBe(true); + expect(info.status).toBe('connecting'); + }); + + it('inject failure → status error, error message captured', async () => { + const injector = { + inject: vi.fn(() => { throw new Error('inject boom'); }), + unload: vi.fn(), + }; + const session = new HookSession(1234, { + injector, + makeClient: () => new FakeClient() as unknown as QqHookClient, + pipeWatcher: { isPipeLive: () => false }, + }); + const info = await session.load(); + expect(info.status).toBe('error'); + expect(info.error).toBe('inject boom'); + }); +}); + +describe('HookSession — pipe up/down → connect lifecycle', () => { + it('onPipeUp after load: client connects → status loaded', async () => { + const ctx = makeSession({ pipeLive: true }); + await ctx.session.load(); + ctx.session.onPipeUp(); + await flush(); + + expect(ctx.session.status).toBe('loaded'); + expect(ctx.clients).toHaveLength(1); + }); + + it('emits "login" with (uin, sender) after client signals loggedIn', async () => { + const ctx = makeSession({ pipeLive: true }); + const loginSpy = vi.fn(); + ctx.session.on('login', loginSpy); + + await ctx.session.load(); + ctx.session.onPipeUp(); + await flush(); + ctx.currentClient().fireLogin('10001'); + + expect(loginSpy).toHaveBeenCalledOnce(); + const [uin, sender] = loginSpy.mock.calls[0]!; + expect(uin).toBe('10001'); + expect(typeof (sender as { sendPacket: unknown }).sendPacket).toBe('function'); + expect(ctx.session.status).toBe('online'); + expect(ctx.session.uin).toBe('10001'); + }); + + it('does not re-emit "login" on duplicate loginState with same uin', async () => { + const ctx = makeSession({ pipeLive: true }); + const loginSpy = vi.fn(); + ctx.session.on('login', loginSpy); + + await ctx.session.load(); + ctx.session.onPipeUp(); + await flush(); + + ctx.currentClient().fireLogin('10001'); + ctx.currentClient().fireLogin('10001'); + + expect(loginSpy).toHaveBeenCalledOnce(); + }); + + it('connect failure: stays in connecting, error message captured (will retry on next tick)', async () => { + const ctx = makeSession({ pipeLive: true, clientFailsConnect: true }); + await ctx.session.load(); + ctx.session.onPipeUp(); + await flush(); + + expect(ctx.session.status).toBe('connecting'); + expect(ctx.session.error).toBe('connect failed'); + }); + + it('onPipeDown while logged in: emits disconnected(true), status disconnected', async () => { + const ctx = makeSession({ pipeLive: true }); + const discSpy = vi.fn(); + ctx.session.on('disconnected', discSpy); + + await ctx.session.load(); + ctx.session.onPipeUp(); + await flush(); + ctx.currentClient().fireLogin('10001'); + + ctx.session.onPipeDown(); + await flush(); + + expect(discSpy).toHaveBeenCalledWith(true); + expect(ctx.session.status).toBe('disconnected'); + }); + + it('onPipeDown while connected-but-not-logged-in: emits disconnected(false), status connecting', async () => { + const ctx = makeSession({ pipeLive: true }); + const discSpy = vi.fn(); + ctx.session.on('disconnected', discSpy); + + await ctx.session.load(); + ctx.session.onPipeUp(); + await flush(); + // No login fired — we're connected but not logged in. + + ctx.session.onPipeDown(); + await flush(); + + // disconnected(false) is currently NOT emitted — disconnect events are + // reserved for "we owe BridgeManager a disconnect notification". This + // preserves the original behaviour. + expect(discSpy).not.toHaveBeenCalled(); + expect(ctx.session.status).toBe('connecting'); + }); + + it('repeated pipe down → up cycles reach consistent state', async () => { + const ctx = makeSession({ pipeLive: true }); + await ctx.session.load(); + ctx.session.onPipeUp(); + await flush(); + ctx.currentClient().fireLogin('10001'); + expect(ctx.session.status).toBe('online'); + + ctx.session.onPipeDown(); + await flush(); + expect(ctx.session.status).toBe('disconnected'); + + // Pipe returns — session builds a fresh client. + ctx.session.onPipeUp(); + await flush(); + expect(ctx.clients.length).toBeGreaterThan(1); + expect(ctx.session.status).toBe('loaded'); + }); +}); + +describe('HookSession — unload', () => { + it('while logged in: emits disconnected(true), calls unload, status available', async () => { + const ctx = makeSession({ pipeLive: false }); + await ctx.session.load(); + ctx.setPipeLive(true); + ctx.session.onPipeUp(); + await flush(); + ctx.currentClient().fireLogin('10001'); + + const discSpy = vi.fn(); + ctx.session.on('disconnected', discSpy); + ctx.setPipeLive(false); // unload verification will see the pipe gone + + await ctx.session.unload(); + + expect(discSpy).toHaveBeenCalledWith(true); + expect(ctx.injector.unload).toHaveBeenCalledOnce(); + expect(ctx.session.status).toBe('available'); + }); + + it('when pipe stays live after unload: status connecting with retry message', async () => { + const ctx = makeSession({ pipeLive: false }); + await ctx.session.load(); + // Simulate the unload-failed scenario: pipe is still up after unload. + ctx.setPipeLive(true); + + const info = await ctx.session.unload(); + + expect(info.status).toBe('connecting'); + expect(info.error).toContain('命名管道仍然存在'); + }); +}); + +describe('HookSession — serialization', () => { + it('user mashing load → unload → load runs in order, end state consistent', async () => { + const ctx = makeSession({ pipeLive: false }); + + const p1 = ctx.session.load(); + const p2 = ctx.session.unload(); + const p3 = ctx.session.load(); + await Promise.all([p1, p2, p3]); + + expect(ctx.injector.inject).toHaveBeenCalledTimes(2); + expect(ctx.injector.unload).toHaveBeenCalledTimes(1); + expect(ctx.session.status).toBe('connecting'); + }); + + it('onPipeUp queued behind in-flight load resolves correctly', async () => { + const ctx = makeSession({ pipeLive: true }); + + const loadPromise = ctx.session.load(); + ctx.session.onPipeUp(); // queued behind load + + await loadPromise; + await flush(); + + expect(ctx.session.status).toBe('loaded'); + }); +}); + +describe('HookSession — process gone', () => { + it('emits disconnected(true) then disposed when killed while logged in', async () => { + const ctx = makeSession({ pipeLive: true }); + await ctx.session.load(); + ctx.session.onPipeUp(); + await flush(); + ctx.currentClient().fireLogin('10001'); + + const events: string[] = []; + ctx.session.on('disconnected', () => events.push('disconnected')); + ctx.session.on('disposed', () => events.push('disposed')); + + ctx.session.notifyProcessGone(); + await flush(); + + expect(events).toEqual(['disconnected', 'disposed']); + expect(ctx.session.isDisposed).toBe(true); + }); + + it('emits only disposed when killed before login', async () => { + const ctx = makeSession({ pipeLive: true }); + await ctx.session.load(); + ctx.session.onPipeUp(); + await flush(); + + const events: string[] = []; + ctx.session.on('disconnected', () => events.push('disconnected')); + ctx.session.on('disposed', () => events.push('disposed')); + + ctx.session.notifyProcessGone(); + await flush(); + + expect(events).toEqual(['disposed']); + }); +}); diff --git a/packages/core/tests/pipe-watcher.test.ts b/packages/core/tests/pipe-watcher.test.ts new file mode 100644 index 00000000..5486971d --- /dev/null +++ b/packages/core/tests/pipe-watcher.test.ts @@ -0,0 +1,197 @@ +import { describe, it, expect } from 'vitest'; +import { PipeWatcher } from '../src/hook/pipe-watcher'; +import type { HookProcessBaseInfo } from '../src/hook/injector'; + +const flush = () => new Promise(r => setImmediate(r)); + +function setupWatcher(initial: { processes: HookProcessBaseInfo[]; live: Set }) { + let processes = initial.processes; + let live = initial.live; + const watcher = new PipeWatcher({ + listProcesses: () => processes, + // Defensively copy so the watcher can't mutate the test's reference. + listLivePipes: async () => new Set(live), + intervalMs: 60_000, // disable the internal timer; tests drive ticks manually + }); + return { + watcher, + setProcesses: (p: HookProcessBaseInfo[]) => { processes = p; }, + setLive: (s: Set) => { live = s; }, + }; +} + +type EventRow = [string, unknown]; + +function captureEvents(watcher: PipeWatcher): EventRow[] { + const events: EventRow[] = []; + watcher.on('process-discovered', info => events.push(['discovered', (info as HookProcessBaseInfo).pid])); + watcher.on('process-gone', pid => events.push(['gone', pid])); + watcher.on('pipe-up', pid => events.push(['up', pid])); + watcher.on('pipe-down', pid => events.push(['down', pid])); + return events; +} + +describe('PipeWatcher', () => { + it('start() emits process-discovered + pipe-up for live PIDs on first tick', async () => { + const ctx = setupWatcher({ + processes: [{ pid: 1234, name: 'QQ.exe', path: '' }], + live: new Set([1234]), + }); + const events = captureEvents(ctx.watcher); + await ctx.watcher.start(); + + expect(events).toEqual([ + ['discovered', 1234], + ['up', 1234], + ]); + expect(ctx.watcher.isPipeLive(1234)).toBe(true); + expect(ctx.watcher.isProcessAlive(1234)).toBe(true); + + ctx.watcher.stop(); + }); + + it('pipe-down emitted when a previously-live pipe disappears', async () => { + const ctx = setupWatcher({ + processes: [{ pid: 1234, name: 'QQ.exe', path: '' }], + live: new Set([1234]), + }); + await ctx.watcher.start(); + const events = captureEvents(ctx.watcher); + + ctx.setLive(new Set()); + await ctx.watcher.tickNow(); + + expect(events).toEqual([['down', 1234]]); + expect(ctx.watcher.isPipeLive(1234)).toBe(false); + ctx.watcher.stop(); + }); + + it('process-gone + pipe-down both emitted (pipe-down first) when QQ.exe is killed with a live pipe', async () => { + const ctx = setupWatcher({ + processes: [{ pid: 1234, name: 'QQ.exe', path: '' }], + live: new Set([1234]), + }); + await ctx.watcher.start(); + const events = captureEvents(ctx.watcher); + + ctx.setProcesses([]); + ctx.setLive(new Set()); + await ctx.watcher.tickNow(); + + expect(events).toEqual([ + ['down', 1234], + ['gone', 1234], + ]); + ctx.watcher.stop(); + }); + + it('ignores live pipes whose process is not running', async () => { + const ctx = setupWatcher({ + processes: [], + live: new Set([9999]), + }); + const events = captureEvents(ctx.watcher); + await ctx.watcher.start(); + + expect(events).toEqual([]); + expect(ctx.watcher.isPipeLive(9999)).toBe(false); + ctx.watcher.stop(); + }); + + it('emits pipe-up again after a pipe-down → pipe-up cycle', async () => { + const ctx = setupWatcher({ + processes: [{ pid: 1234, name: 'QQ.exe', path: '' }], + live: new Set(), + }); + await ctx.watcher.start(); + const events = captureEvents(ctx.watcher); + + ctx.setLive(new Set([1234])); + await ctx.watcher.tickNow(); + expect(events).toEqual([['up', 1234]]); + + ctx.setLive(new Set()); + await ctx.watcher.tickNow(); + expect(events).toEqual([['up', 1234], ['down', 1234]]); + + ctx.setLive(new Set([1234])); + await ctx.watcher.tickNow(); + expect(events).toEqual([['up', 1234], ['down', 1234], ['up', 1234]]); + + ctx.watcher.stop(); + }); + + it('does not double-emit on idempotent ticks (no state change)', async () => { + const ctx = setupWatcher({ + processes: [{ pid: 1234, name: 'QQ.exe', path: '' }], + live: new Set([1234]), + }); + await ctx.watcher.start(); + const events = captureEvents(ctx.watcher); + + await ctx.watcher.tickNow(); + await ctx.watcher.tickNow(); + + expect(events).toEqual([]); + ctx.watcher.stop(); + }); + + it('emits "tick" after every poll', async () => { + const ctx = setupWatcher({ processes: [], live: new Set() }); + let ticks = 0; + ctx.watcher.on('tick', () => { ticks++; }); + + await ctx.watcher.start(); + expect(ticks).toBe(1); + + await ctx.watcher.tickNow(); + expect(ticks).toBe(2); + + ctx.watcher.stop(); + }); + + it('wake() pulls the next tick forward', async () => { + const ctx = setupWatcher({ + processes: [{ pid: 1234, name: 'QQ.exe', path: '' }], + live: new Set(), + }); + await ctx.watcher.start(); + const events = captureEvents(ctx.watcher); + + // Wait on 'tick' rather than guessing how many event-loop turns + // setTimeout(0) needs (it's clamped to ~1ms and races setImmediate). + const nextTick = new Promise(resolve => ctx.watcher.once('tick', () => resolve())); + ctx.setLive(new Set([1234])); + ctx.watcher.wake(); + await nextTick; + + expect(events).toEqual([['up', 1234]]); + ctx.watcher.stop(); + }); + + it('survives a throwing listProcesses without crashing the watcher', async () => { + let processes: HookProcessBaseInfo[] = []; + let live = new Set(); + let shouldThrow = true; + const watcher = new PipeWatcher({ + listProcesses: () => { + if (shouldThrow) throw new Error('boom'); + return processes; + }, + listLivePipes: async () => new Set(live), + intervalMs: 60_000, + }); + + await watcher.start(); + expect(watcher.isProcessAlive(1234)).toBe(false); + + shouldThrow = false; + processes = [{ pid: 1234, name: 'QQ.exe', path: '' }]; + live = new Set([1234]); + const events = captureEvents(watcher); + await watcher.tickNow(); + + expect(events).toEqual([['discovered', 1234], ['up', 1234]]); + watcher.stop(); + }); +});