diff --git a/src/main/daemon/daemon-health.test.ts b/src/main/daemon/daemon-health.test.ts index 2b9884f07..9aba26764 100644 --- a/src/main/daemon/daemon-health.test.ts +++ b/src/main/daemon/daemon-health.test.ts @@ -1,11 +1,17 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { spawn, type ChildProcess } from 'child_process' import { mkdtempSync, rmSync, writeFileSync } from 'fs' import { tmpdir } from 'os' import { join } from 'path' import { createServer, connect, type Server } from 'net' import { DaemonServer } from './daemon-server' -import { getDaemonPidPath } from './daemon-spawner' -import { healthCheckDaemon, killStaleDaemon } from './daemon-health' +import { getDaemonPidPath, serializeDaemonPidFile } from './daemon-spawner' +import { + getProcessStartedAtMs, + healthCheckDaemon, + killStaleDaemon, + parseDaemonPidFile +} from './daemon-health' import type { SubprocessHandle } from './session' function createMockSubprocess(): SubprocessHandle { @@ -50,6 +56,27 @@ function canConnect(socketPath: string): Promise { }) } +function waitForExit(child: ChildProcess, timeoutMs = 5_000): Promise { + if (child.exitCode !== null || child.signalCode !== null) { + return Promise.resolve() + } + return new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error('child did not exit')), timeoutMs) + child.once('exit', () => { + clearTimeout(timer) + resolve() + }) + }) +} + +function spawnDaemonLikeProcess(socketPath: string, tokenPath: string): ChildProcess { + return spawn( + process.execPath, + ['-e', 'setInterval(() => {}, 1000)', 'daemon-entry', socketPath, tokenPath], + { stdio: 'ignore' } + ) +} + describe('daemon health', () => { let dir: string let socketPath: string @@ -65,6 +92,15 @@ describe('daemon health', () => { rmSync(dir, { recursive: true, force: true }) }) + it('parses JSON and legacy pid files', () => { + expect(parseDaemonPidFile('{"pid":123,"startedAtMs":456}')).toEqual({ + pid: 123, + startedAtMs: 456 + }) + expect(parseDaemonPidFile('123')).toEqual({ pid: 123, startedAtMs: null }) + expect(parseDaemonPidFile('not-json')).toBeNull() + }) + it('passes when a daemon answers ping', async () => { const server = new DaemonServer({ socketPath, @@ -106,4 +142,39 @@ describe('daemon health', () => { await closeServer(server) } }) + + it('kills a daemon-like process from a legacy integer pid file', async () => { + const child = spawnDaemonLikeProcess(socketPath, tokenPath) + expect(child.pid).toBeTypeOf('number') + writeFileSync(getDaemonPidPath(dir), String(child.pid), { mode: 0o600 }) + + try { + await expect(killStaleDaemon(dir, socketPath, tokenPath)).resolves.toBe(true) + await expect(waitForExit(child)).resolves.toBeUndefined() + } finally { + if (!child.killed) { + child.kill('SIGKILL') + } + } + }) + + it('kills a daemon-like process from a JSON pid file', async () => { + const child = spawnDaemonLikeProcess(socketPath, tokenPath) + expect(child.pid).toBeTypeOf('number') + const pid = child.pid! + writeFileSync( + getDaemonPidPath(dir), + serializeDaemonPidFile({ pid, startedAtMs: getProcessStartedAtMs(pid) }), + { mode: 0o600 } + ) + + try { + await expect(killStaleDaemon(dir, socketPath, tokenPath)).resolves.toBe(true) + await expect(waitForExit(child)).resolves.toBeUndefined() + } finally { + if (!child.killed) { + child.kill('SIGKILL') + } + } + }) }) diff --git a/src/main/daemon/daemon-health.ts b/src/main/daemon/daemon-health.ts index a0ab5025c..e87be1721 100644 --- a/src/main/daemon/daemon-health.ts +++ b/src/main/daemon/daemon-health.ts @@ -1,3 +1,5 @@ +/* oxlint-disable max-lines -- Why: pid validation shares process-identity +helpers with kill escalation so the SIGKILL safety checks stay co-located. */ import { execFileSync } from 'child_process' import { existsSync, readFileSync, unlinkSync } from 'fs' import { connect, type Socket } from 'net' @@ -8,6 +10,12 @@ import { PROTOCOL_VERSION, type HelloMessage, type HelloResponse } from './types const HEALTH_CHECK_TIMEOUT_MS = 3_000 const KILL_WAIT_MS = 3_000 const KILL_POLL_MS = 100 +const START_TIME_TOLERANCE_MS = 1_500 + +type ParsedDaemonPid = { + pid: number + startedAtMs: number | null +} function canConnectSocket(socketPath: string): Promise { return new Promise((resolve) => { @@ -128,7 +136,94 @@ function commandLineMatchesDaemon( ) } -function isDaemonProcess(pid: number, socketPath: string, tokenPath: string): boolean { +export function parseDaemonPidFile(contents: string): ParsedDaemonPid | null { + const trimmed = contents.trim() + try { + const parsed = JSON.parse(trimmed) as { pid?: unknown; startedAtMs?: unknown } + if (typeof parsed.pid === 'number' && Number.isFinite(parsed.pid)) { + return { + pid: parsed.pid, + startedAtMs: + typeof parsed.startedAtMs === 'number' && Number.isFinite(parsed.startedAtMs) + ? parsed.startedAtMs + : null + } + } + } catch { + // Legacy daemons wrote the pid file as a bare integer. + } + + const pid = Number(trimmed) + return Number.isFinite(pid) ? { pid, startedAtMs: null } : null +} + +function getLinuxProcessStartedAtMs(pid: number): number | null { + try { + const stat = readFileSync(`/proc/${pid}/stat`, 'utf8') + const afterCommand = stat.slice(stat.lastIndexOf(')') + 2) + const fields = afterCommand.split(' ') + const startTicks = Number(fields[19]) + const bootTimeLine = readFileSync('/proc/stat', 'utf8') + .split('\n') + .find((line) => line.startsWith('btime ')) + const bootTimeSeconds = bootTimeLine ? Number(bootTimeLine.split(/\s+/)[1]) : Number.NaN + const ticksPerSecond = Number( + execFileSync('getconf', ['CLK_TCK'], { encoding: 'utf8', timeout: 1_000 }).trim() + ) + if ( + !Number.isFinite(startTicks) || + !Number.isFinite(bootTimeSeconds) || + !Number.isFinite(ticksPerSecond) || + ticksPerSecond <= 0 + ) { + return null + } + return bootTimeSeconds * 1000 + (startTicks / ticksPerSecond) * 1000 + } catch { + return null + } +} + +export function getProcessStartedAtMs(pid: number): number | null { + if (process.platform === 'linux') { + return getLinuxProcessStartedAtMs(pid) + } + + if (process.platform === 'win32') { + return null + } + + try { + const output = execFileSync('ps', ['-p', String(pid), '-o', 'lstart='], { + encoding: 'utf8', + timeout: 2_000 + }).trim() + const startedAtMs = Date.parse(output) + return Number.isFinite(startedAtMs) ? startedAtMs : null + } catch { + return null + } +} + +function startTimeMatches(pid: number, expectedStartedAtMs: number | null): boolean { + if (expectedStartedAtMs === null) { + return true + } + + const actualStartedAtMs = getProcessStartedAtMs(pid) + if (actualStartedAtMs === null) { + return true + } + + return Math.abs(actualStartedAtMs - expectedStartedAtMs) <= START_TIME_TOLERANCE_MS +} + +function isDaemonProcess( + pid: number, + socketPath: string, + tokenPath: string, + startedAtMs: number | null +): boolean { try { process.kill(pid, 0) } catch { @@ -153,7 +248,10 @@ function isDaemonProcess(pid: number, socketPath: string, tokenPath: string): bo // Why: image names are too broad after PID reuse. Match the daemon entry // plus the exact socket/token args so we only kill the daemon for this // userData protocol endpoint. - return commandLineMatchesDaemon(output, socketPath, tokenPath) + return ( + commandLineMatchesDaemon(output, socketPath, tokenPath) && + startTimeMatches(pid, startedAtMs) + ) } catch { return false } @@ -161,14 +259,19 @@ function isDaemonProcess(pid: number, socketPath: string, tokenPath: string): bo try { const cmdline = readFileSync(`/proc/${pid}/cmdline`, 'utf8') - return commandLineMatchesDaemon(cmdline, socketPath, tokenPath) + return ( + commandLineMatchesDaemon(cmdline, socketPath, tokenPath) && startTimeMatches(pid, startedAtMs) + ) } catch { try { const output = execFileSync('ps', ['-p', String(pid), '-o', 'command='], { encoding: 'utf8', timeout: 2_000 }) - return commandLineMatchesDaemon(output, socketPath, tokenPath) + return ( + commandLineMatchesDaemon(output, socketPath, tokenPath) && + startTimeMatches(pid, startedAtMs) + ) } catch { return false } @@ -184,8 +287,9 @@ export async function killStaleDaemon( const pidPath = getDaemonPidPath(runtimeDir, protocolVersion) let killedDaemon = false try { - const pid = Number.parseInt(readFileSync(pidPath, 'utf8').trim(), 10) - if (Number.isFinite(pid) && isDaemonProcess(pid, socketPath, tokenPath)) { + const parsedPid = parseDaemonPidFile(readFileSync(pidPath, 'utf8')) + if (parsedPid && isDaemonProcess(parsedPid.pid, socketPath, tokenPath, parsedPid.startedAtMs)) { + const { pid, startedAtMs } = parsedPid process.kill(pid, 'SIGTERM') const deadline = Date.now() + KILL_WAIT_MS let exited = false @@ -199,14 +303,22 @@ export async function killStaleDaemon( await new Promise((resolve) => setTimeout(resolve, KILL_POLL_MS)) } if (!exited) { - try { - process.kill(pid, 'SIGKILL') + if (!isDaemonProcess(pid, socketPath, tokenPath, startedAtMs)) { + console.warn('[daemon] Skipping SIGKILL for stale daemon: reason=pid_recycled') exited = true - } catch { - // Already dead + killedDaemon = true + } else { + try { + process.kill(pid, 'SIGKILL') + exited = true + } catch { + // Already dead + } } } - killedDaemon = exited + if (!killedDaemon) { + killedDaemon = exited + } } } catch { // PID file missing or process already dead diff --git a/src/main/daemon/daemon-init.test.ts b/src/main/daemon/daemon-init.test.ts new file mode 100644 index 000000000..9a4c4d2d0 --- /dev/null +++ b/src/main/daemon/daemon-init.test.ts @@ -0,0 +1,206 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { createServer, type Server } from 'net' +import { mkdtempSync, rmSync } from 'fs' +import { tmpdir } from 'os' +import { join } from 'path' +import { getDaemonSocketPath } from './daemon-spawner' +import { PREVIOUS_DAEMON_PROTOCOL_VERSIONS } from './types' + +type ClientPlan = { + ensureReject?: boolean + requestReject?: boolean + sessions?: { sessionId: string; isAlive: boolean }[] + delayMs?: number +} + +const mocks = vi.hoisted(() => ({ + killStaleDaemon: vi.fn(async () => true), + setLocalPtyProvider: vi.fn(), + clientPlans: [] as ClientPlan[], + clientInstances: [] as MockDaemonClient[] +})) + +class MockDaemonClient { + plan: ClientPlan + ensureConnected = vi.fn(async () => { + if (this.plan.delayMs) { + await new Promise((resolve) => setTimeout(resolve, this.plan.delayMs)) + } + if (this.plan.ensureReject) { + throw new Error('connect failed') + } + }) + request = vi.fn(async (method: string) => { + if (this.plan.requestReject) { + throw new Error('request failed') + } + if (method === 'listSessions') { + return { sessions: this.plan.sessions ?? [] } + } + return {} + }) + disconnect = vi.fn() + + constructor() { + this.plan = mocks.clientPlans.shift() ?? {} + mocks.clientInstances.push(this) + } +} + +vi.mock('electron', () => ({ + app: { + getPath: vi.fn(() => mkdtempSync(join(tmpdir(), 'daemon-init-app-test-'))), + getAppPath: vi.fn(() => '/app'), + isPackaged: false + } +})) + +vi.mock('../ipc/pty', () => ({ + setLocalPtyProvider: mocks.setLocalPtyProvider +})) + +vi.mock('./client', () => ({ + DaemonClient: MockDaemonClient +})) + +vi.mock('./daemon-health', () => ({ + getProcessStartedAtMs: vi.fn(() => 1), + healthCheckDaemon: vi.fn(async () => false), + killStaleDaemon: mocks.killStaleDaemon +})) + +function listen(socketPath: string): Promise { + const server = createServer((socket) => socket.end()) + return new Promise((resolve, reject) => { + server.once('error', reject) + server.listen(socketPath, () => { + server.off('error', reject) + resolve(server) + }) + }) +} + +function closeServer(server: Server): Promise { + return new Promise((resolve) => server.close(() => resolve())) +} + +describe('daemon init legacy cleanup', () => { + let dir: string + let servers: Server[] + + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'daemon-init-test-')) + servers = [] + mocks.clientPlans.length = 0 + mocks.clientInstances.length = 0 + mocks.killStaleDaemon.mockClear() + mocks.setLocalPtyProvider.mockClear() + }) + + afterEach(async () => { + await Promise.all(servers.map((server) => closeServer(server).catch(() => {}))) + rmSync(dir, { recursive: true, force: true }) + delete process.env.ORCA_DISABLE_LEGACY_CLEANUP + }) + + async function openLegacySocket(protocolVersion: number): Promise { + servers.push(await listen(getDaemonSocketPath(dir, protocolVersion))) + } + + it('cleans up an idle legacy daemon and returns no adapter', async () => { + const { processLegacyVersion } = await import('./daemon-init') + await openLegacySocket(1) + mocks.clientPlans.push({ sessions: [] }, { sessions: [] }) + + await expect(processLegacyVersion(dir, 1)).resolves.toBeNull() + + expect(mocks.clientInstances).toHaveLength(2) + expect(mocks.clientInstances[1].request).toHaveBeenCalledWith('shutdown', { + killSessions: true + }) + }) + + it('wraps a live legacy daemon without calling cleanup', async () => { + const { processLegacyVersion } = await import('./daemon-init') + await openLegacySocket(1) + mocks.clientPlans.push({ sessions: [{ sessionId: 'legacy-1', isAlive: true }] }) + + const adapter = await processLegacyVersion(dir, 1) + + expect(adapter).not.toBeNull() + expect(adapter?.protocolVersion).toBe(1) + expect(mocks.clientInstances[0].request).toHaveBeenCalledWith('listSessions', undefined) + expect( + mocks.clientInstances.some((client) => client.request.mock.calls[0]?.[0] === 'shutdown') + ).toBe(false) + }) + + it('falls back to stale pid cleanup for a wedged legacy daemon', async () => { + const { processLegacyVersion } = await import('./daemon-init') + await openLegacySocket(1) + mocks.clientPlans.push({ ensureReject: true }, { ensureReject: true }) + + await expect(processLegacyVersion(dir, 1)).resolves.toBeNull() + + expect(mocks.killStaleDaemon).toHaveBeenCalledWith( + dir, + getDaemonSocketPath(dir, 1), + expect.any(String), + 1 + ) + expect(mocks.clientInstances[0].disconnect).toHaveBeenCalled() + }) + + it('does not open a client when the legacy socket is missing', async () => { + const { processLegacyVersion } = await import('./daemon-init') + + await expect(processLegacyVersion(dir, 1)).resolves.toBeNull() + + expect(mocks.clientInstances).toHaveLength(0) + expect(mocks.killStaleDaemon).not.toHaveBeenCalled() + }) + + it('aggregates mixed legacy cleanup outcomes', async () => { + const { createLegacyDaemonAdapters } = await import('./daemon-init') + await openLegacySocket(1) + await openLegacySocket(2) + mocks.clientPlans.push( + { sessions: [] }, + { sessions: [{ sessionId: 'legacy-2', isAlive: true }] }, + { sessions: [] } + ) + + const adapters = await createLegacyDaemonAdapters(dir) + + expect(adapters).toHaveLength(1) + expect(adapters[0].protocolVersion).toBe(2) + }) + + it('runs per-version probes in parallel', async () => { + const { createLegacyDaemonAdapters } = await import('./daemon-init') + for (const version of PREVIOUS_DAEMON_PROTOCOL_VERSIONS) { + await openLegacySocket(version) + mocks.clientPlans.push({ + sessions: [{ sessionId: `legacy-${version}`, isAlive: true }], + delayMs: 80 + }) + } + + const start = Date.now() + const adapters = await createLegacyDaemonAdapters(dir) + + expect(adapters).toHaveLength(PREVIOUS_DAEMON_PROTOCOL_VERSIONS.length) + expect(Date.now() - start).toBeLessThan(180) + }) + + it('honors the legacy cleanup killswitch', async () => { + const { getLegacyAdaptersForStartup } = await import('./daemon-init') + process.env.ORCA_DISABLE_LEGACY_CLEANUP = '1' + await openLegacySocket(1) + mocks.clientPlans.push({ sessions: [{ sessionId: 'legacy-1', isAlive: true }] }) + + await expect(getLegacyAdaptersForStartup(dir)).resolves.toEqual([]) + + expect(mocks.clientInstances).toHaveLength(0) + }) +}) diff --git a/src/main/daemon/daemon-init.ts b/src/main/daemon/daemon-init.ts index 7a0cad3ef..c23de0eee 100644 --- a/src/main/daemon/daemon-init.ts +++ b/src/main/daemon/daemon-init.ts @@ -1,3 +1,6 @@ +/* oxlint-disable max-lines -- Why: legacy cleanup adds startup-only cleanup +paths beside existing daemon lifecycle code; splitting would force tests to +export more lifecycle internals across files. */ import { join } from 'path' import { app } from 'electron' import { mkdirSync, existsSync, unlinkSync, writeFileSync } from 'fs' @@ -8,6 +11,7 @@ import { getDaemonPidPath, getDaemonSocketPath, getDaemonTokenPath, + serializeDaemonPidFile, type DaemonLauncher } from './daemon-spawner' import { DaemonPtyAdapter } from './daemon-pty-adapter' @@ -18,7 +22,7 @@ import { PROTOCOL_VERSION, type ListSessionsResult } from './types' -import { healthCheckDaemon, killStaleDaemon } from './daemon-health' +import { getProcessStartedAtMs, healthCheckDaemon, killStaleDaemon } from './daemon-health' import { setLocalPtyProvider } from '../ipc/pty' let spawner: DaemonSpawner | null = null @@ -130,7 +134,14 @@ function createOutOfProcessLauncher(runtimeDir: string): DaemonLauncher { if (msg && typeof msg === 'object' && (msg as { type?: string }).type === 'ready') { clearTimeout(timer) if (child.pid) { - writeFileSync(getDaemonPidPath(runtimeDir), String(child.pid), { mode: 0o600 }) + writeFileSync( + getDaemonPidPath(runtimeDir), + serializeDaemonPidFile({ + pid: child.pid, + startedAtMs: getProcessStartedAtMs(child.pid) + }), + { mode: 0o600 } + ) } // Why: disconnect IPC channel and unref so Electron can exit // without waiting for the daemon. The daemon keeps running. @@ -191,16 +202,30 @@ export async function initDaemonPtyProvider(): Promise { } }) - const legacyAdapters = await createLegacyDaemonAdapters(runtimeDir) - const routedAdapter = - legacyAdapters.length > 0 - ? new DaemonPtyRouter({ - current: newAdapter, - legacy: legacyAdapters - }) - : newAdapter - if (routedAdapter instanceof DaemonPtyRouter) { + const legacyAdapters = await getLegacyAdaptersForStartup(runtimeDir) + let routedAdapter: DaemonPtyAdapter | DaemonPtyRouter = newAdapter + if (legacyAdapters.length > 0) { + routedAdapter = new DaemonPtyRouter({ + current: newAdapter, + legacy: legacyAdapters, + onLegacyDrained: async (drainedAdapter) => { + try { + drainedAdapter.dispose() + const result = await cleanupDaemonForProtocol(runtimeDir, drainedAdapter.protocolVersion) + console.log( + `[daemon] legacy v${drainedAdapter.protocolVersion} cleanup: reason=drain ` + + `killedSessions=${result.killedCount}` + ) + } catch (err) { + console.warn( + `[daemon] legacy v${drainedAdapter.protocolVersion} drain cleanup failed:`, + err + ) + } + } + }) await routedAdapter.discoverLegacySessions() + routedAdapter.sweepDrainedLegacyAdapters() } spawner = newSpawner @@ -239,7 +264,7 @@ export type OrphanedDaemonCleanupResult = { killedCount: number } -async function cleanupDaemonForProtocol( +export async function cleanupDaemonForProtocol( runtimeDir: string, protocolVersion: number ): Promise { @@ -313,33 +338,69 @@ async function cleanupDaemonForProtocol( return { cleaned: didRequestShutdown || didKillStaleDaemon, killedCount } } -async function createLegacyDaemonAdapters(runtimeDir: string): Promise { - const adapters: DaemonPtyAdapter[] = [] - for (const protocolVersion of PREVIOUS_DAEMON_PROTOCOL_VERSIONS) { - const socketPath = getDaemonSocketPath(runtimeDir, protocolVersion) - const tokenPath = getDaemonTokenPath(runtimeDir, protocolVersion) - if (!(await probeSocket(socketPath))) { - continue - } - // Why: old daemon PTYs can be running long-lived agents during an app - // upgrade. Keep those sessions routed to their original daemon while new - // terminals use the current protocol, instead of killing background work. - // Legacy adapters intentionally do not respawn: respawning an old protocol - // daemon from new code would recreate stale env semantics and can be less - // predictable than letting the session fail if that old daemon dies. - // Why historyPath is still passed: checkpoint writes will fail silently - // (pre-v4 daemons don't support getSnapshot), but the HistoryManager is - // still needed for cleanup — close/exit events must remove history dirs - // and mark meta.json as ended. Without it, a later v4 session reusing - // the same ID could false-restore stale scrollback.bin. - adapters.push( - new DaemonPtyAdapter({ - socketPath, - tokenPath, - protocolVersion, - historyPath: getHistoryDir() - }) - ) +export async function getLegacyAdaptersForStartup(runtimeDir: string): Promise { + if (process.env.ORCA_DISABLE_LEGACY_CLEANUP === '1') { + return [] } - return adapters + return createLegacyDaemonAdapters(runtimeDir) +} + +export async function createLegacyDaemonAdapters(runtimeDir: string): Promise { + const results = await Promise.all( + PREVIOUS_DAEMON_PROTOCOL_VERSIONS.map((protocolVersion) => + processLegacyVersion(runtimeDir, protocolVersion) + ) + ) + return results.filter((adapter): adapter is DaemonPtyAdapter => adapter !== null) +} + +export async function processLegacyVersion( + runtimeDir: string, + protocolVersion: number +): Promise { + const socketPath = getDaemonSocketPath(runtimeDir, protocolVersion) + const tokenPath = getDaemonTokenPath(runtimeDir, protocolVersion) + if (!(await probeSocket(socketPath))) { + return null + } + + let liveCount = 0 + let wedged = false + const probeClient = new DaemonClient({ socketPath, tokenPath, protocolVersion }) + try { + await probeClient.ensureConnected() + const { sessions } = await probeClient.request('listSessions', undefined) + liveCount = sessions.filter((session) => session.isAlive).length + } catch { + // Why: if an old daemon has a live socket but cannot answer RPC, no new + // client can safely reattach to its sessions; reclaim the wedged process. + wedged = true + } finally { + probeClient.disconnect() + } + + if (liveCount === 0) { + const reason = wedged ? 'wedged' : 'idle' + try { + const result = await cleanupDaemonForProtocol(runtimeDir, protocolVersion) + console.log( + `[daemon] legacy v${protocolVersion} cleanup: reason=${reason} ` + + `killedSessions=${result.killedCount}` + ) + } catch (err) { + console.warn(`[daemon] legacy v${protocolVersion} cleanup failed:`, err) + } + return null + } + + // Why: old daemon PTYs can be running long-lived agents during an app + // upgrade. Keep those sessions routed to their original daemon while new + // terminals use the current protocol, instead of killing background work. + console.log(`[daemon] legacy v${protocolVersion} wrapped for drain: liveSessions=${liveCount}`) + return new DaemonPtyAdapter({ + socketPath, + tokenPath, + protocolVersion, + historyPath: getHistoryDir() + }) } diff --git a/src/main/daemon/daemon-pty-adapter.test.ts b/src/main/daemon/daemon-pty-adapter.test.ts index 610937387..9ed38d2dc 100644 --- a/src/main/daemon/daemon-pty-adapter.test.ts +++ b/src/main/daemon/daemon-pty-adapter.test.ts @@ -93,6 +93,13 @@ describe('DaemonPtyAdapter (IPtyProvider)', () => { }) describe('spawn', () => { + it('exposes the protocol version used by the daemon client', () => { + const legacyAdapter = new DaemonPtyAdapter({ socketPath, tokenPath, protocolVersion: 3 }) + + expect(legacyAdapter.protocolVersion).toBe(3) + legacyAdapter.dispose() + }) + it('returns a result with an id', async () => { const result = await adapter.spawn({ cols: 80, rows: 24 }) expect(result.id).toBeDefined() diff --git a/src/main/daemon/daemon-pty-adapter.ts b/src/main/daemon/daemon-pty-adapter.ts index 1e4273ae5..e80ce1c0c 100644 --- a/src/main/daemon/daemon-pty-adapter.ts +++ b/src/main/daemon/daemon-pty-adapter.ts @@ -39,6 +39,7 @@ export class TerminalKilledError extends Error { } export class DaemonPtyAdapter implements IPtyProvider { + public readonly protocolVersion: number private client: DaemonClient private historyManager: HistoryManager | null private historyReader: HistoryReader | null @@ -71,15 +72,16 @@ export class DaemonPtyAdapter implements IPtyProvider { private static CHECKPOINT_INTERVAL_MS = 5_000 constructor(opts: DaemonPtyAdapterOptions) { + this.protocolVersion = opts.protocolVersion ?? PROTOCOL_VERSION this.client = new DaemonClient({ socketPath: opts.socketPath, tokenPath: opts.tokenPath, - protocolVersion: opts.protocolVersion + protocolVersion: this.protocolVersion }) this.historyManager = opts.historyPath ? new HistoryManager(opts.historyPath) : null this.historyReader = opts.historyPath ? new HistoryReader(opts.historyPath) : null this.respawnFn = opts.respawn ?? null - this.supportsCheckpoints = (opts.protocolVersion ?? PROTOCOL_VERSION) >= 4 + this.supportsCheckpoints = this.protocolVersion >= 4 } getHistoryManager(): HistoryManager | null { diff --git a/src/main/daemon/daemon-pty-router.test.ts b/src/main/daemon/daemon-pty-router.test.ts index 1594da80d..904b37030 100644 --- a/src/main/daemon/daemon-pty-router.test.ts +++ b/src/main/daemon/daemon-pty-router.test.ts @@ -74,6 +74,7 @@ function createAdapter( reconcileOnStartup: vi.fn(async () => reconcileResult ?? { alive: sessions, killed: [] }), dispose: vi.fn(), disconnectOnly: vi.fn(async () => {}), + protocolVersion: label === 'current' ? 4 : 3, emitData: (id: string, data: string) => { for (const listener of dataListeners) { listener({ id, data }) @@ -110,7 +111,8 @@ describe('DaemonPtyRouter', () => { it('drops a legacy mapping after the routed session exits', async () => { const current = createAdapter('current') const legacy = createAdapter('legacy', ['legacy-session']) - const router = new DaemonPtyRouter({ current, legacy: [legacy] }) + const onLegacyDrained = vi.fn() + const router = new DaemonPtyRouter({ current, legacy: [legacy], onLegacyDrained }) await router.discoverLegacySessions() @@ -118,6 +120,102 @@ describe('DaemonPtyRouter', () => { await router.spawn({ sessionId: 'legacy-session', cols: 80, rows: 24 }) expect(current.spawn).toHaveBeenCalledWith({ sessionId: 'legacy-session', cols: 80, rows: 24 }) + expect(onLegacyDrained).toHaveBeenCalledWith(legacy) + }) + + it('fires drain only after every session on a legacy adapter exits', async () => { + const current = createAdapter('current') + const legacy = createAdapter('legacy', ['one', 'two', 'three']) + const onLegacyDrained = vi.fn() + const router = new DaemonPtyRouter({ current, legacy: [legacy], onLegacyDrained }) + + await router.discoverLegacySessions() + + legacy.emitExit('one', 0) + legacy.emitExit('two', 0) + expect(onLegacyDrained).not.toHaveBeenCalled() + + legacy.emitExit('three', 0) + expect(onLegacyDrained).toHaveBeenCalledTimes(1) + expect(onLegacyDrained).toHaveBeenCalledWith(legacy) + }) + + it('drains one legacy adapter without touching another', async () => { + const current = createAdapter('current') + const legacy1 = createAdapter('legacy-1', ['one']) + const legacy2 = createAdapter('legacy-2', ['two']) + const onLegacyDrained = vi.fn() + const router = new DaemonPtyRouter({ + current, + legacy: [legacy1, legacy2], + onLegacyDrained + }) + + await router.discoverLegacySessions() + + legacy1.emitExit('one', 0) + router.write('two', 'still-live\n') + + expect(onLegacyDrained).toHaveBeenCalledTimes(1) + expect(onLegacyDrained).toHaveBeenCalledWith(legacy1) + expect(legacy2.write).toHaveBeenCalledWith('two', 'still-live\n') + }) + + it('does not fire drain for current adapter exits', async () => { + const current = createAdapter('current') + const legacy = createAdapter('legacy', ['legacy-session']) + const onLegacyDrained = vi.fn() + const router = new DaemonPtyRouter({ current, legacy: [legacy], onLegacyDrained }) + + const currentSession = await router.spawn({ cols: 80, rows: 24 }) + current.emitExit(currentSession.id, 0) + + expect(onLegacyDrained).not.toHaveBeenCalled() + }) + + it('does not query drained adapters in listProcesses', async () => { + const current = createAdapter('current') + const legacy = createAdapter('legacy', ['legacy-session']) + const router = new DaemonPtyRouter({ + current, + legacy: [legacy], + onLegacyDrained: vi.fn() + }) + + await router.discoverLegacySessions() + legacy.emitExit('legacy-session', 0) + vi.mocked(legacy.listProcesses).mockClear() + + await router.listProcesses() + + expect(legacy.listProcesses).not.toHaveBeenCalled() + }) + + it('guards against double drain events for the same adapter', async () => { + const current = createAdapter('current') + const legacy = createAdapter('legacy', ['legacy-session']) + const onLegacyDrained = vi.fn() + const router = new DaemonPtyRouter({ current, legacy: [legacy], onLegacyDrained }) + + await router.discoverLegacySessions() + + legacy.emitExit('legacy-session', 0) + legacy.emitExit('legacy-session', 0) + + expect(onLegacyDrained).toHaveBeenCalledTimes(1) + }) + + it('sweeps adapters that drain before discovery registers sessions', async () => { + const current = createAdapter('current') + const legacy = createAdapter('legacy') + const onLegacyDrained = vi.fn() + const router = new DaemonPtyRouter({ current, legacy: [legacy], onLegacyDrained }) + + await router.discoverLegacySessions() + router.sweepDrainedLegacyAdapters() + + expect(onLegacyDrained).toHaveBeenCalledTimes(1) + expect(onLegacyDrained).toHaveBeenCalledWith(legacy) }) it('merges startup reconciliation and updates route mappings', async () => { diff --git a/src/main/daemon/daemon-pty-router.ts b/src/main/daemon/daemon-pty-router.ts index e69b21aa6..bd5e2432f 100644 --- a/src/main/daemon/daemon-pty-router.ts +++ b/src/main/daemon/daemon-pty-router.ts @@ -5,16 +5,22 @@ export class DaemonPtyRouter implements IPtyProvider { private current: DaemonPtyAdapter private legacy: DaemonPtyAdapter[] private sessionAdapters = new Map() - private unsubscribers: (() => void)[] = [] + private unsubscribersByAdapter = new Map void)[]>() + private onLegacyDrained?: (adapter: DaemonPtyAdapter) => void private dataListeners: ((payload: { id: string; data: string }) => void)[] = [] private exitListeners: ((payload: { id: string; code: number }) => void)[] = [] - constructor(opts: { current: DaemonPtyAdapter; legacy: DaemonPtyAdapter[] }) { + constructor(opts: { + current: DaemonPtyAdapter + legacy: DaemonPtyAdapter[] + onLegacyDrained?: (adapter: DaemonPtyAdapter) => void + }) { this.current = opts.current this.legacy = opts.legacy + this.onLegacyDrained = opts.onLegacyDrained for (const adapter of this.allAdapters()) { - this.unsubscribers.push( + const unsubscribers = [ adapter.onData((payload) => { for (const listener of this.dataListeners) { listener(payload) @@ -25,8 +31,10 @@ export class DaemonPtyRouter implements IPtyProvider { for (const listener of this.exitListeners) { listener(payload) } + this.drainLegacyAdapterIfEmpty(adapter) }) - ) + ] + this.unsubscribersByAdapter.set(adapter, unsubscribers) } } @@ -43,6 +51,12 @@ export class DaemonPtyRouter implements IPtyProvider { } } + sweepDrainedLegacyAdapters(): void { + for (const adapter of Array.from(this.legacy)) { + this.drainLegacyAdapterIfEmpty(adapter) + } + } + async spawn(opts: PtySpawnOptions): Promise { const adapter = opts.sessionId ? this.sessionAdapters.get(opts.sessionId) : undefined const target = adapter ?? this.current @@ -172,18 +186,14 @@ export class DaemonPtyRouter implements IPtyProvider { } dispose(): void { - for (const unsubscribe of this.unsubscribers.splice(0)) { - unsubscribe() - } + this.unsubscribeAllAdapters() for (const adapter of this.allAdapters()) { adapter.dispose() } } async disconnectOnly(): Promise { - for (const unsubscribe of this.unsubscribers.splice(0)) { - unsubscribe() - } + this.unsubscribeAllAdapters() await Promise.all([...this.allAdapters()].map((adapter) => adapter.disconnectOnly())) } @@ -191,6 +201,43 @@ export class DaemonPtyRouter implements IPtyProvider { return this.sessionAdapters.get(sessionId) ?? this.current } + private drainLegacyAdapterIfEmpty(adapter: DaemonPtyAdapter): void { + // Why: only previous-version adapters are cleaned up here. The current + // daemon lifecycle must remain byte-identical when its sessions exit. + if (!this.legacy.includes(adapter) || this.hasActiveSessionsOn(adapter)) { + return + } + this.legacy = this.legacy.filter((a) => a !== adapter) + this.unsubscribeAdapter(adapter) + this.onLegacyDrained?.(adapter) + } + + private hasActiveSessionsOn(adapter: DaemonPtyAdapter): boolean { + for (const mappedAdapter of this.sessionAdapters.values()) { + if (mappedAdapter === adapter) { + return true + } + } + return false + } + + private unsubscribeAdapter(adapter: DaemonPtyAdapter): void { + const unsubscribers = this.unsubscribersByAdapter.get(adapter) + if (!unsubscribers) { + return + } + for (const unsubscribe of unsubscribers) { + unsubscribe() + } + this.unsubscribersByAdapter.delete(adapter) + } + + private unsubscribeAllAdapters(): void { + for (const adapter of Array.from(this.unsubscribersByAdapter.keys())) { + this.unsubscribeAdapter(adapter) + } + } + private allAdapters(): DaemonPtyAdapter[] { return [this.current, ...this.legacy] } diff --git a/src/main/daemon/daemon-spawner.test.ts b/src/main/daemon/daemon-spawner.test.ts index 63a65aeb2..d96c6caae 100644 --- a/src/main/daemon/daemon-spawner.test.ts +++ b/src/main/daemon/daemon-spawner.test.ts @@ -6,7 +6,8 @@ import { DaemonSpawner, getDaemonPidPath, getDaemonSocketPath, - getDaemonTokenPath + getDaemonTokenPath, + serializeDaemonPidFile } from './daemon-spawner' import { startDaemon, type DaemonHandle } from './daemon-main' import { DaemonClient } from './client' @@ -82,6 +83,13 @@ describe('DaemonSpawner', () => { expect(pidPath).toBe(join(dir, `daemon-v${PROTOCOL_VERSION}.pid`)) }) + it('serializes pid files with process start metadata', () => { + expect(JSON.parse(serializeDaemonPidFile({ pid: 123, startedAtMs: 456 }))).toEqual({ + pid: 123, + startedAtMs: 456 + }) + }) + it('starts daemon and returns connection info', async () => { const s = createSpawner() const info = await s.ensureRunning() diff --git a/src/main/daemon/daemon-spawner.ts b/src/main/daemon/daemon-spawner.ts index 4b6144bca..d57b79e41 100644 --- a/src/main/daemon/daemon-spawner.ts +++ b/src/main/daemon/daemon-spawner.ts @@ -7,6 +7,11 @@ export type DaemonConnectionInfo = { tokenPath: string } +export type DaemonPidFile = { + pid: number + startedAtMs: number | null +} + export type DaemonProcessHandle = { shutdown(): Promise } @@ -80,3 +85,7 @@ export function getDaemonTokenPath(runtimeDir: string, protocolVersion = PROTOCO export function getDaemonPidPath(runtimeDir: string, protocolVersion = PROTOCOL_VERSION): string { return join(runtimeDir, `daemon-v${protocolVersion}.pid`) } + +export function serializeDaemonPidFile(pidFile: DaemonPidFile): string { + return JSON.stringify(pidFile) +} diff --git a/src/main/daemon/types.test.ts b/src/main/daemon/types.test.ts new file mode 100644 index 000000000..ce0850960 --- /dev/null +++ b/src/main/daemon/types.test.ts @@ -0,0 +1,14 @@ +import { describe, expect, it } from 'vitest' +import { PREVIOUS_DAEMON_PROTOCOL_VERSIONS, PROTOCOL_VERSION } from './types' + +describe('daemon protocol version invariants', () => { + it('does not include the current protocol in previous daemon versions', () => { + expect(PREVIOUS_DAEMON_PROTOCOL_VERSIONS).not.toContain(PROTOCOL_VERSION) + }) + + it('lists every previous protocol version', () => { + expect(PREVIOUS_DAEMON_PROTOCOL_VERSIONS).toEqual( + Array.from({ length: PROTOCOL_VERSION - 1 }, (_, index) => index + 1) + ) + }) +})