mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
feat(opencode): surface server startup and recovery failures in-app
This commit is contained in:
1 parent
53a70d8545
commit
7e9afc3da4
19 files changed
+454
-181
No files matched your search
@@ -606,8 +606,7 @@ class OpenCodeServerManager {
|
||||
await prepareOpenCodeServiceLaunch(serverEnv, password)
|
||||
} catch (error) {
|
||||
const message = `Failed to prepare the OpenCode service settings: ${error instanceof Error ? error.message : String(error)}`
|
||||
this.lastStartupError = message
|
||||
logger.error(message)
|
||||
this.recordStartupError(message)
|
||||
throw new Error(message)
|
||||
}
|
||||
|
||||
@@ -617,7 +616,7 @@ class OpenCodeServerManager {
|
||||
{
|
||||
cwd: openCodeServerDirectory,
|
||||
detached: !isDevelopment,
|
||||
stdio: isDevelopment ? 'inherit' : ['ignore', 'pipe', 'pipe'],
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
env: serverEnv,
|
||||
}
|
||||
)
|
||||
@@ -625,36 +624,46 @@ class OpenCodeServerManager {
|
||||
const openCodeStdoutLog = createProcessLogForwarder({ source: 'opencode', defaultLevel: 'info' })
|
||||
const openCodeStderrLog = createProcessLogForwarder({ source: 'opencode', defaultLevel: 'error' })
|
||||
|
||||
if (!isDevelopment && this.serverProcess.stderr) {
|
||||
this.serverProcess.stderr.on('data', (data) => {
|
||||
const text = data.toString()
|
||||
stderrOutput += text
|
||||
if (stderrOutput.length > MAX_STDERR_SIZE) {
|
||||
stderrOutput = stderrOutput.slice(-MAX_STDERR_SIZE)
|
||||
}
|
||||
openCodeStderrLog.write(data)
|
||||
})
|
||||
this.serverProcess.stderr.on('end', () => openCodeStderrLog.flush())
|
||||
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)
|
||||
}
|
||||
openCodeStderrLog.write(data)
|
||||
})
|
||||
this.serverProcess.stderr?.on('end', () => openCodeStderrLog.flush())
|
||||
|
||||
this.serverProcess.stdout?.on('data', (data) => {
|
||||
if (isDevelopment) process.stdout.write(data)
|
||||
openCodeStdoutLog.write(data)
|
||||
})
|
||||
this.serverProcess.stdout?.on('end', () => openCodeStdoutLog.flush())
|
||||
|
||||
let spawnedProcessExitError: string | null = null
|
||||
const recordSpawnedProcessExit = (message: string) => {
|
||||
spawnedProcessExitError = message
|
||||
this.recordStartupError(message)
|
||||
}
|
||||
|
||||
if (!isDevelopment && this.serverProcess.stdout) {
|
||||
this.serverProcess.stdout.on('data', (data) => openCodeStdoutLog.write(data))
|
||||
this.serverProcess.stdout.on('end', () => openCodeStdoutLog.flush())
|
||||
}
|
||||
this.serverProcess.on('error', (error) => {
|
||||
recordSpawnedProcessExit(`Failed to launch the OpenCode server (${openCodeExecutable}): ${error.message}`)
|
||||
})
|
||||
|
||||
const spawnedServerPid = this.serverProcess.pid
|
||||
this.serverProcess.on('exit', (code, signal) => {
|
||||
const exitedBeforeHealthy = !this.isHealthy
|
||||
if (spawnedServerPid !== undefined && this.serverPid === spawnedServerPid) {
|
||||
this.serverPid = null
|
||||
this.isHealthy = false
|
||||
this.stopChildStateMarkerRefresh()
|
||||
}
|
||||
if (code !== null && code !== 0) {
|
||||
this.lastStartupError = `Server exited with code ${code}${stderrOutput ? `: ${stderrOutput.slice(-500)}` : ''}`
|
||||
logger.error('OpenCode server process exited:', this.lastStartupError)
|
||||
recordSpawnedProcessExit(`OpenCode server exited with code ${code}${stderrOutput ? `: ${stderrOutput.slice(-500)}` : ''}`)
|
||||
} else if (signal) {
|
||||
this.lastStartupError = `Server terminated by signal ${signal}`
|
||||
logger.error('OpenCode server process terminated:', this.lastStartupError)
|
||||
recordSpawnedProcessExit(`OpenCode server terminated by signal ${signal}`)
|
||||
} else if (exitedBeforeHealthy) {
|
||||
recordSpawnedProcessExit('OpenCode server exited with code 0 before becoming healthy')
|
||||
}
|
||||
})
|
||||
|
||||
@@ -667,8 +676,7 @@ class OpenCodeServerManager {
|
||||
const startToken = await readProcessStartTokenWithRetry(this.serverPid)
|
||||
if (startToken === null) {
|
||||
const message = 'Failed to read the process identity of the freshly spawned OpenCode server; refusing to detach an unattestable child'
|
||||
this.lastStartupError = message
|
||||
logger.error(message)
|
||||
this.recordStartupError(message)
|
||||
await this.stop(true)
|
||||
throw new Error(message)
|
||||
}
|
||||
@@ -687,8 +695,7 @@ class OpenCodeServerManager {
|
||||
})
|
||||
} catch (error) {
|
||||
const message = `Failed to persist the OpenCode child state marker: ${error instanceof Error ? error.message : String(error)}`
|
||||
this.lastStartupError = message
|
||||
logger.error(message)
|
||||
this.recordStartupError(message)
|
||||
await this.stop(true)
|
||||
throw new Error(message)
|
||||
}
|
||||
@@ -699,10 +706,14 @@ class OpenCodeServerManager {
|
||||
|
||||
logger.info(`OpenCode server started with PID ${this.serverPid}`)
|
||||
|
||||
const healthy = await this.waitForHealth(STARTUP_HEALTH_TIMEOUT_MS)
|
||||
const healthy = await this.waitForHealth(STARTUP_HEALTH_TIMEOUT_MS, () => spawnedProcessExitError !== null)
|
||||
if (!healthy) {
|
||||
this.lastStartupError = `Server failed to become healthy after ${Math.round(STARTUP_HEALTH_TIMEOUT_MS / 1000)}s${stderrOutput ? `. Last error: ${stderrOutput.slice(-500)}` : ''}`
|
||||
throw new Error('OpenCode server failed to become healthy')
|
||||
if (spawnedProcessExitError !== null) {
|
||||
throw new Error(spawnedProcessExitError)
|
||||
}
|
||||
const message = `OpenCode server failed to become healthy after ${Math.round(STARTUP_HEALTH_TIMEOUT_MS / 1000)}s${stderrOutput ? `. Last error: ${stderrOutput.slice(-500)}` : ''}`
|
||||
this.recordStartupError(message)
|
||||
throw new Error(message)
|
||||
}
|
||||
|
||||
if (sandboxEnforced || replacingExistingServer) {
|
||||
@@ -711,16 +722,14 @@ class OpenCodeServerManager {
|
||||
portOwners = await this.findProcessesByPort(openCodeServerPort)
|
||||
} catch (inspectionError) {
|
||||
const message = `Could not verify port ${openCodeServerPort} ownership after health; refusing to mark the server healthy: ${inspectionError instanceof Error ? inspectionError.message : String(inspectionError)}`
|
||||
this.lastStartupError = message
|
||||
logger.error(message)
|
||||
this.recordStartupError(message)
|
||||
await this.stop(true)
|
||||
throw new Error(message)
|
||||
}
|
||||
if (this.serverPid === null || !portOwners.some((proc) => proc.pid === this.serverPid)) {
|
||||
const owners = portOwners.length > 0 ? `; port ${openCodeServerPort} is owned by PID(s) ${portOwners.map((proc) => proc.pid).join(', ')}` : `; no process owns port ${openCodeServerPort}`
|
||||
const message = `The newly started OpenCode server (PID ${this.serverPid ?? 'unknown'}) does not own the OpenCode port${owners}; refusing to mark the server healthy`
|
||||
this.lastStartupError = message
|
||||
logger.error(message)
|
||||
this.recordStartupError(message)
|
||||
await this.stop(true)
|
||||
throw new Error(message)
|
||||
}
|
||||
@@ -866,10 +875,14 @@ class OpenCodeServerManager {
|
||||
this.lastStartupErrorNonRecoverable = false
|
||||
}
|
||||
|
||||
private failNonRecoverable(message: string): never {
|
||||
private recordStartupError(message: string): void {
|
||||
this.lastStartupError = message
|
||||
this.lastStartupErrorNonRecoverable = true
|
||||
logger.error(message)
|
||||
}
|
||||
|
||||
private failNonRecoverable(message: string): never {
|
||||
this.lastStartupErrorNonRecoverable = true
|
||||
this.recordStartupError(message)
|
||||
throw new NonRecoverableStartupError(message)
|
||||
}
|
||||
|
||||
@@ -973,8 +986,7 @@ class OpenCodeServerManager {
|
||||
const killed = await this.waitForProcessOrGroupExit(pid, groupTarget, PROCESS_SIGKILL_CONFIRM_MS)
|
||||
if (!killed) {
|
||||
const message = `${context} (PID ${pid}${groupTarget !== null ? `, process group ${groupTarget}` : ''}) ${failurePhrase}`
|
||||
this.lastStartupError = message
|
||||
logger.error(message)
|
||||
this.recordStartupError(message)
|
||||
throw new Error(message)
|
||||
}
|
||||
}
|
||||
@@ -996,8 +1008,7 @@ class OpenCodeServerManager {
|
||||
}
|
||||
if (survivors.length > 0) {
|
||||
const message = `Failed to terminate the existing OpenCode server process(es) on port ${getOpenCodeServerPort()}: PID(s) ${survivors.join(', ')} still own the port or retain live process-group members; refusing to spawn a new server`
|
||||
this.lastStartupError = message
|
||||
logger.error(message)
|
||||
this.recordStartupError(message)
|
||||
throw new Error(message)
|
||||
}
|
||||
}
|
||||
@@ -1039,8 +1050,7 @@ class OpenCodeServerManager {
|
||||
const currentMembers = resolveProcessIdentityProvider().readProcessGroupMembers(marker.pgid)
|
||||
if (currentMembers.length > 0 && !target.groupAttested) {
|
||||
const message = `Previous OpenCode server process (PID ${marker.pid}) has exited but process group ${marker.pgid} still exists and cannot be proven to belong to it; refusing to signal an unverified process group before starting an enforced server`
|
||||
this.lastStartupError = message
|
||||
logger.error(message)
|
||||
this.recordStartupError(message)
|
||||
throw new Error(message)
|
||||
}
|
||||
}
|
||||
@@ -1080,8 +1090,7 @@ class OpenCodeServerManager {
|
||||
if (currentMembers.length > 0) {
|
||||
if (!target.groupAttested || target.groupTarget === null) {
|
||||
const message = `Previous OpenCode server leader (PID ${marker.pid}) has exited but process group ${marker.pgid} still exists and cannot be proven to belong to it; refusing to replace the child state marker while live processes may survive`
|
||||
this.lastStartupError = message
|
||||
logger.error(message)
|
||||
this.recordStartupError(message)
|
||||
throw new Error(message)
|
||||
}
|
||||
logger.warn(
|
||||
@@ -1135,12 +1144,15 @@ class OpenCodeServerManager {
|
||||
}
|
||||
}
|
||||
|
||||
private async waitForHealth(timeoutMs: number): Promise<boolean> {
|
||||
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()) {
|
||||
return false
|
||||
}
|
||||
await new Promise(r => setTimeout(r, 500))
|
||||
}
|
||||
return false
|
||||
|
||||
@@ -4,28 +4,12 @@ import { ENV } from '@opencode-manager/shared/config/env'
|
||||
import { archiveBrokenOpenCodeConfigFile, writeHealthWatchArtifact } from './opencode-config-file'
|
||||
import { restoreLastKnownGoodOpenCodeConfig, seedOpenCodeConfigFile } from './opencode-config-apply'
|
||||
import type { OpenCodeServerManager } from './opencode-single-server'
|
||||
|
||||
export const OPENCODE_LIFECYCLE_STATES = [
|
||||
'idle',
|
||||
'starting',
|
||||
'healthy',
|
||||
'unhealthy',
|
||||
'recovering',
|
||||
'failed',
|
||||
'stopping',
|
||||
'stopped',
|
||||
] as const
|
||||
|
||||
export type OpenCodeLifecycleState = (typeof OPENCODE_LIFECYCLE_STATES)[number]
|
||||
|
||||
export const OPENCODE_RECOVERY_ACTIONS = [
|
||||
'restart',
|
||||
'debug_capture',
|
||||
'rollback_last_known_good',
|
||||
'seed_default_config',
|
||||
] as const
|
||||
|
||||
export type OpenCodeRecoveryAction = (typeof OPENCODE_RECOVERY_ACTIONS)[number]
|
||||
import {
|
||||
OPENCODE_RECOVERY_ACTIONS,
|
||||
type OpenCodeLifecycleState,
|
||||
type OpenCodeLifecycleStatus,
|
||||
type OpenCodeRecoveryAction,
|
||||
} from '@opencode-manager/shared/opencode'
|
||||
|
||||
const MAX_QUEUED_LIFECYCLE_OPERATIONS = 2
|
||||
|
||||
@@ -36,22 +20,6 @@ export type OpenCodeOperationReason =
|
||||
| 'settings_reload'
|
||||
| 'manual'
|
||||
|
||||
export interface OpenCodeLifecycleStatus {
|
||||
state: OpenCodeLifecycleState
|
||||
healthy: boolean
|
||||
port: number
|
||||
version: string | null
|
||||
minVersion: string
|
||||
versionSupported: boolean
|
||||
lastError: string | null
|
||||
activeRecoveryAction: OpenCodeRecoveryAction | null
|
||||
attemptedRecoveryActions: OpenCodeRecoveryAction[]
|
||||
nextRecoveryAction: OpenCodeRecoveryAction | null
|
||||
failureCount: number
|
||||
watching: boolean
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
interface OpenCodeSupervisorOptions {
|
||||
pollIntervalMs?: number
|
||||
failureThreshold?: number
|
||||
@@ -267,6 +235,7 @@ export class OpenCodeSupervisor {
|
||||
}
|
||||
|
||||
this.activeRecoveryAction = null
|
||||
logger.error(`OpenCode server failed after recovery actions [${this.attemptedRecoveryActions.join(', ')}]: ${this.lastError ?? 'unknown error'}`)
|
||||
this.setState('failed')
|
||||
this.openCodeServerManager.setLifecycleInitialized(false)
|
||||
return this.getStatus()
|
||||
|
||||
@@ -705,6 +705,48 @@ describe('OpenCodeServerManager - server auth', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('fails startup immediately with the exit reason when the spawned server exits before becoming healthy', async () => {
|
||||
setOpenCodeEnv({ host: '127.0.0.1', password: 'envpassword123' })
|
||||
createOpenCodeClientMock.mockImplementationOnce(() => ({
|
||||
api: { server: { info: vi.fn().mockRejectedValue(new Error('connection refused')) } },
|
||||
forwardRaw: vi.fn(),
|
||||
}))
|
||||
spawnMock.mockImplementationOnce(() => ({
|
||||
pid: 1234,
|
||||
stderr: null,
|
||||
on: vi.fn((event: string, handler: (code: number | null, signal: string | null) => void) => {
|
||||
if (event === 'exit') queueMicrotask(() => handler(1, null))
|
||||
}),
|
||||
}))
|
||||
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(manager.getLastStartupError()).toBe('OpenCode server exited with code 1')
|
||||
})
|
||||
|
||||
it('records a launch failure when the OpenCode executable cannot be spawned', async () => {
|
||||
setOpenCodeEnv({ host: '127.0.0.1', password: 'envpassword123' })
|
||||
createOpenCodeClientMock.mockImplementationOnce(() => ({
|
||||
api: { server: { info: vi.fn().mockRejectedValue(new Error('connection refused')) } },
|
||||
forwardRaw: vi.fn(),
|
||||
}))
|
||||
spawnMock.mockImplementationOnce(() => ({
|
||||
pid: undefined as unknown as number,
|
||||
stderr: null,
|
||||
on: vi.fn((event: string, handler: (error: Error) => void) => {
|
||||
if (event === 'error') queueMicrotask(() => handler(new Error('spawn opencode ENOENT')))
|
||||
}),
|
||||
}))
|
||||
const { OpenCodeServerManager } = await import('../../src/services/opencode-single-server')
|
||||
const manager = OpenCodeServerManager.getInstance()
|
||||
|
||||
await expect(manager.start()).rejects.toThrow('spawn opencode ENOENT')
|
||||
expect(manager.getLastStartupError()).toBe('Failed to launch the OpenCode server (opencode): spawn opencode ENOENT')
|
||||
})
|
||||
|
||||
it('honors a user-supplied HOME serverEnvVars entry while enforced', async () => {
|
||||
sandboxRuntimeServiceMock.SandboxRuntimeService.mockImplementation(() => ({
|
||||
isEnabled: () => true,
|
||||
|
||||
@@ -28,11 +28,15 @@ Each entry shows a timestamp, severity level, source, and message:
|
||||
|
||||
If entries were evicted before you opened the tab, a notice above the view reports how many earlier entries were dropped.
|
||||
|
||||
## OpenCode Server Issues
|
||||
|
||||
While the OpenCode server is unhealthy, recovering, or failed, a panel above the log stream shows the current failure reason (including the server's exit code and stderr tail when it crashed during startup) and the recovery actions already attempted. **Show errors only** switches the filters to errors from all sources, so the Manager's startup messages appear alongside the server's own output.
|
||||
|
||||
## Limits and Behavior
|
||||
|
||||
- The buffer is **in-memory** on the Manager backend and holds up to **2,000** entries (`DEFAULTS.LOGS.BUFFER_CAPACITY`). Older entries are evicted first.
|
||||
- Individual entries are truncated at **4,000** characters (`DEFAULTS.LOGS.MAX_ENTRY_LENGTH`).
|
||||
- The buffer is **cleared when the Manager process restarts**. When the frontend detects a backend restart it resets its view and re-polls from the start.
|
||||
- **Child-process capture is production-only.** In development the OpenCode server inherits the terminal, so only Manager lines appear in the tab.
|
||||
- OpenCode server stdout and stderr are captured in every mode; in development they are also mirrored to the terminal.
|
||||
- The frontend polls the backend every **3 seconds** (`DEFAULTS.LOGS.POLL_INTERVAL_MS`); backend pages are capped at 1,000 entries per response.
|
||||
- `docker-compose logs` remains the fallback for failures that happen **before** the Manager's HTTP server is up — nothing can be captured in-app at that point.
|
||||
@@ -53,6 +53,14 @@ The health-watch ladder is the only automatic repair path. When the supervised O
|
||||
|
||||
Because the ladder only runs after repeated failed health checks, a config file that fails validation but does not make the server unhealthy is left in place. Setting `OPENCODE_HEALTH_WATCH_ENABLED=false` disables the ladder entirely, leaving no automatic repair path.
|
||||
|
||||
## Failure Reporting
|
||||
|
||||
When startup fails without a recovery path, or every recovery action has been tried, the server enters the **failed** state:
|
||||
|
||||
- A persistent error toast shows the failure reason, with **View logs** (opens Settings → Logs) and **Restart** actions. It appears once per distinct failure, including when the app is opened while the server is already failed, and is replaced by a "back online" notice once the server is healthy again. Transient unhealthy or recovering states do not toast.
|
||||
- The Settings → Logs tab shows the failure reason and the recovery actions already attempted above the log stream.
|
||||
- A server process that exits or cannot be launched (for example, a missing executable) fails startup immediately with its exit code and the tail of its stderr, rather than waiting for the 30-second health timeout.
|
||||
|
||||
The last known good config is a snapshot of every recognized source file (including which ones exist), captured before every write made through the Settings UI, the internal API, or a host config import, so any of those can be undone with `POST /api/settings/opencode-rollback` or by the ladder. Restoring a snapshot rewrites the sources it contains and removes recognized sources it does not. Archived broken configs and debug snapshots are kept under `.opencode/state/health-watch/` in the workspace, pruned to the newest 20 files.
|
||||
|
||||
Earlier releases stored named configuration profiles in the Manager database. On first start after upgrading, each profile is archived to `.config/opencode-configs-archive/<name>.json` in the workspace, the default profile is restored to `opencode.json` if that file does not exist yet, and the database table is dropped.
|
||||
|
||||
+22
-3
@@ -32,7 +32,9 @@ import { loginLoader, setupLoader, registerLoader, protectedLoader } from './lib
|
||||
import { getSwipeBackTarget } from '@/lib/navigation'
|
||||
import { onNotificationClick } from '@/lib/serviceWorker'
|
||||
import { useAuth } from '@/hooks/useAuth'
|
||||
import { useServerHealth } from '@/hooks/useServerHealth'
|
||||
import { useOpenCodeFailureToast } from '@/hooks/useOpenCodeFailureToast'
|
||||
import { useOpenCodeServerActions } from '@/hooks/useOpenCodeServerActions'
|
||||
import { RestartServerDialog } from '@/components/settings/RestartServerDialog'
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
@@ -57,8 +59,25 @@ function SSHHostKeyDialogWrapper() {
|
||||
|
||||
function HealthMonitor() {
|
||||
const { isAuthenticated } = useAuth()
|
||||
useServerHealth(isAuthenticated)
|
||||
return null
|
||||
const {
|
||||
restartServerMutation,
|
||||
confirmOpen,
|
||||
setConfirmOpen,
|
||||
activeSessionCount,
|
||||
requestRestart,
|
||||
confirmRestart,
|
||||
} = useOpenCodeServerActions()
|
||||
useOpenCodeFailureToast(isAuthenticated, requestRestart)
|
||||
return (
|
||||
<RestartServerDialog
|
||||
open={confirmOpen}
|
||||
onOpenChange={setConfirmOpen}
|
||||
activeSessionCount={activeSessionCount}
|
||||
isRestarting={restartServerMutation.isPending}
|
||||
onCancel={() => setConfirmOpen(false)}
|
||||
onConfirm={confirmRestart}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function PermissionDialogWrapper() {
|
||||
|
||||
@@ -6,6 +6,7 @@ export { FetchError }
|
||||
interface FetchWrapperOptions extends RequestInit {
|
||||
timeout?: number
|
||||
params?: Record<string, string | number | boolean | undefined>
|
||||
acceptedStatuses?: number[]
|
||||
}
|
||||
|
||||
function formatDetails(details: unknown): string | undefined {
|
||||
@@ -71,7 +72,7 @@ async function fetchWithTimeout(
|
||||
url: string,
|
||||
options: FetchWrapperOptions = {}
|
||||
): Promise<Response> {
|
||||
const { timeout = 30000, params, ...fetchOptions } = options
|
||||
const { timeout = 30000, params, acceptedStatuses, ...fetchOptions } = options
|
||||
const urlObj = buildUrl(url, params)
|
||||
|
||||
const controller = new AbortController()
|
||||
@@ -86,7 +87,7 @@ async function fetchWithTimeout(
|
||||
|
||||
if (timeoutId) clearTimeout(timeoutId)
|
||||
|
||||
if (!response.ok) {
|
||||
if (!response.ok && !acceptedStatuses?.includes(response.status)) {
|
||||
await handleResponse(response)
|
||||
}
|
||||
|
||||
|
||||
@@ -97,13 +97,6 @@ export const settingsApi = {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-active-sessions`)
|
||||
},
|
||||
|
||||
rollbackOpenCodeConfig: async (): Promise<{ success: boolean; message: string; fallback?: boolean }> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-rollback`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
},
|
||||
|
||||
getOpenCodeImportStatus: async (): Promise<OpenCodeImportStatus> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-import/status`)
|
||||
},
|
||||
|
||||
@@ -69,8 +69,6 @@ const mockServerHealth = (health?: Partial<ReturnType<typeof useServerHealth>['d
|
||||
isLoading: false,
|
||||
error: null,
|
||||
refetch: vi.fn(),
|
||||
restartMutation: { mutate: vi.fn(), mutateAsync: vi.fn(), isPending: false },
|
||||
rollbackMutation: { mutate: vi.fn(), mutateAsync: vi.fn(), isPending: false },
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -3,9 +3,18 @@ import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { LogsViewer } from './LogsViewer'
|
||||
import { useManagerLogs } from '@/hooks/useManagerLogs'
|
||||
import { useServerHealth, type HealthResponse } from '@/hooks/useServerHealth'
|
||||
import type { ManagerLogEntry } from '@opencode-manager/shared/schemas'
|
||||
|
||||
vi.mock('@/hooks/useManagerLogs')
|
||||
vi.mock('@/hooks/useServerHealth', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('@/hooks/useServerHealth')>()),
|
||||
useServerHealth: vi.fn(),
|
||||
}))
|
||||
|
||||
function mockHealth(health: Partial<HealthResponse> | undefined) {
|
||||
vi.mocked(useServerHealth).mockReturnValue({ data: health } as ReturnType<typeof useServerHealth>)
|
||||
}
|
||||
|
||||
const entries: ManagerLogEntry[] = [
|
||||
{
|
||||
@@ -39,6 +48,47 @@ describe('LogsViewer', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockLogs()
|
||||
mockHealth({ opencode: 'healthy', status: 'healthy' })
|
||||
})
|
||||
|
||||
it('does not render a server issue panel while OpenCode is healthy', () => {
|
||||
render(<LogsViewer />)
|
||||
|
||||
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders the startup failure, attempted recovery and an errors-only shortcut', async () => {
|
||||
const user = userEvent.setup()
|
||||
mockHealth({
|
||||
opencode: 'unhealthy',
|
||||
status: 'unhealthy',
|
||||
opencodeLifecycle: {
|
||||
state: 'failed',
|
||||
healthy: false,
|
||||
port: 5551,
|
||||
version: null,
|
||||
minVersion: '2.0.15',
|
||||
versionSupported: false,
|
||||
lastError: 'OpenCode server exited with code 1: invalid config',
|
||||
activeRecoveryAction: null,
|
||||
attemptedRecoveryActions: ['restart', 'rollback_last_known_good'],
|
||||
nextRecoveryAction: null,
|
||||
failureCount: 3,
|
||||
watching: true,
|
||||
updatedAt: '2026-01-01T00:00:00.000Z',
|
||||
},
|
||||
})
|
||||
render(<LogsViewer />)
|
||||
|
||||
const alert = screen.getByRole('alert')
|
||||
expect(alert).toHaveTextContent('OpenCode server failed')
|
||||
expect(alert).toHaveTextContent('OpenCode server exited with code 1: invalid config')
|
||||
expect(alert).toHaveTextContent('Recovery attempted: restart, rollback last known good')
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Show errors only' }))
|
||||
|
||||
expect(vi.mocked(useManagerLogs).mock.lastCall?.[0]).toMatchObject({ level: 'error', source: undefined })
|
||||
expect(screen.queryByRole('button', { name: 'Show errors only' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders entries with their message, level and source', () => {
|
||||
|
||||
@@ -1,15 +1,23 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { Pause, Play, Trash2 } from 'lucide-react'
|
||||
import { AlertTriangle, Pause, Play, Trash2 } from 'lucide-react'
|
||||
import type { ManagerLogLevel, ManagerLogSource } from '@opencode-manager/shared/schemas'
|
||||
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { CopyButton } from '@/components/ui/copy-button'
|
||||
import { useManagerLogs } from '@/hooks/useManagerLogs'
|
||||
import { getOpenCodeServerIssue, useServerHealth, type OpenCodeServerIssue } from '@/hooks/useServerHealth'
|
||||
import { DEFAULTS } from '@/config'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
const ISSUE_TITLES: Record<OpenCodeServerIssue['state'], string> = {
|
||||
failed: 'OpenCode server failed',
|
||||
recovering: 'OpenCode server is recovering',
|
||||
unhealthy: 'OpenCode server is unhealthy',
|
||||
}
|
||||
|
||||
type LevelFilter = ManagerLogLevel | 'all'
|
||||
type SourceFilter = ManagerLogSource | 'all'
|
||||
|
||||
@@ -45,6 +53,8 @@ export function LogsViewer() {
|
||||
const [paused, setPaused] = useState(false)
|
||||
const [isFollowing, setIsFollowing] = useState(true)
|
||||
const scrollRef = useRef<HTMLDivElement>(null)
|
||||
const { data: health } = useServerHealth()
|
||||
const serverIssue = getOpenCodeServerIssue(health)
|
||||
|
||||
const { entries, dropped, clear } = useManagerLogs({
|
||||
level: level === 'all' ? undefined : level,
|
||||
@@ -122,6 +132,32 @@ export function LogsViewer() {
|
||||
<CopyButton content={copyContent} title="Copy log entries" variant="ghost" />
|
||||
</div>
|
||||
</div>
|
||||
{serverIssue && (
|
||||
<Alert variant={serverIssue.state === 'failed' ? 'destructive' : 'default'} className="shrink-0">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertTitle>{ISSUE_TITLES[serverIssue.state]}</AlertTitle>
|
||||
<AlertDescription className="space-y-2">
|
||||
<p className="max-h-32 overflow-y-auto whitespace-pre-wrap break-words font-mono text-xs">{serverIssue.message}</p>
|
||||
{serverIssue.attemptedRecoveryActions.length > 0 && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Recovery attempted: {serverIssue.attemptedRecoveryActions.map((action) => action.replaceAll('_', ' ')).join(', ')}
|
||||
</p>
|
||||
)}
|
||||
{(level !== 'error' || source !== 'all') && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
setLevel('error')
|
||||
setSource('all')
|
||||
}}
|
||||
>
|
||||
Show errors only
|
||||
</Button>
|
||||
)}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
<div
|
||||
ref={scrollRef}
|
||||
onScroll={handleScroll}
|
||||
|
||||
@@ -33,8 +33,6 @@ function mockHealth(sandbox?: { available: boolean; enforced: boolean; reason?:
|
||||
isLoading: false,
|
||||
error: null,
|
||||
refetch: vi.fn(),
|
||||
restartMutation: { mutate: vi.fn(), mutateAsync: vi.fn(), isPending: false },
|
||||
rollbackMutation: { mutate: vi.fn(), mutateAsync: vi.fn(), isPending: false },
|
||||
} as ReturnType<typeof useServerHealth>)
|
||||
}
|
||||
|
||||
@@ -123,8 +121,6 @@ describe('SandboxSettings', () => {
|
||||
isLoading: true,
|
||||
error: null,
|
||||
refetch: vi.fn(),
|
||||
restartMutation: { mutate: vi.fn(), mutateAsync: vi.fn(), isPending: false },
|
||||
rollbackMutation: { mutate: vi.fn(), mutateAsync: vi.fn(), isPending: false },
|
||||
} as ReturnType<typeof useServerHealth>)
|
||||
|
||||
await renderSandbox()
|
||||
|
||||
@@ -17,8 +17,6 @@ function mockHealth() {
|
||||
isLoading: false,
|
||||
error: null,
|
||||
refetch: vi.fn(),
|
||||
restartMutation: { mutate: vi.fn(), mutateAsync: vi.fn(), isPending: false },
|
||||
rollbackMutation: { mutate: vi.fn(), mutateAsync: vi.fn(), isPending: false },
|
||||
} as ReturnType<typeof useServerHealth>)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { OpenCodeLifecycleStatus } from '@opencode-manager/shared/opencode'
|
||||
import { renderHookWithRouter } from '@/test/test-utils'
|
||||
import { OPENCODE_FAILURE_TOAST_ID, useOpenCodeFailureToast } from './useOpenCodeFailureToast'
|
||||
import { useServerHealth, type HealthResponse } from './useServerHealth'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
showToast: {
|
||||
error: vi.fn(),
|
||||
success: vi.fn(),
|
||||
dismiss: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/toast', () => ({
|
||||
showToast: mocks.showToast,
|
||||
}))
|
||||
|
||||
vi.mock('./useServerHealth', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('./useServerHealth')>()),
|
||||
useServerHealth: vi.fn(),
|
||||
}))
|
||||
|
||||
function lifecycle(overrides: Partial<OpenCodeLifecycleStatus>): OpenCodeLifecycleStatus {
|
||||
return {
|
||||
state: 'healthy',
|
||||
healthy: true,
|
||||
port: 5551,
|
||||
version: '2.0.15',
|
||||
minVersion: '2.0.15',
|
||||
versionSupported: true,
|
||||
lastError: null,
|
||||
activeRecoveryAction: null,
|
||||
attemptedRecoveryActions: [],
|
||||
nextRecoveryAction: null,
|
||||
failureCount: 0,
|
||||
watching: true,
|
||||
updatedAt: '2026-01-01T00:00:00.000Z',
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function mockHealth(opencodeLifecycle: OpenCodeLifecycleStatus) {
|
||||
const health: Partial<HealthResponse> = {
|
||||
opencode: opencodeLifecycle.healthy ? 'healthy' : 'unhealthy',
|
||||
status: opencodeLifecycle.healthy ? 'healthy' : 'unhealthy',
|
||||
opencodeLifecycle,
|
||||
}
|
||||
vi.mocked(useServerHealth).mockReturnValue({ data: health } as ReturnType<typeof useServerHealth>)
|
||||
}
|
||||
|
||||
describe('useOpenCodeFailureToast', () => {
|
||||
const onRestart = vi.fn()
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('raises one persistent toast per distinct failure, including when the app loads already failed', () => {
|
||||
mockHealth(lifecycle({ state: 'failed', healthy: false, lastError: 'OpenCode server exited with code 1' }))
|
||||
const { rerender } = renderHookWithRouter(() => useOpenCodeFailureToast(true, onRestart))
|
||||
|
||||
expect(mocks.showToast.error).toHaveBeenCalledTimes(1)
|
||||
expect(mocks.showToast.error).toHaveBeenCalledWith('OpenCode server failed', expect.objectContaining({
|
||||
id: OPENCODE_FAILURE_TOAST_ID,
|
||||
duration: Infinity,
|
||||
description: 'OpenCode server exited with code 1',
|
||||
action: expect.objectContaining({ label: 'View logs' }),
|
||||
cancel: { label: 'Restart', onClick: onRestart },
|
||||
}))
|
||||
|
||||
rerender()
|
||||
expect(mocks.showToast.error).toHaveBeenCalledTimes(1)
|
||||
|
||||
mockHealth(lifecycle({ state: 'failed', healthy: false, lastError: 'Unsupported OpenCode version' }))
|
||||
rerender()
|
||||
expect(mocks.showToast.error).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('does not toast while recovery is still in progress', () => {
|
||||
mockHealth(lifecycle({ state: 'recovering', healthy: false, lastError: 'health check failed' }))
|
||||
renderHookWithRouter(() => useOpenCodeFailureToast(true, onRestart))
|
||||
|
||||
expect(mocks.showToast.error).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('dismisses the failure and announces recovery only once the server is healthy again', () => {
|
||||
mockHealth(lifecycle({ state: 'failed', healthy: false, lastError: 'boom' }))
|
||||
const { rerender } = renderHookWithRouter(() => useOpenCodeFailureToast(true, onRestart))
|
||||
|
||||
mockHealth(lifecycle({ state: 'starting', healthy: false }))
|
||||
rerender()
|
||||
expect(mocks.showToast.success).not.toHaveBeenCalled()
|
||||
|
||||
mockHealth(lifecycle({ state: 'healthy', healthy: true }))
|
||||
rerender()
|
||||
expect(mocks.showToast.dismiss).toHaveBeenCalledWith(OPENCODE_FAILURE_TOAST_ID)
|
||||
expect(mocks.showToast.success).toHaveBeenCalledWith('OpenCode server is back online')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,42 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { getOpenCodeServerIssue, useServerHealth } from '@/hooks/useServerHealth'
|
||||
import { useSettingsDialog } from '@/hooks/useSettingsDialog'
|
||||
|
||||
export const OPENCODE_FAILURE_TOAST_ID = 'opencode-server-failure'
|
||||
|
||||
/**
|
||||
* Raises one persistent error toast per distinct terminal OpenCode server
|
||||
* failure (startup failure or exhausted recovery), offering to open the Logs
|
||||
* settings tab or restart the server, and announces when the server recovers.
|
||||
*/
|
||||
export function useOpenCodeFailureToast(enabled: boolean, onRestart: () => void) {
|
||||
const { data: health } = useServerHealth(enabled)
|
||||
const { setActiveTab } = useSettingsDialog()
|
||||
const notifiedFailureRef = useRef<string | null>(null)
|
||||
|
||||
const issue = getOpenCodeServerIssue(health)
|
||||
const failureMessage = issue?.state === 'failed' ? issue.message : null
|
||||
const isHealthy = health?.opencodeLifecycle ? health.opencodeLifecycle.healthy : health?.opencode === 'healthy'
|
||||
|
||||
useEffect(() => {
|
||||
if (failureMessage !== null) {
|
||||
if (notifiedFailureRef.current === failureMessage) return
|
||||
notifiedFailureRef.current = failureMessage
|
||||
showToast.error('OpenCode server failed', {
|
||||
id: OPENCODE_FAILURE_TOAST_ID,
|
||||
duration: Infinity,
|
||||
description: failureMessage,
|
||||
action: { label: 'View logs', onClick: () => setActiveTab('logs') },
|
||||
cancel: { label: 'Restart', onClick: onRestart },
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (isHealthy && notifiedFailureRef.current !== null) {
|
||||
notifiedFailureRef.current = null
|
||||
showToast.dismiss(OPENCODE_FAILURE_TOAST_ID)
|
||||
showToast.success('OpenCode server is back online')
|
||||
}
|
||||
}, [failureMessage, isHealthy, setActiveTab, onRestart])
|
||||
}
|
||||
@@ -1,11 +1,8 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
import { settingsApi } from '@/api/settings'
|
||||
import { invalidateConfigCaches, invalidateSettingsCaches } from '@/lib/queryInvalidation'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import type { OpenCodeLifecycleStatus, OpenCodeRecoveryAction } from '@opencode-manager/shared/opencode'
|
||||
import { fetchWrapper } from '@/api/fetchWrapper'
|
||||
|
||||
interface HealthResponse {
|
||||
export interface HealthResponse {
|
||||
status: 'healthy' | 'degraded' | 'unhealthy'
|
||||
timestamp: string
|
||||
database: 'connected' | 'disconnected'
|
||||
@@ -16,51 +13,49 @@ interface HealthResponse {
|
||||
opencodeVersionSupported: boolean
|
||||
opencodeManagerVersion: string | null
|
||||
opencodeRestartPending?: boolean
|
||||
opencodeLifecycle?: OpenCodeLifecycleStatus
|
||||
sandbox?: { available: boolean; enabled: boolean; enforced: boolean; reason?: string; msbVersion?: string }
|
||||
error?: string
|
||||
}
|
||||
|
||||
export interface OpenCodeServerIssue {
|
||||
state: 'failed' | 'recovering' | 'unhealthy'
|
||||
message: string
|
||||
attemptedRecoveryActions: OpenCodeRecoveryAction[]
|
||||
}
|
||||
|
||||
const DEFAULT_ISSUE_MESSAGE = 'OpenCode server is not responding'
|
||||
|
||||
async function fetchHealth(): Promise<HealthResponse> {
|
||||
return fetchWrapper<HealthResponse>('/api/health')
|
||||
return fetchWrapper<HealthResponse>('/api/health', { acceptedStatuses: [503] })
|
||||
}
|
||||
|
||||
/**
|
||||
* Derives the current OpenCode server problem from a health payload, preferring
|
||||
* the supervisor lifecycle (which distinguishes in-progress recovery from a
|
||||
* terminal failure) and falling back to the raw health probe.
|
||||
*/
|
||||
export function getOpenCodeServerIssue(health: HealthResponse | undefined): OpenCodeServerIssue | null {
|
||||
if (!health) return null
|
||||
const lifecycle = health.opencodeLifecycle
|
||||
if (lifecycle) {
|
||||
if (lifecycle.state !== 'failed' && lifecycle.state !== 'recovering' && lifecycle.state !== 'unhealthy') return null
|
||||
return {
|
||||
state: lifecycle.state,
|
||||
message: lifecycle.lastError ?? health.error ?? DEFAULT_ISSUE_MESSAGE,
|
||||
attemptedRecoveryActions: lifecycle.attemptedRecoveryActions,
|
||||
}
|
||||
}
|
||||
if (health.opencode === 'healthy') return null
|
||||
return {
|
||||
state: health.status === 'unhealthy' ? 'failed' : 'unhealthy',
|
||||
message: health.error ?? DEFAULT_ISSUE_MESSAGE,
|
||||
attemptedRecoveryActions: [],
|
||||
}
|
||||
}
|
||||
|
||||
export function useServerHealth(enabled = true) {
|
||||
const queryClient = useQueryClient()
|
||||
const lastHealthStatusRef = useRef<'healthy' | 'unhealthy'>('healthy')
|
||||
const prevHealthRef = useRef<string | null>(null)
|
||||
|
||||
const restartMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
return await settingsApi.restartOpenCodeServer()
|
||||
},
|
||||
onSuccess: () => {
|
||||
invalidateConfigCaches(queryClient)
|
||||
toast.success('OpenCode server restarted', { id: 'reload-config' })
|
||||
},
|
||||
onError: (error: unknown) => {
|
||||
const errorMessage = error && typeof error === 'object' && 'response' in error
|
||||
? ((error as { response?: { data?: { details?: string; error?: string } } }).response?.data?.details
|
||||
|| (error as { response?: { data?: { details?: string; error?: string } } }).response?.data?.error
|
||||
|| 'Failed to restart OpenCode server')
|
||||
: 'Failed to restart OpenCode server'
|
||||
toast.error(errorMessage, { id: 'reload-config' })
|
||||
},
|
||||
})
|
||||
|
||||
const rollbackMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
return await settingsApi.rollbackOpenCodeConfig()
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
invalidateSettingsCaches(queryClient)
|
||||
toast.success(data.message, { id: 'rollback-config' })
|
||||
},
|
||||
onError: () => {
|
||||
toast.error('Failed to rollback to previous config', { id: 'rollback-config' })
|
||||
},
|
||||
})
|
||||
|
||||
const query = useQuery<HealthResponse>({
|
||||
return useQuery<HealthResponse>({
|
||||
queryKey: ['health'],
|
||||
queryFn: fetchHealth,
|
||||
refetchInterval: 30000,
|
||||
@@ -68,39 +63,4 @@ export function useServerHealth(enabled = true) {
|
||||
enabled,
|
||||
staleTime: 10000,
|
||||
})
|
||||
|
||||
const { data: health } = query
|
||||
|
||||
useEffect(() => {
|
||||
if (!health) return
|
||||
|
||||
const isUnhealthy = health.opencode !== 'healthy'
|
||||
const currentStatus = isUnhealthy ? 'unhealthy' : 'healthy'
|
||||
const previousStatus = lastHealthStatusRef.current
|
||||
const prevHealth = prevHealthRef.current
|
||||
|
||||
if (prevHealth && currentStatus !== prevHealth) {
|
||||
if (isUnhealthy && previousStatus === 'healthy') {
|
||||
toast.error(health.error || 'OpenCode server is currently unhealthy', {
|
||||
id: 'server-health-unhealthy',
|
||||
duration: Infinity,
|
||||
action: {
|
||||
label: 'Restart',
|
||||
onClick: () => restartMutation.mutate(),
|
||||
},
|
||||
})
|
||||
} else if (!isUnhealthy && previousStatus === 'unhealthy') {
|
||||
toast.success('Server is back online', { id: 'server-health-online' })
|
||||
}
|
||||
}
|
||||
|
||||
lastHealthStatusRef.current = currentStatus
|
||||
prevHealthRef.current = currentStatus
|
||||
}, [health, restartMutation])
|
||||
|
||||
return {
|
||||
...query,
|
||||
restartMutation,
|
||||
rollbackMutation,
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,10 @@ interface ToastOptions {
|
||||
label: string
|
||||
onClick: () => void
|
||||
}
|
||||
cancel?: {
|
||||
label: string
|
||||
onClick: () => void
|
||||
}
|
||||
id?: string | number
|
||||
}
|
||||
|
||||
|
||||
@@ -79,6 +79,10 @@ export {
|
||||
parseOpenCodeVersionOutput,
|
||||
} from './release'
|
||||
|
||||
export { OPENCODE_LIFECYCLE_STATES, OPENCODE_RECOVERY_ACTIONS } from './lifecycle'
|
||||
|
||||
export type { OpenCodeLifecycleState, OpenCodeLifecycleStatus, OpenCodeRecoveryAction } from './lifecycle'
|
||||
|
||||
export const OPENCODE_SERVER_USERNAME = 'opencode'
|
||||
|
||||
export type OpenCodeApi = ReturnType<typeof OpenCode.make>
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
export const OPENCODE_LIFECYCLE_STATES = [
|
||||
'idle',
|
||||
'starting',
|
||||
'healthy',
|
||||
'unhealthy',
|
||||
'recovering',
|
||||
'failed',
|
||||
'stopping',
|
||||
'stopped',
|
||||
] as const
|
||||
|
||||
export type OpenCodeLifecycleState = (typeof OPENCODE_LIFECYCLE_STATES)[number]
|
||||
|
||||
export const OPENCODE_RECOVERY_ACTIONS = [
|
||||
'restart',
|
||||
'debug_capture',
|
||||
'rollback_last_known_good',
|
||||
'seed_default_config',
|
||||
] as const
|
||||
|
||||
export type OpenCodeRecoveryAction = (typeof OPENCODE_RECOVERY_ACTIONS)[number]
|
||||
|
||||
export interface OpenCodeLifecycleStatus {
|
||||
state: OpenCodeLifecycleState
|
||||
healthy: boolean
|
||||
port: number
|
||||
version: string | null
|
||||
minVersion: string
|
||||
versionSupported: boolean
|
||||
lastError: string | null
|
||||
activeRecoveryAction: OpenCodeRecoveryAction | null
|
||||
attemptedRecoveryActions: OpenCodeRecoveryAction[]
|
||||
nextRecoveryAction: OpenCodeRecoveryAction | null
|
||||
failureCount: number
|
||||
watching: boolean
|
||||
updatedAt: string
|
||||
}
|
||||
Reference in new issue
Block a user