From f7e89c6c8b205d71934c434e3d2bf5b73ac0f152 Mon Sep 17 00:00:00 2001 From: Ramzi <79337754+heyramzi@users.noreply.github.com> Date: Mon, 13 Apr 2026 06:31:31 +0100 Subject: [PATCH] fix: dispose PTY event listeners before kill to prevent SIGABRT crash (#534) * fix: dispose PTY event listeners before kill to prevent SIGABRT crash node-pty's onData/onExit callbacks register native NAPI ThreadSafeFunction objects. When a PTY process is killed without deregistering these callbacks, the stale ThreadSafeFunction references survive into the Node environment cleanup phase (node::FreeEnvironment). NAPI then attempts to invoke CallJS on the destroyed environment, causing Napi::Error::ThrowAsJavaScriptException to throw a C++ exception that terminates the process with SIGABRT. Store the IDisposable handles returned by proc.onData() and proc.onExit(), and dispose them in clearPtyState() before the process is killed. This covers all teardown paths: explicit pty:kill IPC, runtime controller kill, page-reload orphan cleanup, and app-quit killAllPty. Co-Authored-By: Claude Opus 4.6 (1M context) * fix: use T[] array syntax instead of Array to satisfy oxlint Co-Authored-By: Claude Opus 4.6 (1M context) --------- Co-authored-by: Claude Opus 4.6 (1M context) --- src/main/ipc/pty.test.ts | 130 +++++++++++++++++++++++++++++++++++++-- src/main/ipc/pty.ts | 79 +++++++++++++++--------- 2 files changed, 177 insertions(+), 32 deletions(-) diff --git a/src/main/ipc/pty.test.ts b/src/main/ipc/pty.test.ts index 340abfc75..de09971ab 100644 --- a/src/main/ipc/pty.test.ts +++ b/src/main/ipc/pty.test.ts @@ -68,6 +68,10 @@ vi.mock('../pi/titlebar-extension-service', () => ({ })) import { registerPtyHandlers } from './pty' +function makeDisposable() { + return { dispose: vi.fn() } +} + describe('registerPtyHandlers', () => { const handlers = new Map unknown>() const mainWindow = { @@ -113,8 +117,8 @@ describe('registerPtyHandlers', () => { : '/tmp/orca-pi-agent-overlay' })) spawnMock.mockReturnValue({ - onData: vi.fn(), - onExit: vi.fn(), + onData: vi.fn(() => makeDisposable()), + onExit: vi.fn(() => makeDisposable()), write: vi.fn(), resize: vi.fn(), kill: vi.fn() @@ -372,8 +376,8 @@ describe('registerPtyHandlers', () => { it('cleans up provider-specific PTY overlays when a PTY is killed', () => { const proc = { - onData: vi.fn(), - onExit: vi.fn(), + onData: vi.fn(() => makeDisposable()), + onExit: vi.fn(() => makeDisposable()), write: vi.fn(), resize: vi.fn(), kill: vi.fn() @@ -391,4 +395,122 @@ describe('registerPtyHandlers', () => { expect(openCodeClearPtyMock).toHaveBeenCalledWith(spawnResult.id) expect(piClearPtyMock).toHaveBeenCalledWith(spawnResult.id) }) + + it('disposes PTY listeners before manual kill IPC', () => { + const onDataDisposable = makeDisposable() + const onExitDisposable = makeDisposable() + const proc = { + onData: vi.fn(() => onDataDisposable), + onExit: vi.fn(() => onExitDisposable), + write: vi.fn(), + resize: vi.fn(), + kill: vi.fn() + } + spawnMock.mockReturnValue(proc) + + registerPtyHandlers(mainWindow as never) + const spawnResult = handlers.get('pty:spawn')!(null, { cols: 80, rows: 24 }) as { id: string } + + handlers.get('pty:kill')!(null, { id: spawnResult.id }) + + expect(onDataDisposable.dispose.mock.invocationCallOrder[0]).toBeLessThan( + proc.kill.mock.invocationCallOrder[0] + ) + expect(onExitDisposable.dispose.mock.invocationCallOrder[0]).toBeLessThan( + proc.kill.mock.invocationCallOrder[0] + ) + }) + + it('disposes PTY listeners before runtime controller kill', () => { + const onDataDisposable = makeDisposable() + const onExitDisposable = makeDisposable() + const proc = { + onData: vi.fn(() => onDataDisposable), + onExit: vi.fn(() => onExitDisposable), + write: vi.fn(), + resize: vi.fn(), + kill: vi.fn() + } + const runtime = { + setPtyController: vi.fn(), + onPtySpawned: vi.fn(), + onPtyData: vi.fn(), + onPtyExit: vi.fn() + } + spawnMock.mockReturnValue(proc) + + registerPtyHandlers(mainWindow as never, runtime as never) + const spawnResult = handlers.get('pty:spawn')!(null, { cols: 80, rows: 24 }) as { id: string } + const runtimeController = runtime.setPtyController.mock.calls[0]?.[0] as { + kill: (ptyId: string) => boolean + } + + expect(runtimeController.kill(spawnResult.id)).toBe(true) + expect(onDataDisposable.dispose.mock.invocationCallOrder[0]).toBeLessThan( + proc.kill.mock.invocationCallOrder[0] + ) + expect(onExitDisposable.dispose.mock.invocationCallOrder[0]).toBeLessThan( + proc.kill.mock.invocationCallOrder[0] + ) + }) + + it('disposes PTY listeners before did-finish-load orphan cleanup', () => { + const onDataDisposable = makeDisposable() + const onExitDisposable = makeDisposable() + const proc = { + onData: vi.fn(() => onDataDisposable), + onExit: vi.fn(() => onExitDisposable), + write: vi.fn(), + resize: vi.fn(), + kill: vi.fn() + } + const runtime = { + setPtyController: vi.fn(), + onPtySpawned: vi.fn(), + onPtyData: vi.fn(), + onPtyExit: vi.fn() + } + spawnMock.mockReturnValue(proc) + + registerPtyHandlers(mainWindow as never, runtime as never) + const didFinishLoad = mainWindow.webContents.on.mock.calls.find( + ([eventName]) => eventName === 'did-finish-load' + )?.[1] as (() => void) | undefined + expect(didFinishLoad).toBeTypeOf('function') + handlers.get('pty:spawn')!(null, { cols: 80, rows: 24 }) + + // The first load after spawn only advances generation. The second one sees + // this PTY as belonging to a prior page load and kills it as orphaned. + didFinishLoad?.() + didFinishLoad?.() + + expect(onDataDisposable.dispose.mock.invocationCallOrder[0]).toBeLessThan( + proc.kill.mock.invocationCallOrder[0] + ) + expect(onExitDisposable.dispose.mock.invocationCallOrder[0]).toBeLessThan( + proc.kill.mock.invocationCallOrder[0] + ) + }) + + it('clears PTY state even when kill reports the process is already gone', () => { + const proc = { + onData: vi.fn(() => makeDisposable()), + onExit: vi.fn(() => makeDisposable()), + write: vi.fn(), + resize: vi.fn(), + kill: vi.fn(() => { + throw new Error('already dead') + }) + } + spawnMock.mockReturnValue(proc) + + registerPtyHandlers(mainWindow as never) + const spawnResult = handlers.get('pty:spawn')!(null, { cols: 80, rows: 24 }) as { id: string } + + handlers.get('pty:kill')!(null, { id: spawnResult.id }) + + expect(handlers.get('pty:hasChildProcesses')!(null, { id: spawnResult.id })).toBe(false) + expect(openCodeClearPtyMock).toHaveBeenCalledWith(spawnResult.id) + expect(piClearPtyMock).toHaveBeenCalledWith(spawnResult.id) + }) }) diff --git a/src/main/ipc/pty.ts b/src/main/ipc/pty.ts index 1f994c2b3..59c6780b2 100644 --- a/src/main/ipc/pty.ts +++ b/src/main/ipc/pty.ts @@ -16,6 +16,13 @@ let ptyCounter = 0 const ptyProcesses = new Map() /** Basename of the shell binary each PTY was spawned with (e.g. "zsh"). */ const ptyShellName = new Map() +// Why: node-pty's onData/onExit register native NAPI ThreadSafeFunction +// callbacks. If the PTY is killed without disposing these listeners, the +// stale callbacks survive into node::FreeEnvironment() where NAPI attempts +// to invoke/clean them up on a destroyed environment, triggering a SIGABRT +// via Napi::Error::ThrowAsJavaScriptException. Storing and calling the +// disposables before proc.kill() prevents the use-after-free crash. +const ptyDisposables = new Map void }[]>() // Track which "page load generation" each PTY belongs to. // When the renderer reloads, we only kill PTYs from previous generations, @@ -26,12 +33,48 @@ let loadGeneration = 0 const ptyLoadGeneration = new Map() let didEnsureSpawnHelperExecutable = false +function disposePtyListeners(id: string): void { + const disposables = ptyDisposables.get(id) + if (disposables) { + for (const d of disposables) { + d.dispose() + } + ptyDisposables.delete(id) + } +} + function clearPtyState(id: string): void { + disposePtyListeners(id) + clearPtyRegistryState(id) +} + +function clearPtyRegistryState(id: string): void { ptyProcesses.delete(id) ptyShellName.delete(id) ptyLoadGeneration.delete(id) } +function killPtyProcess(id: string, proc: pty.IPty): boolean { + // Why: node-pty's listener disposables must be torn down before proc.kill() + // on every explicit teardown path, not just app quit. Some kills happen + // during reload/manual-close flows where waiting for later state cleanup is + // too late to stop the stale NAPI callbacks from surviving into shutdown. + disposePtyListeners(id) + let killed = true + try { + proc.kill() + } catch { + killed = false + } + // Why: once an explicit kill path decides this PTY is done, we must clear + // the bookkeeping maps even if node-pty reports the process was already + // gone. Leaving the stale registry entry behind makes later lookups think + // the PTY is still live even though runtime teardown already ran. + clearPtyRegistryState(id) + clearProviderPtyState(id) + return killed +} + function clearProviderPtyState(id: string): void { // Why: OpenCode and Pi both allocate PTY-scoped runtime state outside the // node-pty process table. Centralizing provider cleanup avoids drift where a @@ -120,13 +163,7 @@ export function registerPtyHandlers( for (const [id, proc] of ptyProcesses) { const gen = ptyLoadGeneration.get(id) ?? -1 if (gen < loadGeneration) { - try { - proc.kill() - } catch { - // Process may already be dead - } - clearPtyState(id) - clearProviderPtyState(id) + killPtyProcess(id, proc) // Why: notify runtime so the agent detector can close out any live // agent sessions. Without this, killed PTYs would remain in the // detector's liveAgents map and accumulate inflated durations. @@ -151,13 +188,9 @@ export function registerPtyHandlers( if (!proc) { return false } - try { - proc.kill() - } catch { + if (!killPtyProcess(ptyId, proc)) { return false } - clearPtyState(ptyId) - clearProviderPtyState(ptyId) runtime?.onPtyExit(ptyId, -1) return true } @@ -357,14 +390,14 @@ export function registerPtyHandlers( ptyLoadGeneration.set(id, loadGeneration) runtime?.onPtySpawned(id) - proc.onData((data) => { + const onDataDisposable = proc.onData((data) => { runtime?.onPtyData(id, data, Date.now()) if (!mainWindow.isDestroyed()) { mainWindow.webContents.send('pty:data', { id, data }) } }) - proc.onExit(({ exitCode }) => { + const onExitDisposable = proc.onExit(({ exitCode }) => { clearPtyState(id) clearProviderPtyState(id) runtime?.onPtyExit(id, exitCode) @@ -373,6 +406,8 @@ export function registerPtyHandlers( } }) + ptyDisposables.set(id, [onDataDisposable, onExitDisposable]) + return { id } } ) @@ -394,13 +429,7 @@ export function registerPtyHandlers( ipcMain.handle('pty:kill', (_event, args: { id: string }) => { const proc = ptyProcesses.get(args.id) if (proc) { - try { - proc.kill() - } catch { - // Process may already be dead - } - clearPtyState(args.id) - clearProviderPtyState(args.id) + killPtyProcess(args.id, proc) runtime?.onPtyExit(args.id, -1) } }) @@ -451,12 +480,6 @@ export function registerPtyHandlers( */ export function killAllPty(): void { for (const [id, proc] of ptyProcesses) { - try { - proc.kill() - } catch { - // Process may already be dead - } - clearPtyState(id) - clearProviderPtyState(id) + killPtyProcess(id, proc) } }