fix: surface config validation errors in settings

This commit is contained in:
Chris Scott committed 2026-04-12 13:04:53 -04:00
1 parent 9669570e97
commit d893148d3d
5 files changed
+153 -29

No files matched your search

+1 -1
View File
@@ -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)
+46 -2
View File
@@ -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')
}
+66 -16
View File
@@ -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<string, unknown>
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<string, unknown>; validationIssues?: OpenCodeConfigValidationIssue[]; isValid: boolean } {
const parsed = parseJsonc(rawContent)
const content = parsed && typeof parsed === 'object' && !Array.isArray(parsed)
? parsed as Record<string, unknown>
: {}
const validated = OpenCodeConfigSchema.safeParse(parsed)
if (validated.success) {
return {
content: validated.data as Record<string, unknown>,
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<string, unknown>,
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<string, unknown>,
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,
+6 -1
View File
@@ -76,8 +76,13 @@ export interface UpdateSettingsRequest {
export interface OpenCodeConfig {
id: number
name: string
content: OpenCodeConfigContent
content: Record<string, unknown>
rawContent?: string
validationIssues?: Array<{
path: string
message: string
}>
isValid: boolean
isDefault: boolean
createdAt: number
updatedAt: number
@@ -469,7 +469,7 @@ export function OpenCodeConfigManager() {
<CardHeader className="pb-3">
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
<div>
<CardTitle className="text-sm sm:text-base">Existing OpenCode Host Import</CardTitle>
<CardTitle className="text-sm sm:text-base">Existing OpenCode Host Import</CardTitle>
<p className="text-sm text-muted-foreground mt-1">
Import your standalone OpenCode config and session state into this workspace, then restart the server so existing chats can reconnect.
</p>
@@ -562,12 +562,12 @@ export function OpenCodeConfigManager() {
</Card>
<MemoryPluginConfig
memoryPluginEnabled={configs.find(c => 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() {
<div className="flex items-center justify-between">
<div className="flex items-center gap-2 flex-wrap">
<CardTitle className="text-sm sm:text-base">{config.name}</CardTitle>
{!config.isValid && (
<Badge variant="destructive">
Invalid Config
</Badge>
)}
{config.isDefault && (
<Badge variant="default" className="text-green-500 bg-green-500/10">
Current
@@ -741,7 +746,7 @@ export function OpenCodeConfigManager() {
<SelectContent>
{configs.map(config => (
<SelectItem key={config.id} value={config.name}>
{config.name} {config.isDefault && '(Default)'}
{config.name} {config.isDefault && '(Default)'} {!config.isValid && '(Invalid)'}
</SelectItem>
))}
</SelectContent>
@@ -751,6 +756,26 @@ export function OpenCodeConfigManager() {
<div className="flex flex-col gap-4 pb-20 min-w-0">
{selectedConfig ? (
<>
{!selectedConfig.isValid && selectedConfig.validationIssues && selectedConfig.validationIssues.length > 0 && (
<div className="rounded-lg border border-destructive/40 bg-destructive/5 p-4">
<p className="font-medium text-destructive">This configuration has validation issues</p>
<p className="mt-1 text-sm text-destructive/90">
OpenCode may fail to start until these fields are corrected. Open the config editor to fix the file directly.
</p>
<ul className="mt-3 list-disc space-y-1 pl-5 text-sm text-destructive/90">
{selectedConfig.validationIssues.slice(0, 8).map((issue) => (
<li key={`${issue.path}-${issue.message}`}>
<span className="font-mono text-xs">{issue.path}</span>: {issue.message}
</li>
))}
</ul>
{selectedConfig.validationIssues.length > 8 && (
<p className="mt-2 text-xs text-destructive/80">
Showing 8 of {selectedConfig.validationIssues.length} issues. Open the config editor to review and fix the file.
</p>
)}
</div>
)}
<div className="bg-card border border-border rounded-lg overflow-hidden min-w-0">
<button
ref={commandsRef}
@@ -840,7 +865,7 @@ export function OpenCodeConfigManager() {
<div className="flex items-center gap-3 min-w-0">
<h4 className="text-sm font-medium truncate">Skills</h4>
<span className="text-xs text-muted-foreground">
{managedSkills.length + (selectedConfig.content?.skills?.paths?.length ?? 0) + (selectedConfig.content?.skills?.urls?.length ?? 0)} configured
{managedSkills.length + (((selectedConfig.content?.skills as { paths?: string[]; urls?: string[] } | undefined)?.paths?.length) ?? 0) + (((selectedConfig.content?.skills as { paths?: string[]; urls?: string[] } | undefined)?.urls?.length) ?? 0)} configured
</span>
</div>
<ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.skills ? 'rotate-90' : ''}`} />
@@ -848,7 +873,7 @@ export function OpenCodeConfigManager() {
<div className={`${expandedSections.skills ? 'block' : 'hidden'} border-t border-border`}>
<div className="p-4 max-h-[50vh] overflow-y-auto">
<SkillsEditor
skills={selectedConfig.content?.skills}
skills={selectedConfig.content?.skills as { paths?: string[]; urls?: string[] } | undefined}
managedSkills={managedSkills}
onChange={(skills) => {
const paths = skills?.paths?.filter(Boolean)