Files
opencode-manager/backend/test/services/opencode-supervisor.test.ts

515 lines
18 KiB
TypeScript

import { afterAll, beforeEach, beforeAll, describe, expect, it, vi } from 'vitest'
import fs from 'node:fs'
import path from 'node:path'
import { getOpenCodeConfigFilePath, getOpenCodeHealthWatchPath } from '@opencode-manager/shared/config/env'
import { OPENCODE_CONFIG_SEED, readOpenCodeConfigFile } from '../../src/services/opencode-config-file'
import { OpenCodeSupervisor, type OpenCodeSupervisorManager } from '../../src/services/opencode-supervisor'
import { SettingsService } from '../../src/services/settings'
import { createTestDatabase } from '../helpers/test-database'
import { createTempWorkspace, type TempWorkspace } from '../helpers/test-env'
const LAST_KNOWN_GOOD = JSON.stringify({ $schema: 'https://opencode.ai/config.json', theme: 'tokyo' })
const BROKEN_CONFIG = '{ "invalid": '
function writeBrokenConfigFile(): void {
fs.mkdirSync(path.dirname(getOpenCodeConfigFilePath()), { recursive: true })
fs.writeFileSync(getOpenCodeConfigFilePath(), BROKEN_CONFIG, 'utf-8')
}
function readConfigText(): string | null {
try {
return fs.readFileSync(getOpenCodeConfigFilePath(), 'utf-8')
} catch {
return null
}
}
async function readConfigContent() {
const config = await readOpenCodeConfigFile()
return config?.content ?? null
}
function healthArtifacts(prefix: string): string[] {
try {
return fs.readdirSync(getOpenCodeHealthWatchPath()).filter((name) => name.startsWith(prefix))
} catch {
return []
}
}
function createManager() {
return {
start: vi.fn<OpenCodeSupervisorManager['start']>(async () => undefined),
stop: vi.fn<OpenCodeSupervisorManager['stop']>(async () => undefined),
isOperationInProgress: vi.fn<OpenCodeSupervisorManager['isOperationInProgress']>(() => false),
checkHealth: vi.fn<OpenCodeSupervisorManager['checkHealth']>(async () => true),
restart: vi.fn<OpenCodeSupervisorManager['restart']>(async () => undefined),
clearStartupError: vi.fn<OpenCodeSupervisorManager['clearStartupError']>(() => undefined),
getLastStartupError: vi.fn<OpenCodeSupervisorManager['getLastStartupError']>(() => null),
isLastStartupErrorNonRecoverable: vi.fn<OpenCodeSupervisorManager['isLastStartupErrorNonRecoverable']>(() => false),
setLifecycleInitialized: vi.fn<OpenCodeSupervisorManager['setLifecycleInitialized']>(() => undefined),
getPort: vi.fn<OpenCodeSupervisorManager['getPort']>(() => 5551),
getVersion: vi.fn<OpenCodeSupervisorManager['getVersion']>(() => '2.0.15'),
getMinVersion: vi.fn<OpenCodeSupervisorManager['getMinVersion']>(() => '2.0.15'),
isVersionSupported: vi.fn<OpenCodeSupervisorManager['isVersionSupported']>(() => true),
}
}
describe('OpenCodeSupervisor', () => {
let workspace: TempWorkspace
let previousLogLevel: string | undefined
let settings: SettingsService
beforeAll(() => {
workspace = createTempWorkspace('ocm-opencode-supervisor-')
previousLogLevel = process.env.LOG_LEVEL
process.env.LOG_LEVEL = 'error'
})
afterAll(() => {
workspace.restore()
if (previousLogLevel === undefined) delete process.env.LOG_LEVEL
else process.env.LOG_LEVEL = previousLogLevel
})
beforeEach(() => {
const db = createTestDatabase()
settings = new SettingsService(db)
fs.rmSync(getOpenCodeHealthWatchPath(), { recursive: true, force: true })
fs.rmSync(path.dirname(getOpenCodeConfigFilePath()), { recursive: true, force: true })
})
it('recovers a startup failure through rollback and keeps watching', async () => {
const manager = createManager()
settings.saveLastKnownGoodConfig(LAST_KNOWN_GOOD)
writeBrokenConfigFile()
const supervisor = new OpenCodeSupervisor(manager, settings, {
failureThreshold: 1,
watchEnabled: true,
pollIntervalMs: 60_000,
})
manager.start.mockRejectedValueOnce(new Error('startup failed'))
manager.checkHealth
.mockResolvedValueOnce(false)
.mockResolvedValueOnce(false)
.mockResolvedValueOnce(true)
const status = await supervisor.start()
expect(status.healthy).toBe(true)
expect(status.state).toBe('healthy')
expect(manager.restart).toHaveBeenCalledTimes(3)
expect(healthArtifacts('opencode-config-broken')).not.toHaveLength(0)
expect(await readConfigContent()).toEqual(JSON.parse(LAST_KNOWN_GOOD))
expect(status.watching).toBe(true)
await supervisor.stop()
})
it('seeds the default config when the recovery ladder reaches the seed action', async () => {
const manager = createManager()
settings.saveLastKnownGoodConfig(LAST_KNOWN_GOOD)
writeBrokenConfigFile()
const supervisor = new OpenCodeSupervisor(manager, settings, {
failureThreshold: 1,
watchEnabled: false,
})
manager.start.mockRejectedValueOnce(new Error('startup failed'))
manager.checkHealth.mockResolvedValue(false)
const status = await supervisor.start()
expect(status.state).toBe('failed')
expect(healthArtifacts('opencode-config-broken')).not.toHaveLength(0)
expect(await readConfigContent()).toEqual(JSON.parse(OPENCODE_CONFIG_SEED))
await supervisor.stop()
})
it('opens the proxy lifecycle gate when the managed child is attested healthy', async () => {
const manager = createManager()
const supervisor = new OpenCodeSupervisor(manager, settings, {
failureThreshold: 1,
watchEnabled: false,
})
await supervisor.start()
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
})
it('keeps the proxy lifecycle gate closed when startup fails non-recoverably', async () => {
const manager = createManager()
const supervisor = new OpenCodeSupervisor(manager, settings, {
failureThreshold: 1,
watchEnabled: false,
})
manager.start.mockRejectedValueOnce(new Error('OpenCode version 1.18.15 does not support sandboxed bash tool rewriting'))
manager.isLastStartupErrorNonRecoverable.mockReturnValue(true)
const status = await supervisor.start()
expect(status.healthy).toBe(false)
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(false)
})
it('closes the proxy lifecycle gate when recovery is exhausted and reopens it once health returns', async () => {
const manager = createManager()
const supervisor = new OpenCodeSupervisor(manager, settings, {
failureThreshold: 1,
watchEnabled: false,
})
manager.start.mockRejectedValueOnce(new Error('startup failed'))
manager.checkHealth
.mockResolvedValueOnce(false)
.mockResolvedValueOnce(false)
.mockResolvedValueOnce(false)
.mockResolvedValueOnce(false)
.mockResolvedValueOnce(true)
const failed = await supervisor.start()
expect(failed.healthy).toBe(false)
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(false)
const recovered = await supervisor.checkNow('manual')
expect(recovered.healthy).toBe(true)
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
await supervisor.stop()
})
it('does not recover polling failures until the threshold is reached', async () => {
const manager = createManager()
const supervisor = new OpenCodeSupervisor(manager, settings, {
failureThreshold: 2,
watchEnabled: false,
})
manager.checkHealth.mockResolvedValueOnce(false)
const status = await supervisor.checkNow('manual')
expect(status.state).toBe('unhealthy')
expect(status.failureCount).toBe(1)
expect(manager.restart).not.toHaveBeenCalled()
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(false)
})
it('closes the proxy lifecycle gate on a below-threshold health failure and reopens it once health returns', async () => {
const manager = createManager()
const supervisor = new OpenCodeSupervisor(manager, settings, {
failureThreshold: 2,
watchEnabled: false,
})
await supervisor.start()
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
manager.checkHealth.mockResolvedValueOnce(false)
const unhealthy = await supervisor.checkNow('manual')
expect(unhealthy.state).toBe('unhealthy')
expect(unhealthy.failureCount).toBe(1)
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(false)
expect(manager.restart).not.toHaveBeenCalled()
manager.checkHealth.mockResolvedValueOnce(true)
const recovered = await supervisor.checkNow('manual')
expect(recovered.healthy).toBe(true)
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
})
it('captures debug state before debug recovery', async () => {
const manager = createManager()
const supervisor = new OpenCodeSupervisor(manager, settings, {
failureThreshold: 1,
watchEnabled: false,
})
manager.checkHealth
.mockResolvedValueOnce(false)
.mockResolvedValueOnce(false)
.mockResolvedValueOnce(true)
const status = await supervisor.checkNow('manual')
expect(status.healthy).toBe(true)
expect(healthArtifacts('opencode-health')).not.toHaveLength(0)
expect(manager.restart).toHaveBeenCalledTimes(2)
})
it('skips checks while OpenCode manager is busy', async () => {
const manager = createManager()
const supervisor = new OpenCodeSupervisor(manager, settings)
manager.isOperationInProgress.mockReturnValue(true)
await supervisor.checkNow('manual')
expect(manager.checkHealth).not.toHaveBeenCalled()
})
it('does not run configuration recovery for a non-recoverable startup failure', async () => {
const manager = createManager()
writeBrokenConfigFile()
const supervisor = new OpenCodeSupervisor(manager, settings, {
failureThreshold: 1,
})
manager.start.mockRejectedValueOnce(new Error('OpenCode version 1.18.15 does not support sandboxed bash tool rewriting'))
manager.isLastStartupErrorNonRecoverable.mockReturnValue(true)
const status = await supervisor.start()
expect(status.state).toBe('failed')
expect(status.healthy).toBe(false)
expect(status.lastError).toContain('does not support sandboxed bash tool rewriting')
expect(manager.restart).not.toHaveBeenCalled()
expect(healthArtifacts('opencode-config-broken')).toHaveLength(0)
expect(healthArtifacts('opencode-health')).toHaveLength(0)
expect(readConfigText()).toBe(BROKEN_CONFIG)
await supervisor.stop()
})
it('does not run configuration recovery when a manual restart fails non-recoverably', async () => {
const manager = createManager()
writeBrokenConfigFile()
const supervisor = new OpenCodeSupervisor(manager, settings, {
failureThreshold: 1,
})
manager.restart.mockRejectedValueOnce(new Error('Failed to install a generated OpenCode plugin; refusing to start an enforced server'))
manager.isLastStartupErrorNonRecoverable.mockReturnValue(true)
const status = await supervisor.restart('settings_restart')
expect(status.state).toBe('failed')
expect(healthArtifacts('opencode-config-broken')).toHaveLength(0)
expect(healthArtifacts('opencode-health')).toHaveLength(0)
expect(readConfigText()).toBe(BROKEN_CONFIG)
await supervisor.stop()
})
it('stops the recovery ladder when a recovery restart fails non-recoverably', async () => {
const manager = createManager()
writeBrokenConfigFile()
const supervisor = new OpenCodeSupervisor(manager, settings, {
failureThreshold: 1,
})
manager.start.mockRejectedValueOnce(new Error('startup failed'))
manager.checkHealth.mockResolvedValue(false)
manager.restart.mockImplementation(async () => {
manager.isLastStartupErrorNonRecoverable.mockReturnValue(true)
throw new Error('Failed to install a generated OpenCode plugin; refusing to start an enforced server')
})
const status = await supervisor.start()
expect(status.state).toBe('failed')
expect(status.lastError).toContain('Failed to install a generated OpenCode plugin')
expect(manager.restart).toHaveBeenCalledTimes(1)
expect(healthArtifacts('opencode-config-broken')).toHaveLength(0)
expect(healthArtifacts('opencode-health')).toHaveLength(0)
expect(readConfigText()).toBe(BROKEN_CONFIG)
await supervisor.stop()
})
it('still follows the normal recovery ladder for a recoverable startup failure', async () => {
const manager = createManager()
settings.saveLastKnownGoodConfig(LAST_KNOWN_GOOD)
writeBrokenConfigFile()
const supervisor = new OpenCodeSupervisor(manager, settings, {
failureThreshold: 1,
})
manager.start.mockRejectedValueOnce(new Error('OpenCode config validation failed: command.review: Invalid'))
manager.checkHealth
.mockResolvedValueOnce(false)
.mockResolvedValueOnce(false)
.mockResolvedValueOnce(true)
const status = await supervisor.start()
expect(status.state).toBe('healthy')
expect(healthArtifacts('opencode-config-broken')).not.toHaveLength(0)
expect(await readConfigContent()).toEqual(JSON.parse(LAST_KNOWN_GOOD))
await supervisor.stop()
})
it('executes a restart requested during an active restart after the active restart completes', async () => {
const manager = createManager()
const supervisor = new OpenCodeSupervisor(manager, settings, {
failureThreshold: 1,
watchEnabled: false,
})
let releaseRestart!: () => void
manager.restart.mockImplementationOnce(
() => new Promise<void>((resolve) => { releaseRestart = resolve }),
)
manager.checkHealth.mockResolvedValue(true)
const first = supervisor.restart('settings_restart')
await vi.waitFor(() => expect(manager.restart).toHaveBeenCalledTimes(1))
const second = supervisor.restart('manual')
await new Promise((resolve) => setTimeout(resolve, 20))
expect(manager.restart).toHaveBeenCalledTimes(1)
releaseRestart()
const [firstStatus, secondStatus] = await Promise.all([first, second])
expect(manager.restart).toHaveBeenCalledTimes(2)
expect(firstStatus.healthy).toBe(true)
expect(secondStatus.healthy).toBe(true)
})
it('closes the proxy lifecycle gate for the whole restart transition and reopens once healthy', async () => {
const manager = createManager()
const supervisor = new OpenCodeSupervisor(manager, settings, {
failureThreshold: 1,
watchEnabled: false,
})
await supervisor.start()
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
let releaseRestart!: () => void
manager.restart.mockImplementationOnce(
() => new Promise<void>((resolve) => { releaseRestart = resolve }),
)
manager.checkHealth.mockResolvedValue(true)
const restart = supervisor.restart('settings_restart')
await vi.waitFor(() => expect(manager.restart).toHaveBeenCalledTimes(1))
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(false)
releaseRestart()
const status = await restart
expect(status.healthy).toBe(true)
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
})
it('closes the proxy lifecycle gate while stopping and never reopens it', async () => {
const manager = createManager()
const supervisor = new OpenCodeSupervisor(manager, settings, {
failureThreshold: 1,
watchEnabled: false,
})
await supervisor.start()
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
let releaseStop!: () => void
manager.stop.mockImplementationOnce(
() => new Promise<void>((resolve) => { releaseStop = resolve }),
)
const stopPromise = supervisor.stop()
await vi.waitFor(() => expect(manager.stop).toHaveBeenCalledTimes(1))
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(false)
releaseStop()
await stopPromise
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(false)
})
it('closes the proxy lifecycle gate while recovering a polling failure until health returns', async () => {
const manager = createManager()
const supervisor = new OpenCodeSupervisor(manager, settings, {
failureThreshold: 1,
watchEnabled: false,
})
await supervisor.start()
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
let releaseRestart!: () => void
manager.restart.mockImplementationOnce(
() => new Promise<void>((resolve) => { releaseRestart = resolve }),
)
manager.checkHealth.mockResolvedValueOnce(false)
const recovering = supervisor.checkNow('manual')
await vi.waitFor(() => expect(manager.restart).toHaveBeenCalledTimes(1))
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(false)
releaseRestart()
const status = await recovering
expect(status.healthy).toBe(true)
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
})
it('executes a stop requested during an active restart after the restart completes', async () => {
const manager = createManager()
const supervisor = new OpenCodeSupervisor(manager, settings, {
failureThreshold: 1,
watchEnabled: false,
})
let releaseRestart!: () => void
manager.restart.mockImplementationOnce(
() => new Promise<void>((resolve) => { releaseRestart = resolve }),
)
manager.checkHealth.mockResolvedValue(true)
const restart = supervisor.restart('manual')
await vi.waitFor(() => expect(manager.restart).toHaveBeenCalledTimes(1))
const stopPromise = supervisor.stop()
await new Promise((resolve) => setTimeout(resolve, 20))
expect(manager.stop).not.toHaveBeenCalled()
releaseRestart()
await Promise.all([restart, stopPromise])
expect(manager.restart).toHaveBeenCalledTimes(1)
expect(manager.stop).toHaveBeenCalledTimes(1)
})
it('drops a restart stacked behind an already queued restart but never drops a stop', async () => {
const manager = createManager()
const supervisor = new OpenCodeSupervisor(manager, settings, {
failureThreshold: 1,
watchEnabled: false,
})
let releaseRestart!: () => void
manager.restart.mockImplementationOnce(
() => new Promise<void>((resolve) => { releaseRestart = resolve }),
)
manager.checkHealth.mockResolvedValue(true)
const running = supervisor.restart('manual')
await vi.waitFor(() => expect(manager.restart).toHaveBeenCalledTimes(1))
const queued = supervisor.restart('manual')
const dropped = supervisor.restart('manual')
const stopPromise = supervisor.stop()
await expect(dropped).resolves.toMatchObject({ state: 'starting' })
releaseRestart()
await Promise.all([running, queued, stopPromise])
expect(manager.restart).toHaveBeenCalledTimes(2)
expect(manager.stop).toHaveBeenCalledTimes(1)
})
})