fix(opencode): harden supervised server startup failure diagnostics

This commit is contained in:
Chris Scott committed 2026-10-01 17:26:45 -04:00
1 parent 7e9afc3da4
commit e77badb444
2 files changed
+532 -30

No files matched your search

+188 -30
View File
@@ -1,6 +1,7 @@
import { spawn, execSync, spawnSync } from 'child_process'
import path from 'path'
import os from 'os'
import { StringDecoder } from 'node:string_decoder'
import { promises as fs, accessSync, constants } from 'fs'
import { logger } from '../utils/logger'
import { createGitIdentityEnv, resolveGitIdentity } from '../utils/git-auth'
@@ -49,6 +50,8 @@ import { OPENCODE_SERVICE_SERVE_ARGS, prepareOpenCodeServiceLaunch } from './ope
const MAX_STDERR_SIZE = 10240
const STARTUP_HEALTH_TIMEOUT_MS = 30000
const HEALTH_POLL_INTERVAL_MS = 500
const CHILD_EXIT_DIAGNOSTIC_DRAIN_MS = 1000
const PROCESS_SIGTERM_GRACE_MS = 10000
const PROCESS_SIGKILL_CONFIRM_MS = 2000
const PROCESS_EXIT_POLL_MS = 50
@@ -152,6 +155,48 @@ async function readProcessGroupIdWithRetry(pid: number): Promise<number | null>
return null
}
type AbortRaceOutcome<T> = { completed: true; value: T } | { completed: false }
function raceWithAbort<T>(promise: Promise<T>, signal: AbortSignal): Promise<AbortRaceOutcome<T>> {
if (signal.aborted) {
return Promise.resolve({ completed: false })
}
return new Promise<AbortRaceOutcome<T>>((resolve, reject) => {
const onAbort = () => {
signal.removeEventListener('abort', onAbort)
resolve({ completed: false })
}
signal.addEventListener('abort', onAbort, { once: true })
promise.then(
(value) => {
signal.removeEventListener('abort', onAbort)
resolve({ completed: true, value })
},
(error) => {
signal.removeEventListener('abort', onAbort)
reject(error)
},
)
})
}
function waitForPollInterval(signal: AbortSignal, ms: number): Promise<boolean> {
if (signal.aborted) {
return Promise.resolve(false)
}
return new Promise<boolean>((resolve) => {
const timer = setTimeout(() => {
signal.removeEventListener('abort', onAbort)
resolve(true)
}, ms)
function onAbort() {
clearTimeout(timer)
resolve(false)
}
signal.addEventListener('abort', onAbort, { once: true })
})
}
function readDurableRestartGeneration(db: Database | null): number {
if (!db) return 0
try {
@@ -259,6 +304,8 @@ class OpenCodeServerManager {
private sandboxEnforced: boolean = false
private lifecycleInitialized: boolean = false
private markerRefreshTimer: ReturnType<typeof setInterval> | null = null
private processGeneration = 0
private intentionalStop: { pid: number; generation: number } | null = null
private constructor() {}
@@ -565,6 +612,13 @@ class OpenCodeServerManager {
const openCodeExecutable = resolveOpenCodeExecutable() ?? 'opencode'
let stderrOutput = ''
const stderrDecoder = new StringDecoder('utf8')
const appendStderrOutput = (chunk: string) => {
stderrOutput += chunk
if (stderrOutput.length > MAX_STDERR_SIZE) {
stderrOutput = stderrOutput.slice(-MAX_STDERR_SIZE)
}
}
const microsandboxEnv = resolveManagerMicrosandboxEnv()
@@ -624,15 +678,89 @@ class OpenCodeServerManager {
const openCodeStdoutLog = createProcessLogForwarder({ source: 'opencode', defaultLevel: 'info' })
const openCodeStderrLog = createProcessLogForwarder({ source: 'opencode', defaultLevel: 'error' })
const spawnedServerPid = this.serverProcess.pid
const spawnedServerStderr = this.serverProcess.stderr
const spawnedGeneration = ++this.processGeneration
const childExitController = new AbortController()
let spawnedProcessExitError: string | null = null
let stderrEnded = false
let stderrDecoderFlushed = false
let exitDiagnosticFinalized = false
let exitDiagnosticCode: number | null = null
let exitDiagnosticSignal: NodeJS.Signals | null = null
let exitDiagnosticExitedBeforeHealthy = false
let exitDiagnosticIntentionalStop = false
let exitDiagnosticDrainTimer: ReturnType<typeof setTimeout> | null = null
let exitDiagnosticDrainResolve: (() => void) | null = null
const flushStderrDecoder = () => {
if (stderrDecoderFlushed) return
stderrDecoderFlushed = true
appendStderrOutput(stderrDecoder.end())
}
const clearExitDiagnosticDrainTimer = () => {
if (exitDiagnosticDrainTimer !== null) {
clearTimeout(exitDiagnosticDrainTimer)
exitDiagnosticDrainTimer = null
}
}
const finalizeExitDiagnostic = (message: string | null) => {
if (exitDiagnosticFinalized) return
exitDiagnosticFinalized = true
clearExitDiagnosticDrainTimer()
if (message !== null) {
spawnedProcessExitError = message
if (this.processGeneration === spawnedGeneration) {
this.recordStartupError(message)
}
}
const resolve = exitDiagnosticDrainResolve
exitDiagnosticDrainResolve = null
if (resolve) resolve()
}
const buildExitDiagnostic = (): string | null => {
if (exitDiagnosticIntentionalStop) return null
if (exitDiagnosticCode !== null && exitDiagnosticCode !== 0) {
return `OpenCode server exited with code ${exitDiagnosticCode}${stderrOutput ? `: ${stderrOutput.slice(-500)}` : ''}`
}
if (exitDiagnosticSignal !== null) {
return `OpenCode server terminated by signal ${exitDiagnosticSignal}`
}
if (exitDiagnosticExitedBeforeHealthy) {
return 'OpenCode server exited with code 0 before becoming healthy'
}
return null
}
const finalizeExitDiagnosticFromState = () => {
flushStderrDecoder()
finalizeExitDiagnostic(buildExitDiagnostic())
}
const awaitExitDiagnostic = (): Promise<void> => {
if (exitDiagnosticFinalized) return Promise.resolve()
return new Promise<void>((resolve) => {
exitDiagnosticDrainResolve = resolve
})
}
this.serverProcess.stderr?.on('data', (data) => {
if (isDevelopment) process.stderr.write(data)
stderrOutput += data.toString()
if (stderrOutput.length > MAX_STDERR_SIZE) {
stderrOutput = stderrOutput.slice(-MAX_STDERR_SIZE)
}
appendStderrOutput(stderrDecoder.write(data))
openCodeStderrLog.write(data)
})
this.serverProcess.stderr?.on('end', () => openCodeStderrLog.flush())
this.serverProcess.stderr?.on('end', () => {
stderrEnded = true
flushStderrDecoder()
openCodeStderrLog.flush()
if (childExitController.signal.aborted) {
finalizeExitDiagnosticFromState()
}
})
this.serverProcess.stdout?.on('data', (data) => {
if (isDevelopment) process.stdout.write(data)
@@ -640,30 +768,46 @@ class OpenCodeServerManager {
})
this.serverProcess.stdout?.on('end', () => openCodeStdoutLog.flush())
let spawnedProcessExitError: string | null = null
const recordSpawnedProcessExit = (message: string) => {
spawnedProcessExitError = message
this.recordStartupError(message)
}
this.serverProcess.on('error', (error) => {
recordSpawnedProcessExit(`Failed to launch the OpenCode server (${openCodeExecutable}): ${error.message}`)
childExitController.abort()
finalizeExitDiagnostic(`Failed to launch the OpenCode server (${openCodeExecutable}): ${error.message}`)
})
const spawnedServerPid = this.serverProcess.pid
this.serverProcess.on('exit', (code, signal) => {
childExitController.abort()
const exitedBeforeHealthy = !this.isHealthy
if (spawnedServerPid !== undefined && this.serverPid === spawnedServerPid) {
this.serverPid = null
this.isHealthy = false
this.stopChildStateMarkerRefresh()
}
if (code !== null && code !== 0) {
recordSpawnedProcessExit(`OpenCode server exited with code ${code}${stderrOutput ? `: ${stderrOutput.slice(-500)}` : ''}`)
} else if (signal) {
recordSpawnedProcessExit(`OpenCode server terminated by signal ${signal}`)
} else if (exitedBeforeHealthy) {
recordSpawnedProcessExit('OpenCode server exited with code 0 before becoming healthy')
exitDiagnosticCode = code
exitDiagnosticSignal = signal
exitDiagnosticExitedBeforeHealthy = exitedBeforeHealthy
const intentionalStop = this.intentionalStop
exitDiagnosticIntentionalStop = intentionalStop !== null
&& intentionalStop.pid === spawnedServerPid
&& intentionalStop.generation === spawnedGeneration
&& (signal === 'SIGTERM' || signal === 'SIGKILL' || code === 0)
if (exitDiagnosticFinalized) return
const hasDiagnostic = (code !== null && code !== 0) || signal !== null || exitedBeforeHealthy
if (!hasDiagnostic) {
finalizeExitDiagnostic(null)
return
}
if (spawnedServerStderr == null || stderrEnded) {
finalizeExitDiagnosticFromState()
return
}
exitDiagnosticDrainTimer = setTimeout(() => {
exitDiagnosticDrainTimer = null
finalizeExitDiagnosticFromState()
}, CHILD_EXIT_DIAGNOSTIC_DRAIN_MS)
})
this.serverProcess.on('close', () => {
if (childExitController.signal.aborted) {
finalizeExitDiagnosticFromState()
}
})
@@ -706,8 +850,11 @@ class OpenCodeServerManager {
logger.info(`OpenCode server started with PID ${this.serverPid}`)
const healthy = await this.waitForHealth(STARTUP_HEALTH_TIMEOUT_MS, () => spawnedProcessExitError !== null)
const healthy = await this.waitForHealth(STARTUP_HEALTH_TIMEOUT_MS, childExitController.signal)
if (!healthy) {
if (childExitController.signal.aborted) {
await awaitExitDiagnostic()
}
if (spawnedProcessExitError !== null) {
throw new Error(spawnedProcessExitError)
}
@@ -791,6 +938,7 @@ class OpenCodeServerManager {
if (groupTarget !== null) {
logger.info(`Terminating OpenCode process group ${groupTarget} so host-executed descendants do not survive the stop`)
}
this.intentionalStop = { pid, generation: this.processGeneration }
try {
await this.terminateAndConfirm(
pid,
@@ -799,6 +947,7 @@ class OpenCodeServerManager {
'retained live processes after SIGTERM and SIGKILL; refusing to complete the stop while host-executed processes may survive',
)
} catch (error) {
this.intentionalStop = null
this.isHealthy = false
throw error
}
@@ -908,13 +1057,15 @@ class OpenCodeServerManager {
advanceDurableRestartGeneration(this.db)
}
async checkHealth(): Promise<boolean> {
async checkHealth(signal?: AbortSignal): Promise<boolean> {
if (!this.openCodeClient) {
return false
}
const timeoutSignal = AbortSignal.timeout(ENV.TIMEOUTS.HEALTH_CHECK_TIMEOUT_MS)
const requestSignal = signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal
try {
await this.openCodeClient.api.server.info({
signal: AbortSignal.timeout(ENV.TIMEOUTS.HEALTH_CHECK_TIMEOUT_MS),
signal: requestSignal,
})
return true
} catch {
@@ -1144,16 +1295,23 @@ class OpenCodeServerManager {
}
}
private async waitForHealth(timeoutMs: number, hasProcessExited: () => boolean): Promise<boolean> {
const start = Date.now()
while (Date.now() - start < timeoutMs) {
if (await this.checkHealth()) {
return true
}
if (hasProcessExited()) {
private async waitForHealth(timeoutMs: number, exitSignal: AbortSignal): Promise<boolean> {
const deadline = Date.now() + timeoutMs
while (Date.now() < deadline) {
if (exitSignal.aborted) {
return false
}
const probe = await raceWithAbort(this.checkHealth(exitSignal), exitSignal)
if (exitSignal.aborted) {
return false
}
if (probe.completed && probe.value) {
return true
}
const polled = await waitForPollInterval(exitSignal, HEALTH_POLL_INTERVAL_MS)
if (!polled) {
return false
}
await new Promise(r => setTimeout(r, 500))
}
return false
}
@@ -727,6 +727,95 @@ describe('OpenCodeServerManager - server auth', () => {
expect(manager.getLastStartupError()).toBe('OpenCode server exited with code 1')
})
it('aborts an in-flight health probe and fails promptly when the child exits', async () => {
setOpenCodeEnv({ host: '127.0.0.1', password: 'envpassword123' })
let capturedSignal: AbortSignal | undefined
let emitExit: (code: number | null, signal: NodeJS.Signals | null) => void = () => {}
const info = vi.fn((options: { signal?: AbortSignal }) => {
capturedSignal = options.signal
queueMicrotask(() => emitExit(1, null))
return new Promise<never>(() => {})
})
createOpenCodeClientMock.mockImplementationOnce(() => ({
api: { server: { info } },
forwardRaw: vi.fn(),
}))
spawnMock.mockImplementationOnce(() => ({
pid: 1234,
stdout: null,
stderr: null,
on: vi.fn((event: string, handler: (code: number | null, signal: NodeJS.Signals | null) => void) => {
if (event === 'exit') emitExit = handler
}),
}))
const { OpenCodeServerManager } = await import('../../src/services/opencode-single-server')
const manager = OpenCodeServerManager.getInstance()
const startedAt = Date.now()
await expect(manager.start()).rejects.toThrow('OpenCode server exited with code 1')
expect(Date.now() - startedAt).toBeLessThan(5000)
expect(capturedSignal?.aborted).toBe(true)
expect(manager.getLastStartupError()).toBe('OpenCode server exited with code 1')
}, 15000)
it('marks the server healthy when a health probe succeeds while the child is still running', async () => {
setOpenCodeEnv({ host: '127.0.0.1', password: 'envpassword123' })
let capturedSignal: AbortSignal | undefined
const info = vi.fn(async (options: { signal?: AbortSignal }) => {
capturedSignal = options.signal
return { version: '2.0.15', pid: 1234, urls: ['http://127.0.0.1:5551'], paths: { tmp: '/tmp' } }
})
createOpenCodeClientMock.mockImplementationOnce(() => ({
api: { server: { info } },
forwardRaw: vi.fn(),
}))
spawnMock.mockImplementationOnce(() => ({
pid: 1234,
stdout: null,
stderr: null,
on: vi.fn(),
}))
const { OpenCodeServerManager } = await import('../../src/services/opencode-single-server')
const manager = OpenCodeServerManager.getInstance()
await manager.start()
expect(info).toHaveBeenCalledTimes(1)
expect(capturedSignal?.aborted).toBe(false)
expect(manager.getLastStartupError()).toBeNull()
}, 15000)
it('fails startup when a health probe succeeds only after the child has exited', async () => {
setOpenCodeEnv({ host: '127.0.0.1', password: 'envpassword123' })
let capturedSignal: AbortSignal | undefined
let emitExit: (code: number | null, signal: NodeJS.Signals | null) => void = () => {}
const info = vi.fn((options: { signal?: AbortSignal }) => {
capturedSignal = options.signal
queueMicrotask(() => emitExit(1, null))
return new Promise((resolve) => {
setTimeout(() => resolve({ version: '2.0.15', pid: 1234, urls: [], paths: { tmp: '/tmp' } }), 0)
})
})
createOpenCodeClientMock.mockImplementationOnce(() => ({
api: { server: { info } },
forwardRaw: vi.fn(),
}))
spawnMock.mockImplementationOnce(() => ({
pid: 1234,
stdout: null,
stderr: null,
on: vi.fn((event: string, handler: (code: number | null, signal: NodeJS.Signals | null) => void) => {
if (event === 'exit') emitExit = handler
}),
}))
const { OpenCodeServerManager } = await import('../../src/services/opencode-single-server')
const manager = OpenCodeServerManager.getInstance()
await expect(manager.start()).rejects.toThrow('OpenCode server exited with code 1')
expect(capturedSignal?.aborted).toBe(true)
expect(manager.getLastStartupError()).toBe('OpenCode server exited with code 1')
}, 15000)
it('records a launch failure when the OpenCode executable cannot be spawned', async () => {
setOpenCodeEnv({ host: '127.0.0.1', password: 'envpassword123' })
createOpenCodeClientMock.mockImplementationOnce(() => ({
@@ -1546,6 +1635,7 @@ describe('OpenCodeServerManager - server auth', () => {
expect(messages.filter((message) => message === 'partial tail FINAL')).toHaveLength(1)
expect((manager as any).serverPid).toBeNull()
expect(manager.getLastStartupError()).toContain('exited with code 1')
expect(manager.getLastStartupError()).toContain('partial tail FINAL')
} finally {
readFileSyncMock.mockReset()
readdirSyncMock.mockReset()
@@ -1553,6 +1643,133 @@ describe('OpenCodeServerManager - server auth', () => {
}
}, 15000)
it('preserves a split multibyte UTF-8 character in the startup stderr diagnostic tail', async () => {
const { manager, stderr, emitExit, cleanup } = await captureSpawnedServerStderrStream()
try {
const encoded = Buffer.from('Fatal: café', 'utf8')
const accentByteIndex = encoded.length - 1
stderr.emit('data', encoded.subarray(0, accentByteIndex))
stderr.emit('data', encoded.subarray(accentByteIndex))
stderr.emit('end')
emitExit(1)
const startupError = manager.getLastStartupError()
expect(startupError).toContain('Fatal: café')
expect(startupError).not.toContain('\uFFFD')
} finally {
cleanup()
}
}, 15000)
it('flushes an incomplete multibyte sequence when the stderr stream ends', async () => {
const { manager, stderr, emitExit, cleanup } = await captureSpawnedServerStderrStream()
try {
stderr.emit('data', Buffer.from([0xC3]))
stderr.emit('end')
emitExit(1)
expect(manager.getLastStartupError()).toContain('\uFFFD')
} finally {
cleanup()
}
}, 15000)
it('includes stderr that arrives after a startup crash exit in the startup diagnostic', async () => {
setOpenCodeEnv({ host: '127.0.0.1', password: 'envpassword123' })
createOpenCodeClientMock.mockImplementationOnce(() => ({
api: { server: { info: vi.fn().mockRejectedValue(new Error('connection refused')) } },
forwardRaw: vi.fn(),
}))
const { EventEmitter } = await import('events')
const stderr = new EventEmitter()
spawnMock.mockImplementationOnce(() => ({
pid: 1234,
stdout: null,
stderr,
on: vi.fn((event: string, handler: (code: number | null, signal: NodeJS.Signals | null) => void) => {
if (event === 'exit') {
queueMicrotask(() => {
handler(1, null)
stderr.emit('data', Buffer.from('late startup crash detail'))
stderr.emit('end')
})
}
}),
}))
const { OpenCodeServerManager } = await import('../../src/services/opencode-single-server')
const manager = OpenCodeServerManager.getInstance()
await expect(manager.start()).rejects.toThrow('OpenCode server exited with code 1')
expect(manager.getLastStartupError()).toContain('late startup crash detail')
}, 15000)
it('finalizes the exit diagnostic after the drain bound when stderr never ends', async () => {
setOpenCodeEnv({ host: '127.0.0.1', password: 'envpassword123' })
createOpenCodeClientMock.mockImplementationOnce(() => ({
api: { server: { info: vi.fn().mockRejectedValue(new Error('connection refused')) } },
forwardRaw: vi.fn(),
}))
const { EventEmitter } = await import('events')
const stderr = new EventEmitter()
spawnMock.mockImplementationOnce(() => ({
pid: 1234,
stdout: null,
stderr,
on: vi.fn((event: string, handler: (code: number | null, signal: NodeJS.Signals | null) => void) => {
if (event === 'exit') {
queueMicrotask(() => {
handler(1, null)
stderr.emit('data', Buffer.from('drain bound detail'))
})
}
}),
}))
const { OpenCodeServerManager } = await import('../../src/services/opencode-single-server')
const manager = OpenCodeServerManager.getInstance()
vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] })
try {
const startPromise = manager.start()
startPromise.catch(() => {})
await vi.advanceTimersByTimeAsync(1000)
await expect(startPromise).rejects.toThrow('OpenCode server exited with code 1')
expect(manager.getLastStartupError()).toContain('drain bound detail')
} finally {
vi.useRealTimers()
}
}, 15000)
it('finalizes the exit diagnostic on child close when stderr never ends', async () => {
setOpenCodeEnv({ host: '127.0.0.1', password: 'envpassword123' })
createOpenCodeClientMock.mockImplementationOnce(() => ({
api: { server: { info: vi.fn().mockRejectedValue(new Error('connection refused')) } },
forwardRaw: vi.fn(),
}))
const { EventEmitter } = await import('events')
const stderr = new EventEmitter()
let closeHandler: (() => void) | undefined
spawnMock.mockImplementationOnce(() => ({
pid: 1234,
stdout: null,
stderr,
on: vi.fn((event: string, handler: (...args: unknown[]) => void) => {
if (event === 'close') closeHandler = handler as () => void
if (event === 'exit') {
queueMicrotask(() => {
handler(1, null)
stderr.emit('data', Buffer.from('close fallback detail'))
closeHandler?.()
})
}
}),
}))
const { OpenCodeServerManager } = await import('../../src/services/opencode-single-server')
const manager = OpenCodeServerManager.getInstance()
await expect(manager.start()).rejects.toThrow('OpenCode server exited with code 1')
expect(manager.getLastStartupError()).toContain('close fallback detail')
}, 15000)
it('reconciles an attested surviving descendant group before an unenforced replacement start', async () => {
const originalNodeEnv = ENV.SERVER.NODE_ENV
Object.defineProperty(ENV.SERVER, 'NODE_ENV', { value: 'production', configurable: true, writable: true })
@@ -2202,6 +2419,87 @@ describe('OpenCodeServerManager - server auth', () => {
}
}, 15000)
async function startProductionServerWithControllableExit() {
const originalNodeEnv = ENV.SERVER.NODE_ENV
Object.defineProperty(ENV.SERVER, 'NODE_ENV', { value: 'production', configurable: true, writable: true })
const killSpy = vi.spyOn(process, 'kill')
readFileMock.mockReset()
readdirSyncMock.mockReset()
sandboxRuntimeServiceMock.SandboxRuntimeService.mockImplementation(() => ({
isEnabled: () => false,
}))
execSyncMock.mockImplementation(() => {
throw new Error('not found')
})
readFileSyncMock.mockReturnValue(procStatStringWithGroup(1234, '42'))
killSpy.mockImplementation(((pid: number, signal?: number | string) => {
if (pid === -1234 && signal !== 0) return true
const error = new Error('No such process') as NodeJS.ErrnoException
error.code = 'ESRCH'
throw error
}) as typeof process.kill)
spawnMock.mockImplementationOnce(() => ({ pid: 1234, stdout: null, stderr: null, on: vi.fn() }))
const { OpenCodeServerManager } = await import('../../src/services/opencode-single-server')
const manager = OpenCodeServerManager.getInstance()
manager.setDatabase(createPasswordDb(null))
await manager.start()
const spawnedChild = spawnMock.mock.results[0]!.value as { on: ReturnType<typeof vi.fn> }
const exitCall = spawnedChild.on.mock.calls.find((call: unknown[]) => call[0] === 'exit')
expect(exitCall).toBeDefined()
return {
manager,
emitExit: (code: number | null, signal: NodeJS.Signals | null) => {
;(exitCall![1] as (code: number | null, signal: NodeJS.Signals | null) => void)(code, signal)
},
cleanup: () => {
killSpy.mockRestore()
Object.defineProperty(ENV.SERVER, 'NODE_ENV', { value: originalNodeEnv, configurable: true, writable: true })
},
}
}
it('does not record a deliberate SIGTERM stop as a startup failure', async () => {
const { manager, emitExit, cleanup } = await startProductionServerWithControllableExit()
try {
await manager.stop()
emitExit(null, 'SIGTERM')
expect(manager.getLastStartupError()).toBeNull()
} finally {
cleanup()
}
}, 15000)
it('records an unexpected SIGTERM exit as a startup failure', async () => {
const { manager, emitExit, cleanup } = await startProductionServerWithControllableExit()
try {
emitExit(null, 'SIGTERM')
expect(manager.getLastStartupError()).toContain('terminated by signal SIGTERM')
} finally {
cleanup()
}
}, 15000)
it('records a nonzero exit even while the manager is deliberately stopping the child', async () => {
const { manager, emitExit, cleanup } = await startProductionServerWithControllableExit()
try {
await manager.stop()
emitExit(1, null)
expect(manager.getLastStartupError()).toContain('exited with code 1')
} finally {
cleanup()
}
}, 15000)
it('adopts an existing healthy process in production when enforcement is off and the child state is attested as unenforced', async () => {
const originalNodeEnv = ENV.SERVER.NODE_ENV
Object.defineProperty(ENV.SERVER, 'NODE_ENV', { value: 'production', configurable: true, writable: true })
@@ -2948,6 +3246,52 @@ describe('OpenCodeServerManager - server auth', () => {
return `${pid} (opencode) ${fields.join(' ')}`
}
async function captureSpawnedServerStderrStream() {
const originalNodeEnv = ENV.SERVER.NODE_ENV
Object.defineProperty(ENV.SERVER, 'NODE_ENV', { value: 'production', configurable: true, writable: true })
sandboxRuntimeServiceMock.SandboxRuntimeService.mockImplementation(() => ({
isEnabled: () => false,
}))
execSyncMock.mockImplementation(() => {
throw new Error('not found')
})
readdirSyncMock.mockReturnValue([])
readFileSyncMock.mockImplementation((filePath: string) => {
if (String(filePath).includes('/proc/1234/stat')) return procStatStringWithGroup(1234, '42')
const error = new Error('No such process') as NodeJS.ErrnoException
error.code = 'ENOENT'
throw error
})
const { EventEmitter } = await import('events')
const stdout = new EventEmitter()
const stderr = new EventEmitter()
spawnMock.mockImplementationOnce(() => ({ pid: 1234, stdout, stderr, on: vi.fn() }))
const { OpenCodeServerManager } = await import('../../src/services/opencode-single-server')
const manager = OpenCodeServerManager.getInstance()
manager.setDatabase(createPasswordDb(null))
await manager.start()
const spawnedChild = spawnMock.mock.results[0]!.value as { pid: number; on: ReturnType<typeof vi.fn> }
const exitCall = spawnedChild.on.mock.calls.find((call: unknown[]) => call[0] === 'exit')
expect(exitCall).toBeDefined()
return {
manager,
stderr,
emitExit: (code: number) => {
;(exitCall![1] as (code: number | null, signal: NodeJS.Signals | null) => void)(code, null)
},
cleanup: () => {
readFileSyncMock.mockReset()
readdirSyncMock.mockReset()
Object.defineProperty(ENV.SERVER, 'NODE_ENV', { value: originalNodeEnv, configurable: true, writable: true })
},
}
}
const FAKE_SECRETS = Symbol('fakeSecrets')
function createAppSecretsFake(initial: Record<string, string> = {}) {