mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +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
@@ -1,5 +1,9 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
|
||||
vi.mock('node:fs', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('node:fs')>()),
|
||||
existsSync: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('fs/promises', () => ({
|
||||
cp: vi.fn(),
|
||||
@@ -20,11 +24,22 @@ vi.mock('../../src/services/file-operations', () => ({
|
||||
ensureDirectoryExists: vi.fn(),
|
||||
fileExists: vi.fn(),
|
||||
readFileContent: vi.fn(),
|
||||
writeFileContent: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/settings', () => ({
|
||||
SettingsService: vi.fn(),
|
||||
vi.mock('../../src/services/opencode-config-file', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('../../src/services/opencode-config-file')>()),
|
||||
readOpenCodeConfigFile: vi.fn(),
|
||||
writeOpenCodeConfigFile: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/opencode-single-server', () => ({
|
||||
opencodeServerManager: {
|
||||
clearStartupError: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/opencode/config-recovery', () => ({
|
||||
patchConfigWithRecovery: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@opencode-manager/shared/config/env', () => ({
|
||||
@@ -33,37 +48,33 @@ vi.mock('@opencode-manager/shared/config/env', () => ({
|
||||
}))
|
||||
|
||||
import path from 'path'
|
||||
import { existsSync } from 'node:fs'
|
||||
import { readdir, rm, cp, mkdtemp, rename } from 'fs/promises'
|
||||
import { Database as SQLiteDatabase } from 'bun:sqlite'
|
||||
import { ensureDirectoryExists, fileExists, readFileContent, writeFileContent } from '../../src/services/file-operations'
|
||||
import { SettingsService } from '../../src/services/settings'
|
||||
import { getOpenCodeImportStatus, syncOpenCodeImport } from '../../src/services/opencode-import'
|
||||
import { ensureDirectoryExists, fileExists, readFileContent } from '../../src/services/file-operations'
|
||||
import { readOpenCodeConfigFile, writeOpenCodeConfigFile } from '../../src/services/opencode-config-file'
|
||||
import type { SettingsService } from '../../src/services/settings'
|
||||
import { getFirstExistingConfigSourcePath, getOpenCodeImportStatus, syncOpenCodeImport } from '../../src/services/opencode-import'
|
||||
|
||||
const mockReaddir = readdir as unknown as ReturnType<typeof vi.fn>
|
||||
const mockExistsSync = existsSync as ReturnType<typeof vi.fn>
|
||||
const mockFileExists = fileExists as ReturnType<typeof vi.fn>
|
||||
const mockReadFileContent = readFileContent as ReturnType<typeof vi.fn>
|
||||
const mockWriteFileContent = writeFileContent as ReturnType<typeof vi.fn>
|
||||
const mockEnsureDirectoryExists = ensureDirectoryExists as ReturnType<typeof vi.fn>
|
||||
const MockSettingsService = SettingsService as unknown as ReturnType<typeof vi.fn>
|
||||
const mockReadOpenCodeConfigFile = readOpenCodeConfigFile as ReturnType<typeof vi.fn>
|
||||
const mockWriteOpenCodeConfigFile = writeOpenCodeConfigFile as ReturnType<typeof vi.fn>
|
||||
const MockSQLiteDatabase = SQLiteDatabase as unknown as ReturnType<typeof vi.fn>
|
||||
const mockMkdtemp = mkdtemp as unknown as ReturnType<typeof vi.fn>
|
||||
const mockRename = rename as unknown as ReturnType<typeof vi.fn>
|
||||
|
||||
describe('opencode-import service', () => {
|
||||
const mockDb = {} as unknown as Database
|
||||
const settingsService = {
|
||||
getOpenCodeConfigByName: vi.fn(),
|
||||
updateOpenCodeConfig: vi.fn(),
|
||||
createOpenCodeConfig: vi.fn(),
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
MockSettingsService.mockImplementation(() => settingsService)
|
||||
mockReadFileContent.mockResolvedValue('{"$schema":"https://opencode.ai/config.json"}')
|
||||
mockReaddir.mockResolvedValue([])
|
||||
mockMkdtemp.mockResolvedValue('/tmp/workspace/.opencode/state/opencode-import-123')
|
||||
mockRename.mockResolvedValue(undefined)
|
||||
mockExistsSync.mockImplementation((candidate: string) => candidate === process.env.OPENCODE_IMPORT_CONFIG_PATH)
|
||||
})
|
||||
|
||||
it('detects importable host config and state paths with opencode.db', async () => {
|
||||
@@ -108,23 +119,14 @@ describe('opencode-import service', () => {
|
||||
|| candidate === '/tmp/workspace/.opencode/state/opencode/opencode.db'
|
||||
})
|
||||
|
||||
settingsService.getOpenCodeConfigByName.mockReturnValue({ name: 'default' })
|
||||
|
||||
const result = await syncOpenCodeImport({
|
||||
db: mockDb,
|
||||
userId: 'default',
|
||||
overwriteState: true,
|
||||
})
|
||||
|
||||
expect(result.configImported).toBe(true)
|
||||
expect(result.stateImported).toBe(true)
|
||||
expect(result.workspaceStateExists).toBe(true)
|
||||
expect(settingsService.updateOpenCodeConfig).toHaveBeenCalledWith('default', {
|
||||
content: '{"$schema":"https://opencode.ai/config.json"}',
|
||||
isDefault: true,
|
||||
}, 'default')
|
||||
expect(mockWriteFileContent).toHaveBeenCalledWith(
|
||||
'/tmp/workspace/.config/opencode/opencode.json',
|
||||
expect(mockWriteOpenCodeConfigFile).toHaveBeenCalledWith(
|
||||
'{"$schema":"https://opencode.ai/config.json"}'
|
||||
)
|
||||
expect(mockEnsureDirectoryExists).toHaveBeenCalledWith('/tmp/workspace/.opencode/state')
|
||||
@@ -135,6 +137,35 @@ describe('opencode-import service', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('captures the previous on-disk config as last known good before importing over it', async () => {
|
||||
process.env.OPENCODE_IMPORT_CONFIG_PATH = '/import/opencode-config/opencode.json'
|
||||
|
||||
mockFileExists.mockImplementation(async (candidate: string) => candidate === '/import/opencode-config/opencode.json')
|
||||
mockReadOpenCodeConfigFile.mockResolvedValue({
|
||||
isValid: true,
|
||||
rawContent: '{"theme":"previous"}',
|
||||
})
|
||||
const settingsService = { saveLastKnownGoodConfig: vi.fn() } as unknown as SettingsService
|
||||
|
||||
await syncOpenCodeImport({ overwriteState: true, settingsService })
|
||||
|
||||
expect(settingsService.saveLastKnownGoodConfig).toHaveBeenCalledWith('{"theme":"previous"}')
|
||||
expect(mockWriteOpenCodeConfigFile).toHaveBeenCalledWith('{"$schema":"https://opencode.ai/config.json"}')
|
||||
})
|
||||
|
||||
it('does not capture last known good when no previous config file exists', async () => {
|
||||
process.env.OPENCODE_IMPORT_CONFIG_PATH = '/import/opencode-config/opencode.json'
|
||||
|
||||
mockFileExists.mockImplementation(async (candidate: string) => candidate === '/import/opencode-config/opencode.json')
|
||||
mockReadOpenCodeConfigFile.mockResolvedValue(null)
|
||||
const settingsService = { saveLastKnownGoodConfig: vi.fn() } as unknown as SettingsService
|
||||
|
||||
await syncOpenCodeImport({ overwriteState: true, settingsService })
|
||||
|
||||
expect(settingsService.saveLastKnownGoodConfig).not.toHaveBeenCalled()
|
||||
expect(mockWriteOpenCodeConfigFile).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not report state imported when source db is missing', async () => {
|
||||
process.env.OPENCODE_IMPORT_CONFIG_PATH = '/import/opencode-config/opencode.json'
|
||||
process.env.OPENCODE_IMPORT_STATE_PATH = '/import/opencode-state'
|
||||
@@ -145,8 +176,6 @@ describe('opencode-import service', () => {
|
||||
})
|
||||
|
||||
const result = await syncOpenCodeImport({
|
||||
db: mockDb,
|
||||
userId: 'default',
|
||||
overwriteState: true,
|
||||
})
|
||||
|
||||
@@ -155,6 +184,39 @@ describe('opencode-import service', () => {
|
||||
expect(mockEnsureDirectoryExists).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('resolves the first existing import config candidate synchronously', () => {
|
||||
process.env.OPENCODE_IMPORT_CONFIG_PATH = process.execPath
|
||||
|
||||
expect(getFirstExistingConfigSourcePath()).toBe(process.execPath)
|
||||
})
|
||||
|
||||
it('rejects invalid importable config content with the existing error', async () => {
|
||||
process.env.OPENCODE_IMPORT_CONFIG_PATH = '/import/opencode-config/opencode.json'
|
||||
|
||||
mockFileExists.mockImplementation(async (candidate: string) => candidate === '/import/opencode-config/opencode.json')
|
||||
mockReadFileContent.mockResolvedValue('{"model": 123}')
|
||||
|
||||
await expect(syncOpenCodeImport({ overwriteState: true })).rejects.toThrow('Importable OpenCode config is invalid')
|
||||
expect(mockWriteOpenCodeConfigFile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('imports state without rewriting the config when importConfig is false', async () => {
|
||||
process.env.OPENCODE_IMPORT_CONFIG_PATH = '/import/opencode-config/opencode.json'
|
||||
process.env.OPENCODE_IMPORT_STATE_PATH = '/import/opencode-state'
|
||||
|
||||
mockFileExists.mockImplementation(async (candidate: string) => {
|
||||
return candidate === '/import/opencode-config/opencode.json'
|
||||
|| candidate === '/import/opencode-state'
|
||||
|| candidate === '/import/opencode-state/opencode.db'
|
||||
})
|
||||
|
||||
const result = await syncOpenCodeImport({ overwriteState: false, importConfig: false })
|
||||
|
||||
expect(result.configImported).toBe(false)
|
||||
expect(result.stateImported).toBe(true)
|
||||
expect(mockWriteOpenCodeConfigFile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('reads distinct session directories from imported workspace state', async () => {
|
||||
mockFileExists.mockImplementation(async (candidate: string) => candidate === '/tmp/workspace/.opencode/state/opencode/opencode.db')
|
||||
|
||||
@@ -237,13 +299,11 @@ describe('opencode-import service', () => {
|
||||
})
|
||||
|
||||
await expect(syncOpenCodeImport({
|
||||
db: mockDb,
|
||||
userId: 'default',
|
||||
overwriteState: false,
|
||||
protectExistingState: true,
|
||||
})).rejects.toThrow('OpenCode host import was blocked to protect existing workspace state')
|
||||
|
||||
expect(settingsService.updateOpenCodeConfig).not.toHaveBeenCalled()
|
||||
expect(mockWriteOpenCodeConfigFile).not.toHaveBeenCalled()
|
||||
expect(mockEnsureDirectoryExists).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
|
||||
Reference in new issue
Block a user