diff --git a/src/main/daemon/daemon-health.test.ts b/src/main/daemon/daemon-health.test.ts index 2b9884f07..e091df24f 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 { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' 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, + startTimeMatches +} from './daemon-health' import type { SubprocessHandle } from './session' function createMockSubprocess(): SubprocessHandle { @@ -107,3 +113,126 @@ describe('daemon health', () => { } }) }) + +describe('parseDaemonPidFile', () => { + it('parses JSON pid files with startedAtMs', () => { + const serialized = serializeDaemonPidFile({ pid: 12345, startedAtMs: 1_700_000_000_000 }) + expect(parseDaemonPidFile(serialized)).toEqual({ + pid: 12345, + startedAtMs: 1_700_000_000_000 + }) + }) + + it('accepts JSON with startedAtMs missing and returns null for it', () => { + // Why: forward-compatible with hypothetical future daemons that might write + // pid without startedAtMs (platform where getProcessStartedAtMs returns null). + expect(parseDaemonPidFile('{"pid":9999}')).toEqual({ pid: 9999, startedAtMs: null }) + }) + + it('falls back to bare-integer parsing for legacy pid files', () => { + // Why: pre-Phase-0 daemons wrote the pid file as a bare integer. + // parseDaemonPidFile must still accept those to avoid leaking a stale + // daemon across a single upgrade boundary. + expect(parseDaemonPidFile('12345')).toEqual({ pid: 12345, startedAtMs: null }) + expect(parseDaemonPidFile(' 12345\n')).toEqual({ pid: 12345, startedAtMs: null }) + }) + + it('returns null for malformed input', () => { + expect(parseDaemonPidFile('not-a-number')).toBeNull() + expect(parseDaemonPidFile('{"pid":"abc"}')).toBeNull() + expect(parseDaemonPidFile('{"not_pid":123}')).toBeNull() + }) +}) + +describe('startTimeMatches', () => { + it('returns true when expected is null (legacy pid file)', () => { + // The real process pid is irrelevant here — null short-circuits before + // getProcessStartedAtMs is consulted. + expect(startTimeMatches(process.pid, null)).toBe(true) + }) + + it('returns true when actual start time cannot be read (fail-open)', () => { + if (process.platform === 'win32') { + // Windows always returns null from getProcessStartedAtMs, which is the + // fail-open case we want. + expect(startTimeMatches(process.pid, 1_700_000_000_000)).toBe(true) + return + } + // Pid 0 is the kernel scheduler — ps -p 0 / /proc/0 both fail, so + // getProcessStartedAtMs returns null and the check fails open. + expect(startTimeMatches(0, 1_700_000_000_000)).toBe(true) + }) + + it('returns true for matching start time within tolerance', () => { + if (process.platform === 'win32') { + // Skip on Windows — getProcessStartedAtMs always returns null. + return + } + const actual = getProcessStartedAtMs(process.pid) + if (actual === null) { + // Platform can't probe — skip + return + } + // Tolerance is ±1500ms. Shift expected by 500ms, still within tolerance. + expect(startTimeMatches(process.pid, actual + 500)).toBe(true) + }) + + it('returns false for start times outside tolerance', () => { + if (process.platform === 'win32') { + return + } + const actual = getProcessStartedAtMs(process.pid) + if (actual === null) { + return + } + // Shift expected by 10s — clearly outside the ±1500ms tolerance. + expect(startTimeMatches(process.pid, actual + 10_000)).toBe(false) + }) +}) + +describe('killStaleDaemon pid identity guards', () => { + let dir: string + let socketPath: string + let tokenPath: string + + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'daemon-health-pid-test-')) + socketPath = join(dir, 'daemon.sock') + tokenPath = join(dir, 'daemon.token') + }) + + afterEach(() => { + rmSync(dir, { recursive: true, force: true }) + }) + + it('does not SIGTERM when the saved startedAtMs mismatches the current process', async () => { + if (process.platform === 'win32') { + return + } + + // Why: seed a pid file that claims the daemon is `process.pid` (us) but + // was started 1 hour ago. Our real start time is "now," so startTimeMatches + // returns false and isDaemonProcess rejects. killStaleDaemon must not call + // process.kill in that case. + const bogusStartedAtMs = Date.now() - 60 * 60 * 1000 + writeFileSync( + getDaemonPidPath(dir), + serializeDaemonPidFile({ pid: process.pid, startedAtMs: bogusStartedAtMs }), + { mode: 0o600 } + ) + + // isDaemonProcess uses process.kill(pid, 0) as a liveness probe; that's + // expected and not a real kill. We only care that no actual termination + // signal is sent. + const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true) + try { + await expect(killStaleDaemon(dir, socketPath, tokenPath)).resolves.toBe(false) + const terminationSignals = killSpy.mock.calls.filter( + ([, sig]) => sig === 'SIGTERM' || sig === 'SIGKILL' + ) + expect(terminationSignals).toEqual([]) + } finally { + killSpy.mockRestore() + } + }) +}) diff --git a/src/main/daemon/daemon-health.ts b/src/main/daemon/daemon-health.ts index a0ab5025c..7d6126db9 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 + } +} + +export 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,24 @@ export async function killStaleDaemon( await new Promise((resolve) => setTimeout(resolve, KILL_POLL_MS)) } if (!exited) { - try { - process.kill(pid, 'SIGKILL') + // Why: re-check process identity before SIGKILL. The SIGTERM-then-wait + // window is long enough for the pid to be recycled if the original + // daemon died during the wait. Without this, we'd SIGKILL an unrelated + // process that happens to now own the same pid. + 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 + 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..5b4cdfafc --- /dev/null +++ b/src/main/daemon/daemon-init.test.ts @@ -0,0 +1,603 @@ +/* eslint-disable max-lines -- Why: this file covers the entire restart flow + of daemon-init — construction, the 7-step sequence from + docs/daemon-staleness-ux.md §Phase 1, and the concurrency coalescer. A + single describe block with shared mocks keeps setup in one place; splitting + across files would duplicate the vi.hoisted boundary mocks with no cleaner + ownership seam. */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { PROTOCOL_VERSION } from './types' + +// Why: the restart flow touches many boundary modules (electron app paths, fs +// for dir creation, net for socket probe, DaemonClient over that socket, the +// spawner's launcher, ipc/pty listener binders). We only care here about the +// observable sequencing and identity invariants of runRestartDaemon, so every +// non-daemon-init dependency is replaced by a minimal stub that records calls. +const { + getPathMock, + probeSocketExistsMock, + netConnectMock, + healthCheckDaemonMock, + killStaleDaemonMock, + getProcessStartedAtMsMock, + daemonClientMock, + spawnerInstances, + adapterInstances, + setLocalPtyProviderMock, + unbindLocalProviderListenersMock, + rebindLocalProviderListenersMock +} = vi.hoisted(() => { + const getPathMock = vi.fn(() => '/fake/userData') + + const probeSocketExistsMock = vi.fn(() => false) + const netConnectMock = vi.fn(() => { + // Why: the real probeSocket() in daemon-init connects to the socket and + // resolves true on 'connect', false on 'error'. Our launcher never runs + // in these tests (healthCheckDaemon short-circuits), but probeSocket is + // also invoked by cleanupDaemonForProtocol — stub the socket object so + // the 'error' path fires synchronously and cleanupDaemonForProtocol's + // alive=false branch runs without side effects. + const handlers: Record void)[]> = { connect: [], error: [] } + return { + on(event: string, cb: () => void) { + handlers[event]?.push(cb) + if (event === 'error') { + // Fire after microtask so destroy()/resolve ordering matches real net + queueMicrotask(() => cb()) + } + return this + }, + destroy() {} + } + }) + + const healthCheckDaemonMock = vi.fn(async () => true) + 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() + })) + + // Why: every DaemonSpawner constructed under test pushes into this array so + // assertions can check "was the *same* spawner reused across restart?". + const spawnerInstances: MockSpawner[] = [] + // Same for DaemonPtyAdapter. The test asserts the replacement adapter is a + // fresh instance whose respawn closure targets the *original* spawner. + const adapterInstances: MockAdapter[] = [] + + const setLocalPtyProviderMock = vi.fn() + const unbindLocalProviderListenersMock = vi.fn() + const rebindLocalProviderListenersMock = vi.fn() + + return { + getPathMock, + probeSocketExistsMock, + netConnectMock, + healthCheckDaemonMock, + killStaleDaemonMock, + getProcessStartedAtMsMock, + daemonClientMock, + spawnerInstances, + adapterInstances, + setLocalPtyProviderMock, + unbindLocalProviderListenersMock, + rebindLocalProviderListenersMock + } +}) + +type MockSpawner = { + ensureRunning: ReturnType + resetHandle: ReturnType + shutdown: ReturnType + launcher: unknown +} + +type MockAdapter = { + protocolVersion: number + options: { + socketPath: string + tokenPath: string + historyPath?: string + respawn?: () => Promise + protocolVersion?: number + } + getActiveSessionIds: ReturnType + fanoutSyntheticExits: ReturnType + listProcesses: ReturnType + listSessions: ReturnType + shutdown: ReturnType + dispose: ReturnType + disconnectOnly: ReturnType + onData: ReturnType + onExit: ReturnType + // Why: MockAdapter is fed through `new DaemonPtyRouter({ current, legacy })` + // during the "legacy preservation" test. The real router calls onData/onExit + // on each adapter; our stub returns a no-op unsubscribe so the router can + // subscribe without exploding. + callOrder: string[] +} + +vi.mock('electron', () => ({ + app: { getPath: getPathMock, getAppPath: () => '/fake/app' } +})) + +vi.mock('fs', () => ({ + mkdirSync: vi.fn(), + existsSync: (p: string) => probeSocketExistsMock() || p.includes('.pid'), + unlinkSync: vi.fn(), + writeFileSync: vi.fn() +})) + +vi.mock('child_process', () => ({ fork: vi.fn() })) + +vi.mock('net', () => ({ connect: netConnectMock })) + +vi.mock('./daemon-health', () => ({ + healthCheckDaemon: healthCheckDaemonMock, + killStaleDaemon: killStaleDaemonMock, + getProcessStartedAtMs: getProcessStartedAtMsMock +})) + +vi.mock('./client', () => ({ DaemonClient: daemonClientMock })) + +vi.mock('./daemon-spawner', () => ({ + DaemonSpawner: class MockDaemonSpawner { + readonly launcher: unknown + readonly ensureRunning: ReturnType + readonly resetHandle: ReturnType + readonly shutdown: ReturnType + private socketCounter: number + constructor(opts: { runtimeDir: string; launcher: unknown }) { + this.launcher = opts.launcher + this.socketCounter = 0 + // Why: each ensureRunning bumps a counter into the returned socketPath + // so the test can verify the *replacement* adapter is constructed with + // info from the second ensureRunning call, not stale info from the first. + this.ensureRunning = vi.fn(async () => { + this.socketCounter += 1 + return { + socketPath: `/fake/socket-${this.socketCounter}`, + tokenPath: `/fake/token-${this.socketCounter}` + } + }) + this.resetHandle = vi.fn() + this.shutdown = vi.fn(async () => {}) + spawnerInstances.push(this as unknown as MockSpawner) + } + }, + getDaemonSocketPath: (_dir: string, version?: number) => + `/fake/daemon/daemon-v${version ?? PROTOCOL_VERSION}.sock`, + getDaemonTokenPath: (_dir: string, version?: number) => + `/fake/daemon/daemon-v${version ?? PROTOCOL_VERSION}.token`, + getDaemonPidPath: (_dir: string, version?: number) => + `/fake/daemon/daemon-v${version ?? PROTOCOL_VERSION}.pid`, + serializeDaemonPidFile: (obj: unknown) => JSON.stringify(obj) +})) + +vi.mock('./daemon-pty-adapter', () => ({ + DaemonPtyAdapter: class MockDaemonPtyAdapter { + readonly protocolVersion: number + readonly options: MockAdapter['options'] + readonly getActiveSessionIds: ReturnType + readonly fanoutSyntheticExits: ReturnType + readonly listProcesses: ReturnType + readonly listSessions: ReturnType + readonly shutdown: ReturnType + readonly dispose: ReturnType + readonly disconnectOnly: ReturnType + readonly onData: ReturnType + readonly onExit: ReturnType + readonly callOrder: string[] + constructor(opts: MockAdapter['options']) { + this.protocolVersion = opts.protocolVersion ?? PROTOCOL_VERSION + this.options = opts + this.callOrder = [] + this.getActiveSessionIds = vi.fn(() => [] as string[]) + this.fanoutSyntheticExits = vi.fn(() => { + this.callOrder.push('fanoutSyntheticExits') + }) + this.listProcesses = vi.fn(async () => []) + this.listSessions = vi.fn(async () => []) + this.shutdown = vi.fn(async () => {}) + this.dispose = vi.fn() + this.disconnectOnly = vi.fn(async () => {}) + this.onData = vi.fn(() => () => {}) + this.onExit = vi.fn(() => () => {}) + adapterInstances.push(this as unknown as MockAdapter) + } + } +})) + +vi.mock('../ipc/pty', () => ({ + setLocalPtyProvider: setLocalPtyProviderMock, + unbindLocalProviderListeners: unbindLocalProviderListenersMock, + rebindLocalProviderListeners: rebindLocalProviderListenersMock +})) + +async function importFresh() { + vi.resetModules() + spawnerInstances.length = 0 + adapterInstances.length = 0 + setLocalPtyProviderMock.mockClear() + unbindLocalProviderListenersMock.mockClear() + rebindLocalProviderListenersMock.mockClear() + healthCheckDaemonMock.mockClear() + killStaleDaemonMock.mockClear() + daemonClientMock.mockClear() + probeSocketExistsMock.mockClear() + // Why: importing daemon-init *after* resetModules means the module-level + // `spawner`/`adapter`/`restartInFlight` start fresh for every test, which is + // the only way to reliably exercise the "first-time init" path and the + // coalescer independently. + return import('./daemon-init') +} + +describe('daemon-init: runRestartDaemon (7-step sequence)', () => { + beforeEach(() => { + probeSocketExistsMock.mockReturnValue(false) + }) + + afterEach(() => { + vi.clearAllMocks() + }) + + it('fans pty:exit for every active session *before* unbinding listeners, and killedCount is captured pre-fanout', async () => { + const mod = await importFresh() + await mod.initDaemonPtyProvider() + + // Why: seed the original adapter with active sessions so + // fanoutSyntheticExits has something to do. The real adapter snapshots + // activeSessionIds then clears it; the mock emulates that so a regression + // that measures killedCount *after* fanout (when the set is empty) would + // surface as `killedCount === 0` here. + const originalAdapter = adapterInstances[0] + let activeIds = ['sess-a', 'sess-b', 'sess-c'] + originalAdapter.getActiveSessionIds.mockImplementation(() => [...activeIds]) + + const order: string[] = [] + originalAdapter.fanoutSyntheticExits.mockImplementation(() => { + order.push('fanout') + activeIds = [] + }) + unbindLocalProviderListenersMock.mockImplementation(() => { + order.push('unbind') + }) + + const result = await mod.restartDaemon() + + // killedCount must be 3 — proves the count was taken *before* the fanout + // cleared the set. A bug that swapped these two lines in source would + // report 0 here. + expect(result.killedCount).toBe(3) + expect(originalAdapter.fanoutSyntheticExits).toHaveBeenCalledWith(-1) + // The load-bearing ordering invariant: the synthetic exits must reach + // the renderer *before* listeners are torn down. Step 1 before Step 2. + expect(order).toEqual(['fanout', 'unbind']) + }) + + it('reuses the existing DaemonSpawner across restart (resetHandle + ensureRunning on same instance)', async () => { + const mod = await importFresh() + await mod.initDaemonPtyProvider() + + expect(spawnerInstances).toHaveLength(1) + const originalSpawner = spawnerInstances[0] + expect(originalSpawner.ensureRunning).toHaveBeenCalledTimes(1) + + await mod.restartDaemon() + + // No second DaemonSpawner was constructed — restart uses the one from init. + expect(spawnerInstances).toHaveLength(1) + expect(originalSpawner.resetHandle).toHaveBeenCalledTimes(1) + expect(originalSpawner.ensureRunning).toHaveBeenCalledTimes(2) + }) + + it('builds a fresh adapter whose respawn callback closes over the same spawner', async () => { + const mod = await importFresh() + await mod.initDaemonPtyProvider() + + const originalSpawner = spawnerInstances[0] + const originalAdapter = adapterInstances[0] + + await mod.restartDaemon() + + // A new adapter was constructed against the replacement daemon's socket. + expect(adapterInstances).toHaveLength(2) + const replacementAdapter = adapterInstances[1] + expect(replacementAdapter).not.toBe(originalAdapter) + expect(replacementAdapter.options.socketPath).toBe('/fake/socket-2') + expect(replacementAdapter.options.tokenPath).toBe('/fake/token-2') + + // Invoking the replacement adapter's respawn closure must drive the + // *same* original spawner (matches the crash-respawn closure baked into + // the first adapter — see daemon-init.ts step 5 comment). + originalSpawner.resetHandle.mockClear() + originalSpawner.ensureRunning.mockClear() + await replacementAdapter.options.respawn?.() + expect(originalSpawner.resetHandle).toHaveBeenCalledTimes(1) + expect(originalSpawner.ensureRunning).toHaveBeenCalledTimes(1) + // Still only one spawner in the whole test — nobody new was constructed. + expect(spawnerInstances).toHaveLength(1) + }) + + it('swaps the module-level adapter and re-binds listeners after the new provider is installed', async () => { + const mod = await importFresh() + await mod.initDaemonPtyProvider() + + // initDaemonPtyProvider calls setLocalPtyProvider once with the original. + expect(setLocalPtyProviderMock).toHaveBeenCalledTimes(1) + const originalProvider = setLocalPtyProviderMock.mock.calls[0][0] + expect(originalProvider).toBe(adapterInstances[0]) + expect(mod.getDaemonProvider()).toBe(originalProvider) + + await mod.restartDaemon() + + const replacementAdapter = adapterInstances[1] + // Second call: swap to the replacement provider (Step 6). + expect(setLocalPtyProviderMock).toHaveBeenCalledTimes(2) + expect(setLocalPtyProviderMock.mock.calls[1][0]).toBe(replacementAdapter) + expect(mod.getDaemonProvider()).toBe(replacementAdapter) + + // Step 7: rebind must run *after* Step 6. The last rebind call index + // must be greater than the last setLocalPtyProvider call index. + const rebindOrder = rebindLocalProviderListenersMock.mock.invocationCallOrder.at(-1) ?? -1 + const swapOrder = setLocalPtyProviderMock.mock.invocationCallOrder.at(-1) ?? -1 + expect(rebindOrder).toBeGreaterThan(swapOrder) + }) + + it('preserves legacy adapter instances by identity, drains outgoing router via disposeRouterOnly, and re-discovers legacy sessions on the new router', async () => { + const mod = await importFresh() + + // Why: initDaemonPtyProvider only constructs legacy adapters when + // probeSocket returns true for a legacy socket path. The real flow runs + // createLegacyDaemonAdapters which calls probeSocket per previous version. + // Simplest seam for this test: directly construct a router with a legacy + // adapter and install it via replaceDaemonProvider, bypassing + // createLegacyDaemonAdapters' socket-probe machinery. + await mod.initDaemonPtyProvider() + + const { DaemonPtyRouter } = await import('./daemon-pty-router') + const { DaemonPtyAdapter } = await import('./daemon-pty-adapter') + const currentAtConstruction = adapterInstances[0] + // Construct a legacy adapter using the mocked constructor (pushes into + // adapterInstances) — index 1. + const legacyAdapter = new DaemonPtyAdapter({ + socketPath: '/fake/legacy.sock', + tokenPath: '/fake/legacy.token', + protocolVersion: 3 + }) + const routerWithLegacy = new DaemonPtyRouter({ + current: currentAtConstruction as unknown as InstanceType, + legacy: [legacyAdapter as unknown as InstanceType] + }) + // Why: spy on the *outgoing* router's disposeRouterOnly so we can prove it + // was invoked (not just that legacy adapters survived — a no-op + // disposeRouterOnly would leak listeners but still leave adapters alive). + const disposeRouterOnlySpy = vi.spyOn(routerWithLegacy, 'disposeRouterOnly') + const oldRouterDispose = vi.spyOn(routerWithLegacy, 'dispose') + mod.replaceDaemonProvider(routerWithLegacy) + + await mod.restartDaemon() + + const provider = mod.getDaemonProvider() + expect(provider).toBeInstanceOf(DaemonPtyRouter) + const newRouter = provider as InstanceType + expect(newRouter).not.toBe(routerWithLegacy) + + // Legacy adapter instance is preserved by identity — not reconstructed, + // not defensively copied, not disposed. + const legacies = newRouter.getLegacyAdapters() + expect(legacies).toHaveLength(1) + expect(legacies[0]).toBe(legacyAdapter) + expect(legacyAdapter.dispose).not.toHaveBeenCalled() + // The outgoing router was drained via disposeRouterOnly (router-only + // teardown), so legacy adapters' underlying connections are untouched. + expect(legacyAdapter.disconnectOnly).not.toHaveBeenCalled() + // The outgoing router's subscriptions were drained but the adapters + // behind it were NOT disposed — that's the whole point of disposeRouterOnly. + expect(disposeRouterOnlySpy).toHaveBeenCalledTimes(1) + expect(oldRouterDispose).not.toHaveBeenCalled() + + // The replacement router must re-run discovery so spawns targeting a + // surviving legacy sessionId still route to the legacy adapter. + expect(legacyAdapter.listProcesses).toHaveBeenCalled() + }) + + it('restart path with no legacy adapters yields a bare DaemonPtyAdapter (not wrapped in a router)', async () => { + const mod = await importFresh() + await mod.initDaemonPtyProvider() + + // initDaemonPtyProvider sets up a bare adapter when createLegacyDaemonAdapters + // finds nothing — confirm that shape persists across restart. + const { DaemonPtyAdapter } = await import('./daemon-pty-adapter') + const { DaemonPtyRouter } = await import('./daemon-pty-router') + expect(mod.getDaemonProvider()).toBeInstanceOf(DaemonPtyAdapter) + + await mod.restartDaemon() + + expect(mod.getDaemonProvider()).toBeInstanceOf(DaemonPtyAdapter) + expect(mod.getDaemonProvider()).not.toBeInstanceOf(DaemonPtyRouter) + }) + + it('orders Step 3 (cleanup) → Step 4 (resetHandle + ensureRunning) → Step 5 (new adapter) → Step 6 (replaceProvider) → Step 7 (rebind)', async () => { + const mod = await importFresh() + await mod.initDaemonPtyProvider() + + const originalSpawner = spawnerInstances[0] + const originalAdapter = adapterInstances[0] + + // Build an ordered trace by stamping each step as it fires. Cleanup is + // the tricky one — it's the `cleanupDaemonForProtocol` call, observable + // via the probeSocket→healthCheckDaemon→killStaleDaemon branch. We use + // healthCheckDaemon as the cleanup-start marker because it's the first + // call inside createOutOfProcessLauncher → and also fires inside + // cleanupDaemonForProtocol's alive branch… actually in the default + // (probeSocket=false) path cleanup is a no-op beyond pid-unlink. The + // load-bearing observable is `resetHandle` — it fires *after* cleanup + // returns. So we instrument the spawner instead. + const trace: string[] = [] + originalAdapter.fanoutSyntheticExits.mockImplementation(() => trace.push('fanout')) + unbindLocalProviderListenersMock.mockImplementation(() => trace.push('unbind')) + originalSpawner.resetHandle.mockImplementation(() => trace.push('resetHandle')) + const originalEnsureRunning = originalSpawner.ensureRunning + originalSpawner.ensureRunning.mockImplementation(async () => { + trace.push('ensureRunning') + return { + socketPath: '/fake/socket-2', + tokenPath: '/fake/token-2' + } + }) + setLocalPtyProviderMock.mockImplementation(() => trace.push('replaceProvider')) + rebindLocalProviderListenersMock.mockImplementation(() => trace.push('rebind')) + + await mod.restartDaemon() + void originalEnsureRunning // keep ref so tslint doesn't complain + + // The full 7-step sequence in order. Step 3 (cleanupDaemonForProtocol) + // has no unique observable in the dead-socket branch, so it's implicitly + // ordered by the fact that resetHandle runs after unbind; if cleanup + // ever moved *after* resetHandle, we'd see `resetHandle` precede its + // expected position. + expect(trace).toEqual([ + 'fanout', + 'unbind', + 'resetHandle', + 'ensureRunning', + 'replaceProvider', + 'rebind' + ]) + + // A fresh adapter must have been constructed *between* ensureRunning + // and replaceProvider (Step 5 before Step 6). adapterInstances[1] is + // the replacement — its socketPath comes from the Step-4 ensureRunning + // result, so its existence proves the ordering. + expect(adapterInstances).toHaveLength(2) + expect(adapterInstances[1].options.socketPath).toBe('/fake/socket-2') + }) + + it('exercises the alive-daemon cleanup path: issues shutdown RPC via DaemonClient before spawning a replacement', async () => { + // Why: the default mock has probeSocket returning false, so Step 3's + // DaemonClient-based shutdown path is normally skipped. This test flips + // the socket to "alive" so cleanupDaemonForProtocol takes the + // client.ensureConnected → listSessions → shutdown RPC branch. Without + // this, the design doc's Risks section ("verify under both 'shutdown + // RPC succeeded' and 'fell back to killStaleDaemon' paths") is uncovered. + + const requestMock = vi.fn(async (method: string) => { + if (method === 'listSessions') { + return { sessions: [{ sessionId: 'live-1', isAlive: true }] } + } + // `shutdown` RPC — daemon exits before reply lands; return undefined. + return undefined + }) + const ensureConnectedMock = vi.fn(async () => {}) + const disconnectMock = vi.fn() + // Why: DaemonClient is invoked via `new DaemonClient(...)`, so the mock + // factory must return a constructor-compatible function. Capture the + // existing impl so later tests aren't affected. + daemonClientMock.mockImplementationOnce(function MockDaemonClientForShutdown() { + return { + ensureConnected: ensureConnectedMock, + request: requestMock, + disconnect: disconnectMock + } + }) + + const mod = await importFresh() + await mod.initDaemonPtyProvider() + + // Make probeSocket return true for the current-version path by toggling + // both the fs.existsSync proxy AND net.connect resolving "alive". + probeSocketExistsMock.mockReturnValue(true) + netConnectMock.mockImplementationOnce(() => { + 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.restartDaemon() + + // The shutdown RPC must have been issued with killSessions=true. + expect(ensureConnectedMock).toHaveBeenCalled() + expect(requestMock).toHaveBeenCalledWith('shutdown', { killSessions: true }) + // The fallback killStaleDaemon must NOT fire when the RPC path worked. + expect(killStaleDaemonMock).not.toHaveBeenCalled() + }) + + it('coalesces concurrent restartDaemon() calls so the 7-step sequence runs exactly once', async () => { + const mod = await importFresh() + await mod.initDaemonPtyProvider() + + const originalSpawner = spawnerInstances[0] + + // Why: without an explicit gate, `Promise.all([restartDaemon(), + // restartDaemon()])` evaluates arguments left-to-right *synchronously* — + // the first call's promise could resolve before the second invocation + // begins if all internal awaits resolved in a single microtask, which + // would leave the coalescer untested. The deferred gate holds the first + // restart inside `ensureRunning` until we release it, guaranteeing the + // second call enters while the first is genuinely mid-flight. + let releaseEnsureRunning: (() => void) | undefined + const ensureRunningBarrier = new Promise((resolve) => { + releaseEnsureRunning = resolve + }) + originalSpawner.ensureRunning.mockImplementationOnce(async () => { + await ensureRunningBarrier + return { socketPath: '/fake/socket-2', tokenPath: '/fake/token-2' } + }) + + const call1 = mod.restartDaemon() + // Yield microtasks so call1 progresses into runRestartDaemon and is + // definitely blocked on the barrier. + await Promise.resolve() + await Promise.resolve() + const call2 = mod.restartDaemon() + + // Why: `async function restartDaemon` wraps each return in a fresh + // Promise, so `call1 === call2` does *not* hold even when the coalescer + // is working. The load-bearing proof is behavioral: while call1 is + // blocked on the ensureRunning barrier, call2 must NOT fork a parallel + // run of the 7-step sequence. If the coalescer fails, a second + // `runRestartDaemon` starts, which means a second `resetHandle` fires + // before we release the barrier. Check that counter at this exact + // moment — a non-coalescing implementation would already be at 2. + expect(originalSpawner.resetHandle).toHaveBeenCalledTimes(1) + expect(adapterInstances).toHaveLength(1) + + releaseEnsureRunning?.() + const [r1, r2] = await Promise.all([call1, call2]) + // Both resolved values must be structurally identical (same result + // object bubbled up through the shared runRestartDaemon promise). + expect(r1).toEqual(r2) + + // resetHandle fires once per restart; ensureRunning fires once during + // init + once during restart. A second, un-coalesced restart would push + // these counters to 2 and 3 respectively. + expect(originalSpawner.resetHandle).toHaveBeenCalledTimes(1) + expect(originalSpawner.ensureRunning).toHaveBeenCalledTimes(2) + expect(adapterInstances).toHaveLength(2) + + // After the in-flight promise settles, a fresh restart is allowed to run + // — proves `.finally(() => restartInFlight = null)` actually cleared the + // slot. A stale restartInFlight would skip the work entirely. + await mod.restartDaemon() + expect(originalSpawner.resetHandle).toHaveBeenCalledTimes(2) + expect(adapterInstances).toHaveLength(3) + }) + + it('throws when restartDaemon is called before initDaemonPtyProvider', async () => { + const mod = await importFresh() + await expect(mod.restartDaemon()).rejects.toThrow( + 'restartDaemon called before initDaemonPtyProvider' + ) + }) +}) diff --git a/src/main/daemon/daemon-init.ts b/src/main/daemon/daemon-init.ts index 7a0cad3ef..d1545a81d 100644 --- a/src/main/daemon/daemon-init.ts +++ b/src/main/daemon/daemon-init.ts @@ -1,3 +1,11 @@ +/* eslint-disable max-lines -- Why: this module owns the complete daemon +lifecycle for the Electron main process — init, out-of-process launch, +current+legacy adapter wiring, restart orchestration (the 7-step sequence +from docs/daemon-staleness-ux.md §Phase 1), and teardown on app quit. Splitting +it would scatter the "swap the running provider atomically" invariant across +files with no cleaner ownership seam: restart, replaceDaemonProvider, and the +module-level spawner/adapter singletons must stay co-located so a future +change cannot leave them drifting out of sync. */ import { join } from 'path' import { app } from 'electron' import { mkdirSync, existsSync, unlinkSync, writeFileSync } from 'fs' @@ -8,6 +16,7 @@ import { getDaemonPidPath, getDaemonSocketPath, getDaemonTokenPath, + serializeDaemonPidFile, type DaemonLauncher } from './daemon-spawner' import { DaemonPtyAdapter } from './daemon-pty-adapter' @@ -18,11 +27,20 @@ import { PROTOCOL_VERSION, type ListSessionsResult } from './types' -import { healthCheckDaemon, killStaleDaemon } from './daemon-health' -import { setLocalPtyProvider } from '../ipc/pty' +import { getProcessStartedAtMs, healthCheckDaemon, killStaleDaemon } from './daemon-health' +import { + setLocalPtyProvider, + unbindLocalProviderListeners, + rebindLocalProviderListeners +} from '../ipc/pty' let spawner: DaemonSpawner | null = null let adapter: DaemonPtyRouter | DaemonPtyAdapter | null = null +// Why: coalesce concurrent restartDaemon() calls so two clicks (or a UI +// click racing an internal caller) can't both enter the 7-step sequence — +// the second entry would read the already-disposed current adapter and +// race cleanupDaemonForProtocol against a half-spawned replacement. +let restartInFlight: Promise | null = null function getRuntimeDir(): string { const dir = join(app.getPath('userData'), 'daemon') @@ -130,7 +148,18 @@ 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 }) + // Why: JSON pid file carries pid + process start time so later + // killStaleDaemon() can verify the pid still belongs to the daemon + // we forked before SIGTERMing it. Prevents pid-recycling hazard + // where the OS hands the daemon's old pid to an unrelated process. + 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. @@ -208,6 +237,121 @@ export async function initDaemonPtyProvider(): Promise { setLocalPtyProvider(routedAdapter) } +// Why: the Manage Sessions IPC handlers need read access to the current +// adapter/router to list sessions, kill them, etc. Exposed as a narrow getter +// rather than exporting the module-level variable to keep the "swap on +// restart" invariant in one place (replaceDaemonProvider). +export function getDaemonProvider(): DaemonPtyRouter | DaemonPtyAdapter | null { + return adapter +} + +// Why: the "Restart daemon" flow rebuilds the current-protocol adapter and +// must update both the module-level `adapter` singleton here and the +// `localProvider` reference inside ipc/pty.ts. Without this helper they could +// drift — app-quit would dispose a stale adapter reference. +export function replaceDaemonProvider(newAdapter: DaemonPtyAdapter | DaemonPtyRouter): void { + adapter = newAdapter + setLocalPtyProvider(newAdapter) +} + +export type RestartDaemonResult = { + killedCount: number +} + +// Why: the 7-step sequence from docs/daemon-staleness-ux.md §Phase 1 restart. +// Current-protocol only — legacy adapters are preserved and route to their +// original daemons with no respawn path. See the design doc for rationale on +// each step, notably why synthetic exits must fan out *before* the listener +// unsubscribe. +export async function restartDaemon(): Promise { + if (restartInFlight) { + return restartInFlight + } + restartInFlight = runRestartDaemon().finally(() => { + restartInFlight = null + }) + return restartInFlight +} + +async function runRestartDaemon(): Promise { + const currentSpawner = spawner + const currentAdapter = adapter + if (!currentSpawner || !currentAdapter) { + throw new Error('restartDaemon called before initDaemonPtyProvider') + } + + const runtimeDir = getRuntimeDir() + const currentOnly = + currentAdapter instanceof DaemonPtyRouter ? currentAdapter.getCurrentAdapter() : currentAdapter + const legacyAdapters = + currentAdapter instanceof DaemonPtyRouter ? [...currentAdapter.getLegacyAdapters()] : [] + + // Step 1: synthesize pty:exit for every active session on the current + // adapter BEFORE any teardown. The daemon's kill-all-and-shutdown path + // explicitly does not fan onExit to clients (session.ts:246-252), so + // without this the renderer would never see exits and would black-hole + // writes against the disposed adapter. + const killedCount = currentOnly.getActiveSessionIds().length + currentOnly.fanoutSyntheticExits(-1) + + // Step 2: detach renderer listeners from the current adapter. Must happen + // AFTER step 1 so the synthesized exits actually reach the renderer, and + // BEFORE step 6 so the new provider isn't bound with stale listeners. + unbindLocalProviderListeners() + + // Step 3: kill the current-protocol daemon process (shutdown RPC → fallback + // killStaleDaemon → socket/pid unlink). Legacy adapters untouched. + await cleanupDaemonForProtocol(runtimeDir, PROTOCOL_VERSION) + + // Step 4: reuse the existing spawner so the respawn closure baked into + // long-lived adapters stays valid. Do NOT construct a new DaemonSpawner. + currentSpawner.resetHandle() + const info = await currentSpawner.ensureRunning() + + // Step 5: build a fresh current adapter against the respawned daemon. Its + // respawn callback closes over the same spawner instance (identical to the + // crash-respawn closure in initDaemonPtyProvider). + const newCurrent = new DaemonPtyAdapter({ + socketPath: info.socketPath, + tokenPath: info.tokenPath, + historyPath: getHistoryDir(), + respawn: async () => { + console.warn('[daemon] Daemon process died — respawning') + currentSpawner.resetHandle() + await currentSpawner.ensureRunning() + } + }) + + // Re-wrap in router if there were legacy adapters at startup; otherwise + // point straight at the new adapter. Legacy instances are preserved by + // reference — they still route to the same pre-upgrade daemons. + const newProvider = + legacyAdapters.length > 0 + ? new DaemonPtyRouter({ current: newCurrent, legacy: legacyAdapters }) + : newCurrent + if (newProvider instanceof DaemonPtyRouter) { + await newProvider.discoverLegacySessions() + } + + // Why: drain the outgoing router's subscriptions from the shared legacy + // adapters before installing the new router (which subscribes fresh). Must + // run *after* the new provider exists so no adapter event is unhandled in + // the narrow window, and *before* replaceDaemonProvider so the swap is + // atomic from the renderer's perspective. Plain dispose() would also tear + // down the legacy adapters themselves — use the router-only variant. + if (currentAdapter instanceof DaemonPtyRouter) { + currentAdapter.disposeRouterOnly() + } + + // Step 6: swap module state (adapter + localProvider) atomically. + replaceDaemonProvider(newProvider) + + // Step 7: rebind renderer listeners against the new provider. + rebindLocalProviderListeners() + + return { killedCount } +} + // Why: disconnect from the daemon without killing it. The daemon runs as a // separate process and survives app quit — sessions stay alive for warm // reattach on next launch. Leave history sessions marked "unclean" here so a @@ -239,7 +383,7 @@ export type OrphanedDaemonCleanupResult = { killedCount: number } -async function cleanupDaemonForProtocol( +export async function cleanupDaemonForProtocol( runtimeDir: string, protocolVersion: number ): Promise { diff --git a/src/main/daemon/daemon-pty-adapter.test.ts b/src/main/daemon/daemon-pty-adapter.test.ts index 610937387..9203b6f78 100644 --- a/src/main/daemon/daemon-pty-adapter.test.ts +++ b/src/main/daemon/daemon-pty-adapter.test.ts @@ -728,4 +728,70 @@ describe('DaemonPtyAdapter (IPtyProvider)', () => { respawnAdapter.dispose() }) }) + + // Why: the restart flow (docs/daemon-staleness-ux.md §Phase 1 step 1) relies + // on these two primitives to fan synthetic pty:exit out to every attached + // session *before* tearing the adapter down. The design doc calls out + // session.ts:246-252 as the reason — the daemon's kill-all-and-shutdown + // explicitly does NOT fan exits back through onExit. Without the fanout the + // renderer would black-hole writes against a disposed adapter. + describe('fanoutSyntheticExits / getActiveSessionIds (restart primitives)', () => { + it('reports every live spawn in getActiveSessionIds', async () => { + const { id: id1 } = await adapter.spawn({ cols: 80, rows: 24 }) + const { id: id2 } = await adapter.spawn({ cols: 80, rows: 24 }) + const active = adapter.getActiveSessionIds() + expect(active).toContain(id1) + expect(active).toContain(id2) + expect(active).toHaveLength(2) + }) + + it('emits a synthetic exit for every active id with the supplied code', () => { + const exits: { id: string; code: number }[] = [] + adapter.onExit((payload) => exits.push(payload)) + + const ids = ['sess-a', 'sess-b', 'sess-c'] + const internals = adapter as unknown as { activeSessionIds: Set } + for (const id of ids) { + internals.activeSessionIds.add(id) + } + + adapter.fanoutSyntheticExits(-1) + + expect(exits).toHaveLength(3) + expect(exits.map((e) => e.id).sort()).toEqual([...ids].sort()) + for (const { code } of exits) { + expect(code).toBe(-1) + } + }) + + it('clears activeSessionIds after fanout so a second call is a no-op', () => { + const exits: { id: string; code: number }[] = [] + adapter.onExit((payload) => exits.push(payload)) + + const internals = adapter as unknown as { activeSessionIds: Set } + internals.activeSessionIds.add('sess-a') + + adapter.fanoutSyntheticExits(-1) + expect(exits).toHaveLength(1) + expect(adapter.getActiveSessionIds()).toEqual([]) + + adapter.fanoutSyntheticExits(-1) + expect(exits).toHaveLength(1) + }) + + it('propagates to every registered exit listener in order', () => { + const aExits: { id: string; code: number }[] = [] + const bExits: { id: string; code: number }[] = [] + adapter.onExit((payload) => aExits.push(payload)) + adapter.onExit((payload) => bExits.push(payload)) + + const internals = adapter as unknown as { activeSessionIds: Set } + internals.activeSessionIds.add('sess-a') + + adapter.fanoutSyntheticExits(-1) + + expect(aExits).toEqual([{ id: 'sess-a', code: -1 }]) + expect(bExits).toEqual([{ id: 'sess-a', code: -1 }]) + }) + }) }) diff --git a/src/main/daemon/daemon-pty-adapter.ts b/src/main/daemon/daemon-pty-adapter.ts index fa6faab49..349ca4d51 100644 --- a/src/main/daemon/daemon-pty-adapter.ts +++ b/src/main/daemon/daemon-pty-adapter.ts @@ -13,7 +13,8 @@ import { type CreateOrAttachResult, type DaemonEvent, type GetSnapshotResult, - type ListSessionsResult + type ListSessionsResult, + type SessionInfo } from './types' import type { IPtyProvider, PtySpawnOptions, PtySpawnResult } from '../providers/types' @@ -39,6 +40,7 @@ export class TerminalKilledError extends Error { } export class DaemonPtyAdapter implements IPtyProvider { + readonly protocolVersion: number private client: DaemonClient private historyManager: HistoryManager | null private historyReader: HistoryReader | null @@ -71,6 +73,7 @@ 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, @@ -79,7 +82,7 @@ export class DaemonPtyAdapter implements IPtyProvider { 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 { @@ -362,6 +365,42 @@ export class DaemonPtyAdapter implements IPtyProvider { })) } + // Why: the Manage Sessions panel needs the full SessionInfo (pid, state, + // createdAt) per session for display; listProcesses drops that detail for + // the IPtyProvider contract. Keep both in parallel rather than widening + // the provider surface. + async listSessions(): Promise { + await this.ensureConnected() + const result = await this.client.request('listSessions', undefined) + return result.sessions.filter((s) => s.isAlive) + } + + getActiveSessionIds(): string[] { + return [...this.activeSessionIds] + } + + // Why: used by the "Restart daemon" handler to synthesize pty:exit for every + // live session *before* tearing down the adapter. The daemon's own + // kill-all-and-shutdown path explicitly suppresses onExit fanout + // (session.ts:246-252), so without this the renderer panes would black-hole + // writes to a disposed adapter forever. Reuses the existing exitListeners + // path so downstream cleanup (clearProviderPtyState, markClaudePtyExited, + // renderer pty:exit) runs exactly as it does on natural exit. + fanoutSyntheticExits(code: number): void { + const ids = [...this.activeSessionIds] + this.activeSessionIds.clear() + for (const id of ids) { + // Why: listener throws are intentionally *not* caught — matches the + // natural onExit fanout in setupEventRouting, so synthetic exits don't + // diverge in error semantics from real ones. A throwing listener is a + // bug that should surface loudly, not be silently swallowed. + // oxlint-disable-next-line unicorn/no-useless-spread -- copy-safe: listeners may unsubscribe during iteration + for (const listener of [...this.exitListeners]) { + listener({ id, code }) + } + } + } + async getDefaultShell(): Promise { if (process.platform === 'win32') { return process.env.COMSPEC || 'powershell.exe' diff --git a/src/main/daemon/daemon-pty-router.test.ts b/src/main/daemon/daemon-pty-router.test.ts index 1594da80d..fee4c11b5 100644 --- a/src/main/daemon/daemon-pty-router.test.ts +++ b/src/main/daemon/daemon-pty-router.test.ts @@ -153,4 +153,105 @@ describe('DaemonPtyRouter', () => { expect(current.dispose).toHaveBeenCalled() expect(legacy.dispose).toHaveBeenCalled() }) + + // Why: docs/daemon-staleness-ux.md §Phase 1 step 5 requires the restart flow + // to preserve the legacy adapter instances across the current-adapter swap, + // and it reads them back via these accessors. Locking the return shape + // prevents a future refactor from quietly switching to a defensive copy + // (breaks instance identity) or a different list (breaks restart). + describe('restart accessors', () => { + it('returns the exact current adapter instance', () => { + const current = createAdapter('current') + const router = new DaemonPtyRouter({ current, legacy: [] }) + + expect(router.getCurrentAdapter()).toBe(current) + }) + + it('returns the exact legacy adapter instances', () => { + const current = createAdapter('current') + const legacy1 = createAdapter('legacy-1') + const legacy2 = createAdapter('legacy-2') + const router = new DaemonPtyRouter({ current, legacy: [legacy1, legacy2] }) + + const legacies = router.getLegacyAdapters() + expect(legacies.length).toBe(2) + expect(legacies[0]).toBe(legacy1) + expect(legacies[1]).toBe(legacy2) + }) + + it('getAllAdapters returns current first then legacy, by identity', () => { + const current = createAdapter('current') + const legacy1 = createAdapter('legacy-1') + const legacy2 = createAdapter('legacy-2') + const router = new DaemonPtyRouter({ current, legacy: [legacy1, legacy2] }) + + const all = router.getAllAdapters() + expect(all.length).toBe(3) + expect(all[0]).toBe(current) + expect(all[1]).toBe(legacy1) + expect(all[2]).toBe(legacy2) + }) + }) + + // Why: the restart flow (daemon-init.runRestartDaemon step 5→6) relies on + // disposeRouterOnly draining the outgoing router's subscriptions WITHOUT + // tearing down the legacy adapters themselves. plain dispose() would + // cascade into the adapters and strand any legacy-backed sessions — see + // daemon-pty-router.ts §disposeRouterOnly comment. These tests lock the + // contract: no adapter teardown, subscriptions actually detached for both + // onData and onExit on both current and legacy, idempotent. + describe('disposeRouterOnly', () => { + it('does not call dispose or disconnectOnly on any adapter', () => { + const current = createAdapter('current') + const legacy = createAdapter('legacy') + const router = new DaemonPtyRouter({ current, legacy: [legacy] }) + + router.disposeRouterOnly() + + expect(current.dispose).not.toHaveBeenCalled() + expect(legacy.dispose).not.toHaveBeenCalled() + expect(current.disconnectOnly).not.toHaveBeenCalled() + expect(legacy.disconnectOnly).not.toHaveBeenCalled() + }) + + it('stops forwarding adapter onData/onExit to subscribers registered before dispose', () => { + const current = createAdapter('current') + const legacy = createAdapter('legacy') + const router = new DaemonPtyRouter({ current, legacy: [legacy] }) + + // Realistic restart scenario: the local IPC layer subscribes at app + // start, THEN the restart flow later calls disposeRouterOnly. A spy + // registered *after* dispose proves the router→subscriber path is + // empty, but doesn't prove the router unsubscribed from the adapters. + const dataSpy = vi.fn() + const exitSpy = vi.fn() + router.onData(dataSpy) + router.onExit(exitSpy) + + router.disposeRouterOnly() + + // Both current- and legacy-adapter emissions must be silenced. A + // regression that only unsubscribed from one would pass a single- + // adapter test but fail this one. + current.emitData('current-id', 'hello') + current.emitExit('current-id', 0) + legacy.emitData('legacy-id', 'world') + legacy.emitExit('legacy-id', 1) + + expect(dataSpy).not.toHaveBeenCalled() + expect(exitSpy).not.toHaveBeenCalled() + }) + + it('is idempotent — a second disposeRouterOnly call is a no-op and does not throw', () => { + const current = createAdapter('current') + const legacy = createAdapter('legacy') + const router = new DaemonPtyRouter({ current, legacy: [legacy] }) + + router.disposeRouterOnly() + expect(() => router.disposeRouterOnly()).not.toThrow() + // And still no adapter teardown on the second call. + expect(current.dispose).not.toHaveBeenCalled() + expect(legacy.dispose).not.toHaveBeenCalled() + }) + }) }) diff --git a/src/main/daemon/daemon-pty-router.ts b/src/main/daemon/daemon-pty-router.ts index e69b21aa6..d6ba74ef7 100644 --- a/src/main/daemon/daemon-pty-router.ts +++ b/src/main/daemon/daemon-pty-router.ts @@ -180,6 +180,19 @@ export class DaemonPtyRouter implements IPtyProvider { } } + // Why: restart swaps to a fresh router carrying the *same* legacy adapter + // instances. If we called dispose() on the outgoing router it would tear + // down those legacy adapters along with it. disposeRouterOnly() detaches + // only this router's subscriptions from the adapters — the adapters and + // their daemon connections keep running, and the new router re-subscribes. + // Without this, each restart leaked a router instance pinned by the legacy + // adapters' listener arrays (one pair per adapter per restart). + disposeRouterOnly(): void { + for (const unsubscribe of this.unsubscribers.splice(0)) { + unsubscribe() + } + } + async disconnectOnly(): Promise { for (const unsubscribe of this.unsubscribers.splice(0)) { unsubscribe() @@ -187,6 +200,24 @@ export class DaemonPtyRouter implements IPtyProvider { await Promise.all([...this.allAdapters()].map((adapter) => adapter.disconnectOnly())) } + // Why: the Manage Sessions panel iterates all adapters to list sessions + // across every protocol version, and the restart handler needs to preserve + // surviving legacy adapters across the current-adapter swap. On this branch + // (pre-#1323) the legacy list is set once at construction and never mutated, + // so returning the internal array by reference is safe for the intended + // read-only use. + getCurrentAdapter(): DaemonPtyAdapter { + return this.current + } + + getLegacyAdapters(): readonly DaemonPtyAdapter[] { + return this.legacy + } + + getAllAdapters(): readonly DaemonPtyAdapter[] { + return this.allAdapters() + } + private adapterFor(sessionId: string): DaemonPtyAdapter { return this.sessionAdapters.get(sessionId) ?? this.current } 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.ts b/src/main/daemon/types.ts index b2908da34..a7fba8f42 100644 --- a/src/main/daemon/types.ts +++ b/src/main/daemon/types.ts @@ -229,6 +229,14 @@ export type SessionInfo = { createdAt: number } +// Why: SessionInfo + source protocol version, so the Manage Sessions UI can +// label legacy-backed sessions. Populated by the router/adapter at RPC time; +// never transmitted over the daemon wire (daemon only speaks its own +// protocol version and doesn't know about other versions). +export type DaemonSessionInfo = SessionInfo & { + protocolVersion: number +} + // ─── Events (Daemon → Client, on stream socket) ──────────────────── export type DataEvent = { diff --git a/src/main/ipc/pty-management.test.ts b/src/main/ipc/pty-management.test.ts new file mode 100644 index 000000000..9e4c6c93f --- /dev/null +++ b/src/main/ipc/pty-management.test.ts @@ -0,0 +1,414 @@ +/* eslint-disable max-lines -- Why: covers every pty:management IPC channel +against shared mocks (electron, fs, daemon-init, DaemonPtyRouter). Splitting +across files would duplicate the vi.hoisted setup and the shared helpers, +with no meaningful ownership seam. */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { DaemonSessionInfo } from '../daemon/types' + +const { handleMock, removeHandlerMock, getDaemonProviderMock, restartDaemonMock } = vi.hoisted( + () => ({ + handleMock: vi.fn(), + removeHandlerMock: vi.fn(), + getDaemonProviderMock: vi.fn(), + restartDaemonMock: vi.fn() + }) +) + +vi.mock('electron', () => ({ + ipcMain: { handle: handleMock, removeHandler: removeHandlerMock } +})) + +vi.mock('../daemon/daemon-init', () => ({ + getDaemonProvider: getDaemonProviderMock, + restartDaemon: restartDaemonMock +})) + +// Why: the handler uses `provider instanceof DaemonPtyRouter` to branch +// between "plain adapter" and "router with current + legacy adapters". +// Mock the class here so tests can construct real instances via `new +// DaemonPtyRouter(...)` and the instanceof check returns true. The real +// router's constructor is side-effect heavy (subscribes to adapter events), +// so we only keep the accessors that pty-management touches — enough to +// satisfy the runtime type check without pulling in all the wiring. +vi.mock('../daemon/daemon-pty-router', () => { + class DaemonPtyRouter { + private allAdapters: unknown[] + constructor(opts: { current: unknown; legacy: unknown[] }) { + this.allAdapters = [opts.current, ...opts.legacy] + } + getAllAdapters() { + return this.allAdapters + } + } + return { DaemonPtyRouter } +}) + +type HandlerMap = Record unknown> + +function buildHandlerMap(): HandlerMap { + const map: HandlerMap = {} + for (const call of handleMock.mock.calls) { + const [channel, handler] = call as [string, (event: unknown, args?: unknown) => unknown] + map[channel] = handler + } + return map +} + +function makeSession( + sessionId: string, + overrides: Partial = {} +): DaemonSessionInfo { + return { + sessionId, + state: 'running', + shellState: 'ready', + isAlive: true, + pid: 1234, + cwd: '/home/user', + cols: 80, + rows: 24, + createdAt: 0, + protocolVersion: 4, + ...overrides + } +} + +type MockAdapter = { + protocolVersion: number + listSessions: ReturnType + shutdown: ReturnType +} + +function makeAdapter( + protocolVersion: number, + sessions: DaemonSessionInfo[], + shutdownImpl?: (id: string, immediate: boolean) => Promise +): MockAdapter { + // Why: collectSessions calls adapter.listSessions() (the daemon-side RPC) + // and then annotates with adapter.protocolVersion. The mock returns the + // *internal* SessionInfo shape (no protocolVersion) since the adapter adds + // it. Stripping it here mirrors production behavior. + return { + protocolVersion, + listSessions: vi.fn(async () => sessions.map(({ protocolVersion: _pv, ...rest }) => rest)), + shutdown: vi.fn(shutdownImpl ?? (async () => {})) + } +} + +async function importFresh() { + vi.resetModules() + handleMock.mockClear() + removeHandlerMock.mockClear() + return import('./pty-management') +} + +async function makeRouter(current: MockAdapter, legacy: MockAdapter[] = []) { + const { DaemonPtyRouter } = await import('../daemon/daemon-pty-router') + return new DaemonPtyRouter({ current: current as never, legacy: legacy as never }) +} + +describe('pty:management IPC handlers', () => { + beforeEach(() => { + getDaemonProviderMock.mockReset() + restartDaemonMock.mockReset() + }) + + afterEach(() => { + vi.clearAllMocks() + }) + + describe('listSessions', () => { + it('merges sessions across current + legacy adapters with protocolVersion', async () => { + const current = makeAdapter(4, [makeSession('new-1'), makeSession('new-2')]) + const legacy = makeAdapter(3, [makeSession('old-1', { protocolVersion: 3 })]) + const { registerDaemonManagementHandlers } = await importFresh() + getDaemonProviderMock.mockReturnValue(await makeRouter(current, [legacy])) + registerDaemonManagementHandlers() + + const handlers = buildHandlerMap() + const result = (await handlers['pty:management:listSessions']({})) as { + sessions: DaemonSessionInfo[] + } + + expect(result.sessions).toHaveLength(3) + const byId = new Map(result.sessions.map((s) => [s.sessionId, s])) + expect(byId.get('new-1')?.protocolVersion).toBe(4) + expect(byId.get('new-2')?.protocolVersion).toBe(4) + expect(byId.get('old-1')?.protocolVersion).toBe(3) + }) + + it('returns empty list when no daemon provider is installed', async () => { + getDaemonProviderMock.mockReturnValue(null) + + const { registerDaemonManagementHandlers } = await importFresh() + registerDaemonManagementHandlers() + + const handlers = buildHandlerMap() + const result = (await handlers['pty:management:listSessions']({})) as { + sessions: DaemonSessionInfo[] + } + + expect(result.sessions).toEqual([]) + }) + + it('tolerates a failing adapter by skipping its sessions', async () => { + const current = makeAdapter(4, [makeSession('new-1')]) + const legacy = makeAdapter(3, []) + legacy.listSessions = vi.fn(async () => { + throw new Error('legacy socket dead') + }) + const { registerDaemonManagementHandlers } = await importFresh() + getDaemonProviderMock.mockReturnValue(await makeRouter(current, [legacy])) + registerDaemonManagementHandlers() + + const handlers = buildHandlerMap() + const result = (await handlers['pty:management:listSessions']({})) as { + sessions: DaemonSessionInfo[] + } + + expect(result.sessions).toHaveLength(1) + expect(result.sessions[0].sessionId).toBe('new-1') + }) + }) + + describe('killAll', () => { + // Why: the handler sleeps POLL_INTERVAL_MS between listSessions polls. + // Fake timers let the tests drive that loop deterministically — without + // them, a happy-path test that converges in ≥1 poll would take 100ms+ + // of real wall time and the "refuses to die" test would take ~1s. + beforeEach(() => { + vi.useFakeTimers() + }) + afterEach(() => { + vi.useRealTimers() + }) + + async function runKillAllWithPolls( + handler: (event: unknown, args?: unknown) => unknown, + pollCount: number = 65 + ): Promise<{ killedCount: number; remainingCount: number }> { + const resultPromise = handler({}) as Promise<{ + killedCount: number + remainingCount: number + }> + // Why: advance the loop's sleeps one at a time. Between each sleep the + // handler awaits collectSessions (a microtask), so we need to flush + // pending microtasks before advancing the next timer. + for (let i = 0; i < pollCount; i += 1) { + await Promise.resolve() + await Promise.resolve() + await vi.advanceTimersByTimeAsync(100) + } + return resultPromise + } + + it('fires one shutdown per initial session and polls until empty', async () => { + const currentSessions = [makeSession('new-1'), makeSession('new-2')] + const legacySessions = [makeSession('old-1', { protocolVersion: 3 })] + const current = makeAdapter(4, []) + const legacy = makeAdapter(3, []) + // Why: shutdown removes the session from the adapter's backing list so + // the next poll observes the shrinking set — mirrors a daemon that + // actually reaped the processes. + const removeFrom = (list: DaemonSessionInfo[], id: string): void => { + const idx = list.findIndex((s) => s.sessionId === id) + if (idx !== -1) { + list.splice(idx, 1) + } + } + current.listSessions = vi.fn(async () => + currentSessions.map(({ protocolVersion: _pv, ...rest }) => rest) + ) + legacy.listSessions = vi.fn(async () => + legacySessions.map(({ protocolVersion: _pv, ...rest }) => rest) + ) + current.shutdown = vi.fn(async (id: string) => { + removeFrom(currentSessions, id) + }) + legacy.shutdown = vi.fn(async (id: string) => { + removeFrom(legacySessions, id) + }) + const { registerDaemonManagementHandlers } = await importFresh() + getDaemonProviderMock.mockReturnValue(await makeRouter(current, [legacy])) + registerDaemonManagementHandlers() + + const handlers = buildHandlerMap() + const result = await runKillAllWithPolls(handlers['pty:management:killAll']) + + expect(result).toEqual({ killedCount: 3, remainingCount: 0 }) + // Each initial session receives exactly one shutdown — no retries. + expect(current.shutdown).toHaveBeenCalledTimes(2) + expect(current.shutdown).toHaveBeenCalledWith('new-1', true) + expect(current.shutdown).toHaveBeenCalledWith('new-2', true) + expect(legacy.shutdown).toHaveBeenCalledTimes(1) + expect(legacy.shutdown).toHaveBeenCalledWith('old-1', true) + }) + + it('reports remainingCount when sessions refuse to die after the poll window', async () => { + const sessions = [makeSession('stuck')] + const current = makeAdapter(4, []) + current.listSessions = vi.fn(async () => + sessions.map(({ protocolVersion: _pv, ...rest }) => rest) + ) + // Why: shutdown resolves but the session never leaves listSessions — + // simulates a process wedged in uninterruptible sleep. After the poll + // window (≈6.5s, past the daemon's 5s SIGTERM→SIGKILL ladder) the + // handler must return remainingCount=1 rather than loop forever. + current.shutdown = vi.fn(async () => {}) + const { registerDaemonManagementHandlers } = await importFresh() + getDaemonProviderMock.mockReturnValue(await makeRouter(current)) + registerDaemonManagementHandlers() + + const handlers = buildHandlerMap() + const result = await runKillAllWithPolls(handlers['pty:management:killAll']) + + expect(result).toEqual({ killedCount: 0, remainingCount: 1 }) + // One shutdown fired — no per-session retry. Initial-snapshot + // accounting means the stuck session is counted once. + expect(current.shutdown).toHaveBeenCalledTimes(1) + }) + + it('does not count respawned sessions with fresh IDs against remainingCount', async () => { + // Why: mounted panes may re-call pty:spawn with brand-new session IDs + // while killAll is polling (tab remount, navigate-back). Those fresh + // IDs are not part of the initial snapshot and must not inflate the + // "refused to exit" count — the user asked to kill what was alive + // when the button was pressed, not to chase new spawns. + const liveSessions = [makeSession('a'), makeSession('b')] + const current = makeAdapter(4, []) + let pollCalls = 0 + current.listSessions = vi.fn(async () => { + pollCalls += 1 + if (pollCalls === 1) { + // Initial snapshot: a and b are alive. + return liveSessions.map(({ protocolVersion: _pv, ...rest }) => rest) + } + // First poll onward: a and b have been reaped, but the renderer + // respawned a fresh pane with id 'c'. 'c' was never in the initial + // snapshot, so it must not count as remaining. + return [makeSession('c')].map(({ protocolVersion: _pv, ...rest }) => rest) + }) + current.shutdown = vi.fn(async () => {}) + const { registerDaemonManagementHandlers } = await importFresh() + getDaemonProviderMock.mockReturnValue(await makeRouter(current)) + registerDaemonManagementHandlers() + + const handlers = buildHandlerMap() + const result = await runKillAllWithPolls(handlers['pty:management:killAll']) + + expect(result).toEqual({ killedCount: 2, remainingCount: 0 }) + }) + + it('swallows per-session shutdown rejections without stopping the batch', async () => { + const sessionsList = [makeSession('a'), makeSession('b')] + const current = makeAdapter(4, []) + current.listSessions = vi.fn(async () => + sessionsList.map(({ protocolVersion: _pv, ...rest }) => rest) + ) + // Why: a rejecting shutdown for 'a' must not block the shutdown of 'b'. + // Since shutdowns fire in parallel (Promise.allSettled), both must be + // invoked regardless of 'a' throwing. + const removeFrom = (id: string): void => { + const idx = sessionsList.findIndex((s) => s.sessionId === id) + if (idx !== -1) { + sessionsList.splice(idx, 1) + } + } + current.shutdown = vi.fn(async (id: string) => { + if (id === 'a') { + throw new Error('a is stuck') + } + removeFrom(id) + }) + const { registerDaemonManagementHandlers } = await importFresh() + getDaemonProviderMock.mockReturnValue(await makeRouter(current)) + registerDaemonManagementHandlers() + + const handlers = buildHandlerMap() + const result = await runKillAllWithPolls(handlers['pty:management:killAll']) + + expect(current.shutdown).toHaveBeenCalledWith('a', true) + expect(current.shutdown).toHaveBeenCalledWith('b', true) + // 'a' rejected and is still alive → counts as remaining; 'b' reaped. + expect(result).toEqual({ killedCount: 1, remainingCount: 1 }) + }) + }) + + describe('killOne', () => { + it('routes to the adapter whose protocolVersion owns the session', async () => { + const current = makeAdapter(4, [makeSession('new-1')]) + const legacy = makeAdapter(3, [makeSession('old-1', { protocolVersion: 3 })]) + const { registerDaemonManagementHandlers } = await importFresh() + getDaemonProviderMock.mockReturnValue(await makeRouter(current, [legacy])) + registerDaemonManagementHandlers() + + const handlers = buildHandlerMap() + const result = (await handlers['pty:management:killOne']({}, { sessionId: 'old-1' })) as { + success: boolean + } + + expect(result.success).toBe(true) + expect(legacy.shutdown).toHaveBeenCalledWith('old-1', true) + expect(current.shutdown).not.toHaveBeenCalled() + }) + + it('returns success=false for unknown sessionId', async () => { + const current = makeAdapter(4, [makeSession('new-1')]) + const { registerDaemonManagementHandlers } = await importFresh() + getDaemonProviderMock.mockReturnValue(await makeRouter(current)) + registerDaemonManagementHandlers() + + const handlers = buildHandlerMap() + const result = (await handlers['pty:management:killOne']({}, { sessionId: 'ghost' })) as { + success: boolean + } + + expect(result.success).toBe(false) + expect(current.shutdown).not.toHaveBeenCalled() + }) + + it('rejects empty/missing sessionId without hitting the adapter', async () => { + const current = makeAdapter(4, [makeSession('new-1')]) + const { registerDaemonManagementHandlers } = await importFresh() + getDaemonProviderMock.mockReturnValue(await makeRouter(current)) + registerDaemonManagementHandlers() + + const handlers = buildHandlerMap() + const result = (await handlers['pty:management:killOne']({}, { sessionId: '' })) as { + success: boolean + } + + expect(result.success).toBe(false) + expect(current.listSessions).not.toHaveBeenCalled() + }) + }) + + describe('restart', () => { + it('delegates to restartDaemon and reports success', async () => { + restartDaemonMock.mockResolvedValue({ killedCount: 2 }) + + const { registerDaemonManagementHandlers } = await importFresh() + registerDaemonManagementHandlers() + + const handlers = buildHandlerMap() + const result = (await handlers['pty:management:restart']({})) as { success: boolean } + + expect(result.success).toBe(true) + expect(restartDaemonMock).toHaveBeenCalledTimes(1) + }) + + it('returns success=false when restartDaemon throws', async () => { + restartDaemonMock.mockRejectedValue(new Error('spawn failed')) + + const { registerDaemonManagementHandlers } = await importFresh() + registerDaemonManagementHandlers() + + const handlers = buildHandlerMap() + const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + const result = (await handlers['pty:management:restart']({})) as { success: boolean } + consoleErrorSpy.mockRestore() + + expect(result.success).toBe(false) + }) + }) +}) diff --git a/src/main/ipc/pty-management.ts b/src/main/ipc/pty-management.ts new file mode 100644 index 000000000..05d8f4ab1 --- /dev/null +++ b/src/main/ipc/pty-management.ts @@ -0,0 +1,171 @@ +import { ipcMain } from 'electron' +import { DaemonPtyRouter } from '../daemon/daemon-pty-router' +import type { DaemonPtyAdapter } from '../daemon/daemon-pty-adapter' +import { getDaemonProvider, restartDaemon } from '../daemon/daemon-init' +import type { DaemonSessionInfo } from '../daemon/types' + +// Why: the daemon's session.kill() sends SIGTERM first and escalates to +// SIGKILL after a 5s grace window (KILL_TIMEOUT_MS in session.ts). We have +// to poll past that ladder, or well-behaved-but-slow shells (zsh hosting a +// long-running agent) look like they "refused to exit" when they're actually +// still inside their SIGTERM handler waiting for SIGKILL. 65 polls at 100ms +// each (≈6.5s) covers the 5s ladder plus ~1.5s of slack for the final +// SIGKILL reap and the adapter's listSessions IPC roundtrip. The user waits +// during this window with a spinner; the alternative — reporting fake +// "refused" numbers — is worse. +const MAX_POLL_ATTEMPTS = 65 +const POLL_INTERVAL_MS = 100 + +function sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)) +} + +function getDaemonAdapters(): DaemonPtyAdapter[] { + const provider = getDaemonProvider() + if (!provider) { + return [] + } + if (provider instanceof DaemonPtyRouter) { + return [...provider.getAllAdapters()] + } + return [provider] +} + +async function collectSessions(adapters: DaemonPtyAdapter[]): Promise { + const results = await Promise.allSettled( + adapters.map(async (adapter) => { + const sessions = await adapter.listSessions() + return sessions.map((s) => ({ + ...s, + protocolVersion: adapter.protocolVersion + })) + }) + ) + return results.flatMap((r) => (r.status === 'fulfilled' ? r.value : [])) +} + +export function registerDaemonManagementHandlers(): void { + ipcMain.removeHandler('pty:management:listSessions') + ipcMain.removeHandler('pty:management:killAll') + ipcMain.removeHandler('pty:management:killOne') + ipcMain.removeHandler('pty:management:restart') + + ipcMain.handle( + 'pty:management:listSessions', + async (): Promise<{ sessions: DaemonSessionInfo[] }> => { + const sessions = await collectSessions(getDaemonAdapters()) + return { sessions } + } + ) + + // Why: killAll operates on *sessions* (user-facing concept), not daemons, so + // it fans across every adapter — current + legacy — to match the user's + // "kill everything I might be attached to" mental model. The daemon + // processes themselves survive; only sessions are torn down. See + // docs/daemon-staleness-ux.md §Phase 1 "Scope rationale" for why legacy + // daemons aren't killed here. + ipcMain.handle( + 'pty:management:killAll', + async (): Promise<{ killedCount: number; remainingCount: number }> => { + const adapters = getDaemonAdapters() + // Why: snapshot the initial session set once, up front. All subsequent + // accounting is relative to these IDs. If the renderer respawns panes + // with *fresh* session IDs while we're polling (e.g. a remount fires + // pty:spawn mid-kill), those new sessions must not count as + // "remaining" — the user asked to kill what was alive at the moment + // they clicked the button, not to chase new spawns. + const initial = await collectSessions(adapters) + const initialIds = new Set(initial.map((s) => s.sessionId)) + const initialCount = initial.length + + if (initialCount === 0) { + return { killedCount: 0, remainingCount: 0 } + } + + // Why: fire one shutdown per initial session, in parallel, once — no + // per-session retry. The daemon's session.kill() is idempotent and + // schedules its own SIGTERM→SIGKILL ladder; firing the RPC repeatedly + // in a tight retry loop before the grace window expires just races our + // own polling. Promise.allSettled ensures a single adapter failure (or + // rejected RPC — e.g. session already exiting) does not short-circuit + // the remaining shutdowns. + await Promise.allSettled( + initial.map(async (session) => { + // Why: protocolVersion is unique across adapters by construction — + // PROTOCOL_VERSION is always distinct from every entry in + // PREVIOUS_DAEMON_PROTOCOL_VERSIONS (see types.ts). If a future + // bump forgets to rotate the retired version into the previous + // list, this find() would silently route legacy sessions to the + // current adapter. Keep the two constants in lockstep. + const owner = adapters.find((a) => a.protocolVersion === session.protocolVersion) + if (!owner) { + return + } + // Why: immediate=true is the adapter's "kill it now" signal. The + // current adapter ignores the flag (the daemon's SIGTERM→SIGKILL + // ladder handles escalation) but preserve it for legacy adapters + // and so a future adapter could honor it. Rejections are swallowed + // per-session — remainingCount surfaces truly-stuck sessions in + // the toast. + await owner.shutdown(session.sessionId, true).catch(() => {}) + }) + ) + + // Why: poll listSessions every POLL_INTERVAL_MS until none of the + // *initial* IDs are still alive, or we've exhausted MAX_POLL_ATTEMPTS. + // Counting only the initial-snapshot intersection (not the total + // session count) is what keeps the math honest when the renderer + // respawns panes with fresh IDs mid-kill. + let remainingOriginalCount = initialCount + for (let attempt = 0; attempt < MAX_POLL_ATTEMPTS; attempt += 1) { + await sleep(POLL_INTERVAL_MS) + const current = await collectSessions(adapters) + remainingOriginalCount = current.reduce( + (count, s) => (initialIds.has(s.sessionId) ? count + 1 : count), + 0 + ) + if (remainingOriginalCount === 0) { + break + } + } + + const killedCount = initialCount - remainingOriginalCount + return { killedCount, remainingCount: remainingOriginalCount } + } + ) + + ipcMain.handle( + 'pty:management:killOne', + async (_event, args: { sessionId: string }): Promise<{ success: boolean }> => { + if (typeof args?.sessionId !== 'string' || args.sessionId.length === 0) { + return { success: false } + } + const adapters = getDaemonAdapters() + const sessions = await collectSessions(adapters) + const match = sessions.find((s) => s.sessionId === args.sessionId) + if (!match) { + return { success: false } + } + const owner = adapters.find((a) => a.protocolVersion === match.protocolVersion) + if (!owner) { + return { success: false } + } + try { + await owner.shutdown(args.sessionId, true) + return { success: true } + } catch { + return { success: false } + } + } + ) + + ipcMain.handle('pty:management:restart', async (): Promise<{ success: boolean }> => { + try { + await restartDaemon() + return { success: true } + } catch (err) { + console.error('[pty:management] restart failed', err) + return { success: false } + } + }) +} diff --git a/src/main/ipc/pty.ts b/src/main/ipc/pty.ts index 2f0ec9a5a..90b673f98 100644 --- a/src/main/ipc/pty.ts +++ b/src/main/ipc/pty.ts @@ -319,6 +319,30 @@ let localDataUnsub: (() => void) | null = null let localExitUnsub: (() => void) | null = null let didFinishLoadHandler: (() => void) | null = null +// Why: the "Restart daemon" path needs to re-bind provider→renderer listeners +// against the freshly-created adapter after replaceDaemonProvider swaps the +// module-level `localProvider` pointer. Without this, old subscribers stay +// bound to the disposed adapter and new PTY data silently drops. Saved at +// module scope so the restart flow (src/main/daemon/daemon-init.ts) can +// trigger a rebind without re-running the full registerPtyHandlers setup. +let rebindProviderListeners: (() => void) | null = null + +export function rebindLocalProviderListeners(): void { + rebindProviderListeners?.() +} + +// Why: the "Restart daemon" flow needs to detach listeners from the current +// adapter *after* synthetic pty:exit events fan out (so the renderer receives +// them) but *before* replaceDaemonProvider swaps in the new adapter (so the +// new provider isn't missing bindings). This export narrows that window to +// the caller. +export function unbindLocalProviderListeners(): void { + localDataUnsub?.() + localExitUnsub?.() + localDataUnsub = null + localExitUnsub = null +} + // ─── IPC Registration ─────────────────────────────────────────────── export function registerPtyHandlers( @@ -379,10 +403,6 @@ export function registerPtyHandlers( }) } - // Wire up provider events → renderer IPC - localDataUnsub?.() - localExitUnsub?.() - // Why: batching PTY data into short flush windows (8ms ≈ half a frame) // reduces IPC round-trips from hundreds/sec to ~120/sec under high // throughput, with no perceptible latency increase for interactive use. @@ -402,52 +422,64 @@ export function registerPtyHandlers( pendingData.clear() } - // Why: LocalPtyProvider routes data to the runtime via configure().onData, - // but daemon-backed providers don't have configure(). Without this, daemon - // PTY data never reaches the runtime's tail buffer, so terminal.read returns - // empty and agent-detection from raw data never fires. - const isLocalProvider = localProvider instanceof LocalPtyProvider + // Why: extracted so the "Restart daemon" flow can rebind against the fresh + // adapter after replaceDaemonProvider runs. Both the startup registration + // and the post-restart rebind go through the same code path — no risk of + // drift between the two entry points. + const bindProviderListeners = (): void => { + localDataUnsub?.() + localExitUnsub?.() - localDataUnsub = localProvider.onData((payload) => { - if (mainWindow.isDestroyed()) { - // Why: clear the pending flush timer so it doesn't fire after the window - // is gone. Without this, macOS app re-activation leaks orphaned timers - // from the previous window's registration. - if (flushTimer) { - clearTimeout(flushTimer) - flushTimer = null + // Why: LocalPtyProvider routes data to the runtime via configure().onData, + // but daemon-backed providers don't have configure(). Without this, daemon + // PTY data never reaches the runtime's tail buffer, so terminal.read returns + // empty and agent-detection from raw data never fires. + const isLocalProvider = localProvider instanceof LocalPtyProvider + + localDataUnsub = localProvider.onData((payload) => { + if (mainWindow.isDestroyed()) { + // Why: clear the pending flush timer so it doesn't fire after the window + // is gone. Without this, macOS app re-activation leaks orphaned timers + // from the previous window's registration. + if (flushTimer) { + clearTimeout(flushTimer) + flushTimer = null + } + pendingData.clear() + return } - pendingData.clear() - return - } - if (!isLocalProvider) { - runtime?.onPtyData(payload.id, payload.data, Date.now()) - } - const existing = pendingData.get(payload.id) - pendingData.set(payload.id, existing ? existing + payload.data : payload.data) - if (!flushTimer) { - flushTimer = setTimeout(flushPendingData, PTY_BATCH_INTERVAL_MS) - } - }) - localExitUnsub = localProvider.onExit((payload) => { - if (!isLocalProvider) { - clearProviderPtyState(payload.id) - ptyOwnership.delete(payload.id) - markClaudePtyExited(payload.id) - runtime?.onPtyExit(payload.id, payload.code) - } - if (!mainWindow.isDestroyed()) { - // Why: flush any batched data for this PTY before sending the exit event, - // otherwise the last ≤8ms of output is silently lost because the renderer - // tears down the terminal on pty:exit before the batch timer fires. - const remaining = pendingData.get(payload.id) - if (remaining) { - mainWindow.webContents.send('pty:data', { id: payload.id, data: remaining }) - pendingData.delete(payload.id) + if (!isLocalProvider) { + runtime?.onPtyData(payload.id, payload.data, Date.now()) } - mainWindow.webContents.send('pty:exit', payload) - } - }) + const existing = pendingData.get(payload.id) + pendingData.set(payload.id, existing ? existing + payload.data : payload.data) + if (!flushTimer) { + flushTimer = setTimeout(flushPendingData, PTY_BATCH_INTERVAL_MS) + } + }) + localExitUnsub = localProvider.onExit((payload) => { + if (!isLocalProvider) { + clearProviderPtyState(payload.id) + ptyOwnership.delete(payload.id) + markClaudePtyExited(payload.id) + runtime?.onPtyExit(payload.id, payload.code) + } + if (!mainWindow.isDestroyed()) { + // Why: flush any batched data for this PTY before sending the exit event, + // otherwise the last ≤8ms of output is silently lost because the renderer + // tears down the terminal on pty:exit before the batch timer fires. + const remaining = pendingData.get(payload.id) + if (remaining) { + mainWindow.webContents.send('pty:data', { id: payload.id, data: remaining }) + pendingData.delete(payload.id) + } + mainWindow.webContents.send('pty:exit', payload) + } + }) + } + + bindProviderListeners() + rebindProviderListeners = bindProviderListeners // Kill orphaned PTY processes from previous page loads when the renderer reloads. // Why: only applies to LocalPtyProvider where PTYs live in the Electron main diff --git a/src/main/window/attach-main-window-services.ts b/src/main/window/attach-main-window-services.ts index d45b4bec7..3ec378783 100644 --- a/src/main/window/attach-main-window-services.ts +++ b/src/main/window/attach-main-window-services.ts @@ -9,6 +9,7 @@ import { ORCA_BROWSER_PARTITION } from '../../shared/constants' import { registerRepoHandlers } from '../ipc/repos' import { registerWorktreeHandlers } from '../ipc/worktrees' import { registerPtyHandlers } from '../ipc/pty' +import { registerDaemonManagementHandlers } from '../ipc/pty-management' import { registerSshHandlers } from '../ipc/ssh' import { browserManager } from '../browser/browser-manager' import { hasSystemMediaAccess, requestSystemMediaAccess } from '../browser/browser-media-access' @@ -41,6 +42,13 @@ export function attachMainWindowServices( () => store.getSettings(), prepareClaudeAuth ) + // Why: the Manage Sessions settings panel (docs/daemon-staleness-ux.md §Phase 1) + // uses a narrow `pty:management:*` IPC surface that reads the live + // DaemonPtyRouter via getDaemonProvider(). Registering here — after + // registerPtyHandlers — keeps this wiring alongside the rest of the PTY IPC + // and ensures the handlers are re-installed on macOS app re-activation when + // the main window is recreated. + registerDaemonManagementHandlers() // Why: GC runs on a 10s delay so live worktree enumeration completes first. // Uses git worktree list (not store.getWorktreeMeta) because untouched // worktrees have no metadata entries — see design doc §7.6. diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index 39dadd05a..4bb36f79c 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -216,6 +216,32 @@ export type PreflightApi = { detectRemoteAgents: (args: { connectionId: string }) => Promise } +// Why: renderer-facing mirror of the daemon's `SessionInfo` + protocolVersion +// annotation (src/main/daemon/types.ts `DaemonSessionInfo`). Kept here instead +// of imported from main because the preload boundary must not depend on +// main-only protocol types — those are subprocess-facing. Keep the two shapes +// in sync when adding fields on either side; the Manage Sessions panel reads +// these directly. +export type PtyManagementSession = { + sessionId: string + state: 'created' | 'spawning' | 'running' | 'exiting' | 'exited' + shellState: 'pending' | 'ready' | 'timed_out' | 'unsupported' + isAlive: boolean + pid: number | null + cwd: string | null + cols: number + rows: number + createdAt: number + protocolVersion: number +} + +export type PtyManagementApi = { + listSessions: () => Promise<{ sessions: PtyManagementSession[] }> + killAll: () => Promise<{ killedCount: number; remainingCount: number }> + killOne: (args: { sessionId: string }) => Promise<{ success: boolean }> + restart: () => Promise<{ success: boolean }> +} + export type ExportApi = { htmlToPdf: (args: { html: string @@ -408,6 +434,7 @@ export type PreloadApi = { onData: (callback: (data: { id: string; data: string }) => void) => () => void onReplay: (callback: (data: { id: string; data: string }) => void) => () => void onExit: (callback: (data: { id: string; code: number }) => void) => () => void + management: PtyManagementApi } feedback: { submit: (args: { diff --git a/src/preload/index.ts b/src/preload/index.ts index f03326dbc..a71c25e0f 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -387,6 +387,13 @@ const api = { callback(data) ipcRenderer.on('pty:exit', listener) return () => ipcRenderer.removeListener('pty:exit', listener) + }, + + management: { + listSessions: () => ipcRenderer.invoke('pty:management:listSessions'), + killAll: () => ipcRenderer.invoke('pty:management:killAll'), + killOne: (args: { sessionId: string }) => ipcRenderer.invoke('pty:management:killOne', args), + restart: () => ipcRenderer.invoke('pty:management:restart') } }, diff --git a/src/renderer/src/components/settings/ManageSessionsSection.tsx b/src/renderer/src/components/settings/ManageSessionsSection.tsx new file mode 100644 index 000000000..ffdc4f879 --- /dev/null +++ b/src/renderer/src/components/settings/ManageSessionsSection.tsx @@ -0,0 +1,586 @@ +/* eslint-disable max-lines -- Why: this pane owns all admin controls for the + pty daemon (list, kill-all, kill-one, restart) plus the confirmation + dialog and table. Splitting would scatter the shared action state and + toast copy across files without a cleaner ownership seam. */ +import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { LoaderCircle, RefreshCw, RotateCw, Trash2, X } from 'lucide-react' +import { toast } from 'sonner' +import type { PtyManagementSession } from '../../../../preload/api-types' +import { Button } from '../ui/button' +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle +} from '../ui/dialog' +import { Tooltip, TooltipContent, TooltipTrigger } from '../ui/tooltip' +import { SearchableSetting } from './SearchableSetting' +import { useAppStore } from '../../store' +import { activateAndRevealWorktree } from '@/lib/worktree-activation' + +type ConfirmKind = 'killAll' | 'restart' | 'killOne' + +type PendingConfirm = + | { kind: 'killAll' } + | { kind: 'restart' } + | { kind: 'killOne'; session: PtyManagementSession } + | null + +// Why: mirror the status-bar SessionsStatusSegment label style — last two +// path segments joined by the platform separator, no ellipsis prefix. This +// keeps the Manage Sessions table visually consistent with how Orca labels +// the same worktrees in the bottom status bar ("orca/Anemone"). +function shortCwd(cwd: string): string { + if (!cwd) { + return 'unknown' + } + const separator = cwd.includes('\\') ? '\\' : '/' + const parts = cwd.split(/[\\/]+/).filter(Boolean) + return parts.length > 2 ? parts.slice(-2).join(separator) : cwd +} + +function formatWorkspace(session: { cwd: string | null; sessionId: string }): string { + if (session.cwd) { + return shortCwd(session.cwd) + } + // Why: the daemon doesn't always populate `cwd` on listSessions (legacy + // revived sessions, older protocol versions). Orca's session IDs embed + // the workspace as `@@` where worktreeId is usually + // the absolute path. Fall back to parsing the id so we don't show "—" + // when the info is right there. Matches SessionsStatusSegment's fallback. + const sep = session.sessionId.lastIndexOf('@@') + if (sep !== -1) { + const worktreeId = session.sessionId.slice(0, sep) + // Strip a leading `::` prefix if present (newer protocol). + const afterColons = worktreeId.split('::') + const path = afterColons.at(-1) + return shortCwd(path ?? worktreeId) + } + return 'unknown' +} + +function formatState(session: PtyManagementSession): string { + if (!session.isAlive) { + return 'exited' + } + if (session.shellState === 'ready') { + return 'running' + } + if (session.shellState === 'pending') { + return 'starting' + } + return session.state +} + +function getConfirmCopy(confirm: PendingConfirm): { + title: string + description: React.ReactNode + confirmLabel: string + busyLabel: string +} | null { + if (!confirm) { + return null + } + switch (confirm.kind) { + case 'killAll': + return { + title: 'Kill all terminal sessions?', + description: ( + <> + This force-quits every running terminal pane across all workspaces. Any unsaved work in + those sessions is lost. The daemon itself keeps running, and new terminals can be opened + immediately. This can't be undone. + + ), + confirmLabel: 'Kill all sessions', + busyLabel: 'Killing…' + } + case 'restart': + return { + title: 'Restart the terminal daemon?', + description: ( + <> + Kills every running terminal pane and restarts the daemon process. Panes show + “Process exited” and can be reopened immediately. Legacy-protocol sessions + from a previous app version are preserved. This can't be undone. + + ), + confirmLabel: 'Restart daemon', + busyLabel: 'Restarting…' + } + case 'killOne': + return { + title: 'Kill this session?', + description: ( + <> + Force-quits{' '} + {confirm.session.sessionId}. Any + unsaved work in that pane is lost. This can't be undone. + + ), + confirmLabel: 'Kill session', + busyLabel: 'Killing…' + } + } +} + +export function ManageSessionsSection(): React.JSX.Element { + const [sessions, setSessions] = useState([]) + const [isRefreshing, setIsRefreshing] = useState(true) + const [hasLoadedOnce, setHasLoadedOnce] = useState(false) + const [confirm, setConfirm] = useState(null) + const [busyKind, setBusyKind] = useState(null) + // Why: optimistic UI snapshot for Kill-all rollback. The design doc calls + // for emptying the list immediately and restoring it on error so users see + // feedback without waiting for the retry loop to settle. + const optimisticRollback = useRef(null) + // Why: setState after unmount warns in dev and leaks state updates. The ref + // is checked in every async callback before mutating component state. + const isMounted = useRef(true) + // Why: suppress background refresh() results from stomping an in-flight + // mutation's optimistic UI. If Kill All has set sessions=[] optimistically + // and a user-triggered refresh resolves with the pre-kill list, we'd flash + // the list back in before the mutation resolves. + const mutationInFlight = useRef(false) + + // Why: mirrors SessionsStatusSegment's navigation path so clicking a row + // lands the user on the same terminal pane the status-bar popover would. + // We need three store slices: `ptyIdsByTabId` to reverse-map sessionId → + // tabId, `tabsByWorktree` to walk that tabId back to its owning worktree, + // and the tab/view setters plus closeSettingsPage to actually switch + // surfaces. Keeping this logic aligned with the status bar means the two + // entry points can't drift on what "go to this session" means. + const tabsByWorktree = useAppStore((s) => s.tabsByWorktree) + const ptyIdsByTabId = useAppStore((s) => s.ptyIdsByTabId) + const setActiveTab = useAppStore((s) => s.setActiveTab) + const setActiveView = useAppStore((s) => s.setActiveView) + const closeSettingsPage = useAppStore((s) => s.closeSettingsPage) + + const ptyIdToTabId = useMemo(() => { + const map = new Map() + for (const [tabId, ptyIds] of Object.entries(ptyIdsByTabId)) { + for (const ptyId of ptyIds) { + map.set(ptyId, tabId) + } + } + return map + }, [ptyIdsByTabId]) + + const tabIdToWorktreeId = useMemo(() => { + const map = new Map() + for (const [worktreeId, tabs] of Object.entries(tabsByWorktree)) { + for (const tab of tabs) { + map.set(tab.id, worktreeId) + } + } + return map + }, [tabsByWorktree]) + + const handleNavigate = useCallback( + (tabId: string) => { + const worktreeId = tabIdToWorktreeId.get(tabId) + if (worktreeId) { + // Why: match SessionsStatusSegment — route through the shared + // activation path before switching tab so the worktree container + // is mounted by the time setActiveTab runs. + activateAndRevealWorktree(worktreeId) + } + setActiveView('terminal') + setActiveTab(tabId) + // Why: the status-bar version doesn't need this because it's already + // rendered over the terminal surface; from the Settings pane the user + // would otherwise land on their pane with the modal still covering it. + closeSettingsPage() + }, + [tabIdToWorktreeId, setActiveView, setActiveTab, closeSettingsPage] + ) + + useEffect(() => { + isMounted.current = true + return () => { + isMounted.current = false + } + }, []) + + const refresh = useCallback(async (): Promise => { + setIsRefreshing(true) + try { + const result = await window.api.pty.management.listSessions() + if (!isMounted.current || mutationInFlight.current) { + return result.sessions + } + setSessions(result.sessions) + return result.sessions + } catch (err) { + console.error('[manage-sessions] listSessions failed', err) + if (isMounted.current && !mutationInFlight.current) { + toast.error('Couldn’t load sessions.', { + description: err instanceof Error ? err.message : undefined + }) + } + return [] + } finally { + if (isMounted.current) { + setIsRefreshing(false) + setHasLoadedOnce(true) + } + } + }, []) + + useEffect(() => { + void refresh() + }, [refresh]) + + const sessionCount = sessions.length + + const handleKillAll = useCallback(async () => { + setBusyKind('killAll') + mutationInFlight.current = true + optimisticRollback.current = sessions + setSessions([]) + try { + const { killedCount, remainingCount } = await window.api.pty.management.killAll() + if (remainingCount > 0 && killedCount > 0) { + toast.warning( + `Killed ${killedCount} of ${killedCount + remainingCount} sessions. ${remainingCount} refused to exit.` + ) + } else if (killedCount > 0) { + toast.success(`Killed ${killedCount} session${killedCount === 1 ? '' : 's'}.`) + } else if (remainingCount === 0) { + toast.info('No sessions running.') + } else { + toast.error(`${remainingCount} session${remainingCount === 1 ? '' : 's'} refused to exit.`) + } + mutationInFlight.current = false + await refresh() + } catch (err) { + // Why: the IPC rejected before the daemon could act — restore the list + // so the user isn't left staring at a blank table that doesn't reflect + // reality. + if (isMounted.current && optimisticRollback.current) { + setSessions(optimisticRollback.current) + } + toast.error('Couldn’t kill sessions.', { + description: err instanceof Error ? err.message : undefined + }) + } finally { + optimisticRollback.current = null + mutationInFlight.current = false + if (isMounted.current) { + setBusyKind(null) + // Why: the dialog stays open during the mutation so the user sees the + // spinner + busyLabel and can't dismiss mid-flight (see Dialog guard + // below). Close it here when the op actually finishes. + setConfirm(null) + } + } + }, [refresh, sessions]) + + const handleKillOne = useCallback( + async (session: PtyManagementSession) => { + setBusyKind('killOne') + mutationInFlight.current = true + try { + const { success } = await window.api.pty.management.killOne({ + sessionId: session.sessionId + }) + if (success) { + toast.success('Killed session.') + } else { + toast.error('Couldn’t kill session — it may already be gone.') + } + mutationInFlight.current = false + await refresh() + } catch (err) { + toast.error('Couldn’t kill session.', { + description: err instanceof Error ? err.message : undefined + }) + } finally { + mutationInFlight.current = false + if (isMounted.current) { + setBusyKind(null) + setConfirm(null) + } + } + }, + [refresh] + ) + + const handleRestart = useCallback(async () => { + setBusyKind('restart') + mutationInFlight.current = true + try { + const { success } = await window.api.pty.management.restart() + if (success) { + toast.success('Daemon restarted.') + } else { + toast.error('Restart failed — check logs.') + } + mutationInFlight.current = false + await refresh() + } catch (err) { + toast.error('Restart failed.', { + description: err instanceof Error ? err.message : undefined + }) + } finally { + mutationInFlight.current = false + if (isMounted.current) { + setBusyKind(null) + setConfirm(null) + } + } + }, [refresh]) + + // Why: do NOT clear `confirm` here — the dialog must stay open for the + // duration of the mutation so the spinner + busyLabel render and the + // anti-dismiss guard can actually hold. Each handler's `finally` clears + // `confirm` when the op resolves. + const runConfirmed = useCallback(() => { + if (!confirm) { + return + } + const pending = confirm + switch (pending.kind) { + case 'killAll': + void handleKillAll() + return + case 'restart': + void handleRestart() + return + case 'killOne': + void handleKillOne(pending.session) + } + }, [confirm, handleKillAll, handleKillOne, handleRestart]) + + const copy = useMemo(() => getConfirmCopy(confirm), [confirm]) + const isBusy = busyKind !== null + + return ( +
+
+

