diff --git a/cli/src/api/apiMachine.test.ts b/cli/src/api/apiMachine.test.ts index 1939b6e6..df38584a 100644 --- a/cli/src/api/apiMachine.test.ts +++ b/cli/src/api/apiMachine.test.ts @@ -974,3 +974,40 @@ describe('ApiMachineClient connect runner-state advertisement', () => { } }) }) + +describe('ApiMachineClient child-exit notices', () => { + beforeEach(() => { + ioMock.mockReset() + }) + + it('reports a dead child on the machine socket with its process generation', () => { + const machine = makeMachine('machine-child-exit') + const socket = { + on: vi.fn(), + emit: vi.fn(), + emitWithAck: vi.fn().mockResolvedValue({ result: 'success', version: 1 }), + close: vi.fn() + } + ioMock.mockReturnValue(socket) + + const client = new ApiMachineClient('cli-token', machine) + try { + client.connect() + client.reportSessionChildExited({ + sid: 'session-1', + pid: 4321, + processStartMarker: 'Mon Jan 1 00:00:00 2024' + }) + + expect(socket.emit).toHaveBeenCalledWith('session-child-exited', { + machineId: machine.id, + sid: 'session-1', + pid: 4321, + processStartMarker: 'Mon Jan 1 00:00:00 2024', + time: expect.any(Number) + }) + } finally { + client.shutdown() + } + }) +}) diff --git a/cli/src/api/apiMachine.ts b/cli/src/api/apiMachine.ts index b1e38dbf..05525cdd 100644 --- a/cli/src/api/apiMachine.ts +++ b/cli/src/api/apiMachine.ts @@ -605,6 +605,27 @@ export class ApiMachineClient { }) } + /** + * Tell the hub a runner-owned child died without the CLI's normal + * session-end handshake. Best effort: the hub also has the child socket + * and its keep-alive expiry as a backstop if this frame is lost. + */ + reportSessionChildExited(payload: { + sid: string + pid: number + processStartMarker?: string + time?: number + }): void { + if (!this.socket) return + this.socket.emit('session-child-exited', { + machineId: this.machine.id, + sid: payload.sid, + pid: payload.pid, + ...(payload.processStartMarker ? { processStartMarker: payload.processStartMarker } : {}), + time: payload.time ?? Date.now() + }) + } + connect(): void { this.socket = io(`${configuration.apiUrl}/cli`, { transports: ['websocket'], diff --git a/cli/src/runner/childExitNotice.test.ts b/cli/src/runner/childExitNotice.test.ts new file mode 100644 index 00000000..4be08a89 --- /dev/null +++ b/cli/src/runner/childExitNotice.test.ts @@ -0,0 +1,69 @@ +import { describe, expect, it } from 'vitest' +import { buildChildExitNotices } from './childExitNotice' + +describe('buildChildExitNotices', () => { + it('reports every HAPI root owned by one runner child exactly once', () => { + const notices = buildChildExitNotices({ + pid: 4321, + processStartMarker: 'Mon Jan 1 00:00:00 2024', + tracked: { + requestedHappySessionId: 'requested', + happySessionId: 'happy', + sharedSessions: { + happy: {}, + sibling: {} + } + }, + requestedSessionId: 'requested', + confirmedSessionId: 'happy', + existingSessionId: 'sibling' + }, { + time: 1_700_000_000_000, + intentional: false + }) + + expect(notices.map((notice) => notice.sid).sort()).toEqual([ + 'happy', + 'requested', + 'sibling' + ]) + expect(notices.every((notice) => notice.pid === 4321)).toBe(true) + expect(notices.every((notice) => notice.processStartMarker === 'Mon Jan 1 00:00:00 2024')).toBe(true) + }) + + it('falls back to the generation reported by the session webhook', () => { + const notices = buildChildExitNotices({ + pid: 7, + tracked: { + sharedSessions: {}, + happySessionMetadataFromLocalWebhook: { + hostStartMarker: 'webhook-marker' + } + }, + confirmedSessionId: 'confirmed' + }, { time: 1, intentional: false }) + + expect(notices).toEqual([{ + sid: 'confirmed', + pid: 7, + processStartMarker: 'webhook-marker' + }]) + }) + + it('does not report an intentional runner stop as an unexpected exit', () => { + expect(buildChildExitNotices({ + pid: 9, + processStartMarker: 'marker', + tracked: { happySessionId: 'archived' }, + confirmedSessionId: 'archived' + }, { time: 1, intentional: true })).toEqual([]) + }) + + it('returns no notice when the child never reported a HAPI session', () => { + expect(buildChildExitNotices({ + pid: 10, + processStartMarker: 'marker', + tracked: { sharedSessions: {} } + }, { time: 2, intentional: false })).toEqual([]) + }) +}) diff --git a/cli/src/runner/childExitNotice.ts b/cli/src/runner/childExitNotice.ts new file mode 100644 index 00000000..346352d9 --- /dev/null +++ b/cli/src/runner/childExitNotice.ts @@ -0,0 +1,62 @@ +export type ChildExitNotice = { + sid: string + pid: number + processStartMarker?: string +} + +type ExitTrackedSession = { + requestedHappySessionId?: string + happySessionId?: string + sharedSessions?: Record + happySessionMetadataFromLocalWebhook?: { hostStartMarker?: string } | null +} + +/** + * One runner child can own several HAPI rows (shared Codex wrapper), and a + * spawn can be referred to by its reserved/requested id before the webhook + * confirms the final row. Collapse all of those aliases into one notice per + * row, carrying the OS generation so a late/duplicate delivery cannot match a + * later child that reused the pid. + */ +export function buildChildExitNotices( + input: { + pid: number + processStartMarker?: string | null + tracked?: ExitTrackedSession | null + requestedSessionId?: string + confirmedSessionId?: string + existingSessionId?: string + }, + options: { + intentional: boolean + // Observation time is carried by the socket payload; accepted here so + // callers pass one timestamp for the whole exit decision. + time?: number + } +): ChildExitNotice[] { + if (options.intentional) return [] + + const processStartMarker = input.processStartMarker + ?? input.tracked?.happySessionMetadataFromLocalWebhook?.hostStartMarker + ?? Object.values(input.tracked?.sharedSessions ?? {}) + .map((metadata) => metadata?.hostStartMarker) + .find((marker): marker is string => typeof marker === 'string' && marker.length > 0) + ?? undefined + + const ids = new Set() + const add = (id: string | undefined) => { + if (typeof id === 'string' && id.length > 0) ids.add(id) + } + add(input.requestedSessionId) + add(input.confirmedSessionId) + add(input.existingSessionId) + add(input.tracked?.requestedHappySessionId) + add(input.tracked?.happySessionId) + for (const id of Object.keys(input.tracked?.sharedSessions ?? {})) add(id) + + return Array.from(ids, (sid) => ({ + sid, + pid: input.pid, + ...(processStartMarker ? { processStartMarker } : {}) + })) +} diff --git a/cli/src/runner/run.intentionalStop.test.ts b/cli/src/runner/run.intentionalStop.test.ts new file mode 100644 index 00000000..21dd321b --- /dev/null +++ b/cli/src/runner/run.intentionalStop.test.ts @@ -0,0 +1,239 @@ +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { EventEmitter } from 'node:events' +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' +import type { CodexRuntimeRecord } from '@/codex/shared/registry' +import type { startRunnerControlServer } from './controlServer' + +// Exercise the real runner closure end to end so the test can observe what +// reportSessionChildExited receives after a stop and a later child exit. + +const mocks = vi.hoisted(() => ({ + controlServer: vi.fn(), + readRuntimes: vi.fn(), + findRuntime: vi.fn(), + reapOrphans: vi.fn(), + kill: vi.fn(), + isProcessAlive: vi.fn<(pid: number) => boolean>(() => true), + spawnHappyCLI: vi.fn(), + reportChildExit: vi.fn(), +})) + +vi.mock('./controlServer', () => ({ startRunnerControlServer: mocks.controlServer })) +vi.mock('./controlClient', () => ({ + isRunnerRunningCurrentlyInstalledHappyVersion: async () => false, + stopRunner: async () => {}, + getInstalledCliMtimeMs: () => undefined, + waitForRunnerHandoff: async () => false, + cleanupRunnerState: async () => {}, +})) +vi.mock('@/persistence', async importOriginal => ({ + ...await importOriginal(), + acquireRunnerLock: async () => ({}), + releaseRunnerLock: async () => {}, +})) +vi.mock('@/ui/auth', () => ({ authAndSetupMachineIfNeeded: async () => ({ machineId: 'machine' }) })) +vi.mock('@/ui/logger', () => ({ + logger: { + debug: (...args: unknown[]) => { if (process.env.HAPI_TEST_VERBOSE) console.log('[runner]', ...args) }, + debugLargeJson: (...args: unknown[]) => { if (process.env.HAPI_TEST_VERBOSE) console.log('[runner:json]', ...args) }, + warn: (...args: unknown[]) => { if (process.env.HAPI_TEST_VERBOSE) console.log('[runner:warn]', ...args) }, + }, +})) +vi.mock('@/ui/doctor', () => ({ getEnvironmentInfo: () => ({}) })) +vi.mock('@/agent/agentAvailability', () => ({ getAgentAvailability: () => ({ available: true }), agentUnavailableMessage: () => '' })) +vi.mock('@/modules/common/cursorModelsPrewarm', () => ({ scheduleCursorModelsPrewarm: () => {} })) +vi.mock('@/codex/shared/registry', () => ({ + readRuntimes: mocks.readRuntimes, + findRuntime: mocks.findRuntime, + runtimeAuthHash: () => 'test-auth', + runtimeMayBeAlive: () => true, +})) +vi.mock('@/runner/orphanReap', () => ({ + reapRunnerSpawnedOrphans: mocks.reapOrphans, + findStopSessionOrphanTargets: vi.fn(), + listWindowsProcessesWithCommandLine: vi.fn(), +})) +vi.mock('@/utils/process', async importOriginal => ({ + ...await importOriginal(), + isWindows: () => false, + isProcessAlive: mocks.isProcessAlive, + getProcessStartMarker: () => 'generation', + killProcess: mocks.kill, + killProcessTreeByPid: mocks.kill, + killProcessByChildProcess: mocks.kill, +})) +vi.mock('@/utils/spawnHappyCLI', () => ({ spawnHappyCLI: mocks.spawnHappyCLI })) +vi.mock('@/api/api', () => ({ + ApiClient: { + create: async () => ({ + getOrCreateMachine: async () => ({ id: 'machine-1' }), + machineSyncClient: () => ({ + setRPCHandlers: vi.fn(), + connect: vi.fn(), + shutdown: vi.fn(), + updateRunnerState: async () => {}, + reportSessionChildExited: mocks.reportChildExit, + }), + }), + }, +})) + +import { configuration } from '@/configuration' +import { startRunner } from './run' + +type RunnerHandlers = Parameters[0] + +const PID_GONE = 5000 + +function makeFakeChild(pid: number): EventEmitter & { pid: number } { + const child = new EventEmitter() as EventEmitter & { pid: number } + child.pid = pid + return child +} + +describe('runner intentional-stop marker cleanup', () => { + let handlers: RunnerHandlers + let runnerPromise: Promise + let home: string + let captured: Error + + beforeAll(async () => { + home = mkdtempSync(join(tmpdir(), 'hapi-intentional-stop-')) + captured = new Error('runner stopped after control handlers captured') + handlers = {} as RunnerHandlers + mocks.controlServer.mockImplementation(async (capturedHandlers: RunnerHandlers) => { + handlers = capturedHandlers + return { port: 0, stop: async () => {} } + }) + vi.spyOn(process, 'on').mockReturnValue(process) + vi.spyOn(process, 'exit').mockImplementation(() => { throw captured }) + vi.stubEnv('HAPI_RUNNER_HANDOFF_FROM_PID', '') + vi.stubEnv('HAPI_RUNNER_HEARTBEAT_INTERVAL', '3600000') + vi.stubEnv('HAPI_DISABLE_VERSION_HANDOFF', '1') + Object.defineProperty(configuration, 'runnerStateFile', { value: join(home, 'runner.json'), configurable: true }) + // A runner restart recovers this durable record: PID_GONE once hosted + // 'sess-gone' and the generation probe verifies it as alive. + writeFileSync(`${configuration.runnerStateFile}.resume-processes.json`, JSON.stringify([ + { requestedSessionId: 'sess-gone', pid: PID_GONE, processStartMarker: 'generation' }, + ])) + runnerPromise = startRunner() + await vi.waitFor(() => expect(handlers.stopSession).toBeTypeOf('function')) + }) + + afterAll(async () => { + handlers.requestShutdown() + await expect(runnerPromise).rejects.toBe(captured) + vi.restoreAllMocks() + vi.unstubAllEnvs() + rmSync(home, { recursive: true, force: true }) + }) + + beforeEach(() => { + vi.clearAllMocks() + mocks.readRuntimes.mockResolvedValue([]) + mocks.findRuntime.mockResolvedValue(undefined) + mocks.reapOrphans.mockResolvedValue(null) + mocks.kill.mockResolvedValue(true) + mocks.isProcessAlive.mockImplementation(() => true) + mocks.spawnHappyCLI.mockImplementation(() => { throw new Error('no child queued for spawn') }) + }) + + // The spawn registers its child asynchronously (workspace validation runs + // first), so the confirming webhook is retried until the awaiter resolves. + async function confirmSpawn(spawnPromise: Promise, sessionId: string, pid: number): Promise { + const metadata = { + path: home, + host: 'localhost', + machineId: 'machine', + hostPid: pid, + startedBy: 'runner', + lifecycleState: 'running', + } + let settled = false + void spawnPromise.then(() => { settled = true }, () => { settled = true }) + const deadline = Date.now() + 4_000 + while (!settled && Date.now() < deadline) { + handlers.onHappySessionWebhook(sessionId, metadata as never) + await new Promise(resolve => setTimeout(resolve, 10)) + } + if (!settled) throw new Error(`Spawn ${sessionId} was not confirmed by webhook`) + } + + it('reports a reused pid unexpected exit after a stop that returned already_gone', async () => { + // The process is already dead when the stop runs: the runner reports + // already_gone without any exit event for it. + mocks.isProcessAlive.mockImplementation((pid: number) => pid !== PID_GONE) + await expect(handlers.stopSession('sess-gone')).resolves.toBe('already_gone') + + // A later spawn reuses the OS pid for a new session and dies on its own. + const reusedChild = makeFakeChild(PID_GONE) + mocks.spawnHappyCLI.mockImplementation(() => reusedChild) + const spawnPromise = handlers.spawnSession({ directory: home, agent: 'claude', existingSessionId: 'sess-new' }) + await confirmSpawn(spawnPromise, 'sess-new', PID_GONE) + await expect(spawnPromise).resolves.toEqual({ type: 'success', sessionId: 'sess-new' }) + + reusedChild.emit('exit', 1, null) + await vi.waitFor(() => expect(mocks.reportChildExit).toHaveBeenCalledTimes(1)) + expect(mocks.reportChildExit).toHaveBeenCalledWith( + expect.objectContaining({ sid: 'sess-new', pid: PID_GONE }) + ) + }) + + it('still suppresses the exit of a child the stop killed intentionally', async () => { + const child = makeFakeChild(6100) + mocks.spawnHappyCLI.mockImplementation(() => child) + const spawnPromise = handlers.spawnSession({ directory: home, agent: 'claude', existingSessionId: 'sess-live' }) + await confirmSpawn(spawnPromise, 'sess-live', 6100) + await expect(spawnPromise).resolves.toEqual({ type: 'success', sessionId: 'sess-live' }) + + await expect(handlers.stopSession('sess-live')).resolves.toBe('stopped') + expect(mocks.kill).toHaveBeenCalled() + + // The killed child's own exit event must not reach the hub as an + // unexpected death: the stop flow already ends the session. + child.emit('exit', 0, null) + await Promise.resolve() + expect(mocks.reportChildExit).not.toHaveBeenCalled() + }) + + it('releases the intentional marker when a stop preserves the shared wrapper for siblings', async () => { + const wrapper = makeFakeChild(6200) + mocks.spawnHappyCLI.mockImplementation(() => wrapper) + const spawnPromise = handlers.spawnSession({ directory: home, agent: 'claude', existingSessionId: 'wrapper-main' }) + await confirmSpawn(spawnPromise, 'wrapper-main', 6200) + await expect(spawnPromise).resolves.toEqual({ type: 'success', sessionId: 'wrapper-main' }) + for (const root of ['root-a', 'sibling-b']) { + handlers.onHappySessionWebhook(root, { + path: home, + host: 'localhost', + machineId: 'machine', + hostPid: 6200, + startedBy: 'runner', + lifecycleState: 'running', + capabilities: { concurrentClients: true }, + } as never) + } + + // Archiving the primary root keeps the wrapper alive for the sibling. + mocks.readRuntimes.mockResolvedValue([{ + id: 'runtime', pid: 6200, marker: 'generation', endpoint: 'unused', + command: 'codex', args: [], codexHome: home, + hub: configuration.apiUrl, authHash: 'test-auth', + sessions: { + 'root-a': { threadId: 'a', namespace: 'test', active: false }, + 'sibling-b': { threadId: 'b', namespace: 'test', active: true }, + }, + }]) + await expect(handlers.stopSession('root-a')).resolves.toBe('stopped') + expect(mocks.kill).not.toHaveBeenCalled() + + // The surviving wrapper later crashes on its own: the sibling's death + // must still be reported, not suppressed by the root's stop marker. + wrapper.emit('exit', 1, null) + await vi.waitFor(() => expect(mocks.reportChildExit).toHaveBeenCalledWith( + expect.objectContaining({ sid: 'sibling-b', pid: 6200 }) + )) + }) +}) \ No newline at end of file diff --git a/cli/src/runner/run.ts b/cli/src/runner/run.ts index 284f3b2d..963aa0f8 100644 --- a/cli/src/runner/run.ts +++ b/cli/src/runner/run.ts @@ -18,6 +18,7 @@ import { getProcessStartMarker, getSystemBootId, getProcessThreadGroupId, normal import { findStopSessionOrphanTargets, listWindowsProcessesWithCommandLine, reapRunnerSpawnedOrphans } from '@/runner/orphanReap'; import { decideUntrackedRunnerWebhook } from '@/runner/lateRunnerWebhook'; import { cleanupFailedStartupAfterExit, sessionStartupTimeout, waitForRecoverableStartup } from './sessionStartup'; +import { buildChildExitNotices, type ChildExitNotice } from './childExitNotice'; import { decideKeepWrapperArchive, decideRawPidStop, @@ -432,6 +433,15 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): // existingSessionId identifies the HAPI row, not a permanent spawn request. // Keep the dedupe entry only while this runner still owns the child PID. const existingSessionIdByChildPid = new Map(); + // PIDs the runner is deliberately killing (archive/stop/switch), consumed + // once when the exit is observed. Their exit must not be reported to the + // hub as an unexpected child death: those flows already end the session + // through the normal session-end / archive path. + const intentionallyStoppedPids = new Set(); + // Wired once the machine socket exists (see apiMachine.connect below). + // Before that an unexpected child exit is not reported; the child's own + // socket plus keep-alive expiry remain the hub-side backstop. + let reportChildExitToHub: ((notice: ChildExitNotice) => void) | null = null; type SpawnFailureDetails = { message: string pid?: number @@ -1162,10 +1172,45 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): ); } - // Stop a session by sessionId or PID fallback - const stopSession = coalesceStopRequests(async ( + // A stop (archive/switch/user stop) kills this session's child. Record the + // owning PIDs before any kill so onChildExited treats their exit as + // deliberate and does not report it as an unexpected child death. + // Returns the marked PIDs plus the subset the runner spawned itself: only + // those have an 'exit' listener that consumes their entry in onChildExited. + const markIntentionalStop = (sessionId: string) => { + const marked = new Set(); + const withExitListener = new Set(); + const mark = (pid: number) => { + marked.add(pid); + intentionallyStoppedPids.add(pid); + if (pidToTrackedSession.get(pid)?.childProcess) withExitListener.add(pid); + }; + for (const [pid, session] of pidToTrackedSession) { + if (session.requestedHappySessionId === sessionId + || session.happySessionId === sessionId + || session.sharedSessions?.[sessionId]) { + mark(pid); + } + } + for (const [pid, record] of persistedResumeProcesses) { + if (record.requestedSessionId === sessionId || record.confirmedSessionId === sessionId) { + mark(pid); + } + } + if (sessionId.startsWith('PID-')) { + const pid = Number(sessionId.slice('PID-'.length)); + if (Number.isInteger(pid) && pid > 0) mark(pid); + } + return { marked, withExitListener }; + }; + + // Stop a session by sessionId or PID fallback. `terminated` collects the + // marked PIDs this attempt actually killed, so the caller can keep their + // suppression only while their own exit event is still pending. + const attemptStopSession = async ( sessionId: string, - opts?: { processStartMarker?: string } + opts?: { processStartMarker?: string }, + terminated: Set = new Set() ): Promise<'stopped' | 'already_gone' | 'still_alive' | 'unknown'> => { logger.debug(`[RUNNER RUN] Attempting to stop session ${sessionId}`); @@ -1348,6 +1393,7 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): return await finishWithOrphanSweep('stopped'); } if (!(await killProcessTreeByPid(pid))) return 'still_alive'; + terminated.add(pid); rememberVerifiedExit(sessionId); return await finishWithOrphanSweep('stopped'); } @@ -1453,6 +1499,7 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): return 'still_alive'; } treeTerminationVerified = true; + terminated.add(pid); logger.debug(`[RUNNER RUN] Requested termination for runner-spawned session ${sessionId}`); } catch (error) { logger.debug(`[RUNNER RUN] Failed to kill session ${sessionId}:`, error); @@ -1462,6 +1509,7 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): // For externally started sessions, try to kill by PID try { if (!(await killProcess(pid))) return 'still_alive'; + terminated.add(pid); logger.debug(`[RUNNER RUN] Requested termination for external session PID ${pid}`); } catch (error) { logger.debug(`[RUNNER RUN] Failed to kill external session PID ${pid}:`, error); @@ -1539,6 +1587,7 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): return decision; } if (!(await killProcessTreeByPid(pid))) return 'still_alive'; + terminated.add(pid); if (requestedSessionId) rememberVerifiedExit(requestedSessionId); if (confirmedSessionId) rememberVerifiedExit(confirmedSessionId); rememberVerifiedExit(`PID-${pid}`); @@ -1610,6 +1659,25 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): // while callers that just spawned this id can treat unknown defensively. logger.debug(`[RUNNER RUN] Session ${sessionId} not found without verified exit`); return 'unknown'; + }; + + // Late RPC retries join the same operation, but every attempt records its + // own intentional PIDs and releases the ones this attempt did not + // terminate: a preserved shared wrapper or a child the stop left alive + // must not suppress its later real unexpected exit. + const stopSession = coalesceStopRequests(async ( + sessionId: string, + opts?: { processStartMarker?: string } + ): Promise<'stopped' | 'already_gone' | 'still_alive' | 'unknown'> => { + const intentional = markIntentionalStop(sessionId); + const terminated = new Set(); + try { + return await attemptStopSession(sessionId, opts, terminated); + } finally { + for (const pid of intentional.marked) { + if (!(intentional.withExitListener.has(pid) && terminated.has(pid))) intentionallyStoppedPids.delete(pid); + } + } }); // A reused PID invalidates a binding, not every runtime for that session. @@ -1640,6 +1708,20 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): spawnSession.onChildExited(existingSessionId); existingSessionIdByChildPid.delete(pid); } + // Tell the hub this generation died, unless we killed it on purpose. + // The marker from the durable resume record outlives a dropped + // TrackedSession (webhook timeout), so a late exit still carries the + // generation the hub compares against. + const intentional = intentionallyStoppedPids.delete(pid); + const notices = buildChildExitNotices({ + pid, + processStartMarker: persistedResumeProcesses.get(pid)?.processStartMarker, + tracked: session, + requestedSessionId, + confirmedSessionId, + existingSessionId + }, { time: Date.now(), intentional }); + for (const notice of notices) reportChildExitToHub?.(notice); pidToTrackedSession.delete(pid); pidToAwaiter.delete(pid); pidToErrorAwaiter.delete(pid); @@ -1762,6 +1844,8 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): // Connect to server apiMachine.connect(); + // Route unexpected child exits to the hub on the same machine socket. + reportChildExitToHub = (notice) => apiMachine.reportSessionChildExited(notice); scheduleCursorModelsPrewarm(); // Visible startup banner. Use console.log so it always appears on stdout, diff --git a/hub/src/socket/handlers/cli/index.ts b/hub/src/socket/handlers/cli/index.ts index d17de2d2..0e62f054 100644 --- a/hub/src/socket/handlers/cli/index.ts +++ b/hub/src/socket/handlers/cli/index.ts @@ -5,7 +5,7 @@ import type { SyncEvent } from '../../../sync/syncEngine' import type { TerminalRegistry } from '../../terminalRegistry' import type { CliSocketWithData, SocketServer } from '../../socketTypes' import type { AccessErrorReason, AccessResult } from './types' -import { registerMachineHandlers } from './machineHandlers' +import { registerMachineHandlers, type SessionChildExitedPayload } from './machineHandlers' import { registerRpcHandlers } from './rpcHandlers' import { registerSessionHandlers } from './sessionHandlers' import { cleanupTerminalHandlers, registerTerminalHandlers } from './terminalHandlers' @@ -47,6 +47,7 @@ export type CliHandlersDeps = { onSessionReady?: (payload: SessionReadyPayload) => void onSessionEnd?: (payload: SessionEndPayload) => void onMachineAlive?: (payload: MachineAlivePayload) => void + onSessionChildExited?: (payload: SessionChildExitedPayload & { namespace: string }) => void onWebappEvent?: (event: SyncEvent) => void onBackgroundTasks?: (sessionId: string, tasks: BackgroundTask[]) => void onSessionActivity?: (sessionId: string, updatedAt: number) => void @@ -84,7 +85,7 @@ const SESSION_ACCESS_CACHE_TTL_MS = 1_000 const SESSION_ACCESS_CACHE_MAX_SESSIONS = 64 export function registerCliHandlers(socket: CliSocketWithData, deps: CliHandlersDeps): void { - const { io, store, rpcRegistry, terminalRegistry, onSessionAlive, onSessionReady, onSessionEnd, onMachineAlive, onWebappEvent, onBackgroundTasks, onSessionActivity, onAgentProgress, onSweepImmediateQueued, onMessagesConsumed } = deps + const { io, store, rpcRegistry, terminalRegistry, onSessionAlive, onSessionReady, onSessionEnd, onMachineAlive, onSessionChildExited, onWebappEvent, onBackgroundTasks, onSessionActivity, onAgentProgress, onSweepImmediateQueued, onMessagesConsumed } = deps const terminalNamespace = io.of('/terminal') const namespace = typeof socket.data.namespace === 'string' ? socket.data.namespace : null @@ -189,6 +190,7 @@ export function registerCliHandlers(socket: CliSocketWithData, deps: CliHandlers resolveMachineAccess, emitAccessError, onMachineAlive, + onSessionChildExited, onWebappEvent }) registerTerminalHandlers(socket, { diff --git a/hub/src/socket/handlers/cli/machineHandlers.ts b/hub/src/socket/handlers/cli/machineHandlers.ts index 2ec6b152..1f07f52a 100644 --- a/hub/src/socket/handlers/cli/machineHandlers.ts +++ b/hub/src/socket/handlers/cli/machineHandlers.ts @@ -35,16 +35,30 @@ const machineUpdateStateSchema = z.object({ runnerState: z.unknown().nullable() }) +// A runner reports a child that exited without the CLI's session-end +// handshake. `pid` + `processStartMarker` identify the OS generation so the +// hub can refuse a notice about a process that was replaced by a resume. +const sessionChildExitedSchema = z.object({ + machineId: z.string(), + sid: z.string(), + pid: z.number().int().positive(), + processStartMarker: z.string().optional(), + time: z.number() +}) + +export type SessionChildExitedPayload = z.infer + export type MachineHandlersDeps = { store: Store resolveMachineAccess: ResolveMachineAccess emitAccessError: EmitAccessError onMachineAlive?: (payload: MachineAlivePayload) => void + onSessionChildExited?: (payload: SessionChildExitedPayload & { namespace: string }) => void onWebappEvent?: (event: SyncEvent) => void } export function registerMachineHandlers(socket: CliSocketWithData, deps: MachineHandlersDeps): void { - const { store, resolveMachineAccess, emitAccessError, onMachineAlive, onWebappEvent } = deps + const { store, resolveMachineAccess, emitAccessError, onMachineAlive, onSessionChildExited, onWebappEvent } = deps socket.on('machine-alive', (data: MachineAlivePayload) => { if (!data || typeof data.machineId !== 'string' || typeof data.time !== 'number') { @@ -159,4 +173,22 @@ export function registerMachineHandlers(socket: CliSocketWithData, deps: Machine socket.on('machine-update-metadata', handleMachineMetadataUpdate) socket.on('machine-update-state', handleMachineStateUpdate) + + socket.on('session-child-exited', (data: unknown) => { + const parsed = sessionChildExitedSchema.safeParse(data) + if (!parsed.success) { + return + } + const machineAccess = resolveMachineAccess(parsed.data.machineId) + if (!machineAccess.ok) { + emitAccessError('machine', parsed.data.machineId, machineAccess.reason) + return + } + onSessionChildExited?.({ + ...parsed.data, + // The socket's namespace is the authorization scope; the session + // owner check happens engine-side against this namespace. + namespace: machineAccess.value.namespace + }) + }) } diff --git a/hub/src/socket/server.ts b/hub/src/socket/server.ts index 3cd02955..81d4cfd5 100644 --- a/hub/src/socket/server.ts +++ b/hub/src/socket/server.ts @@ -43,6 +43,7 @@ export type SocketServerDeps = { onSessionReady?: (payload: { sid: string; time: number }) => void onSessionEnd?: (payload: { sid: string; time: number }) => void onMachineAlive?: (payload: { machineId: string; time: number; health?: unknown }) => void + onSessionChildExited?: (payload: { machineId: string; sid: string; pid: number; processStartMarker?: string; time: number; namespace: string }) => void onBackgroundTasks?: (sessionId: string, tasks: BackgroundTask[]) => void onSessionActivity?: (sessionId: string, updatedAt: number) => void onAgentProgress?: (sessionId: string, at: number) => void @@ -131,6 +132,7 @@ export function createSocketServer(deps: SocketServerDeps): { onSessionReady: deps.onSessionReady, onSessionEnd: deps.onSessionEnd, onMachineAlive: deps.onMachineAlive, + onSessionChildExited: deps.onSessionChildExited, onWebappEvent: deps.onWebappEvent, onBackgroundTasks: deps.onBackgroundTasks, onSessionActivity: deps.onSessionActivity, diff --git a/hub/src/startHub.ts b/hub/src/startHub.ts index 6521db90..0faefa4f 100644 --- a/hub/src/startHub.ts +++ b/hub/src/startHub.ts @@ -201,6 +201,7 @@ export async function startHub(options: StartHubOptions = {}): Promise syncEngine?.handleSessionReady(payload), onSessionEnd: (payload) => syncEngine?.handleSessionEnd(payload), onMachineAlive: (payload) => syncEngine?.handleMachineAlive(payload), + onSessionChildExited: (payload) => syncEngine?.handleSessionChildExited(payload), onBackgroundTasks: (sessionId, tasks) => syncEngine?.handleBackgroundTasks(sessionId, tasks), onSessionActivity: (sessionId, updatedAt) => syncEngine?.recordSessionActivity(sessionId, updatedAt), onAgentProgress: (sessionId, at) => syncEngine?.recordAgentProgress(sessionId, at), diff --git a/hub/src/sync/sessionChildExited.test.ts b/hub/src/sync/sessionChildExited.test.ts new file mode 100644 index 00000000..be6b5073 --- /dev/null +++ b/hub/src/sync/sessionChildExited.test.ts @@ -0,0 +1,299 @@ +import { describe, expect, it } from 'bun:test' +import { Store } from '../store' +import { RpcRegistry } from '../socket/rpcRegistry' +import type { SyncEvent } from '@hapi/protocol/types' +import { SyncEngine } from './syncEngine' + +const NAMESPACE = 'default' +const MACHINE = 'machine-1' +const PID = 4242 +const START_MARKER = 'Mon Jan 1 00:00:00 2024' + +function collectEvents(): { events: SyncEvent[]; sink: { broadcast(event: SyncEvent): void } } { + const events: SyncEvent[] = [] + return { + events, + sink: { broadcast(event: SyncEvent) { events.push(event) } } + } +} + +function createEngine(rooms?: Map>): { + store: Store + engine: SyncEngine + events: SyncEvent[] +} { + const store = new Store(':memory:') + const { events, sink } = collectEvents() + const io = rooms + ? { + of: (_name: string) => ({ + adapter: { rooms }, + to: () => ({ emit: () => {} }) + }) + } + : {} + const engine = new SyncEngine(store, io as never, new RpcRegistry(), sink as never) + return { store, engine, events } +} + +function registerMachine(engine: SyncEngine): void { + engine.getOrCreateMachine( + MACHINE, + { host: 'localhost', platform: 'linux', happyCliVersion: '0.1.0' }, + null, + NAMESPACE + ) + engine.handleMachineAlive({ machineId: MACHINE, time: Date.now() }) +} + +function createOwnedSession( + engine: SyncEngine, + tag: string, + overrides: Record = {} +) { + return engine.getOrCreateSession( + tag, + { + path: '/tmp/project', + host: 'localhost', + machineId: MACHINE, + hostPid: PID, + hostStartMarker: START_MARKER, + startedBy: 'runner', + lifecycleState: 'running', + flavor: 'claude', + claudeSessionId: 'claude-session-1', + ...overrides + }, + null, + NAMESPACE, + 'sonnet' + ) +} + +function markActive(engine: SyncEngine, sessionId: string, thinking = true): void { + engine.handleSessionAlive({ + sid: sessionId, + time: Date.now(), + thinking, + mode: 'remote' + }) +} + +describe('handleSessionChildExited owner guard', () => { + it('marks the current owner inactive instead of waiting for the keep-alive grace', () => { + const { engine } = createEngine() + try { + registerMachine(engine) + const session = createOwnedSession(engine, 'child-exit-current-owner') + markActive(engine, session.id) + + expect(engine.getSession(session.id)?.active).toBe(true) + expect(engine.getSession(session.id)?.thinking).toBe(true) + + const handled = engine.handleSessionChildExited({ + machineId: MACHINE, + namespace: NAMESPACE, + sid: session.id, + pid: PID, + processStartMarker: START_MARKER, + time: Date.now() + }) + + expect(handled).toBe(true) + const after = engine.getSession(session.id) + expect(after?.active).toBe(false) + expect(after?.thinking).toBe(false) + // "inactive, not archived": the row stays resumable. + expect(after?.metadata?.lifecycleState).toBe('running') + expect(after?.metadata?.archivedBy).toBeUndefined() + } finally { + engine.stop() + } + }) + + it('ignores a late notice about an older pid after the session was resumed elsewhere', () => { + const { engine } = createEngine() + try { + registerMachine(engine) + const session = createOwnedSession(engine, 'child-exit-stale-pid') + markActive(engine, session.id) + + // Resume elsewhere: same row, new process generation in metadata. + engine.handleSessionEnd({ sid: session.id, time: Date.now(), reason: 'terminated' }) + const resumedPid = PID + 1 + const current = engine.getSession(session.id)! + current.metadata = { + ...current.metadata!, + hostPid: resumedPid, + hostStartMarker: 'Tue Jan 2 00:00:00 2024' + } + markActive(engine, session.id) + + const handled = engine.handleSessionChildExited({ + machineId: MACHINE, + namespace: NAMESPACE, + sid: session.id, + pid: PID, + processStartMarker: START_MARKER, + time: Date.now() + }) + + expect(handled).toBe(false) + expect(engine.getSession(session.id)?.active).toBe(true) + } finally { + engine.stop() + } + }) + + it('ignores a reused pid whose process generation differs', () => { + const { engine } = createEngine() + try { + registerMachine(engine) + const session = createOwnedSession(engine, 'child-exit-stale-marker') + markActive(engine, session.id) + + const handled = engine.handleSessionChildExited({ + machineId: MACHINE, + namespace: NAMESPACE, + sid: session.id, + pid: PID, + processStartMarker: 'Wed Jan 3 00:00:00 2024', + time: Date.now() + }) + + expect(handled).toBe(false) + expect(engine.getSession(session.id)?.active).toBe(true) + } finally { + engine.stop() + } + }) + + it('ignores a no-marker notice older than the current owner registration when the session has no start marker', () => { + const { engine } = createEngine() + try { + registerMachine(engine) + // sessionFactory leaves hostStartMarker undefined when the + // start-marker probe fails, so the guard must fall back to time. + const firstRegistrationAt = Date.now() - 5_000 + const session = createOwnedSession(engine, 'child-exit-no-marker-stale', { + hostStartMarker: undefined, + lifecycleStateSince: firstRegistrationAt + }) + markActive(engine, session.id) + + // The pid was reused: a new owner generation re-registered the same + // pid (still without a marker) after the old process had exited. + const reregisteredAt = Date.now() - 1_000 + const current = engine.getSession(session.id)! + current.metadata = { + ...current.metadata!, + hostPid: PID, + hostStartMarker: undefined, + lifecycleStateSince: reregisteredAt + } + + const staleHandled = engine.handleSessionChildExited({ + machineId: MACHINE, + namespace: NAMESPACE, + sid: session.id, + pid: PID, + processStartMarker: undefined, + time: firstRegistrationAt + 1_000 + }) + expect(staleHandled).toBe(false) + expect(engine.getSession(session.id)?.active).toBe(true) + + // A notice at or after the current owner's registration is about + // the live owner and must still deactivate immediately. + const handled = engine.handleSessionChildExited({ + machineId: MACHINE, + namespace: NAMESPACE, + sid: session.id, + pid: PID, + processStartMarker: undefined, + time: Date.now() + }) + expect(handled).toBe(true) + expect(engine.getSession(session.id)?.active).toBe(false) + expect(engine.getSession(session.id)?.thinking).toBe(false) + } finally { + engine.stop() + } + }) + + it('ignores a notice carrying a marker when the session registered none', () => { + const { engine } = createEngine() + try { + registerMachine(engine) + const session = createOwnedSession(engine, 'child-exit-notice-marker-only', { + hostStartMarker: undefined + }) + markActive(engine, session.id) + + const handled = engine.handleSessionChildExited({ + machineId: MACHINE, + namespace: NAMESPACE, + sid: session.id, + pid: PID, + processStartMarker: 'Wed Jan 3 00:00:00 2024', + time: Date.now() + }) + + expect(handled).toBe(false) + expect(engine.getSession(session.id)?.active).toBe(true) + } finally { + engine.stop() + } + }) + + it('ignores notices from a different machine or namespace', () => { + const { engine } = createEngine() + try { + registerMachine(engine) + const session = createOwnedSession(engine, 'child-exit-cross-machine') + markActive(engine, session.id) + + expect(engine.handleSessionChildExited({ + machineId: 'machine-2', + namespace: NAMESPACE, + sid: session.id, + pid: PID, + processStartMarker: START_MARKER, + time: Date.now() + })).toBe(false) + expect(engine.handleSessionChildExited({ + machineId: MACHINE, + namespace: 'other', + sid: session.id, + pid: PID, + processStartMarker: START_MARKER, + time: Date.now() + })).toBe(false) + expect(engine.getSession(session.id)?.active).toBe(true) + } finally { + engine.stop() + } + }) + + it('is a no-op for an already inactive session', () => { + const { engine, events } = createEngine() + try { + registerMachine(engine) + const session = createOwnedSession(engine, 'child-exit-already-inactive') + + expect(engine.getSession(session.id)?.active).toBe(false) + expect(engine.handleSessionChildExited({ + machineId: MACHINE, + namespace: NAMESPACE, + sid: session.id, + pid: PID, + processStartMarker: START_MARKER, + time: Date.now() + })).toBe(false) + expect(events.filter((event) => event.type === 'session-ended')).toHaveLength(0) + } finally { + engine.stop() + } + }) +}) diff --git a/hub/src/sync/syncEngine.ts b/hub/src/sync/syncEngine.ts index 4c8e6c6a..ba5ec2ca 100644 --- a/hub/src/sync/syncEngine.ts +++ b/hub/src/sync/syncEngine.ts @@ -908,6 +908,47 @@ export class SyncEngine { clearAgentTerminalBuffer(payload.sid) } + /** + * A runner reported that one of its child processes exited without the + * CLI's normal session-end handshake (crash, SIGKILL, OOM). Accept the + * notice only while the reported OS generation still owns the session, so + * a late notice about a replaced process cannot flip a session that was + * already resumed elsewhere. Accepted notices reuse the existing crash + * path: active/thinking clear immediately, the row stays unarchived and + * resumable, and no second lifecycle event fires for an already-ended row. + */ + handleSessionChildExited(payload: { + machineId: string + namespace: string + sid: string + pid: number + processStartMarker?: string + time: number + }): boolean { + const session = this.sessionCache.getSessionByNamespace(payload.sid, payload.namespace) + if (!session) return false + if (session.metadata?.machineId !== payload.machineId) return false + if (session.metadata?.hostPid !== payload.pid) return false + // A marker on either side binds the notice to one process generation: + // only an exact match proves the dying process is the registered owner. + // When BOTH sides lack a marker (the CLI's start-marker probe can fail), + // a pid-only match must still reject a notice older than the current + // owner's registration — a reused pid's late notice would otherwise + // deactivate the new owner. lifecycleStateSince is written by the CLI + // together with hostPid on every (re)spawn of the row. + const ownerStartMarker = session.metadata?.hostStartMarker + if (ownerStartMarker !== undefined || payload.processStartMarker !== undefined) { + if (ownerStartMarker !== payload.processStartMarker) return false + } else { + const ownerRegisteredAt = session.metadata?.lifecycleStateSince + if (ownerRegisteredAt === undefined || payload.time < ownerRegisteredAt) return false + } + if (!session.active && !session.thinking) return false + + this.handleSessionEnd({ sid: session.id, time: payload.time, reason: 'error' }) + return true + } + handleBackgroundTasks(sessionId: string, tasks: BackgroundTask[]): void { this.sessionCache.setBackgroundTasks(sessionId, tasks) } diff --git a/shared/src/socket.ts b/shared/src/socket.ts index 06523808..27471ec6 100644 --- a/shared/src/socket.ts +++ b/shared/src/socket.ts @@ -273,6 +273,19 @@ export interface ClientToServerEvents { /** CLI agent finished session/load (or equivalent) and can accept prompts. */ 'session-ready': (data: { sid: string; time: number }) => void 'session-end': (data: { sid: string; time: number; reason?: SessionEndReason }) => void + /** + * Machine-scoped notice that a runner's child process for a HAPI session + * exited without going through the normal session-end handshake (crash, + * SIGKILL, OOM, ...). The hub only acts when this pid + process start + * marker still identify the session's current owner. + */ + 'session-child-exited': (data: { + machineId: string + sid: string + pid: number + processStartMarker?: string + time: number + }) => void 'messages-consumed': (data: { sid: string; localIds: string[]; clearQueuedThinkingGrace?: boolean; steered?: boolean }) => void 'messages-indeterminate': (data: { sid: string; localIds: string[] }) => void /** Native shared-engine queue projection. null = positively acknowledged removal. */