Preserve live PTYs during daemon resolver refresh (#2974)

This commit is contained in:
Jinwoo Hong
2026-05-27 23:40:34 -07:00
committed by GitHub
parent 0ce5a525fd
commit 1371402bc6
5 changed files with 214 additions and 17 deletions
+104 -5
View File
@@ -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<string, (() => 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<void> }>
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<void> }>
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'
+38 -5
View File
@@ -99,6 +99,34 @@ function probeSocket(socketPath: string): Promise<boolean> {
})
}
async function getAliveDaemonSessionCount(
socketPath: string,
tokenPath: string,
protocolVersion = PROTOCOL_VERSION
): Promise<number | null> {
const client = new DaemonClient({ socketPath, tokenPath, protocolVersion })
try {
await client.ensureConnected()
const result = await client.request<ListSessionsResult>('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<void> } {
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)
}
}
}
+47 -3
View File
@@ -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()
+21
View File
@@ -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<number | null> {
try {
await this.client.ensureConnected()
const result = await this.client.request<ListSessionsResult>('listSessions', undefined)
return result.sessions.filter((session) => session.isAlive).length
} catch {
return null
}
}
private async doRespawn(message = '[daemon] Daemon died — respawning'): Promise<void> {
console.warn(message)
this.removeEventListener?.()
+4 -4
View File
@@ -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'