mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
refactor(config): make on-disk opencode.json the single source of truth (#354)
* refactor(config): make on-disk opencode.json the single source of truth Make <workspace>/.config/opencode/opencode.json the only store for the active OpenCode configuration. One owner (opencode-config-file.ts) reads, validates, writes, archives, and seeds the file; one owner (opencode-config-apply.ts) decides how an edit is applied: restart pending, or a live patch with recovery. Settings routes, the internal assistant API, the health-watch supervisor, boot, and host import all go through them, so an edit that lands on the file without going through the database is visible immediately instead of at the next Manager boot. Remove the named-config profiles. Migration 019 archives every opencode_configs row to .config/opencode-configs-archive/<name>.json, restores the default row to opencode.json when no file exists, then drops the table, its indexes, and repos.opencode_config_name. The /opencode-configs* and config/switch routes and the CreateConfigDialog/SwitchConfigDialog dialogs are gone, and the ocm tool gains GET/PUT /opencode-config backed by the same apply owner. Harden the write path: serialize and atomically write config updates while preserving the file mode, keep withFileLock usable after a rejection, route reloadConfig's cleaned-config write through the file owner, stop boot from rewriting an existing valid config when importing state, prune the health-watch directory to its newest 20 entries, resolve archive paths with realpath, and share one frontend config query across dialogs. * fix(mirror): canonicalize worktree paths before branch ownership check * refactor(config): unify opencode config apply and rollback paths - share one config route factory between public and internal mounts - capture last-known-good before every config write and restore via one helper - stop auto-restarting on save; flag restart-required fields and live-patch the rest - add CONFIG_PATCH_TIMEOUT_MS for config patch requests - extract canonicalPath helpers, health-watch artifact writer, and useProvidersWithModels hook * refactor(model-state): use OpenCode state file as model state source of truth
This commit is contained in:
1 parent
7a3c5229df
commit
295d24ced7
116 files changed
+10291
-4208
No files matched your search
@@ -26,12 +26,17 @@ import {
|
||||
getOpenCodeTmpHome,
|
||||
ENV,
|
||||
} from '@opencode-manager/shared/config/env'
|
||||
import { parseJsonc } from '@opencode-manager/shared/utils'
|
||||
import { ZodError } from 'zod'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { compareVersions } from '../utils/version-utils'
|
||||
import { patchConfigWithRecovery } from './opencode/config-recovery'
|
||||
import type { OpenCodeClient } from './opencode/client'
|
||||
import { writeFileContent } from './file-operations'
|
||||
import {
|
||||
readOpenCodeConfigFile,
|
||||
toOpenCodeConfigValidationIssues,
|
||||
withOpenCodeConfigLock,
|
||||
writeOpenCodeConfigFile,
|
||||
} from './opencode-config-file'
|
||||
import { getOrCreateInternalToken } from './internal-token'
|
||||
import { installManagedPlugins } from './opencode/plugin-registry'
|
||||
import { getOpenCodePluginDiscoveryHome, restoreQuarantinedOpenCodePlugins } from './opencode-plugin-quarantine'
|
||||
@@ -615,7 +620,7 @@ class OpenCodeServerManager {
|
||||
}
|
||||
logger.warn('Failed to install a generated OpenCode plugin (sandboxing is disabled):', error)
|
||||
}
|
||||
const configuredPlugins = await this.getConfiguredPlugins(openCodeConfigPath)
|
||||
const configuredPlugins = await this.getConfiguredPlugins()
|
||||
await this.installConfiguredPlugins(configuredPlugins)
|
||||
const configuredPluginCount = configuredPlugins.length
|
||||
const openCodeExecutable = resolveOpenCodeExecutable() ?? 'opencode'
|
||||
@@ -957,13 +962,13 @@ class OpenCodeServerManager {
|
||||
return options !== null && typeof options === 'object' && !Array.isArray(options)
|
||||
}
|
||||
|
||||
private async getConfiguredPlugins(configPath: string): Promise<OpenCodePluginSpec[]> {
|
||||
private async getConfiguredPlugins(): Promise<OpenCodePluginSpec[]> {
|
||||
try {
|
||||
const content = await fs.readFile(configPath, 'utf-8')
|
||||
const config = parseJsonc(content) as { plugin?: unknown }
|
||||
if (!Array.isArray(config.plugin)) return []
|
||||
return config.plugin
|
||||
.filter((plugin): plugin is OpenCodePluginSpec => this.isOpenCodePluginSpec(plugin))
|
||||
const file = await readOpenCodeConfigFile()
|
||||
const plugin = file?.content.plugin
|
||||
if (!Array.isArray(plugin)) return []
|
||||
return plugin
|
||||
.filter((entry): entry is OpenCodePluginSpec => this.isOpenCodePluginSpec(entry))
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
@@ -1043,31 +1048,44 @@ class OpenCodeServerManager {
|
||||
try {
|
||||
logger.info('Reloading OpenCode configuration (via API)')
|
||||
try {
|
||||
const configPath = getOpenCodeConfigFilePath()
|
||||
const fileContent = await fs.readFile(configPath, 'utf-8')
|
||||
const fileConfig = parseJsonc(fileContent) as Record<string, unknown>
|
||||
logger.info(`Read config from file for reload: ${configPath}`)
|
||||
|
||||
const patchTarget = fileConfig
|
||||
const patchResult = await patchConfigWithRecovery(this.requireClient(), patchTarget)
|
||||
if (!patchResult.success) {
|
||||
const errorMessage = patchResult.error || 'Failed to reload config'
|
||||
const validationIssues = patchResult.details || []
|
||||
const removedFields = patchResult.removedFields || []
|
||||
if (validationIssues.length > 0) {
|
||||
const issueSummary = validationIssues.map((d) => `${d.path}: ${d.message}`).join('; ')
|
||||
logger.error(`Config reload validation errors: ${issueSummary}`)
|
||||
await withOpenCodeConfigLock(async () => {
|
||||
const file = await readOpenCodeConfigFile()
|
||||
if (file === null) {
|
||||
throw new Error(`OpenCode config file not found: ${getOpenCodeConfigFilePath()}`)
|
||||
}
|
||||
if (removedFields.length > 0) {
|
||||
logger.info(`Removed fields during config reload: ${removedFields.join(', ')}`)
|
||||
}
|
||||
throw new ConfigReloadError(errorMessage, validationIssues, removedFields)
|
||||
}
|
||||
logger.info(`Read config from file for reload: ${file.path}`)
|
||||
|
||||
if (patchResult.removedFields && patchResult.removedFields.length > 0 && patchResult.appliedConfig) {
|
||||
await writeFileContent(configPath, JSON.stringify(patchResult.appliedConfig, null, 2))
|
||||
logger.info(`Persisted cleaned config to ${configPath} after removing fields: ${patchResult.removedFields.join(', ')}`)
|
||||
}
|
||||
const patchResult = await patchConfigWithRecovery(this.requireClient(), file.content)
|
||||
if (!patchResult.success) {
|
||||
const errorMessage = patchResult.error || 'Failed to reload config'
|
||||
const validationIssues = patchResult.details || []
|
||||
const removedFields = patchResult.removedFields || []
|
||||
if (validationIssues.length > 0) {
|
||||
const issueSummary = validationIssues.map((d) => `${d.path}: ${d.message}`).join('; ')
|
||||
logger.error(`Config reload validation errors: ${issueSummary}`)
|
||||
}
|
||||
if (removedFields.length > 0) {
|
||||
logger.info(`Removed fields during config reload: ${removedFields.join(', ')}`)
|
||||
}
|
||||
throw new ConfigReloadError(errorMessage, validationIssues, removedFields)
|
||||
}
|
||||
|
||||
if (patchResult.removedFields && patchResult.removedFields.length > 0 && patchResult.appliedConfig) {
|
||||
const cleanedConfigContent = JSON.stringify(patchResult.appliedConfig, null, 2)
|
||||
try {
|
||||
await writeOpenCodeConfigFile(cleanedConfigContent)
|
||||
} catch (error) {
|
||||
if (error instanceof ZodError) {
|
||||
const validationIssues = toOpenCodeConfigValidationIssues(error.issues)
|
||||
const issueSummary = validationIssues.map((d) => `${d.path}: ${d.message}`).join('; ')
|
||||
logger.error(`Config reload validation errors: ${issueSummary}`)
|
||||
throw new ConfigReloadError('Cleaned config failed validation', validationIssues, patchResult.removedFields)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
logger.info(`Persisted cleaned config to ${file.path} after removing fields: ${patchResult.removedFields.join(', ')}`)
|
||||
}
|
||||
})
|
||||
|
||||
logger.info('OpenCode configuration reloaded successfully')
|
||||
await new Promise(r => setTimeout(r, 500))
|
||||
|
||||
Reference in new issue
Block a user