mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
* 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
192 lines
7.0 KiB
TypeScript
192 lines
7.0 KiB
TypeScript
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
|
import { chmod, mkdir, mkdtemp, readFile, readdir, rm, stat, utimes, writeFile } from 'fs/promises'
|
|
import { tmpdir } from 'os'
|
|
import path from 'path'
|
|
import { ZodError } from 'zod'
|
|
|
|
const paths = vi.hoisted(() => ({ config: '', healthWatch: '' }))
|
|
|
|
vi.mock('@opencode-manager/shared/config/env', () => ({
|
|
getOpenCodeConfigFilePath: () => paths.config,
|
|
getOpenCodeHealthWatchPath: () => paths.healthWatch,
|
|
}))
|
|
|
|
vi.mock('../../src/utils/logger', () => ({
|
|
logger: {
|
|
info: vi.fn(),
|
|
warn: vi.fn(),
|
|
error: vi.fn(),
|
|
},
|
|
}))
|
|
|
|
import {
|
|
HEALTH_WATCH_MAX_ENTRIES,
|
|
OPENCODE_CONFIG_SEED,
|
|
archiveBrokenOpenCodeConfigFile,
|
|
deleteOpenCodeConfigFile,
|
|
pruneHealthWatchDirectory,
|
|
readOpenCodeConfigFile,
|
|
toOpenCodeConfigValidationIssues,
|
|
writeHealthWatchArtifact,
|
|
writeOpenCodeConfigFile,
|
|
} from '../../src/services/opencode-config-file'
|
|
|
|
describe('opencode-config-file', () => {
|
|
let workDir: string
|
|
|
|
beforeEach(async () => {
|
|
vi.clearAllMocks()
|
|
workDir = await mkdtemp(path.join(tmpdir(), 'opencode-config-file-'))
|
|
paths.config = path.join(workDir, 'opencode.json')
|
|
paths.healthWatch = path.join(workDir, 'health-watch')
|
|
})
|
|
|
|
afterEach(async () => {
|
|
await rm(workDir, { recursive: true, force: true })
|
|
})
|
|
|
|
it('returns null when the config file does not exist', async () => {
|
|
await expect(readOpenCodeConfigFile()).resolves.toBeNull()
|
|
})
|
|
|
|
it('writes a valid config and reads it back', async () => {
|
|
const written = await writeOpenCodeConfigFile(OPENCODE_CONFIG_SEED)
|
|
|
|
expect(written.path).toBe(paths.config)
|
|
expect(written.rawContent).toBe(OPENCODE_CONFIG_SEED)
|
|
expect(written.content).toEqual({ $schema: 'https://opencode.ai/config.json' })
|
|
expect(written.isValid).toBe(true)
|
|
expect(written.updatedAt).toBeGreaterThan(0)
|
|
})
|
|
|
|
it('preserves an existing non-default file mode when rewriting atomically', async () => {
|
|
const previousUmask = process.umask(0)
|
|
try {
|
|
await writeFile(paths.config, OPENCODE_CONFIG_SEED, 'utf8')
|
|
await chmod(paths.config, 0o640)
|
|
|
|
await writeOpenCodeConfigFile('{"theme":"dark"}')
|
|
|
|
const stats = await stat(paths.config)
|
|
expect(stats.mode & 0o777).toBe(0o640)
|
|
} finally {
|
|
process.umask(previousUmask)
|
|
}
|
|
})
|
|
|
|
it('rejects invalid content with a ZodError and leaves the previous file untouched', async () => {
|
|
await writeOpenCodeConfigFile(OPENCODE_CONFIG_SEED)
|
|
|
|
await expect(writeOpenCodeConfigFile('{"model": 5}')).rejects.toBeInstanceOf(ZodError)
|
|
await expect(readFile(paths.config, 'utf8')).resolves.toBe(OPENCODE_CONFIG_SEED)
|
|
})
|
|
|
|
it('parses JSONC comments and preserves the raw content', async () => {
|
|
const rawContent = '{\n // user comment\n "theme": "dark"\n}\n'
|
|
await writeFile(paths.config, rawContent, 'utf8')
|
|
|
|
const file = await readOpenCodeConfigFile()
|
|
|
|
expect(file?.content).toEqual({ theme: 'dark' })
|
|
expect(file?.rawContent).toBe(rawContent)
|
|
expect(file?.isValid).toBe(true)
|
|
})
|
|
|
|
it('reports validation issues for schema-invalid content', async () => {
|
|
await writeFile(paths.config, '{"model": 5}', 'utf8')
|
|
|
|
const file = await readOpenCodeConfigFile()
|
|
|
|
expect(file?.isValid).toBe(false)
|
|
expect(file?.validationIssues?.[0]?.path).toBe('model')
|
|
})
|
|
|
|
it('reports a root validation issue when the file is not valid JSONC', async () => {
|
|
await writeFile(paths.config, '{ not json', 'utf8')
|
|
|
|
const file = await readOpenCodeConfigFile()
|
|
|
|
expect(file?.isValid).toBe(false)
|
|
expect(file?.validationIssues?.[0]?.path).toBe('root')
|
|
})
|
|
|
|
it('maps Zod issues to config validation issues with a root fallback', () => {
|
|
const issues = new ZodError([
|
|
{ code: 'custom', path: ['model'], message: 'Invalid model' },
|
|
{ code: 'custom', path: [], message: 'Invalid root' },
|
|
]).issues
|
|
|
|
expect(toOpenCodeConfigValidationIssues(issues)).toEqual([
|
|
{ path: 'model', message: 'Invalid model' },
|
|
{ path: 'root', message: 'Invalid root' },
|
|
])
|
|
})
|
|
|
|
it('writes a health-watch artifact with a shared timestamp and returns its path', async () => {
|
|
const artifactPath = await writeHealthWatchArtifact('opencode-health', (timestamp) => JSON.stringify({ capturedAt: timestamp }))
|
|
|
|
expect(path.dirname(artifactPath)).toBe(paths.healthWatch)
|
|
expect(path.basename(artifactPath)).toMatch(/^opencode-health-.+\.json$/)
|
|
const content = JSON.parse(await readFile(artifactPath, 'utf8')) as { capturedAt: string }
|
|
expect(content.capturedAt).toBe(path.basename(artifactPath).replace(/^opencode-health-/, '').replace(/\.json$/, ''))
|
|
})
|
|
|
|
it('archives the config file under the health-watch directory', async () => {
|
|
await writeOpenCodeConfigFile(OPENCODE_CONFIG_SEED)
|
|
|
|
const archivePath = await archiveBrokenOpenCodeConfigFile()
|
|
|
|
expect(archivePath).toBeTruthy()
|
|
expect(path.dirname(archivePath as string)).toBe(paths.healthWatch)
|
|
await expect(readFile(archivePath as string, 'utf8')).resolves.toBe(OPENCODE_CONFIG_SEED)
|
|
})
|
|
|
|
it('returns null when archiving with no config file present', async () => {
|
|
await expect(archiveBrokenOpenCodeConfigFile()).resolves.toBeNull()
|
|
})
|
|
|
|
it('prunes the health-watch directory to the newest entries', async () => {
|
|
await mkdir(paths.healthWatch, { recursive: true })
|
|
const baseTime = Date.now() - 100_000
|
|
for (let index = 0; index < HEALTH_WATCH_MAX_ENTRIES + 5; index += 1) {
|
|
const filePath = path.join(paths.healthWatch, `entry-${index}.json`)
|
|
await writeFile(filePath, '{}', 'utf8')
|
|
const time = new Date(baseTime + index * 1000)
|
|
await utimes(filePath, time, time)
|
|
}
|
|
|
|
await pruneHealthWatchDirectory(paths.healthWatch)
|
|
|
|
const remaining = await readdir(paths.healthWatch)
|
|
expect(remaining).toHaveLength(HEALTH_WATCH_MAX_ENTRIES)
|
|
expect(remaining).toContain(`entry-${HEALTH_WATCH_MAX_ENTRIES + 4}.json`)
|
|
expect(remaining).not.toContain('entry-0.json')
|
|
expect(remaining).not.toContain('entry-4.json')
|
|
})
|
|
|
|
it('caps the health-watch directory when archiving a broken config', async () => {
|
|
await writeOpenCodeConfigFile(OPENCODE_CONFIG_SEED)
|
|
await mkdir(paths.healthWatch, { recursive: true })
|
|
const baseTime = Date.now() - 100_000
|
|
for (let index = 0; index < HEALTH_WATCH_MAX_ENTRIES + 5; index += 1) {
|
|
const filePath = path.join(paths.healthWatch, `old-${index}.json`)
|
|
await writeFile(filePath, '{}', 'utf8')
|
|
const time = new Date(baseTime + index * 1000)
|
|
await utimes(filePath, time, time)
|
|
}
|
|
|
|
const archivePath = await archiveBrokenOpenCodeConfigFile()
|
|
|
|
const remaining = await readdir(paths.healthWatch)
|
|
expect(remaining).toHaveLength(HEALTH_WATCH_MAX_ENTRIES)
|
|
expect(remaining).toContain(path.basename(archivePath as string))
|
|
})
|
|
|
|
it('deletes the config file and reports whether it existed', async () => {
|
|
await writeOpenCodeConfigFile(OPENCODE_CONFIG_SEED)
|
|
|
|
await expect(deleteOpenCodeConfigFile()).resolves.toBe(true)
|
|
await expect(deleteOpenCodeConfigFile()).resolves.toBe(false)
|
|
})
|
|
})
|