diff --git a/backend/src/routes/settings.ts b/backend/src/routes/settings.ts index 334d2b93..27cf4e6c 100644 --- a/backend/src/routes/settings.ts +++ b/backend/src/routes/settings.ts @@ -188,7 +188,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic const userId = c.req.query('userId') || 'default' const configs = settingsService.getOpenCodeConfigs(userId) const defaultConfig = configs.configs.find((cfg: { isDefault: boolean }) => cfg.isDefault) - const isEnabled = defaultConfig?.content?.plugin?.includes('@opencode-manager/memory') ?? false + const isEnabled = ((defaultConfig?.content?.plugin as string[] | undefined) ?? []).includes('@opencode-manager/memory') return c.json({ memoryPluginEnabled: isEnabled }) } catch (error) { logger.error('Failed to get memory plugin status:', error) diff --git a/backend/src/services/opencode-single-server.ts b/backend/src/services/opencode-single-server.ts index 79c2e00b..edc8eefc 100644 --- a/backend/src/services/opencode-single-server.ts +++ b/backend/src/services/opencode-single-server.ts @@ -25,6 +25,48 @@ const OPENCODE_SERVER_HOST = ENV.OPENCODE.HOST const MIN_OPENCODE_VERSION = '1.0.137' const MAX_STDERR_SIZE = 10240 +type StartupValidationIssue = { + path: string + message: string +} + +function parseStartupValidationIssues(stderrOutput: string): StartupValidationIssue[] { + const match = stderrOutput.match(/ZodError:\s*(\[[\s\S]*?\])(?:\n\s+at |$)/) + if (!match?.[1]) { + return [] + } + + try { + const parsed = JSON.parse(match[1]) as Array<{ path?: unknown; message?: unknown }> + return parsed + .map((issue) => ({ + path: Array.isArray(issue.path) && issue.path.length > 0 ? issue.path.join('.') : 'root', + message: typeof issue.message === 'string' ? issue.message : 'Invalid value', + })) + .filter((issue) => issue.message) + } catch { + return [] + } +} + +function formatStartupError(stderrOutput: string, fallback: string): string { + const validationIssues = parseStartupValidationIssues(stderrOutput) + if (validationIssues.length === 0) { + return fallback + } + + const summary = validationIssues + .slice(0, 8) + .map((issue) => `${issue.path}: ${issue.message}`) + .join('; ') + + const remainder = validationIssues.length > 8 + ? ` (${validationIssues.length - 8} more issue${validationIssues.length - 8 === 1 ? '' : 's'})` + : '' + + return `OpenCode config validation failed: ${summary}${remainder}` +} + // Helper getters to ensure values are computed at runtime (not module load time) // This allows proper mocking in tests const getOpenCodeServerDirectory = () => getWorkspacePath() @@ -208,7 +250,8 @@ class OpenCodeServerManager { this.serverProcess.on('exit', (code, signal) => { if (code !== null && code !== 0) { - this.lastStartupError = `Server exited with code ${code}${stderrOutput ? `: ${stderrOutput.slice(-500)}` : ''}` + const fallback = `Server exited with code ${code}${stderrOutput ? `: ${stderrOutput.slice(-500)}` : ''}` + this.lastStartupError = formatStartupError(stderrOutput, fallback) logger.error('OpenCode server process exited:', this.lastStartupError) } else if (signal) { this.lastStartupError = `Server terminated by signal ${signal}` @@ -222,7 +265,8 @@ class OpenCodeServerManager { const healthy = await this.waitForHealth(30000) if (!healthy) { - this.lastStartupError = `Server failed to become healthy after 30s${stderrOutput ? `. Last error: ${stderrOutput.slice(-500)}` : ''}` + const fallback = `Server failed to become healthy after 30s${stderrOutput ? `. Last error: ${stderrOutput.slice(-500)}` : ''}` + this.lastStartupError = formatStartupError(stderrOutput, fallback) throw new Error('OpenCode server failed to become healthy') } diff --git a/backend/src/services/settings.ts b/backend/src/services/settings.ts index 54890997..1bbaccb8 100644 --- a/backend/src/services/settings.ts +++ b/backend/src/services/settings.ts @@ -3,10 +3,10 @@ import { unlinkSync, existsSync } from 'fs' import { getOpenCodeConfigFilePath } from '@opencode-manager/shared/config/env' import { logger } from '../utils/logger' import { parseJsonc } from '@opencode-manager/shared/utils' +import { z } from 'zod' import type { UserPreferences, SettingsResponse, - OpenCodeConfig, CreateOpenCodeConfigRequest, UpdateOpenCodeConfigRequest } from '../types/settings' @@ -16,8 +16,21 @@ import { DEFAULT_USER_PREFERENCES, } from '../types/settings' -interface OpenCodeConfigWithRaw extends OpenCodeConfig { +interface OpenCodeConfigValidationIssue { + path: string + message: string +} + +interface OpenCodeConfigWithRaw { + id: number + name: string + content: Record rawContent: string + validationIssues?: OpenCodeConfigValidationIssue[] + isValid: boolean + isDefault: boolean + createdAt: number + updatedAt: number } interface OpenCodeConfigResponseWithRaw { @@ -31,6 +44,37 @@ export class SettingsService { constructor(private db: Database) {} + private getValidationIssues(error: z.ZodError): OpenCodeConfigValidationIssue[] { + return error.issues.map((issue) => ({ + path: issue.path.length > 0 ? issue.path.join('.') : 'root', + message: issue.message, + })) + } + + private parseStoredConfig(rawContent: string, configName: string): { content: Record; validationIssues?: OpenCodeConfigValidationIssue[]; isValid: boolean } { + const parsed = parseJsonc(rawContent) + const content = parsed && typeof parsed === 'object' && !Array.isArray(parsed) + ? parsed as Record + : {} + + const validated = OpenCodeConfigSchema.safeParse(parsed) + if (validated.success) { + return { + content: validated.data as Record, + isValid: true, + } + } + + const validationIssues = this.getValidationIssues(validated.error) + logger.error(`Failed to validate config ${configName}: ${validationIssues.map((issue) => `${issue.path}: ${issue.message}`).join('; ')}`) + + return { + content, + validationIssues, + isValid: false, + } + } + initializeLastKnownGoodConfig(userId: string = 'default'): void { const settings = this.getSettings(userId) if (settings.preferences.lastKnownGoodConfig) { @@ -140,14 +184,15 @@ export class SettingsService { for (const row of rows) { try { const rawContent = row.config_content - const content = parseJsonc(rawContent) - const validated = OpenCodeConfigSchema.parse(content) + const parsedConfig = this.parseStoredConfig(rawContent, row.config_name) const config: OpenCodeConfigWithRaw = { id: row.id, name: row.config_name, - content: validated, + content: parsedConfig.content, rawContent: rawContent, + validationIssues: parsedConfig.validationIssues, + isValid: parsedConfig.isValid, isDefault: Boolean(row.is_default), createdAt: row.created_at, updatedAt: row.updated_at, @@ -219,8 +264,9 @@ export class SettingsService { const config: OpenCodeConfigWithRaw = { id: result.lastInsertRowid as number, name: request.name, - content: contentValidated, + content: contentValidated as Record, rawContent: rawContent, + isValid: true, isDefault: shouldBeDefault, createdAt: now, updatedAt: now, @@ -282,8 +328,9 @@ export class SettingsService { const config: OpenCodeConfigWithRaw = { id: existing.id, name: configName, - content: contentValidated, + content: contentValidated as Record, rawContent: rawContent, + isValid: true, isDefault: request.isDefault !== undefined ? request.isDefault : existing.is_default, createdAt: existing.created_at, updatedAt: now, @@ -335,14 +382,15 @@ export class SettingsService { try { const rawContent = existing.config_content - const content = parseJsonc(rawContent) - const validated = OpenCodeConfigSchema.parse(content) + const parsedConfig = this.parseStoredConfig(rawContent, configName) const config: OpenCodeConfigWithRaw = { id: existing.id, name: configName, - content: validated, + content: parsedConfig.content, rawContent: rawContent, + validationIssues: parsedConfig.validationIssues, + isValid: parsedConfig.isValid, isDefault: true, createdAt: existing.created_at, updatedAt: now, @@ -373,14 +421,15 @@ export class SettingsService { try { const rawContent = row.config_content - const content = parseJsonc(rawContent) - const validated = OpenCodeConfigSchema.parse(content) + const parsedConfig = this.parseStoredConfig(rawContent, row.config_name) return { id: row.id, name: row.config_name, - content: validated, + content: parsedConfig.content, rawContent: rawContent, + validationIssues: parsedConfig.validationIssues, + isValid: parsedConfig.isValid, isDefault: true, createdAt: row.created_at, updatedAt: row.updated_at, @@ -409,14 +458,15 @@ export class SettingsService { try { const rawContent = row.config_content - const content = parseJsonc(rawContent) - const validated = OpenCodeConfigSchema.parse(content) + const parsedConfig = this.parseStoredConfig(rawContent, configName) return { id: row.id, name: row.config_name, - content: validated, + content: parsedConfig.content, rawContent: rawContent, + validationIssues: parsedConfig.validationIssues, + isValid: parsedConfig.isValid, isDefault: Boolean(row.is_default), createdAt: row.created_at, updatedAt: row.updated_at, diff --git a/frontend/src/api/types/settings.ts b/frontend/src/api/types/settings.ts index 4c386de1..1316941a 100644 --- a/frontend/src/api/types/settings.ts +++ b/frontend/src/api/types/settings.ts @@ -76,8 +76,13 @@ export interface UpdateSettingsRequest { export interface OpenCodeConfig { id: number name: string - content: OpenCodeConfigContent + content: Record rawContent?: string + validationIssues?: Array<{ + path: string + message: string + }> + isValid: boolean isDefault: boolean createdAt: number updatedAt: number diff --git a/frontend/src/components/settings/OpenCodeConfigManager.tsx b/frontend/src/components/settings/OpenCodeConfigManager.tsx index 30b1f1ab..37ae7981 100644 --- a/frontend/src/components/settings/OpenCodeConfigManager.tsx +++ b/frontend/src/components/settings/OpenCodeConfigManager.tsx @@ -469,7 +469,7 @@ export function OpenCodeConfigManager() {
- Existing OpenCode Host Import + Existing OpenCode Host Import

Import your standalone OpenCode config and session state into this workspace, then restart the server so existing chats can reconnect.

@@ -562,12 +562,12 @@ export function OpenCodeConfigManager() { c.isDefault)?.content?.plugin?.includes('@opencode-manager/memory') ?? false} + memoryPluginEnabled={((configs.find(c => c.isDefault)?.content?.plugin as string[] | undefined) ?? []).includes('@opencode-manager/memory')} onToggle={async (enabled) => { - const defaultConfig = configs.find(c => c.isDefault) - if (!defaultConfig) return - - const currentPlugins = defaultConfig.content?.plugin ?? [] + const defaultConfig = configs.find(c => c.isDefault) + if (!defaultConfig) return + + const currentPlugins = (defaultConfig.content?.plugin as string[] | undefined) ?? [] const memoryPlugin = '@opencode-manager/memory' const newPlugins = enabled ? currentPlugins.includes(memoryPlugin) @@ -616,6 +616,11 @@ export function OpenCodeConfigManager() {
{config.name} + {!config.isValid && ( + + Invalid Config + + )} {config.isDefault && ( Current @@ -741,7 +746,7 @@ export function OpenCodeConfigManager() { {configs.map(config => ( - {config.name} {config.isDefault && '(Default)'} + {config.name} {config.isDefault && '(Default)'} {!config.isValid && '(Invalid)'} ))} @@ -751,6 +756,26 @@ export function OpenCodeConfigManager() {
{selectedConfig ? ( <> + {!selectedConfig.isValid && selectedConfig.validationIssues && selectedConfig.validationIssues.length > 0 && ( +
+

This configuration has validation issues

+

+ OpenCode may fail to start until these fields are corrected. Open the config editor to fix the file directly. +

+
    + {selectedConfig.validationIssues.slice(0, 8).map((issue) => ( +
  • + {issue.path}: {issue.message} +
  • + ))} +
+ {selectedConfig.validationIssues.length > 8 && ( +

+ Showing 8 of {selectedConfig.validationIssues.length} issues. Open the config editor to review and fix the file. +

+ )} +
+ )}
@@ -848,7 +873,7 @@ export function OpenCodeConfigManager() {
{ const paths = skills?.paths?.filter(Boolean)