diff --git a/src/main/daemon/production-launcher.test.ts b/src/main/daemon/production-launcher.test.ts index bfeda791e..cec7d0b6c 100644 --- a/src/main/daemon/production-launcher.test.ts +++ b/src/main/daemon/production-launcher.test.ts @@ -125,6 +125,57 @@ describe('createProductionLauncher', () => { expect(child.disconnect).toHaveBeenCalled() expect(child.unref).toHaveBeenCalled() }) + + it('removes shutdown exit listener when force-kill timeout settles first', async () => { + vi.useFakeTimers() + try { + const handlers: Record void)[]> = { + message: [], + error: [], + exit: [] + } + const child = { + pid: 12345, + killed: false, + on: vi.fn((event: string, cb: (arg?: unknown) => void) => { + handlers[event]?.push(cb) + return child + }), + once: vi.fn((event: string, cb: (arg?: unknown) => void) => { + handlers[event]?.push(cb) + return child + }), + off: vi.fn((event: string, cb: (arg?: unknown) => void) => { + handlers[event] = handlers[event]?.filter((handler) => handler !== cb) ?? [] + return child + }), + kill: vi.fn(), + disconnect: vi.fn(), + unref: vi.fn() + } + forkMock.mockReturnValueOnce(child) + + const launcher = createProductionLauncher({ + getDaemonEntryPath: () => join(dir, 'daemon-entry.js') + }) + + const launch = launcher(socketPathFor(dir), tokenPathFor(dir)) + handlers.message[0]?.({ type: 'ready' }) + const handle = await launch + + const shutdown = handle.shutdown() + expect(handlers.exit).toHaveLength(1) + + await vi.advanceTimersByTimeAsync(5000) + await shutdown + + expect(child.kill).toHaveBeenNthCalledWith(1, 'SIGTERM') + expect(child.kill).toHaveBeenNthCalledWith(2, 'SIGKILL') + expect(handlers.exit).toHaveLength(0) + } finally { + vi.useRealTimers() + } + }) }) function socketPathFor(dir: string): string { diff --git a/src/main/daemon/production-launcher.ts b/src/main/daemon/production-launcher.ts index 10693ef79..bf4ff5973 100644 --- a/src/main/daemon/production-launcher.ts +++ b/src/main/daemon/production-launcher.ts @@ -89,16 +89,28 @@ function shutdownChild(child: ChildProcess): Promise { return } - const timeout = setTimeout(() => { - child.kill('SIGKILL') + let settled = false + let timeout: ReturnType + function finish(): void { + if (settled) { + return + } + settled = true + clearTimeout(timeout) + child.off('exit', onExit) resolve() + } + + function onExit(): void { + finish() + } + + timeout = setTimeout(() => { + child.kill('SIGKILL') + finish() }, 5000) - child.once('exit', () => { - clearTimeout(timeout) - resolve() - }) - + child.once('exit', onExit) child.kill('SIGTERM') }) }