From 8d3f640e67b3cd0e8e7d1dc7e00e157986d31751 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Thu, 9 Apr 2026 23:50:23 -0700 Subject: [PATCH] Fix macOS dev Electron shutdown on Ctrl+C (#435) --- config/scripts/run-electron-vite-dev.mjs | 101 ++++++++++++++++ package.json | 2 +- src/main/index.ts | 4 + .../electron-vite-dev-grandchild.mjs | 1 + .../fake-electron-vite-dev-cli.mjs | 19 +++ src/main/startup/configure-process.test.ts | 112 +++++++++++++++++- src/main/startup/configure-process.ts | 57 +++++++++ .../startup/run-electron-vite-dev.test.ts | 102 ++++++++++++++++ 8 files changed, 396 insertions(+), 2 deletions(-) create mode 100644 config/scripts/run-electron-vite-dev.mjs create mode 100644 src/main/startup/__fixtures__/electron-vite-dev-grandchild.mjs create mode 100644 src/main/startup/__fixtures__/fake-electron-vite-dev-cli.mjs create mode 100644 src/main/startup/run-electron-vite-dev.test.ts diff --git a/config/scripts/run-electron-vite-dev.mjs b/config/scripts/run-electron-vite-dev.mjs new file mode 100644 index 000000000..4794aa387 --- /dev/null +++ b/config/scripts/run-electron-vite-dev.mjs @@ -0,0 +1,101 @@ +import { spawn } from 'node:child_process' +import { createRequire } from 'node:module' +import path from 'node:path' + +const require = createRequire(import.meta.url) +// Why: tests inject a tiny fake CLI here so they can verify Ctrl+C tears down +// the full child tree without depending on a real electron-vite install. +const electronViteCli = + process.env.ORCA_ELECTRON_VITE_CLI || + path.join(path.dirname(require.resolve('electron-vite/package.json')), 'bin', 'electron-vite.js') +const forwardedArgs = ['dev', ...process.argv.slice(2)] +const child = spawn(process.execPath, [electronViteCli, ...forwardedArgs], { + stdio: 'inherit', + // Why: electron-vite launches Electron as a descendant process. Giving the + // dev runner its own process group lets Ctrl+C kill the whole tree on macOS + // instead of leaving the Electron app alive after the terminal exits. + detached: process.platform !== 'win32' +}) + +let isShuttingDown = false +let forcedKillTimer = null + +function signalExitCode(signal) { + if (signal === 'SIGINT') { + return 130 + } + if (signal === 'SIGTERM') { + return 143 + } + return 1 +} + +function terminateChild(signal) { + if (!child.pid) { + return + } + + if (process.platform === 'win32') { + const taskkill = spawn('taskkill', ['/pid', String(child.pid), '/t', '/f'], { + stdio: 'ignore', + windowsHide: true + }) + taskkill.unref() + return + } + + try { + process.kill(-child.pid, signal) + } catch (error) { + const code = error && typeof error === 'object' && 'code' in error ? error.code : null + if (code !== 'ESRCH') { + throw error + } + } +} + +function beginShutdown(signal) { + if (isShuttingDown) { + return + } + isShuttingDown = true + + terminateChild(signal) + forcedKillTimer = setTimeout(() => { + terminateChild('SIGKILL') + }, 5000) +} + +process.on('SIGINT', () => { + beginShutdown('SIGINT') +}) + +process.on('SIGTERM', () => { + beginShutdown('SIGTERM') +}) + +child.on('error', (error) => { + if (forcedKillTimer) { + clearTimeout(forcedKillTimer) + } + console.error(error) + process.exit(1) +}) + +child.on('exit', (code, signal) => { + if (forcedKillTimer) { + clearTimeout(forcedKillTimer) + } + + if (isShuttingDown) { + process.exit(signalExitCode(signal ?? 'SIGINT')) + return + } + + if (signal) { + process.exit(signalExitCode(signal)) + return + } + + process.exit(code ?? 1) +}) diff --git a/package.json b/package.json index 0b38196ea..4cdc842fc 100644 --- a/package.json +++ b/package.json @@ -22,7 +22,7 @@ "typecheck:web": "tsc --noEmit -p config/tsconfig.web.json --composite false", "typecheck": "tsc --noEmit -p config/tsconfig.node.json --composite false && tsc --noEmit -p config/tsconfig.cli.json --composite false && tsc --noEmit -p config/tsconfig.web.json --composite false", "start": "electron-vite preview", - "dev": "electron-vite dev", + "dev": "node config/scripts/run-electron-vite-dev.mjs", "build:cli": "tsc -p config/tsconfig.cli.json --outDir out --composite false --incremental false", "build:electron-vite": "node config/scripts/run-electron-vite-build.mjs", "build": "pnpm run typecheck && pnpm run build:electron-vite && pnpm run build:cli", diff --git a/src/main/index.ts b/src/main/index.ts index d4a9b9989..8221ddfec 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -14,6 +14,8 @@ import { checkForUpdatesFromMenu, isQuittingForUpdate } from './updater' import { configureDevUserDataPath, enableMainProcessGpuFeatures, + installDevParentDisconnectQuit, + installDevParentWatchdog, installUncaughtPipeErrorGuard, patchPackagedProcessPath } from './startup/configure-process' @@ -30,6 +32,8 @@ let runtimeRpc: OrcaRuntimeRpcServer | null = null installUncaughtPipeErrorGuard() patchPackagedProcessPath() configureDevUserDataPath(is.dev) +installDevParentDisconnectQuit(is.dev) +installDevParentWatchdog(is.dev) // Why: must run after configureDevUserDataPath (which redirects userData to // orca-dev in dev mode) but before app.setName('Orca') inside whenReady // (which would change the resolved path on case-sensitive filesystems). diff --git a/src/main/startup/__fixtures__/electron-vite-dev-grandchild.mjs b/src/main/startup/__fixtures__/electron-vite-dev-grandchild.mjs new file mode 100644 index 000000000..c7a964802 --- /dev/null +++ b/src/main/startup/__fixtures__/electron-vite-dev-grandchild.mjs @@ -0,0 +1 @@ +setInterval(() => {}, 1000) diff --git a/src/main/startup/__fixtures__/fake-electron-vite-dev-cli.mjs b/src/main/startup/__fixtures__/fake-electron-vite-dev-cli.mjs new file mode 100644 index 000000000..90528b179 --- /dev/null +++ b/src/main/startup/__fixtures__/fake-electron-vite-dev-cli.mjs @@ -0,0 +1,19 @@ +import { spawn } from 'node:child_process' +import { writeFileSync } from 'node:fs' +import path from 'node:path' +import { fileURLToPath } from 'node:url' + +const __dirname = path.dirname(fileURLToPath(import.meta.url)) +const grandchildPath = path.join(__dirname, 'electron-vite-dev-grandchild.mjs') +const pidFile = process.env.ORCA_DEV_WRAPPER_TEST_PID_FILE + +const grandchild = spawn(process.execPath, [grandchildPath], { + stdio: 'ignore' +}) + +if (!pidFile) { + throw new Error('ORCA_DEV_WRAPPER_TEST_PID_FILE is required') +} + +writeFileSync(pidFile, `${grandchild.pid ?? ''}\n`, 'utf8') +setInterval(() => {}, 1000) diff --git a/src/main/startup/configure-process.test.ts b/src/main/startup/configure-process.test.ts index e88be2120..00e791203 100644 --- a/src/main/startup/configure-process.test.ts +++ b/src/main/startup/configure-process.test.ts @@ -1,5 +1,5 @@ import { join } from 'path' -import { describe, expect, it, vi } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' vi.mock('electron', () => { const paths = new Map([['appData', '/tmp/app-data']]) @@ -9,6 +9,7 @@ vi.mock('electron', () => { setPath: vi.fn((name: string, value: string) => { paths.set(name, value) }), + quit: vi.fn(), commandLine: { appendSwitch: vi.fn() } @@ -16,6 +17,11 @@ vi.mock('electron', () => { } }) +afterEach(() => { + vi.useRealTimers() + vi.restoreAllMocks() +}) + describe('configureDevUserDataPath', () => { it('moves dev runs onto an orca-dev userData path', async () => { const { app } = await import('electron') @@ -38,3 +44,107 @@ describe('configureDevUserDataPath', () => { expect(app.setPath).not.toHaveBeenCalled() }) }) + +describe('installDevParentDisconnectQuit', () => { + it('quits the dev app when the supervising IPC channel disconnects', async () => { + const { app } = await import('electron') + const { installDevParentDisconnectQuit } = await import('./configure-process') + + const originalSend = process.send + const originalOnce = process.once.bind(process) + const disconnectHandlers: (() => void)[] = [] + + process.send = (() => true) as unknown as NodeJS.Process['send'] + process.once = ((event: string | symbol, listener: (...args: any[]) => void) => { + if (event === 'disconnect') { + disconnectHandlers.push(listener as () => void) + } + return process + }) as NodeJS.Process['once'] + + vi.mocked(app.quit).mockClear() + + try { + installDevParentDisconnectQuit(true) + } finally { + process.send = originalSend + process.once = originalOnce + } + + expect(disconnectHandlers).toHaveLength(1) + disconnectHandlers[0]() + expect(app.quit).toHaveBeenCalledTimes(1) + }) + + it('does not register the disconnect hook outside dev ipc launches', async () => { + const { installDevParentDisconnectQuit } = await import('./configure-process') + const originalSend = process.send + const originalOnce = process.once.bind(process) + const onceSpy = vi.fn(originalOnce) + + process.send = undefined + process.once = onceSpy as NodeJS.Process['once'] + + try { + installDevParentDisconnectQuit(true) + installDevParentDisconnectQuit(false) + } finally { + process.send = originalSend + process.once = originalOnce + } + + expect(onceSpy).not.toHaveBeenCalledWith('disconnect', expect.any(Function)) + }) +}) + +describe('installDevParentWatchdog', () => { + it('quits the dev app when the original parent pid disappears', async () => { + const { app } = await import('electron') + const { installDevParentWatchdog } = await import('./configure-process') + + vi.useFakeTimers() + vi.mocked(app.quit).mockClear() + + let parentExists = true + vi.spyOn(process, 'kill').mockImplementation((( + pid: number, + signal?: NodeJS.Signals | number + ) => { + if (signal === 0 && pid === 4242 && !parentExists) { + const error = new Error('missing') as NodeJS.ErrnoException + error.code = 'ESRCH' + throw error + } + return true + }) as typeof process.kill) + + const originalPpid = Object.getOwnPropertyDescriptor(process, 'ppid') + Object.defineProperty(process, 'ppid', { + configurable: true, + get: () => 4242 + }) + + try { + installDevParentWatchdog(true) + await vi.advanceTimersByTimeAsync(1000) + expect(app.quit).not.toHaveBeenCalled() + + parentExists = false + await vi.advanceTimersByTimeAsync(1000) + expect(app.quit).toHaveBeenCalledTimes(1) + } finally { + if (originalPpid) { + Object.defineProperty(process, 'ppid', originalPpid) + } + } + }) + + it('does not start the watchdog outside dev mode', async () => { + const { installDevParentWatchdog } = await import('./configure-process') + const setIntervalSpy = vi.spyOn(globalThis, 'setInterval') + + installDevParentWatchdog(false) + + expect(setIntervalSpy).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/startup/configure-process.ts b/src/main/startup/configure-process.ts index 2e833b23e..5f55fa2ca 100644 --- a/src/main/startup/configure-process.ts +++ b/src/main/startup/configure-process.ts @@ -56,6 +56,63 @@ export function configureDevUserDataPath(isDev: boolean): void { app.setPath('userData', join(app.getPath('appData'), 'orca-dev')) } +export function installDevParentDisconnectQuit(isDev: boolean): void { + if (!isDev || typeof process.send !== 'function') { + return + } + + // Why: electron-vite dev controls the Electron app over Node IPC so it can + // hot-restart the main process. On macOS, Ctrl+C can stop that parent process + // without terminating the app window, so in dev we quit explicitly when the + // supervising IPC channel disconnects instead of leaving a stray Electron app. + process.once('disconnect', () => { + app.quit() + }) +} + +export function installDevParentWatchdog(isDev: boolean): void { + if (!isDev) { + return + } + + const initialParentPid = process.ppid + if (!Number.isInteger(initialParentPid) || initialParentPid <= 1) { + return + } + + const timer = setInterval(() => { + const parentPidChanged = process.ppid !== initialParentPid + let parentMissing = false + + try { + process.kill(initialParentPid, 0) + } catch (error) { + if ( + error && + typeof error === 'object' && + 'code' in error && + (error as NodeJS.ErrnoException).code === 'ESRCH' + ) { + parentMissing = true + } else { + throw error + } + } + + if (parentPidChanged || parentMissing) { + clearInterval(timer) + // Why: electron-vite's dev runner starts Electron with plain spawn() and + // inherited stdio, not an IPC channel. On macOS that means Ctrl+C can end + // the dev runner while leaving Orca open. Watching the original parent PID + // keeps dev shutdown coupled to the terminal session without affecting the + // packaged app, which is not supervised by electron-vite. + app.quit() + } + }, 1000) + + timer.unref() +} + export function enableMainProcessGpuFeatures(): void { app.commandLine.appendSwitch('enable-features', 'Vulkan,UseSkiaGraphite') app.commandLine.appendSwitch('enable-unsafe-webgpu') diff --git a/src/main/startup/run-electron-vite-dev.test.ts b/src/main/startup/run-electron-vite-dev.test.ts new file mode 100644 index 000000000..c1fea6eab --- /dev/null +++ b/src/main/startup/run-electron-vite-dev.test.ts @@ -0,0 +1,102 @@ +import { mkdtempSync, readFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join, resolve } from 'node:path' +import { spawn } from 'node:child_process' +import { afterEach, describe, expect, it } from 'vitest' + +const processesToCleanUp = new Set() + +function sleep(ms: number): Promise { + return new Promise((resolvePromise) => { + setTimeout(resolvePromise, ms) + }) +} + +function processExists(pid: number): boolean { + try { + process.kill(pid, 0) + return true + } catch (error) { + const code = error && typeof error === 'object' && 'code' in error ? error.code : null + if (code === 'ESRCH') { + return false + } + throw error + } +} + +async function waitFor(predicate: () => boolean, timeoutMs = 5000): Promise { + const start = Date.now() + while (!predicate()) { + if (Date.now() - start > timeoutMs) { + throw new Error('Timed out waiting for condition') + } + await sleep(50) + } +} + +describe('run-electron-vite-dev', () => { + afterEach(() => { + for (const pid of processesToCleanUp) { + try { + process.kill(pid, 'SIGKILL') + } catch (error) { + const code = error && typeof error === 'object' && 'code' in error ? error.code : null + if (code !== 'ESRCH') { + throw error + } + } + } + processesToCleanUp.clear() + }) + + it.skipIf(process.platform === 'win32')( + 'kills the descendant process tree on SIGINT', + async () => { + const tempDir = mkdtempSync(join(tmpdir(), 'orca-dev-wrapper-')) + const pidFile = join(tempDir, 'grandchild.pid') + const wrapperPath = resolve('config/scripts/run-electron-vite-dev.mjs') + const fakeCliPath = resolve('src/main/startup/__fixtures__/fake-electron-vite-dev-cli.mjs') + + const wrapper = spawn(process.execPath, [wrapperPath], { + cwd: resolve('.'), + env: { + ...process.env, + ORCA_ELECTRON_VITE_CLI: fakeCliPath, + ORCA_DEV_WRAPPER_TEST_PID_FILE: pidFile + }, + stdio: 'ignore' + }) + + expect(wrapper.pid).toBeTypeOf('number') + processesToCleanUp.add(wrapper.pid!) + + await waitFor(() => { + try { + return readFileSync(pidFile, 'utf8').trim().length > 0 + } catch { + return false + } + }) + + const grandchildPid = Number.parseInt(readFileSync(pidFile, 'utf8').trim(), 10) + expect(Number.isFinite(grandchildPid)).toBe(true) + processesToCleanUp.add(grandchildPid) + expect(processExists(grandchildPid)).toBe(true) + + const exitPromise = new Promise((resolveExit) => { + wrapper.on('exit', (code) => { + resolveExit(code) + }) + }) + + wrapper.kill('SIGINT') + const exitCode = await exitPromise + expect(exitCode).toBe(130) + + await waitFor(() => !processExists(grandchildPid)) + processesToCleanUp.delete(grandchildPid) + processesToCleanUp.delete(wrapper.pid!) + } + ) +})