Fix macOS dev Electron shutdown on Ctrl+C (#435)

This commit is contained in:
Neil
2026-04-09 23:50:23 -07:00
committed by GitHub
parent 5d1eae28c7
commit 8d3f640e67
8 changed files with 396 additions and 2 deletions
+101
View File
@@ -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)
})
+1 -1
View File
@@ -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",
+4
View File
@@ -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).
@@ -0,0 +1 @@
setInterval(() => {}, 1000)
@@ -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)
+111 -1
View File
@@ -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<string, string>([['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()
})
})
+57
View File
@@ -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')
@@ -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<number>()
function sleep(ms: number): Promise<void> {
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<void> {
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<number | null>((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!)
}
)
})