From 9c8811dbc70ea04f6026b1690f5434ab6ab51858 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Thu, 23 Apr 2026 19:55:55 -0400 Subject: [PATCH] refactor: improve OpenCode server restart logic with plugin awareness - Add plugin detection to determine if server restart is required when config changes - Extend health check timeout to 120s when plugins are configured (from 30s) - Implement retry-once logic for plugin installations that may cause initial startup failure - Check agent, plugin, skills, and provider fields for restart decisions (previously only agents) - Improve frontend toast messages to distinguish between restart and apply scenarios - Set XDG_CACHE_HOME in Dockerfile for proper cache directory management --- Dockerfile | 2 +- backend/src/routes/settings.ts | 69 +++++++++++++++++-- .../src/services/opencode-single-server.ts | 26 ++++++- .../settings/OpenCodeConfigManager.tsx | 26 ++++--- 4 files changed, 98 insertions(+), 25 deletions(-) diff --git a/Dockerfile b/Dockerfile index 64785315..5ef124db 100644 --- a/Dockerfile +++ b/Dockerfile @@ -80,6 +80,7 @@ ENV PORT=5003 ENV OPENCODE_SERVER_PORT=5551 ENV DATABASE_PATH=/app/data/opencode.db ENV WORKSPACE_PATH=/workspace +ENV XDG_CACHE_HOME=/home/node/.cache COPY --from=deps --chown=node:node /app/node_modules ./node_modules COPY --from=builder /app/shared ./shared @@ -103,4 +104,3 @@ HEALTHCHECK --interval=30s --timeout=3s --start-period=40s --retries=3 \ ENTRYPOINT ["/docker-entrypoint.sh"] CMD ["bun", "backend/src/index.ts"] - diff --git a/backend/src/routes/settings.ts b/backend/src/routes/settings.ts index 72fa8154..3f88f5bc 100644 --- a/backend/src/routes/settings.ts +++ b/backend/src/routes/settings.ts @@ -68,6 +68,25 @@ function getOpenCodeConfigContentToWrite( return JSON.stringify(appliedConfig, null, 2) } +function didConfigFieldChange( + previous: Record | undefined, + next: Record | undefined, + field: string +): boolean { + return JSON.stringify(previous?.[field]) !== JSON.stringify(next?.[field]) +} + +function needsOpenCodeRestart( + previous: Record | undefined, + next: Record | undefined +): boolean { + return ['agent', 'plugin', 'skills', 'provider'].some((field) => didConfigFieldChange(previous, next, field)) +} + +function hasConfiguredPlugins(config: Record | undefined): boolean { + return Array.isArray(config?.plugin) && config.plugin.length > 0 +} + function execWithTimeout( command: string | [executable: string, ...args: string[]], timeoutMs: number, @@ -313,6 +332,25 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic { suppressAutoDefault: true } ) + if (hasConfiguredPlugins(provisionalConfig.content)) { + const config = settingsService.updateOpenCodeConfig(provisionalConfig.name, { + content: provisionalConfig.rawContent, + isDefault: true, + }, userId) + + if (!config) { + return c.json({ error: 'Failed to finalize OpenCode config creation' }, 500) + } + + const configPath = getOpenCodeConfigFilePath() + await writeFileContent(configPath, provisionalConfig.rawContent) + logger.info(`Wrote default config to: ${configPath}`) + opencodeServerManager.clearStartupError() + await opencodeServerManager.restart() + + return c.json(config) + } + const patchResult = await patchOpenCodeConfig(provisionalConfig.content) if (!patchResult.success) { settingsService.deleteOpenCodeConfig(provisionalConfig.name, userId) @@ -372,7 +410,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic const validated = UpdateOpenCodeConfigSchema.parse(body) const existingConfig = settingsService.getOpenCodeConfigByName(configName, userId) - const existingAgents = existingConfig?.content?.agent + const previousContent = existingConfig?.content const config = settingsService.updateOpenCodeConfig(configName, validated, userId) if (!config) { @@ -380,11 +418,14 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic } if (config.isDefault) { - const newAgents = config.content?.agent - const agentsChanged = JSON.stringify(existingAgents) !== JSON.stringify(newAgents) - - if (agentsChanged) { - logger.info('Agent configuration changed, restarting OpenCode server') + const restartRequired = needsOpenCodeRestart(previousContent, config.content) + const configPath = getOpenCodeConfigFilePath() + + if (restartRequired) { + await writeFileContent(configPath, config.rawContent) + logger.info(`Wrote default config to: ${configPath}`) + logger.info('OpenCode configuration requires process restart') + opencodeServerManager.clearStartupError() await opencodeServerManager.restart() } else { const patchResult = await patchOpenCodeConfig(config.content) @@ -397,7 +438,6 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic }, 500) } - const configPath = getOpenCodeConfigFilePath() const contentToWrite = patchResult.removedFields && patchResult.removedFields.length > 0 ? JSON.stringify(config.content, null, 2) : config.rawContent @@ -451,6 +491,21 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic return c.json({ error: 'Config not found' }, 404) } + if (hasConfiguredPlugins(existingConfig.content)) { + const config = settingsService.setDefaultOpenCodeConfig(configName, userId) + if (!config) { + return c.json({ error: 'Config not found' }, 404) + } + + const configPath = getOpenCodeConfigFilePath() + await writeFileContent(configPath, existingConfig.rawContent) + logger.info(`Wrote default config '${configName}' to: ${configPath}`) + opencodeServerManager.clearStartupError() + await opencodeServerManager.restart() + + return c.json(config) + } + const patchResult = await patchOpenCodeConfig(existingConfig.content) if (!patchResult.success) { return c.json({ diff --git a/backend/src/services/opencode-single-server.ts b/backend/src/services/opencode-single-server.ts index c87af2fd..6687f350 100644 --- a/backend/src/services/opencode-single-server.ts +++ b/backend/src/services/opencode-single-server.ts @@ -17,6 +17,7 @@ import { import { decryptSecret } from '../utils/crypto' import { SettingsService } from './settings' import { getWorkspacePath, getOpenCodeConfigFilePath, ENV } from '@opencode-manager/shared/config/env' +import { parseJsonc } from '@opencode-manager/shared/utils' import type { Database } from 'bun:sqlite' import { compareVersions } from '../utils/version-utils' import { patchOpenCodeConfig } from './proxy' @@ -121,7 +122,7 @@ class OpenCodeServerManager { OpenCodeServerManager.instance = null as unknown as OpenCodeServerManager } - async start(): Promise { + async start(retryAfterPluginInstall = true): Promise { if (this.isHealthy) { logger.info('OpenCode server already running and healthy') return @@ -236,6 +237,7 @@ class OpenCodeServerManager { logger.info(`OpenCode server GIT_SSH_COMMAND: ${gitSshCommand}`) await this.initializeOpencodeBinDirectory() + const configuredPluginCount = await this.getConfiguredPluginCount(openCodeConfigPath) let stderrOutput = '' @@ -296,10 +298,18 @@ class OpenCodeServerManager { logger.info(`OpenCode server started with PID ${this.serverPid}`) - const healthy = await this.waitForHealth(30000) + const healthTimeoutMs = configuredPluginCount > 0 ? 120000 : 30000 + const healthy = await this.waitForHealth(healthTimeoutMs) if (!healthy) { - const fallback = `Server failed to become healthy after 30s${stderrOutput ? `. Last error: ${stderrOutput.slice(-500)}` : ''}` + const fallback = `Server failed to become healthy after ${Math.round(healthTimeoutMs / 1000)}s${stderrOutput ? `. Last error: ${stderrOutput.slice(-500)}` : ''}` this.lastStartupError = formatStartupError(stderrOutput, fallback) + if (configuredPluginCount > 0 && retryAfterPluginInstall) { + logger.warn(`OpenCode server did not become healthy after installing ${configuredPluginCount} configured plugin(s); restarting once`) + await this.stop() + await new Promise(r => setTimeout(r, 1000)) + await this.start(false) + return + } throw new Error('OpenCode server failed to become healthy') } @@ -394,6 +404,16 @@ class OpenCodeServerManager { } } + private async getConfiguredPluginCount(configPath: string): Promise { + try { + const content = await fs.readFile(configPath, 'utf-8') + const config = parseJsonc(content) as { plugin?: unknown } + return Array.isArray(config.plugin) ? config.plugin.length : 0 + } catch { + return 0 + } + } + async restart(): Promise { logger.info('Restarting OpenCode server (full process restart)') await this.stop() diff --git a/frontend/src/components/settings/OpenCodeConfigManager.tsx b/frontend/src/components/settings/OpenCodeConfigManager.tsx index 42ba0baf..6d043b7c 100644 --- a/frontend/src/components/settings/OpenCodeConfigManager.tsx +++ b/frontend/src/components/settings/OpenCodeConfigManager.tsx @@ -102,15 +102,6 @@ export function OpenCodeConfigManager() { } } - const reloadConfigMutation = useMutation({ - mutationFn: async () => { - return await settingsApi.reloadOpenCodeConfig() - }, - onSuccess: () => { - invalidateConfigCaches(queryClient) - }, - }) - const restartServerMutation = useMutation({ mutationFn: async () => { return await settingsApi.restartOpenCodeServer() @@ -238,7 +229,8 @@ export function OpenCodeConfigManager() { const updateConfigContent = async (configName: string, newContent: Record, restartServer = false) => { try { setIsUpdating(true) - const previousContent = configs.find(c => c.name === configName)?.content + const previousConfig = configs.find(c => c.name === configName) + const previousContent = previousConfig?.content const result = await settingsApi.updateOpenCodeConfig(configName, { content: newContent }) @@ -256,15 +248,21 @@ export function OpenCodeConfigManager() { const pluginsChanged = JSON.stringify(previousContent?.plugin) !== JSON.stringify(newContent.plugin) const skillsChanged = JSON.stringify(previousContent?.skills) !== JSON.stringify(newContent.skills) const providersChanged = JSON.stringify(previousContent?.provider) !== JSON.stringify(newContent.provider) - if (restartServer || agentsChanged || pluginsChanged || skillsChanged || providersChanged) { - showToast.loading('Reloading server...', { id: 'update-restart' }) + const defaultConfigChanged = Boolean(previousConfig?.isDefault && (agentsChanged || pluginsChanged || skillsChanged || providersChanged)) + if (restartServer || defaultConfigChanged) { + showToast.loading(restartServer ? 'Restarting server...' : 'Applying server configuration...', { id: 'update-restart' }) try { - await reloadConfigMutation.mutateAsync() + if (restartServer && !defaultConfigChanged) { + await restartServerMutation.mutateAsync() + } if (result.removedFields && result.removedFields.length > 0) { showToast.info(`Configuration updated after removing invalid fields: ${result.removedFields.join(', ')}`, { id: 'update-restart' }) + } else if (pluginsChanged || restartServer) { + showToast.success('Configuration updated and server restarted', { id: 'update-restart' }) } else { - showToast.success('Configuration updated and server reloaded', { id: 'update-restart' }) + showToast.success('Configuration updated and server applied', { id: 'update-restart' }) } + invalidateConfigCaches(queryClient) } catch (error) { showToast.error(getRestartErrorMessage(error), { id: 'update-restart' }) throw error