Files
opencode-manager/frontend/src/hooks/useServerHealth.ts
T
Chris Scott dacde879d6 feat(opencode): migrate OpenCode Manager to OpenCode 2 (#359)
* feat(opencode): migrate OpenCode Manager to OpenCode 2

Port the backend lifecycle, generated plugins, event aggregation,
schedules, worktrees, provider credentials, MCP, config handling, the
frontend chat model, and the ocm CLI to OpenCode 2.

Adopt @opencode/client 2.0.15 as the single typed V2 API contract,
require OpenCode 2.0.0 or newer (pinned 2.0.15), and delete every
V1-only code path.

* refactor(opencode): reload config in place and drop v1 compatibility shims

Route config/skill/AGENTS.md changes through the OpenCode location reload
API instead of a full server restart, stop auto-resuming interrupted
sessions, remove the restart coordinator and v1 MCP/version shims, and pin
support to OpenCode >=2.0.15 <3.0.0. Adds integration-ready retries,
service-mode launch, ocm-cli repo proxy, and new frontend form/MCP helpers.

* refactor(opencode): consolidate v2 migration helpers and harden install, proxy, and session flows

- extract shared semver and model-ref utilities, reuse across version checks
- share the OpenCode release download script across Docker, entrypoint, dev setup
- unify install/upgrade failure recovery and guard externally managed OPENCODE_BIN
- scope the repo proxy location rewrite and surface ocm proxy errors
- rework frontend session projection, permission lookup, and cache invalidation

* fix(schedules): reject unavailable agents before creating a session

* feat(opencode): add ocm install, schedule agent fallback, and session move guards
2026-09-26 13:16:45 -04:00

107 lines
3.5 KiB
TypeScript

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 { fetchWrapper } from '@/api/fetchWrapper'
interface HealthResponse {
status: 'healthy' | 'degraded' | 'unhealthy'
timestamp: string
database: 'connected' | 'disconnected'
opencode: 'healthy' | 'unhealthy'
opencodePort: number
opencodeVersion: string | null
opencodeMinVersion: string
opencodeVersionSupported: boolean
opencodeManagerVersion: string | null
opencodeRestartPending?: boolean
sandbox?: { available: boolean; enabled: boolean; enforced: boolean; reason?: string; msbVersion?: string }
error?: string
}
async function fetchHealth(): Promise<HealthResponse> {
return fetchWrapper<HealthResponse>('/api/health')
}
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>({
queryKey: ['health'],
queryFn: fetchHealth,
refetchInterval: 30000,
retry: false,
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,
}
}