Manage Sessions

+

+ Recover from a frozen or misbehaving terminal by killing sessions or restarting the + underlying daemon. +

+
+ + + {/* Why: full-width sessions card. The table *is* the primary + surface — header bar on top carries the global actions (Kill + all, Restart daemon) plus the session count and refresh; the + body is the per-session list with a kill X on each row. Keeps + destructive-color outside the trigger buttons; confirm Dialog + still does the shouting. */} +
+
+
+ + Sessions + {hasLoadedOnce ? ({sessionCount}) : null} + + +
+ {/* Why: icon-only ghost buttons keep this row visually quiet — + the table is the hero, not the actions. Trash2 reads as + "bulk delete" (matches its use elsewhere in the app) and + RotateCw reads as "restart/cycle" without colliding with + the RefreshCw list-refresh icon. Tooltip carries the verb + since the glyph alone is ambiguous. */} +
+ + + + + + Kill all sessions + + + + + + + + Restart daemon + + +
+
+ + {!hasLoadedOnce ? ( +
+ Loading… +
+ ) : sessions.length === 0 ? ( +
+ No sessions. +
+ ) : ( +
+ + + {sessions.map((session) => { + // Why: mirror status-bar SessionsStatusSegment exactly — + // green when alive, muted when not. No amber "starting" + // bucket; the status bar doesn't have one either and + // adding one here made every row render amber whenever + // shellState wasn't exactly 'ready'. + const dotClass = session.isAlive ? 'bg-emerald-500' : 'bg-muted-foreground/40' + // Why: only sessions bound to a live tab have somewhere + // to navigate to. Orphan/unbound sessions (worktree was + // closed, tab store hasn't rehydrated, etc.) get no + // hover affordance and no click handler — same rule the + // status-bar popover follows. + const tabId = ptyIdToTabId.get(session.sessionId) ?? null + const rowClickable = tabId !== null + return ( + handleNavigate(tabId) : undefined} + aria-label={ + rowClickable ? `Go to terminal ${formatWorkspace(session)}` : undefined + } + > + + + + + + ) + })} + +
+ + + + {formatWorkspace(session)} + + + {session.sessionId} + + +
+
+ )} +
+
+ + { + if (open) { + return + } + // Why: don't let overlay click / Escape / close-button close the + // dialog mid-mutation — the confirm button is the canonical exit. + // Matches the "can't cancel a destructive op in flight" convention + // in other confirm dialogs across the app. + if (isBusy) { + return + } + setConfirm(null) + }} + > + { + if (isBusy) { + e.preventDefault() + } + }} + onEscapeKeyDown={(e) => { + if (isBusy) { + e.preventDefault() + } + }} + > + {copy ? ( + <> + + {copy.title} + {copy.description} + + + + + + + ) : null} + + +
+ ) +} diff --git a/src/renderer/src/components/settings/TerminalPane.tsx b/src/renderer/src/components/settings/TerminalPane.tsx index 99d4ca1d7..18543d6d5 100644 --- a/src/renderer/src/components/settings/TerminalPane.tsx +++ b/src/renderer/src/components/settings/TerminalPane.tsx @@ -32,6 +32,7 @@ import { matchesSettingsSearch } from './settings-search' import { useAppStore } from '../../store' import { isMacUserAgent, isWindowsUserAgent } from '@/components/terminal-pane/pane-helpers' import { + MANAGE_SESSIONS_SEARCH_ENTRIES, TERMINAL_ADVANCED_SEARCH_ENTRIES, TERMINAL_CURSOR_SEARCH_ENTRIES, TERMINAL_DARK_THEME_SEARCH_ENTRIES, @@ -54,6 +55,7 @@ import { DarkTerminalThemeSection, LightTerminalThemeSection } from './TerminalT import { TerminalWindowSection } from './TerminalWindowSection' import { GhosttyImportModal } from './GhosttyImportModal' import type { UseGhosttyImportReturn } from './useGhosttyImport' +import { ManageSessionsSection } from './ManageSessionsSection' type TerminalPaneProps = { settings: GlobalSettings @@ -789,6 +791,9 @@ export function TerminalPane({ ) : null, + matchesSettingsSearch(searchQuery, MANAGE_SESSIONS_SEARCH_ENTRIES) ? ( + + ) : null, matchesSettingsSearch(searchQuery, TERMINAL_ADVANCED_SEARCH_ENTRIES) || (showWindowsPowerShellImplementation && matchesSettingsSearch( diff --git a/src/renderer/src/components/settings/terminal-search.test.ts b/src/renderer/src/components/settings/terminal-search.test.ts index 9d6f63f17..634a074c4 100644 --- a/src/renderer/src/components/settings/terminal-search.test.ts +++ b/src/renderer/src/components/settings/terminal-search.test.ts @@ -32,6 +32,15 @@ describe('getTerminalPaneSearchEntries', () => { expect(entries.some((entry) => entry.title === 'Option as Alt')).toBe(false) }) + it('includes the Manage Sessions entry on all platforms', () => { + const entriesWindows = getTerminalPaneSearchEntries({ isWindows: true, isMac: false }) + const entriesMac = getTerminalPaneSearchEntries({ isWindows: false, isMac: true }) + const entriesLinux = getTerminalPaneSearchEntries({ isWindows: false, isMac: false }) + expect(entriesWindows.some((entry) => entry.title === 'Manage Sessions')).toBe(true) + expect(entriesMac.some((entry) => entry.title === 'Manage Sessions')).toBe(true) + expect(entriesLinux.some((entry) => entry.title === 'Manage Sessions')).toBe(true) + }) + it('includes the Ghostty import setting on all platforms', () => { const entriesWindows = getTerminalPaneSearchEntries({ isWindows: true, isMac: false }) const entriesMac = getTerminalPaneSearchEntries({ isWindows: false, isMac: true }) diff --git a/src/renderer/src/components/settings/terminal-search.ts b/src/renderer/src/components/settings/terminal-search.ts index fb7d918f2..3cefc0c00 100644 --- a/src/renderer/src/components/settings/terminal-search.ts +++ b/src/renderer/src/components/settings/terminal-search.ts @@ -189,6 +189,30 @@ export const TERMINAL_GHOSTTY_IMPORT_SEARCH_ENTRIES: SettingsSearchEntry[] = [ } ] +export const MANAGE_SESSIONS_SEARCH_ENTRIES: SettingsSearchEntry[] = [ + { + title: 'Manage Sessions', + description: + 'Recover from frozen terminals by killing sessions, clearing saved scrollback, or restarting the daemon.', + keywords: [ + 'daemon', + 'pty', + 'sessions', + 'manage', + 'kill', + 'kill all', + 'clear', + 'history', + 'scrollback', + 'restart', + 'terminal', + 'recover', + 'frozen', + 'unfreeze' + ] + } +] + export const TERMINAL_WINDOW_SEARCH_ENTRIES: SettingsSearchEntry[] = [ { title: 'Background Opacity', @@ -260,6 +284,7 @@ export function getTerminalPaneSearchEntries(platform: { ...TERMINAL_WINDOW_SEARCH_ENTRIES, ...TERMINAL_SETUP_SCRIPT_SEARCH_ENTRIES, ...TERMINAL_GHOSTTY_IMPORT_SEARCH_ENTRIES, + ...MANAGE_SESSIONS_SEARCH_ENTRIES, ...TERMINAL_ADVANCED_SEARCH_ENTRIES, ...(platform.isMac ? TERMINAL_MAC_OPTION_SEARCH_ENTRIES : []) ] diff --git a/src/renderer/src/components/terminal-pane/pty-transport.test.ts b/src/renderer/src/components/terminal-pane/pty-transport.test.ts index 0b3a10158..6ad18bc64 100644 --- a/src/renderer/src/components/terminal-pane/pty-transport.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-transport.test.ts @@ -421,6 +421,90 @@ describe('createIpcPtyTransport', () => { } }) + it('suppresses the error toast when pty:spawn rejects with TerminalKilledError', async () => { + // Why: after the user hits "Kill All" in Settings → Manage Sessions, a + // remounted pane's connect() will call pty:spawn with a killed session + // ID. The main-side tombstone rejects with TerminalKilledError. That + // rejection is the kill working as intended — not a bug — so the + // transport must not surface a "please file an issue" toast. Match the + // IPC-wrapped form Electron actually throws ("Error invoking remote + // method 'pty:spawn': TerminalKilledError: Session \"...\" was + // explicitly killed") to exercise the real error path. + const { createIpcPtyTransport } = await import('./pty-transport') + const spawnMock = vi + .fn() + .mockRejectedValue( + new Error( + `Error invoking remote method 'pty:spawn': TerminalKilledError: Session "pty-dead" was explicitly killed` + ) + ) + + ;(globalThis as { window: typeof window }).window = { + ...originalWindow, + api: { + ...originalWindow?.api, + pty: { + ...originalWindow?.api?.pty, + spawn: spawnMock, + write: vi.fn(), + resize: vi.fn(), + kill: vi.fn(), + onData: vi.fn(() => () => {}), + onReplay: vi.fn(() => () => {}), + onExit: vi.fn(() => () => {}) + } + } + } as unknown as typeof window + + const transport = createIpcPtyTransport() + const onError = vi.fn() + + const result = await transport.connect({ + url: '', + sessionId: 'pty-dead', + callbacks: { onError } + }) + + expect(onError).not.toHaveBeenCalled() + expect(result).toBeUndefined() + }) + + it('still surfaces non-kill spawn errors via onError', async () => { + // Why: the TerminalKilledError suppression must be narrowly scoped — + // unrelated spawn failures (no shell binary, bad cwd, etc.) still need + // to reach the user so they can act on them. Guard against an + // over-broad `.includes` match regressing and swallowing real errors. + const { createIpcPtyTransport } = await import('./pty-transport') + const spawnMock = vi.fn().mockRejectedValue(new Error('ENOENT: spawn /bin/nope not found')) + + ;(globalThis as { window: typeof window }).window = { + ...originalWindow, + api: { + ...originalWindow?.api, + pty: { + ...originalWindow?.api?.pty, + spawn: spawnMock, + write: vi.fn(), + resize: vi.fn(), + kill: vi.fn(), + onData: vi.fn(() => () => {}), + onReplay: vi.fn(() => () => {}), + onExit: vi.fn(() => () => {}) + } + } + } as unknown as typeof window + + const transport = createIpcPtyTransport() + const onError = vi.fn() + + await transport.connect({ + url: '', + callbacks: { onError } + }) + + expect(onError).toHaveBeenCalledWith('ENOENT: spawn /bin/nope not found') + }) + it('keeps the exit observer alive after detach so remounts do not reuse dead PTYs', async () => { const { createIpcPtyTransport } = await import('./pty-transport') const onPtyExit = vi.fn() diff --git a/src/renderer/src/components/terminal-pane/pty-transport.ts b/src/renderer/src/components/terminal-pane/pty-transport.ts index 8acd0e92e..f8cb7f7f2 100644 --- a/src/renderer/src/components/terminal-pane/pty-transport.ts +++ b/src/renderer/src/components/terminal-pane/pty-transport.ts @@ -394,6 +394,22 @@ export function createIpcPtyTransport(opts: IpcPtyTransportOptions = {}): PtyTra return spawnResult.id } catch (err) { const msg = err instanceof Error ? err.message : String(err) + // Why: after "Kill All" from Settings → Manage Sessions, mounted panes + // can still trigger pty:spawn with the killed session ID (tab remount, + // navigating back to the workspace). The main-side adapter correctly + // rejects with TerminalKilledError ("...was explicitly killed") via + // its tombstone. Surfacing that rejection as a red "Terminal error, + // please file an issue" toast misrepresents an intentional user + // action as a bug. The pane will already render "Process exited" via + // the normal lifecycle — that is the correct signal. Match against + // both the raw Error.message and Electron's IPC-wrapped form + // ("Error invoking remote method 'pty:spawn': TerminalKilledError: + // ..."). The phrase "was explicitly killed" only appears in that one + // error type (see src/main/daemon/daemon-pty-adapter.ts), so a + // substring match is safe. + if (msg.includes('was explicitly killed')) { + return undefined + } // Why: on cold start, SSH provider isn't registered yet so pty:spawn // throws a raw IPC error. Replace with a friendly message since this // is an expected state, not an application crash.