From 6a2fd9e8f3008aa08624ce47a52afc3d3b3509b7 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Sun, 7 Jun 2026 22:15:07 +0800 Subject: [PATCH] fix(bridge): don't crash the daemon when the hook pipe closes mid-send MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When the control pipe drops while a send() is awaiting its ack, rejectControlPending() rejects both the ack and the reply deferreds. The reply is only awaited after the ack, so an ack-first rejection leaves the reply promise rejected with NO awaiter — an unhandled rejection that, under Node's default policy, kills the process. In Docker supervisor restarts it (every session drops for ~1s); on a bare Windows run it just dies, surfacing as "connection pipe closed" with the bot offline after hours of uptime. Attach a no-op .catch() to each deferred at creation so a rejection can never go unhandled (the real await still observes the value/rejection). Add a regression test that drops the pipe mid-send and asserts no unhandled rejection escapes — it fails without the guard. Also install last-resort process guards (unhandledRejection / uncaughtException) in the app entry: log and keep serving instead of exiting, so any other stray rejection cannot take the daemon down and its stack is captured. The bridge's watcher reconnects the dropped pipe on the next tick. --- packages/bridge/src/qq-hook-client.ts | 7 +++ packages/bridge/tests/qq-hook-client.test.ts | 66 +++++++++++++++++++- packages/core/src/index.ts | 16 +++++ 3 files changed, 88 insertions(+), 1 deletion(-) diff --git a/packages/bridge/src/qq-hook-client.ts b/packages/bridge/src/qq-hook-client.ts index 49b6420d..0651bbc8 100644 --- a/packages/bridge/src/qq-hook-client.ts +++ b/packages/bridge/src/qq-hook-client.ts @@ -465,6 +465,12 @@ export class QqHookClient extends EventEmitter { }); const ackDeferred = createDeferred<{ requestId: number; wantReply: boolean }>(); + // Always attach a handler so a rejection can never become "unhandled" (which + // crashes Node). When the pipe closes, rejectControlPending() rejects every + // pending deferred — but the reply is only `await`ed AFTER the ack, so if the + // ack fails first the reply promise is rejected with NO awaiter. The real + // `await` below still observes the value/rejection (a separate continuation). + ackDeferred.promise.catch(() => { /* observed by the await, or harmless */ }); this.pendingAcks.set(requestId, { resolve: ackDeferred.resolve, reject: ackDeferred.reject, @@ -474,6 +480,7 @@ export class QqHookClient extends EventEmitter { let replyDeferred: Deferred | null = null; if (wantReply) { replyDeferred = createDeferred(); + replyDeferred.promise.catch(() => { /* see note above — prevents unhandled rejection */ }); this.pendingReplies.set(requestId, replyDeferred); } diff --git a/packages/bridge/tests/qq-hook-client.test.ts b/packages/bridge/tests/qq-hook-client.test.ts index b84ae67e..7c27bdbc 100644 --- a/packages/bridge/tests/qq-hook-client.test.ts +++ b/packages/bridge/tests/qq-hook-client.test.ts @@ -1,8 +1,9 @@ +import net from 'net'; import { mkdtemp, rm, writeFile } from 'fs/promises'; import os from 'os'; import path from 'path'; import { afterEach, describe, expect, it, vi } from 'vitest'; -import { listLiveLinuxPipePids } from '../src/qq-hook-client'; +import { listLiveLinuxPipePids, QqHookClient } from '../src/qq-hook-client'; let tmpDir: string | null = null; @@ -42,3 +43,66 @@ describe('listLiveLinuxPipePids', () => { expect(probe).toHaveBeenCalledTimes(2); }); }); + +describe.skipIf(process.platform === 'win32')('QqHookClient — pipe close mid-send', () => { + // Regression: when the control pipe closes while a send() is awaiting its + // ack, rejectControlPending() rejects BOTH the ack and reply deferreds. The + // reply is only `await`ed after the ack, so if the ack rejects first the + // reply promise is rejected with NO awaiter — an UNHANDLED rejection that + // crashes the Node process (Docker: supervisor restarts it ~1s later; on + // Windows it just dies → "connection pipe closed", bot down). The .catch() + // guard on each deferred prevents it; without the guard this test trips the + // unhandledRejection assertion below. + it('does not raise an unhandled rejection', async () => { + const dir = await mkdtemp(path.join(os.tmpdir(), 'snowluma-pipe-')); + const prevRuntimeDir = process.env.SNOWLUMA_HOOK_RUNTIME_DIR; + process.env.SNOWLUMA_HOOK_RUNTIME_DIR = dir; + + const PID = 778899; + const helloFrame = (): Buffer => { + const h = Buffer.alloc(40); + h.writeUInt32LE(0x31504851, 0); // PIPE_MAGIC + h.writeUInt16LE(1, 4); // PIPE_VERSION + h.writeUInt16LE(1, 6); // PipeOp.hello + h.writeBigUInt64LE(BigInt(PID), 32); // value0 = pid + return h; + }; + + let controlConn: net.Socket | null = null; + const controlServer = net.createServer((sock) => { controlConn = sock; sock.write(helloFrame()); }); + const recvServer = net.createServer((sock) => { sock.write(helloFrame()); }); + await new Promise((r) => controlServer.listen(path.join(dir, `mojo.${PID}.control.sock`), () => r())); + await new Promise((r) => recvServer.listen(path.join(dir, `mojo.${PID}.recv.sock`), () => r())); + + const unhandled: unknown[] = []; + const onUnhandled = (reason: unknown): void => { unhandled.push(reason); }; + process.on('unhandledRejection', onUnhandled); + + const client = new QqHookClient(PID); + client.on('error', () => { /* socket reset on destroy — ignore */ }); + try { + await client.connectAll({ recv: true }); + + // Start a reply-expecting send, let it reach the in-flight (awaiting-ack) + // state, then have the "hook" drop the pipe before it answers. + const sent = client.send('noop', null, { wantReply: true, ackTimeoutMs: 1000, replyTimeoutMs: 1000 }) + .then(() => 'resolved' as const, (e: unknown) => e); + await new Promise((r) => setTimeout(r, 30)); + controlConn?.destroy(); + + const outcome = await sent; + await new Promise((r) => setTimeout(r, 50)); // let Node surface any unhandled rejection + + expect(outcome).toBeInstanceOf(Error); + expect(unhandled, `unhandled rejections leaked: ${unhandled.map(String).join(', ')}`).toHaveLength(0); + } finally { + process.off('unhandledRejection', onUnhandled); + client.close(); + await new Promise((r) => controlServer.close(() => r())); + await new Promise((r) => recvServer.close(() => r())); + if (prevRuntimeDir === undefined) delete process.env.SNOWLUMA_HOOK_RUNTIME_DIR; + else process.env.SNOWLUMA_HOOK_RUNTIME_DIR = prevRuntimeDir; + await rm(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 26f84eae..0c31ca61 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -7,6 +7,22 @@ import { BridgeManager } from './bridge/manager'; const runtimeConfig = loadRuntimeConfig(); const log = createLogger('App'); +// Last-resort process guards. This is a long-running daemon: a hooked QQ pipe +// can drop at any moment, and a stray rejection on a detached callback (or a +// throw that escapes one) must NOT take the whole process down — otherwise +// Docker restarts it (dropping every session) and a bare Windows run just dies +// ("connection pipe closed", bot offline). Log and keep serving; the bridge's +// own watcher reconnects the dropped pipe. Targeted handlers still cover the +// known paths (e.g. the hook-client send deferreds) — these only catch what +// slips through, and surface its stack so the real source can be fixed. +process.on('unhandledRejection', (reason) => { + log.error('unhandledRejection (kept alive): %s', + reason instanceof Error ? (reason.stack ?? reason.message) : String(reason)); +}); +process.on('uncaughtException', (error) => { + log.error('uncaughtException (kept alive): %s', error.stack ?? error.message); +}); + async function main() { log.info('SnowLuma starting');