diff --git a/src/main/index.ts b/src/main/index.ts index c5c63bf2b..bd427f31e 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -16,7 +16,7 @@ import { ClaudeUsageStore, initClaudeUsagePath } from './claude-usage/store' import { CodexUsageStore, initCodexUsagePath } from './codex-usage/store' import { OpenCodeUsageStore, initOpenCodeUsagePath } from './opencode-usage/store' import { killAllPty } from './ipc/pty' -import { initDaemonPtyProvider, disconnectDaemon } from './daemon/daemon-init' +import { initDaemonPtyProvider, disconnectDaemon, shutdownDaemon } from './daemon/daemon-init' import { closeAllWatchers } from './ipc/filesystem-watcher' import { registerCoreHandlers } from './ipc/register-core-handlers' import { initObservability, shutdownObservability } from './observability' @@ -47,8 +47,10 @@ import { configureDevUserDataPath, enableMainProcessGpuFeatures, installDevParentDisconnectQuit, + installDevParentSignalQuit, installDevParentWatchdog, installUncaughtPipeErrorGuard, + isDevParentShutdownRequested, patchPackagedProcessPath, shouldInstallManagedHooks } from './startup/configure-process' @@ -346,6 +348,7 @@ if (hasSingleInstanceLock) { const shouldCoupleToDevParent = is.dev && !isServeMode installDevParentDisconnectQuit(shouldCoupleToDevParent) installDevParentWatchdog(shouldCoupleToDevParent) + installDevParentSignalQuit(shouldCoupleToDevParent) // 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). @@ -1426,7 +1429,10 @@ app.on('will-quit', (e) => { // inside `shutdownTelemetry()` are caught by the client itself — we // catch again here defensively so a flush failure cannot cancel the // quit chain. - Promise.allSettled([disconnectDaemon(), rpcStopAndClear, watcherShutdown]) + // Why: normal quits preserve the detached daemon for warm reattach, but a + // dev parent dying means the temp/dev profile has no owner left to reattach. + const daemonTeardown = isDevParentShutdownRequested() ? shutdownDaemon() : disconnectDaemon() + Promise.allSettled([daemonTeardown, rpcStopAndClear, watcherShutdown]) .then(() => shutdownTelemetry()) .then(() => shutdownObservability()) .catch(() => { diff --git a/src/main/startup/configure-process-dev-parent-shutdown.test.ts b/src/main/startup/configure-process-dev-parent-shutdown.test.ts new file mode 100644 index 000000000..6da25bdd4 --- /dev/null +++ b/src/main/startup/configure-process-dev-parent-shutdown.test.ts @@ -0,0 +1,201 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' + +vi.mock('electron', () => ({ + app: { + quit: vi.fn(), + exit: vi.fn(), + isPackaged: false + } +})) + +afterEach(() => { + vi.useRealTimers() + vi.restoreAllMocks() +}) + +describe('installDevParentDisconnectQuit', () => { + it('quits the dev app when the supervising IPC channel disconnects', async () => { + const { app } = await import('electron') + const { + installDevParentDisconnectQuit, + isDevParentShutdownRequested, + resetDevParentShutdownRequestForTests + } = await import('./configure-process') + + vi.useFakeTimers() + resetDevParentShutdownRequestForTests() + 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) + expect(isDevParentShutdownRequested()).toBe(false) + disconnectHandlers[0]() + expect(isDevParentShutdownRequested()).toBe(true) + expect(app.quit).toHaveBeenCalledTimes(1) + expect(app.exit).not.toHaveBeenCalled() + + await vi.advanceTimersByTimeAsync(3000) + expect(app.exit).toHaveBeenCalledWith(0) + }) + + 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, + isDevParentShutdownRequested, + resetDevParentShutdownRequestForTests + } = await import('./configure-process') + + vi.useFakeTimers() + resetDevParentShutdownRequestForTests() + vi.mocked(app.quit).mockClear() + vi.mocked(app.exit).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(isDevParentShutdownRequested()).toBe(true) + expect(app.quit).toHaveBeenCalledTimes(1) + expect(app.exit).not.toHaveBeenCalled() + + await vi.advanceTimersByTimeAsync(3000) + expect(app.exit).toHaveBeenCalledWith(0) + } 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() + }) +}) + +describe('installDevParentSignalQuit', () => { + it('quits the dev app when the supervisor forwards a terminal signal', async () => { + const { app } = await import('electron') + const { + installDevParentSignalQuit, + isDevParentShutdownRequested, + resetDevParentShutdownRequestForTests + } = await import('./configure-process') + + vi.useFakeTimers() + resetDevParentShutdownRequestForTests() + const originalOnce = process.once.bind(process) + const signalHandlers = new Map void>() + + process.once = ((event: string | symbol, listener: (...args: any[]) => void) => { + signalHandlers.set(event, listener as () => void) + return process + }) as NodeJS.Process['once'] + + vi.mocked(app.quit).mockClear() + vi.mocked(app.exit).mockClear() + + try { + installDevParentSignalQuit(true) + } finally { + process.once = originalOnce + } + + expect(signalHandlers.has('SIGINT')).toBe(true) + expect(signalHandlers.has('SIGTERM')).toBe(true) + expect(isDevParentShutdownRequested()).toBe(false) + + signalHandlers.get('SIGTERM')?.() + + expect(isDevParentShutdownRequested()).toBe(true) + expect(app.quit).toHaveBeenCalledTimes(1) + expect(app.exit).not.toHaveBeenCalled() + + await vi.advanceTimersByTimeAsync(3000) + expect(app.exit).toHaveBeenCalledWith(0) + }) + + it('does not register signal handlers outside supervised dev runs', async () => { + const { installDevParentSignalQuit } = await import('./configure-process') + const originalOnce = process.once.bind(process) + const onceSpy = vi.fn(originalOnce) + + process.once = onceSpy as NodeJS.Process['once'] + + try { + installDevParentSignalQuit(false) + } finally { + process.once = originalOnce + } + + expect(onceSpy).not.toHaveBeenCalledWith('SIGINT', expect.any(Function)) + expect(onceSpy).not.toHaveBeenCalledWith('SIGTERM', expect.any(Function)) + }) +}) diff --git a/src/main/startup/configure-process.test.ts b/src/main/startup/configure-process.test.ts index 9ecd76cbd..4f33ea018 100644 --- a/src/main/startup/configure-process.test.ts +++ b/src/main/startup/configure-process.test.ts @@ -165,120 +165,6 @@ describe('shouldInstallManagedHooks', () => { }) }) -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') - - vi.useFakeTimers() - 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) - expect(app.exit).not.toHaveBeenCalled() - - await vi.advanceTimersByTimeAsync(3000) - expect(app.exit).toHaveBeenCalledWith(0) - }) - - 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() - vi.mocked(app.exit).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) - expect(app.exit).not.toHaveBeenCalled() - - await vi.advanceTimersByTimeAsync(3000) - expect(app.exit).toHaveBeenCalledWith(0) - } 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() - }) -}) - describe('enableMainProcessGpuFeatures', () => { const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform') const originalE2EUserDataDir = process.env.ORCA_E2E_USER_DATA_DIR diff --git a/src/main/startup/configure-process.ts b/src/main/startup/configure-process.ts index 2fe01bc91..175cfab54 100644 --- a/src/main/startup/configure-process.ts +++ b/src/main/startup/configure-process.ts @@ -4,12 +4,14 @@ import { getVersionManagerBinPaths } from '../codex-cli/command' import { getMainE2EConfig } from '../e2e-config' const DEV_PARENT_SHUTDOWN_GRACE_MS = 3000 +let devParentShutdownRequested = false function getProcessPathDelimiter(): string { return process.platform === 'win32' ? ';' : ':' } function requestDevParentShutdown(): void { + devParentShutdownRequested = true app.quit() const forceExitTimer = setTimeout(() => { @@ -24,6 +26,14 @@ function requestDevParentShutdown(): void { forceExitTimer.unref() } +export function isDevParentShutdownRequested(): boolean { + return devParentShutdownRequested +} + +export function resetDevParentShutdownRequestForTests(): void { + devParentShutdownRequested = false +} + export function installUncaughtPipeErrorGuard(): void { const onUncaughtException = (error: unknown): void => { if ( @@ -203,6 +213,22 @@ export function installDevParentWatchdog(isDev: boolean): void { timer.unref() } +export function installDevParentSignalQuit(isDev: boolean): void { + if (!isDev) { + return + } + + const onSignal = (): void => { + // Why: run-electron-vite-dev forwards terminal shutdown signals to the + // Electron process group; those are dev-supervisor shutdowns too, so the + // detached daemon should not be preserved for warm reattach. + requestDevParentShutdown() + } + + process.once('SIGINT', onSignal) + process.once('SIGTERM', onSignal) +} + export function enableMainProcessGpuFeatures(): void { if (process.platform === 'linux' && getMainE2EConfig().userDataDir) { // Why: Ubuntu/Xvfb runners can fail Electron startup with