mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
Add config rollback and startup error recovery
This commit is contained in:
1 parent
120d087910
commit
876b444599
10 files changed
+428
-69
No files matched your search
@@ -201,16 +201,19 @@ try {
|
||||
await ensureDirectoryExists(getReposPath())
|
||||
await ensureDirectoryExists(getConfigPath())
|
||||
logger.info('Workspace directories initialized')
|
||||
|
||||
|
||||
await cleanupOrphanedDirectories(db)
|
||||
logger.info('Orphaned directory cleanup completed')
|
||||
|
||||
|
||||
await cleanupExpiredCache()
|
||||
|
||||
|
||||
await ensureDefaultConfigExists()
|
||||
await syncDefaultConfigToDisk()
|
||||
await ensureDefaultAgentsMdExists()
|
||||
|
||||
|
||||
const settingsService = new SettingsService(db)
|
||||
settingsService.initializeLastKnownGoodConfig()
|
||||
|
||||
opencodeServerManager.setDatabase(db)
|
||||
await opencodeServerManager.start()
|
||||
logger.info(`OpenCode server running on port ${opencodeServerManager.getPort()}`)
|
||||
|
||||
@@ -9,10 +9,13 @@ export function createHealthRoutes(db: Database) {
|
||||
try {
|
||||
const dbCheck = db.prepare('SELECT 1').get()
|
||||
const opencodeHealthy = await opencodeServerManager.checkHealth()
|
||||
|
||||
const status = dbCheck && opencodeHealthy ? 'healthy' : 'degraded'
|
||||
|
||||
return c.json({
|
||||
const startupError = opencodeServerManager.getLastStartupError()
|
||||
|
||||
const status = startupError && !opencodeHealthy
|
||||
? 'unhealthy'
|
||||
: (dbCheck && opencodeHealthy ? 'healthy' : 'degraded')
|
||||
|
||||
const response: Record<string, unknown> = {
|
||||
status,
|
||||
timestamp: new Date().toISOString(),
|
||||
database: dbCheck ? 'connected' : 'disconnected',
|
||||
@@ -21,7 +24,13 @@ export function createHealthRoutes(db: Database) {
|
||||
opencodeVersion: opencodeServerManager.getVersion(),
|
||||
opencodeMinVersion: opencodeServerManager.getMinVersion(),
|
||||
opencodeVersionSupported: opencodeServerManager.isVersionSupported()
|
||||
})
|
||||
}
|
||||
|
||||
if (startupError && !opencodeHealthy) {
|
||||
response.error = startupError
|
||||
}
|
||||
|
||||
return c.json(response)
|
||||
} catch (error) {
|
||||
return c.json({
|
||||
status: 'unhealthy',
|
||||
|
||||
@@ -208,17 +208,19 @@ export function createSettingsRoutes(db: Database) {
|
||||
try {
|
||||
const userId = c.req.query('userId') || 'default'
|
||||
const configName = c.req.param('name')
|
||||
|
||||
|
||||
settingsService.saveLastKnownGoodConfig(userId)
|
||||
|
||||
const config = settingsService.setDefaultOpenCodeConfig(configName, userId)
|
||||
if (!config) {
|
||||
return c.json({ error: 'Config not found' }, 404)
|
||||
}
|
||||
|
||||
|
||||
const configPath = getOpenCodeConfigFilePath()
|
||||
const configContent = JSON.stringify(config.content, null, 2)
|
||||
await writeFileContent(configPath, configContent)
|
||||
logger.info(`Wrote default config '${configName}' to: ${configPath}`)
|
||||
|
||||
|
||||
await patchOpenCodeConfig(config.content)
|
||||
|
||||
return c.json(config)
|
||||
@@ -247,11 +249,75 @@ export function createSettingsRoutes(db: Database) {
|
||||
app.post('/opencode-restart', async (c) => {
|
||||
try {
|
||||
logger.info('Manual OpenCode server restart requested')
|
||||
opencodeServerManager.clearStartupError()
|
||||
await opencodeServerManager.restart()
|
||||
return c.json({ success: true, message: 'OpenCode server restarted successfully' })
|
||||
} catch (error) {
|
||||
logger.error('Failed to restart OpenCode server:', error)
|
||||
return c.json({ error: 'Failed to restart OpenCode server' }, 500)
|
||||
const startupError = opencodeServerManager.getLastStartupError()
|
||||
return c.json({
|
||||
error: 'Failed to restart OpenCode server',
|
||||
details: startupError || (error instanceof Error ? error.message : 'Unknown error')
|
||||
}, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/opencode-rollback', async (c) => {
|
||||
try {
|
||||
const userId = c.req.query('userId') || 'default'
|
||||
logger.info('OpenCode config rollback requested')
|
||||
|
||||
const rollbackConfig = settingsService.rollbackToLastKnownGoodHealth(userId)
|
||||
if (!rollbackConfig) {
|
||||
return c.json({ error: 'No previous working config available for rollback' }, 404)
|
||||
}
|
||||
|
||||
const configPath = getOpenCodeConfigFilePath()
|
||||
const config = settingsService.getDefaultOpenCodeConfig(userId)
|
||||
if (!config) {
|
||||
return c.json({ error: 'Failed to get default config after rollback' }, 500)
|
||||
}
|
||||
|
||||
const configContent = JSON.stringify(config.content, null, 2)
|
||||
await writeFileContent(configPath, configContent)
|
||||
logger.info(`Rolled back to config '${rollbackConfig}'`)
|
||||
|
||||
opencodeServerManager.clearStartupError()
|
||||
try {
|
||||
await opencodeServerManager.restart()
|
||||
} catch (restartError) {
|
||||
logger.error('Rollback config also failed to start server, attempting fallback:', restartError)
|
||||
|
||||
const deleted = settingsService.deleteFilesystemConfig()
|
||||
if (deleted) {
|
||||
logger.info('Deleted filesystem config, attempting restart with fallback')
|
||||
await new Promise(r => setTimeout(r, 1000))
|
||||
|
||||
opencodeServerManager.clearStartupError()
|
||||
await opencodeServerManager.restart()
|
||||
|
||||
return c.json({
|
||||
success: true,
|
||||
message: `Server restarted after deleting problematic config. DB config '${rollbackConfig}' preserved for manual recovery.`,
|
||||
fallback: true,
|
||||
configName: rollbackConfig
|
||||
})
|
||||
}
|
||||
|
||||
return c.json({
|
||||
error: 'Failed to rollback and could not delete filesystem config',
|
||||
details: restartError instanceof Error ? restartError.message : 'Unknown error'
|
||||
}, 500)
|
||||
}
|
||||
|
||||
return c.json({
|
||||
success: true,
|
||||
message: `Server restarted with previous working config: ${rollbackConfig}`,
|
||||
configName: rollbackConfig
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error('Failed to rollback OpenCode config:', error)
|
||||
return c.json({ error: 'Failed to rollback OpenCode config' }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ const OPENCODE_SERVER_PORT = ENV.OPENCODE.PORT
|
||||
const OPENCODE_SERVER_DIRECTORY = getWorkspacePath()
|
||||
const OPENCODE_CONFIG_PATH = getOpenCodeConfigFilePath()
|
||||
const MIN_OPENCODE_VERSION = '1.0.137'
|
||||
const MAX_STDERR_SIZE = 10240
|
||||
|
||||
function compareVersions(v1: string, v2: string): number {
|
||||
const parts1 = v1.split('.').map(Number)
|
||||
@@ -31,6 +32,7 @@ class OpenCodeServerManager {
|
||||
private isHealthy: boolean = false
|
||||
private db: Database | null = null
|
||||
private version: string | null = null
|
||||
private lastStartupError: string | null = null
|
||||
|
||||
private constructor() {}
|
||||
|
||||
@@ -105,13 +107,15 @@ class OpenCodeServerManager {
|
||||
|
||||
const gitEnv = gitToken ? createGitHubGitEnv(gitToken) : createNoPromptGitEnv()
|
||||
|
||||
let stderrOutput = ''
|
||||
|
||||
this.serverProcess = spawn(
|
||||
'opencode',
|
||||
'opencode',
|
||||
['serve', '--port', OPENCODE_SERVER_PORT.toString(), '--hostname', '127.0.0.1'],
|
||||
{
|
||||
cwd: OPENCODE_SERVER_DIRECTORY,
|
||||
detached: !isDevelopment,
|
||||
stdio: isDevelopment ? 'inherit' : 'ignore',
|
||||
stdio: isDevelopment ? 'inherit' : ['ignore', 'pipe', 'pipe'],
|
||||
env: {
|
||||
...process.env,
|
||||
...gitEnv,
|
||||
@@ -122,12 +126,32 @@ class OpenCodeServerManager {
|
||||
}
|
||||
)
|
||||
|
||||
if (!isDevelopment && this.serverProcess.stderr) {
|
||||
this.serverProcess.stderr.on('data', (data) => {
|
||||
stderrOutput += data.toString()
|
||||
if (stderrOutput.length > MAX_STDERR_SIZE) {
|
||||
stderrOutput = stderrOutput.slice(-MAX_STDERR_SIZE)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
this.serverProcess.on('exit', (code, signal) => {
|
||||
if (code !== null && code !== 0) {
|
||||
this.lastStartupError = `Server exited with code ${code}${stderrOutput ? `: ${stderrOutput.slice(-500)}` : ''}`
|
||||
logger.error('OpenCode server process exited:', this.lastStartupError)
|
||||
} else if (signal) {
|
||||
this.lastStartupError = `Server terminated by signal ${signal}`
|
||||
logger.error('OpenCode server process terminated:', this.lastStartupError)
|
||||
}
|
||||
})
|
||||
|
||||
this.serverPid = this.serverProcess.pid ?? null
|
||||
|
||||
logger.info(`OpenCode server started with PID ${this.serverPid}`)
|
||||
|
||||
const healthy = await this.waitForHealth(30000)
|
||||
if (!healthy) {
|
||||
this.lastStartupError = `Server failed to become healthy after 30s${stderrOutput ? `. Last error: ${stderrOutput.slice(-500)}` : ''}`
|
||||
throw new Error('OpenCode server failed to become healthy')
|
||||
}
|
||||
|
||||
@@ -191,6 +215,14 @@ class OpenCodeServerManager {
|
||||
return compareVersions(this.version, MIN_OPENCODE_VERSION) >= 0
|
||||
}
|
||||
|
||||
getLastStartupError(): string | null {
|
||||
return this.lastStartupError
|
||||
}
|
||||
|
||||
clearStartupError(): void {
|
||||
this.lastStartupError = null
|
||||
}
|
||||
|
||||
async checkHealth(): Promise<boolean> {
|
||||
try {
|
||||
const response = await fetch(`http://127.0.0.1:${OPENCODE_SERVER_PORT}/doc`, {
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { unlinkSync, existsSync } from 'fs'
|
||||
import { getOpenCodeConfigFilePath } from '@opencode-manager/shared/config/env'
|
||||
import { logger } from '../utils/logger'
|
||||
import stripJsonComments from 'strip-json-comments'
|
||||
import type {
|
||||
@@ -28,8 +30,25 @@ function parseJsonc(content: string): unknown {
|
||||
}
|
||||
|
||||
export class SettingsService {
|
||||
private static lastKnownGoodConfigContent: string | null = null
|
||||
|
||||
constructor(private db: Database) {}
|
||||
|
||||
initializeLastKnownGoodConfig(userId: string = 'default'): void {
|
||||
const settings = this.getSettings(userId)
|
||||
if (settings.preferences.lastKnownGoodConfig) {
|
||||
SettingsService.lastKnownGoodConfigContent = settings.preferences.lastKnownGoodConfig
|
||||
logger.info('Initialized last known good config from database')
|
||||
}
|
||||
}
|
||||
|
||||
persistLastKnownGoodConfig(userId: string = 'default'): void {
|
||||
if (SettingsService.lastKnownGoodConfigContent) {
|
||||
this.updateSettings({ lastKnownGoodConfig: SettingsService.lastKnownGoodConfigContent }, userId)
|
||||
logger.info('Persisted last known good config to database')
|
||||
}
|
||||
}
|
||||
|
||||
getSettings(userId: string = 'default'): SettingsResponse {
|
||||
const row = this.db
|
||||
.query('SELECT preferences, updated_at FROM user_preferences WHERE user_id = ?')
|
||||
@@ -441,4 +460,62 @@ export class SettingsService {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
saveLastKnownGoodConfig(userId: string = 'default'): void {
|
||||
const config = this.getDefaultOpenCodeConfig(userId)
|
||||
if (config) {
|
||||
SettingsService.lastKnownGoodConfigContent = config.rawContent
|
||||
this.persistLastKnownGoodConfig(userId)
|
||||
logger.info(`Saved last known good config: ${config.name}`)
|
||||
}
|
||||
}
|
||||
|
||||
restoreToLastKnownGoodConfig(userId: string = 'default'): { configName: string; content: string } | null {
|
||||
if (!SettingsService.lastKnownGoodConfigContent) {
|
||||
logger.warn('No last known good config available for rollback')
|
||||
return null
|
||||
}
|
||||
|
||||
const configs = this.getOpenCodeConfigs(userId)
|
||||
const defaultConfig = configs.defaultConfig
|
||||
|
||||
if (!defaultConfig) {
|
||||
logger.error('Cannot rollback: no default config found')
|
||||
return null
|
||||
}
|
||||
|
||||
logger.info(`Restoring to last known good config for: ${defaultConfig.name}`)
|
||||
return {
|
||||
configName: defaultConfig.name,
|
||||
content: SettingsService.lastKnownGoodConfigContent
|
||||
}
|
||||
}
|
||||
|
||||
rollbackToLastKnownGoodHealth(userId: string = 'default'): string | null {
|
||||
const lastGood = this.restoreToLastKnownGoodConfig(userId)
|
||||
if (!lastGood) {
|
||||
return null
|
||||
}
|
||||
|
||||
this.updateOpenCodeConfig(lastGood.configName, { content: lastGood.content }, userId)
|
||||
return lastGood.configName
|
||||
}
|
||||
|
||||
deleteFilesystemConfig(): boolean {
|
||||
const configPath = getOpenCodeConfigFilePath()
|
||||
|
||||
if (!existsSync(configPath)) {
|
||||
logger.warn('Config file does not exist:', configPath)
|
||||
return false
|
||||
}
|
||||
|
||||
try {
|
||||
unlinkSync(configPath)
|
||||
logger.info('Deleted filesystem config to allow server startup:', configPath)
|
||||
return true
|
||||
} catch (error) {
|
||||
logger.error('Failed to delete config file:', error)
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,9 +9,9 @@ import { useSettingsDialog } from './hooks/useSettingsDialog'
|
||||
import { useTheme } from './hooks/useTheme'
|
||||
import { TTSProvider } from './contexts/TTSContext'
|
||||
import { PermissionProvider } from '@/contexts/PermissionContext'
|
||||
import { PermissionRequestDialog } from '@/components/session/PermissionRequestDialog'
|
||||
import { usePermissionContext } from '@/contexts/PermissionContext'
|
||||
import { GlobalPermissionNotification } from '@/components/permissions/GlobalPermissionNotification'
|
||||
import { PermissionRequestDialog } from './components/session/PermissionRequestDialog'
|
||||
import { usePermissionContext } from './contexts/PermissionContext'
|
||||
import { GlobalPermissionNotification } from './components/permissions/GlobalPermissionNotification'
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
|
||||
@@ -98,11 +98,16 @@ export const settingsApi = {
|
||||
}
|
||||
},
|
||||
|
||||
restartOpenCodeServer: async (): Promise<{ success: boolean; message: string }> => {
|
||||
restartOpenCodeServer: async (): Promise<{ success: boolean; message: string; details?: string }> => {
|
||||
const { data } = await axios.post(`${API_BASE_URL}/api/settings/opencode-restart`)
|
||||
return data
|
||||
},
|
||||
|
||||
rollbackOpenCodeConfig: async (): Promise<{ success: boolean; message: string; configName?: string }> => {
|
||||
const { data } = await axios.post(`${API_BASE_URL}/api/settings/opencode-rollback`)
|
||||
return data
|
||||
},
|
||||
|
||||
getAgentsMd: async (): Promise<{ content: string }> => {
|
||||
const { data } = await axios.get(`${API_BASE_URL}/api/settings/agents-md`)
|
||||
return data
|
||||
|
||||
@@ -14,6 +14,7 @@ import { AgentsMdEditor } from './AgentsMdEditor'
|
||||
import { McpManager } from './McpManager'
|
||||
import { settingsApi } from '@/api/settings'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { useServerHealth } from '@/hooks/useServerHealth'
|
||||
import { parseJsonc, hasJsoncComments } from '@/lib/jsonc'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import type { OpenCodeConfig } from '@/api/types/settings'
|
||||
@@ -47,6 +48,7 @@ interface Agent {
|
||||
|
||||
export function OpenCodeConfigManager() {
|
||||
const queryClient = useQueryClient()
|
||||
const { data: health } = useServerHealth()
|
||||
const [configs, setConfigs] = useState<OpenCodeConfig[]>([])
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [isUpdating, setIsUpdating] = useState(false)
|
||||
@@ -83,9 +85,30 @@ export function OpenCodeConfigManager() {
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode', 'agents'] })
|
||||
showToast.success('Server restarted successfully', { id: 'update-restart' })
|
||||
},
|
||||
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'
|
||||
showToast.error(errorMessage, { id: 'update-restart' })
|
||||
},
|
||||
})
|
||||
|
||||
const rollbackMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
return await settingsApi.rollbackOpenCodeConfig()
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode', 'agents'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['settings'] })
|
||||
showToast.success(data.message, { id: 'rollback-config' })
|
||||
fetchConfigs()
|
||||
},
|
||||
onError: () => {
|
||||
showToast.error('Failed to restart OpenCode server')
|
||||
showToast.error('Failed to rollback to previous config', { id: 'rollback-config' })
|
||||
},
|
||||
})
|
||||
|
||||
@@ -105,32 +128,27 @@ export function OpenCodeConfigManager() {
|
||||
try {
|
||||
setIsUpdating(true)
|
||||
const previousContent = configs.find(c => c.name === configName)?.content
|
||||
|
||||
|
||||
await settingsApi.updateOpenCodeConfig(configName, { content: newContent })
|
||||
|
||||
// Update the local state
|
||||
setConfigs(prev => prev.map(config =>
|
||||
config.name === configName
|
||||
|
||||
setConfigs(prev => prev.map(config =>
|
||||
config.name === configName
|
||||
? { ...config, content: newContent, updatedAt: Date.now() }
|
||||
: config
|
||||
))
|
||||
|
||||
// Update selected config if it's the one being edited
|
||||
|
||||
if (selectedConfig && selectedConfig.name === configName) {
|
||||
setSelectedConfig({ ...selectedConfig, content: newContent, updatedAt: Date.now() })
|
||||
}
|
||||
|
||||
// Auto-restart server if agents were modified
|
||||
|
||||
const agentsChanged = JSON.stringify(previousContent?.agent) !== JSON.stringify(newContent.agent)
|
||||
if (restartServer || agentsChanged) {
|
||||
showToast.loading('Restarting server...', { id: 'update-restart' })
|
||||
await restartServerMutation.mutateAsync()
|
||||
showToast.success('Config updated and server restarted', { id: 'update-restart' })
|
||||
} else {
|
||||
showToast.success('Configuration updated')
|
||||
}
|
||||
|
||||
// Invalidate agents cache so @ mentions get updated
|
||||
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode', 'agents'] })
|
||||
} catch (error) {
|
||||
console.error('Failed to update config:', error)
|
||||
@@ -156,30 +174,29 @@ export function OpenCodeConfigManager() {
|
||||
try {
|
||||
setIsUpdating(true)
|
||||
const parsedContent = parseJsonc<Record<string, unknown>>(rawContent)
|
||||
|
||||
|
||||
const forbiddenFields = ['id', 'createdAt', 'updatedAt']
|
||||
const foundForbidden = forbiddenFields.filter(field => field in parsedContent)
|
||||
if (foundForbidden.length > 0) {
|
||||
throw new Error(`Invalid fields found: ${foundForbidden.join(', ')}. These fields are managed automatically.`)
|
||||
}
|
||||
|
||||
|
||||
await settingsApi.createOpenCodeConfig({
|
||||
name: name.trim(),
|
||||
content: rawContent,
|
||||
isDefault,
|
||||
})
|
||||
|
||||
|
||||
setIsCreateDialogOpen(false)
|
||||
await fetchConfigs()
|
||||
|
||||
|
||||
if (isDefault) {
|
||||
showToast.loading('Restarting server...', { id: 'create-config' })
|
||||
await restartServerMutation.mutateAsync()
|
||||
showToast.success('Configuration created and server restarted', { id: 'create-config' })
|
||||
} else {
|
||||
showToast.success('Configuration created', { id: 'create-config' })
|
||||
showToast.success('Configuration created')
|
||||
}
|
||||
|
||||
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode', 'agents'] })
|
||||
} catch (error) {
|
||||
console.error('Failed to create config:', error)
|
||||
@@ -217,7 +234,12 @@ export function OpenCodeConfigManager() {
|
||||
showToast.success('Default config updated and server restarted', { id: 'set-default' })
|
||||
} catch (error) {
|
||||
console.error('Failed to set default config:', error)
|
||||
showToast.error('Failed to set default config', { id: 'set-default' })
|
||||
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 set default config')
|
||||
: 'Failed to set default config'
|
||||
showToast.error(errorMessage, { id: 'set-default' })
|
||||
} finally {
|
||||
setIsUpdating(false)
|
||||
}
|
||||
@@ -252,37 +274,81 @@ export function OpenCodeConfigManager() {
|
||||
)
|
||||
}
|
||||
|
||||
const isUnhealthy = health?.opencode !== 'healthy'
|
||||
|
||||
return (
|
||||
<div className="space-y-6 overflow-y-auto">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex gap-2 ">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
showToast.loading('Restarting OpenCode server...', { id: 'manual-restart' })
|
||||
restartServerMutation.mutate()
|
||||
}}
|
||||
disabled={restartServerMutation.isPending}
|
||||
>
|
||||
{restartServerMutation.isPending ? (
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
) : (
|
||||
<RotateCcw className="h-4 w-4 mr-2" />
|
||||
)}
|
||||
Restart Server
|
||||
</Button>
|
||||
<Button type="button" onClick={() => setIsCreateDialogOpen(true)}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
New Config
|
||||
</Button>
|
||||
<CreateConfigDialog
|
||||
isOpen={isCreateDialogOpen}
|
||||
onOpenChange={setIsCreateDialogOpen}
|
||||
onCreate={createConfig}
|
||||
isUpdating={isUpdating}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{health && (
|
||||
<Card className={isUnhealthy ? 'border-destructive' : ''}>
|
||||
<CardContent className="p-3">
|
||||
<div className="flex flex-col sm:flex-row sm:items-center items-center gap-3">
|
||||
<div className="flex items-center gap-2 flex-wrap justify-center sm:justify-start">
|
||||
<div className={`h-3 w-3 rounded-full ${isUnhealthy ? 'bg-destructive animate-pulse' : 'bg-green-500'}`} />
|
||||
<p className="font-medium text-sm sm:text-base">
|
||||
Server Status: {isUnhealthy ? 'Unhealthy' : 'Healthy'}
|
||||
</p>
|
||||
{health.error && (
|
||||
<p className="text-xs text-destructive">
|
||||
{health.error}
|
||||
</p>
|
||||
)}
|
||||
{health.opencodeVersion && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
v{health.opencodeVersion}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2 justify-center sm:justify-end">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
showToast.loading('Restarting OpenCode server...', { id: 'manual-restart' })
|
||||
restartServerMutation.mutate()
|
||||
}}
|
||||
disabled={restartServerMutation.isPending}
|
||||
>
|
||||
{restartServerMutation.isPending ? (
|
||||
<Loader2 className="h-3 w-3 sm:h-4 sm:w-4 mr-1 animate-spin" />
|
||||
) : (
|
||||
<RotateCcw className="h-3 w-3 sm:h-4 sm:w-4 mr-1" />
|
||||
)}
|
||||
<span className="text-xs sm:text-sm">Restart</span>
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
showToast.loading('Rolling back to previous config...', { id: 'rollback-config' })
|
||||
rollbackMutation.mutate()
|
||||
}}
|
||||
disabled={rollbackMutation.isPending}
|
||||
>
|
||||
{rollbackMutation.isPending ? (
|
||||
<Loader2 className="h-3 w-3 sm:h-4 sm:w-4 mr-1 animate-spin" />
|
||||
) : (
|
||||
<RotateCcw className="h-3 w-3 sm:h-4 sm:w-4 mr-1" />
|
||||
)}
|
||||
<span className="text-xs sm:text-sm">Rollback</span>
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => setIsCreateDialogOpen(true)}
|
||||
>
|
||||
<Plus className="h-3 w-3 sm:h-4 sm:w-4 mr-1" />
|
||||
<span className="text-xs sm:text-sm">New Config</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
<CreateConfigDialog
|
||||
isOpen={isCreateDialogOpen}
|
||||
onOpenChange={setIsCreateDialogOpen}
|
||||
onCreate={createConfig}
|
||||
isUpdating={isUpdating}
|
||||
/>
|
||||
|
||||
{configs.length === 0 ? (
|
||||
<Card>
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { toast } from 'sonner'
|
||||
import { settingsApi } from '@/api/settings'
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
|
||||
interface HealthResponse {
|
||||
status: 'healthy' | 'degraded' | 'unhealthy'
|
||||
timestamp: string
|
||||
database: 'connected' | 'disconnected'
|
||||
opencode: 'healthy' | 'unhealthy'
|
||||
opencodePort: number
|
||||
opencodeVersion: string | null
|
||||
opencodeMinVersion: string
|
||||
opencodeVersionSupported: boolean
|
||||
error?: string
|
||||
}
|
||||
|
||||
async function fetchHealth(): Promise<HealthResponse> {
|
||||
const response = await fetch('/api/health')
|
||||
if (!response.ok) {
|
||||
throw new Error('Health check failed')
|
||||
}
|
||||
return response.json()
|
||||
}
|
||||
|
||||
let lastHealthStatus: 'healthy' | 'unhealthy' = 'healthy'
|
||||
|
||||
export function useServerHealth(enabled = true) {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const restartMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
return await settingsApi.restartOpenCodeServer()
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['health'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode', 'agents'] })
|
||||
toast.success('Server restarted successfully')
|
||||
},
|
||||
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 server')
|
||||
: 'Failed to restart server'
|
||||
toast.error(errorMessage)
|
||||
},
|
||||
})
|
||||
|
||||
const rollbackMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
return await settingsApi.rollbackOpenCodeConfig()
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
queryClient.invalidateQueries({ queryKey: ['health'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['settings'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode', 'agents'] })
|
||||
toast.success(data.message)
|
||||
},
|
||||
onError: () => {
|
||||
toast.error('Failed to rollback to previous config')
|
||||
},
|
||||
})
|
||||
|
||||
const query = useQuery<HealthResponse>({
|
||||
queryKey: ['health'],
|
||||
queryFn: fetchHealth,
|
||||
refetchInterval: 30000,
|
||||
retry: false,
|
||||
enabled,
|
||||
staleTime: 10000,
|
||||
})
|
||||
|
||||
const { data: health } = query
|
||||
|
||||
if (health) {
|
||||
const isUnhealthy = health.opencode !== 'healthy'
|
||||
|
||||
if (isUnhealthy && lastHealthStatus === 'healthy') {
|
||||
toast.error(health.error || 'OpenCode server is currently unhealthy', {
|
||||
duration: Infinity,
|
||||
action: {
|
||||
label: 'Restart',
|
||||
onClick: () => restartMutation.mutate(),
|
||||
},
|
||||
})
|
||||
} else if (!isUnhealthy && lastHealthStatus === 'unhealthy') {
|
||||
toast.success('Server is back online')
|
||||
}
|
||||
|
||||
lastHealthStatus = isUnhealthy ? 'unhealthy' : 'healthy'
|
||||
}
|
||||
|
||||
return {
|
||||
...query,
|
||||
restartMutation,
|
||||
rollbackMutation,
|
||||
}
|
||||
}
|
||||
@@ -74,6 +74,7 @@ export const UserPreferencesSchema = z.object({
|
||||
customAgents: z.array(CustomAgentSchema),
|
||||
gitToken: z.string().optional(),
|
||||
tts: TTSConfigSchema.optional(),
|
||||
lastKnownGoodConfig: z.string().optional(),
|
||||
});
|
||||
|
||||
export const DEFAULT_TTS_CONFIG: TTSConfig = {
|
||||
|
||||
Reference in new issue
Block a user