diff --git a/backend/src/services/opencode-single-server.ts b/backend/src/services/opencode-single-server.ts index d457a044..1666fd0a 100644 --- a/backend/src/services/opencode-single-server.ts +++ b/backend/src/services/opencode-single-server.ts @@ -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 { + private async waitForHealth(timeoutMs: number, hasProcessExited: () => boolean): Promise { 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 diff --git a/backend/src/services/opencode-supervisor.ts b/backend/src/services/opencode-supervisor.ts index 54ab5605..e1fd7f2b 100644 --- a/backend/src/services/opencode-supervisor.ts +++ b/backend/src/services/opencode-supervisor.ts @@ -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() diff --git a/backend/test/services/opencode-single-server.test.ts b/backend/test/services/opencode-single-server.test.ts index fc6cf540..ff82bcbe 100644 --- a/backend/test/services/opencode-single-server.test.ts +++ b/backend/test/services/opencode-single-server.test.ts @@ -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, diff --git a/docs/features/logs.md b/docs/features/logs.md index 1f7043d8..967b5383 100644 --- a/docs/features/logs.md +++ b/docs/features/logs.md @@ -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. diff --git a/docs/features/server-health.md b/docs/features/server-health.md index 4f09c15d..a68bfc5b 100644 --- a/docs/features/server-health.md +++ b/docs/features/server-health.md @@ -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/.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. diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 003be3c4..e2917abf 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -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 ( + setConfirmOpen(false)} + onConfirm={confirmRestart} + /> + ) } function PermissionDialogWrapper() { diff --git a/frontend/src/api/fetchWrapper.ts b/frontend/src/api/fetchWrapper.ts index 403abd76..9e81515d 100644 --- a/frontend/src/api/fetchWrapper.ts +++ b/frontend/src/api/fetchWrapper.ts @@ -6,6 +6,7 @@ export { FetchError } interface FetchWrapperOptions extends RequestInit { timeout?: number params?: Record + acceptedStatuses?: number[] } function formatDetails(details: unknown): string | undefined { @@ -71,7 +72,7 @@ async function fetchWithTimeout( url: string, options: FetchWrapperOptions = {} ): Promise { - 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) } diff --git a/frontend/src/api/settings.ts b/frontend/src/api/settings.ts index ac4a24cc..6357bf56 100644 --- a/frontend/src/api/settings.ts +++ b/frontend/src/api/settings.ts @@ -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 => { return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-import/status`) }, diff --git a/frontend/src/components/navigation/MoreDrawer.test.tsx b/frontend/src/components/navigation/MoreDrawer.test.tsx index e89ad1d2..d2ea0a59 100644 --- a/frontend/src/components/navigation/MoreDrawer.test.tsx +++ b/frontend/src/components/navigation/MoreDrawer.test.tsx @@ -69,8 +69,6 @@ const mockServerHealth = (health?: Partial['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 }, }) } diff --git a/frontend/src/components/settings/LogsViewer.test.tsx b/frontend/src/components/settings/LogsViewer.test.tsx index 3bcc54a3..6769ba07 100644 --- a/frontend/src/components/settings/LogsViewer.test.tsx +++ b/frontend/src/components/settings/LogsViewer.test.tsx @@ -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()), + useServerHealth: vi.fn(), +})) + +function mockHealth(health: Partial | undefined) { + vi.mocked(useServerHealth).mockReturnValue({ data: health } as ReturnType) +} 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() + + 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() + + 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', () => { diff --git a/frontend/src/components/settings/LogsViewer.tsx b/frontend/src/components/settings/LogsViewer.tsx index acea0504..f19544ad 100644 --- a/frontend/src/components/settings/LogsViewer.tsx +++ b/frontend/src/components/settings/LogsViewer.tsx @@ -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 = { + 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(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() { + {serverIssue && ( + + + {ISSUE_TITLES[serverIssue.state]} + +

{serverIssue.message}

+ {serverIssue.attemptedRecoveryActions.length > 0 && ( +

+ Recovery attempted: {serverIssue.attemptedRecoveryActions.map((action) => action.replaceAll('_', ' ')).join(', ')} +

+ )} + {(level !== 'error' || source !== 'all') && ( + + )} +
+
+ )}
) } @@ -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) await renderSandbox() diff --git a/frontend/src/components/settings/ServerHealthStatus.test.tsx b/frontend/src/components/settings/ServerHealthStatus.test.tsx index 25ea69a5..c83bfa6b 100644 --- a/frontend/src/components/settings/ServerHealthStatus.test.tsx +++ b/frontend/src/components/settings/ServerHealthStatus.test.tsx @@ -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) } diff --git a/frontend/src/hooks/useOpenCodeFailureToast.test.ts b/frontend/src/hooks/useOpenCodeFailureToast.test.ts new file mode 100644 index 00000000..e49478c1 --- /dev/null +++ b/frontend/src/hooks/useOpenCodeFailureToast.test.ts @@ -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()), + useServerHealth: vi.fn(), +})) + +function lifecycle(overrides: Partial): 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 = { + opencode: opencodeLifecycle.healthy ? 'healthy' : 'unhealthy', + status: opencodeLifecycle.healthy ? 'healthy' : 'unhealthy', + opencodeLifecycle, + } + vi.mocked(useServerHealth).mockReturnValue({ data: health } as ReturnType) +} + +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') + }) +}) diff --git a/frontend/src/hooks/useOpenCodeFailureToast.ts b/frontend/src/hooks/useOpenCodeFailureToast.ts new file mode 100644 index 00000000..3c23bf72 --- /dev/null +++ b/frontend/src/hooks/useOpenCodeFailureToast.ts @@ -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(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]) +} diff --git a/frontend/src/hooks/useServerHealth.ts b/frontend/src/hooks/useServerHealth.ts index 9b94f2a5..d69166b4 100644 --- a/frontend/src/hooks/useServerHealth.ts +++ b/frontend/src/hooks/useServerHealth.ts @@ -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 { - return fetchWrapper('/api/health') + return fetchWrapper('/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(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({ + return useQuery({ 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, - } } diff --git a/frontend/src/lib/toast.ts b/frontend/src/lib/toast.ts index e1a597a3..3392d5d6 100644 --- a/frontend/src/lib/toast.ts +++ b/frontend/src/lib/toast.ts @@ -7,6 +7,10 @@ interface ToastOptions { label: string onClick: () => void } + cancel?: { + label: string + onClick: () => void + } id?: string | number } diff --git a/shared/src/opencode/index.ts b/shared/src/opencode/index.ts index c881e4d8..674f1937 100644 --- a/shared/src/opencode/index.ts +++ b/shared/src/opencode/index.ts @@ -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 diff --git a/shared/src/opencode/lifecycle.ts b/shared/src/opencode/lifecycle.ts new file mode 100644 index 00000000..ca8ccb22 --- /dev/null +++ b/shared/src/opencode/lifecycle.ts @@ -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 +}