diff --git a/src/main/daemon/daemon-init.test.ts b/src/main/daemon/daemon-init.test.ts index 5145152b0..ec91c7592 100644 --- a/src/main/daemon/daemon-init.test.ts +++ b/src/main/daemon/daemon-init.test.ts @@ -64,11 +64,13 @@ const { const killStaleDaemonMock = vi.fn(async () => true) const getProcessStartedAtMsMock = vi.fn(() => 1_000_000) - const daemonClientMock = vi.fn().mockImplementation(() => ({ - ensureConnected: vi.fn(async () => {}), - request: vi.fn(async () => ({ sessions: [] })), - disconnect: vi.fn() - })) + const daemonClientMock = vi.fn().mockImplementation(function MockDaemonClient() { + return { + ensureConnected: vi.fn(async () => {}), + request: vi.fn(async () => ({ sessions: [] })), + disconnect: vi.fn() + } + }) // Why: every DaemonSpawner constructed under test pushes into this array so // assertions can check "was the *same* spawner reused across restart?". @@ -435,6 +437,30 @@ describe('daemon-init: runRestartDaemon (7-step sequence)', () => { expect(legacyAdapter.listProcesses).toHaveBeenCalled() }) + it('routes affected v9 daemon sessions through a legacy adapter on launch', async () => { + const mod = await importFresh() + probeSocketExistsMock.mockImplementation((p?: string) => p?.endsWith('daemon-v9.sock') ?? false) + netConnectMock.mockImplementation(() => { + const handlers: Record void)[]> = { connect: [], error: [] } + return { + on(event: string, cb: () => void) { + handlers[event]?.push(cb) + if (event === 'connect') { + queueMicrotask(() => cb()) + } + return this + }, + destroy() {} + } + }) + + await mod.initDaemonPtyProvider() + + const { DaemonPtyRouter } = await import('./daemon-pty-router') + expect(mod.getDaemonProvider()).toBeInstanceOf(DaemonPtyRouter) + expect(adapterInstances.some((instance) => instance.protocolVersion === 9)).toBe(true) + }) + it('restart path with no legacy adapters yields a bare DaemonPtyAdapter (not wrapped in a router)', async () => { const mod = await importFresh() await mod.initDaemonPtyProvider() @@ -734,6 +760,79 @@ describe('daemon-init: runRestartDaemon (7-step sequence)', () => { ) }) + it('preserves a resolver-unhealthy daemon when it owns live sessions', async () => { + const mod = await importFresh() + await mod.initDaemonPtyProvider() + + const requestMock = vi.fn(async (method: string) => { + if (method === 'listSessions') { + return { + sessions: [ + { sessionId: 'wt-1@@live', isAlive: true }, + { sessionId: 'wt-1@@dead', isAlive: false } + ] + } + } + return {} + }) + const disconnectMock = vi.fn() + daemonClientMock.mockImplementationOnce(function MockDaemonClient() { + return { + ensureConnected: vi.fn(async () => {}), + request: requestMock, + disconnect: disconnectMock + } + }) + + const launcher = spawnerInstances[0].launcher as ( + socketPath: string, + tokenPath: string + ) => Promise<{ shutdown(): Promise }> + getMacDaemonSystemResolverHealthMock.mockReturnValueOnce('unhealthy') + + await launcher('/fake/socket', '/fake/token') + + expect(getMacDaemonSystemResolverHealthMock).toHaveBeenCalledWith('/fake/socket', '/fake/token') + expect(requestMock).toHaveBeenCalledWith('listSessions', undefined) + expect(disconnectMock).toHaveBeenCalledOnce() + expect(getDaemonLaunchIdentityMock).not.toHaveBeenCalled() + expect(killStaleDaemonMock).not.toHaveBeenCalled() + expect(forkMock).not.toHaveBeenCalled() + }) + + it('preserves a resolver-unhealthy daemon when live session state cannot be verified', async () => { + const mod = await importFresh() + await mod.initDaemonPtyProvider() + + const requestMock = vi.fn(async (method: string) => { + if (method === 'listSessions') { + throw new Error('listSessions failed') + } + return {} + }) + const disconnectMock = vi.fn() + daemonClientMock.mockImplementationOnce(function MockDaemonClient() { + return { + ensureConnected: vi.fn(async () => {}), + request: requestMock, + disconnect: disconnectMock + } + }) + + const launcher = spawnerInstances[0].launcher as ( + socketPath: string, + tokenPath: string + ) => Promise<{ shutdown(): Promise }> + getMacDaemonSystemResolverHealthMock.mockReturnValueOnce('unhealthy') + + await launcher('/fake/socket', '/fake/token') + + expect(requestMock).toHaveBeenCalledWith('listSessions', undefined) + expect(disconnectMock).toHaveBeenCalledOnce() + expect(killStaleDaemonMock).not.toHaveBeenCalled() + expect(forkMock).not.toHaveBeenCalled() + }) + it('uses the direct daemon entry when Electron app path is already out/main', async () => { probeSocketExistsMock.mockImplementation( (p?: string) => p === '/fake/app/out/main/daemon-entry.js' diff --git a/src/main/daemon/daemon-init.ts b/src/main/daemon/daemon-init.ts index 9fd10a766..fe741fe57 100644 --- a/src/main/daemon/daemon-init.ts +++ b/src/main/daemon/daemon-init.ts @@ -99,6 +99,34 @@ function probeSocket(socketPath: string): Promise { }) } +async function getAliveDaemonSessionCount( + socketPath: string, + tokenPath: string, + protocolVersion = PROTOCOL_VERSION +): Promise { + const client = new DaemonClient({ socketPath, tokenPath, protocolVersion }) + try { + await client.ensureConnected() + const result = await client.request('listSessions', undefined) + return result.sessions.filter((session) => session.isAlive).length + } catch { + return null + } finally { + client.disconnect() + } +} + +function createPreservedDaemonHandle( + runtimeDir: string, + protocolVersion = PROTOCOL_VERSION +): { shutdown(): Promise } { + return { + shutdown: async () => { + await cleanupDaemonForProtocol(runtimeDir, protocolVersion) + } + } +} + function createOutOfProcessLauncher(runtimeDir: string): DaemonLauncher { return async (socketPath, tokenPath) => { const entryPath = getDaemonEntryPath() @@ -106,6 +134,15 @@ function createOutOfProcessLauncher(runtimeDir: string): DaemonLauncher { if (healthy) { const resolverHealth = await getMacDaemonSystemResolverHealth(socketPath, tokenPath) if (resolverHealth === 'unhealthy') { + const liveSessionCount = await getAliveDaemonSessionCount(socketPath, tokenPath) + if (liveSessionCount !== 0) { + console.warn( + liveSessionCount === null + ? '[daemon] Preserving daemon with unavailable macOS system resolver because live session state could not be verified' + : `[daemon] Preserving daemon with unavailable macOS system resolver because it owns ${liveSessionCount} live session${liveSessionCount === 1 ? '' : 's'}` + ) + return createPreservedDaemonHandle(runtimeDir) + } console.warn('[daemon] Replacing daemon with unavailable macOS system resolver') await cleanupDaemonForProtocol(runtimeDir, PROTOCOL_VERSION) } else { @@ -122,11 +159,7 @@ function createOutOfProcessLauncher(runtimeDir: string): DaemonLauncher { } else { // Why: daemon is already running from a previous app session and // responded to a protocol-level ping. Safe to reuse. - return { - shutdown: async () => { - await cleanupDaemonForProtocol(runtimeDir, PROTOCOL_VERSION) - } - } + return createPreservedDaemonHandle(runtimeDir) } } } diff --git a/src/main/daemon/daemon-pty-adapter.test.ts b/src/main/daemon/daemon-pty-adapter.test.ts index 57f8feb93..8f721c445 100644 --- a/src/main/daemon/daemon-pty-adapter.test.ts +++ b/src/main/daemon/daemon-pty-adapter.test.ts @@ -852,7 +852,52 @@ describe('DaemonPtyAdapter (IPtyProvider)', () => { await respawnServer?.shutdown() }) - it('replaces an unhealthy macOS resolver daemon before creating a fresh session', async () => { + it('preserves an unhealthy macOS resolver daemon when it owns live sessions', async () => { + const respawnFn = vi.fn() + const exits: { id: string; code: number }[] = [] + const respawnAdapter = new DaemonPtyAdapter({ socketPath, tokenPath, respawn: respawnFn }) + respawnAdapter.onExit((payload) => exits.push(payload)) + const existing = await respawnAdapter.spawn({ cols: 80, rows: 24 }) + getMacDaemonSystemResolverHealthMock.mockResolvedValueOnce('unhealthy') + + const next = await respawnAdapter.spawn({ cols: 80, rows: 24, isNewSession: true }) + + expect(getMacDaemonSystemResolverHealthMock).toHaveBeenCalledWith( + socketPath, + tokenPath, + respawnAdapter.protocolVersion + ) + expect(respawnFn).not.toHaveBeenCalled() + expect(exits).toEqual([]) + expect(next.id).toBeDefined() + expect(next.id).not.toBe(existing.id) + + respawnAdapter.dispose() + }) + + it('preserves an unhealthy macOS resolver daemon when live sessions have not been reconciled locally', async () => { + const respawnFn = vi.fn() + const background = await adapter.spawn({ cols: 80, rows: 24 }) + const backgroundSubprocess = lastSubprocess + const respawnAdapter = new DaemonPtyAdapter({ socketPath, tokenPath, respawn: respawnFn }) + getMacDaemonSystemResolverHealthMock.mockResolvedValueOnce('unhealthy') + + const next = await respawnAdapter.spawn({ cols: 80, rows: 24, isNewSession: true }) + + expect(getMacDaemonSystemResolverHealthMock).toHaveBeenCalledWith( + socketPath, + tokenPath, + respawnAdapter.protocolVersion + ) + expect(respawnFn).not.toHaveBeenCalled() + expect(next.id).toBeDefined() + expect(next.id).not.toBe(background.id) + expect(backgroundSubprocess.forceKill).not.toHaveBeenCalled() + + respawnAdapter.dispose() + }) + + it('replaces an unhealthy macOS resolver daemon before creating a fresh session when no sessions are active', async () => { let respawnServer: DaemonServer | undefined const respawnFn = vi.fn(async () => { await server.shutdown() @@ -867,7 +912,6 @@ describe('DaemonPtyAdapter (IPtyProvider)', () => { const exits: { id: string; code: number }[] = [] const respawnAdapter = new DaemonPtyAdapter({ socketPath, tokenPath, respawn: respawnFn }) respawnAdapter.onExit((payload) => exits.push(payload)) - const existing = await respawnAdapter.spawn({ cols: 80, rows: 24 }) getMacDaemonSystemResolverHealthMock.mockResolvedValueOnce('unhealthy') const replacement = await respawnAdapter.spawn({ cols: 80, rows: 24, isNewSession: true }) @@ -878,7 +922,7 @@ describe('DaemonPtyAdapter (IPtyProvider)', () => { respawnAdapter.protocolVersion ) expect(respawnFn).toHaveBeenCalledOnce() - expect(exits).toContainEqual({ id: existing.id, code: -1 }) + expect(exits).toEqual([]) expect(replacement.id).toBeDefined() respawnAdapter.dispose() diff --git a/src/main/daemon/daemon-pty-adapter.ts b/src/main/daemon/daemon-pty-adapter.ts index ce7778d3a..c956c3a63 100644 --- a/src/main/daemon/daemon-pty-adapter.ts +++ b/src/main/daemon/daemon-pty-adapter.ts @@ -670,6 +670,17 @@ export class DaemonPtyAdapter implements IPtyProvider { return } + const daemonLiveSessionCount = await this.getDaemonLiveSessionCount() + const liveSessionCount = Math.max(this.activeSessionIds.size, daemonLiveSessionCount ?? 0) + if (daemonLiveSessionCount === null || liveSessionCount > 0) { + console.warn( + daemonLiveSessionCount === null + ? '[daemon] macOS system resolver unavailable - preserving daemon because live session state could not be verified' + : `[daemon] macOS system resolver unavailable - preserving daemon because it owns ${liveSessionCount} live session${liveSessionCount === 1 ? '' : 's'}` + ) + return + } + // Why: replacing the daemon kills its sessions without daemon-side exit // fanout. Emit exits first so renderer panes do not write to dead PTYs. this.fanoutSyntheticExits(-1) @@ -683,6 +694,16 @@ export class DaemonPtyAdapter implements IPtyProvider { await this.respawnPromise } + private async getDaemonLiveSessionCount(): Promise { + try { + await this.client.ensureConnected() + const result = await this.client.request('listSessions', undefined) + return result.sessions.filter((session) => session.isAlive).length + } catch { + return null + } + } + private async doRespawn(message = '[daemon] Daemon died — respawning'): Promise { console.warn(message) this.removeEventListener?.() diff --git a/src/main/daemon/types.ts b/src/main/daemon/types.ts index 34a3153c4..a1b5501db 100644 --- a/src/main/daemon/types.ts +++ b/src/main/daemon/types.ts @@ -1,10 +1,10 @@ // ─── Protocol Version ──────────────────────────────────────────────── // Why: daemons can survive app updates. Bump for IPC wire-shape changes, or // when daemon-baked behavior cannot be delivered by on-disk wrapper refresh. -// Why: bumped from 8 -> 9 so new app launches do not reuse daemon processes -// that cannot report their own macOS system resolver health. -export const PROTOCOL_VERSION = 9 -export const PREVIOUS_DAEMON_PROTOCOL_VERSIONS = [1, 2, 3, 4, 5, 6, 7, 8] as const +// Why: bumped from 9 -> 10 so affected v9 daemons are preserved as legacy +// instead of being resolver-health replaced while they own live PTY sessions. +export const PROTOCOL_VERSION = 10 +export const PREVIOUS_DAEMON_PROTOCOL_VERSIONS = [1, 2, 3, 4, 5, 6, 7, 8, 9] as const // ─── Session State Machine ────────────────────────────────────────── export type SessionState = 'created' | 'spawning' | 'running' | 'exiting' | 'exited'