mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
section 6: Phase 6: Config.Info validation owner and v2 config types in
This commit is contained in:
1 parent
66b5d1ac06
commit
48ca38c4e3
16 files changed
+232
-79
No files matched your search
@@ -1,5 +1,4 @@
|
||||
import { Hono, type Context } from 'hono'
|
||||
import { z } from 'zod'
|
||||
import {
|
||||
UpdateOpenCodeConfigPatchRequestSchema,
|
||||
UpdateOpenCodeConfigRequestSchema,
|
||||
@@ -20,6 +19,7 @@ import {
|
||||
OpenCodeConfigRedactedValueError,
|
||||
OpenCodeConfigShadowedRemovalError,
|
||||
OpenCodeConfigSourceInvalidError,
|
||||
OpenCodeConfigValidationError,
|
||||
readOpenCodeConfigFile,
|
||||
withOpenCodeConfigLock,
|
||||
} from '../services/opencode-config-file'
|
||||
@@ -198,8 +198,8 @@ async function applyUpdate(
|
||||
if (error instanceof OpenCodeConfigRedactedValueError) {
|
||||
return c.json({ error: error.message, paths: error.paths }, 400)
|
||||
}
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json({ error: 'Invalid config data', details: error.issues }, 400)
|
||||
if (error instanceof OpenCodeConfigValidationError) {
|
||||
return c.json({ error: 'Invalid config data', validationIssues: error.issues }, 400)
|
||||
}
|
||||
if (error instanceof SyntaxError) {
|
||||
return c.json({ error: 'Invalid config data', details: error.message }, 400)
|
||||
|
||||
@@ -4,7 +4,6 @@ import { readFile, readdir, rename, rm, stat } from 'fs/promises'
|
||||
import path from 'path'
|
||||
import { isDeepStrictEqual } from 'node:util'
|
||||
import { applyEdits, modify, type JSONPath } from 'jsonc-parser'
|
||||
import type { ZodIssue } from 'zod'
|
||||
import { getConfigPath, getOpenCodeConfigHome, getOpenCodeHealthWatchPath } from '@opencode-manager/shared/config/env'
|
||||
import {
|
||||
DEFAULT_OPENCODE_CONFIG_SOURCE_NAME,
|
||||
@@ -13,7 +12,7 @@ import {
|
||||
isOpenCodeConfigSourceName,
|
||||
selectPreferredOpenCodeConfigSourceName,
|
||||
} from '@opencode-manager/shared'
|
||||
import { OpenCodeConfigSchema } from '@opencode-manager/shared/schemas'
|
||||
import { validateOpenCodeConfig } from '@opencode-manager/shared/opencode/config-validation'
|
||||
import { parseJsonc } from '@opencode-manager/shared/utils'
|
||||
import type {
|
||||
OpenCodeConfigFile,
|
||||
@@ -107,6 +106,16 @@ export class OpenCodeConfigRedactedValueError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export class OpenCodeConfigValidationError extends Error {
|
||||
readonly issues: OpenCodeConfigValidationIssue[]
|
||||
|
||||
constructor(issues: OpenCodeConfigValidationIssue[]) {
|
||||
super('OpenCode config is invalid')
|
||||
this.name = 'OpenCodeConfigValidationError'
|
||||
this.issues = issues
|
||||
}
|
||||
}
|
||||
|
||||
interface OpenCodeConfigParseResult {
|
||||
content: Record<string, unknown>
|
||||
isValid: boolean
|
||||
@@ -271,11 +280,9 @@ export function withOpenCodeConfigLock<T>(fn: () => Promise<T>): Promise<T> {
|
||||
return withFileLock(getOpenCodeConfigDirectory(), fn)
|
||||
}
|
||||
|
||||
export function toOpenCodeConfigValidationIssues(issues: ZodIssue[]): OpenCodeConfigValidationIssue[] {
|
||||
return issues.map((issue) => ({
|
||||
path: issue.path.length > 0 ? issue.path.join('.') : 'root',
|
||||
message: issue.message,
|
||||
}))
|
||||
function assertValidOpenCodeConfig(value: unknown): void {
|
||||
const result = validateOpenCodeConfig(value)
|
||||
if (!result.success) throw new OpenCodeConfigValidationError(result.issues)
|
||||
}
|
||||
|
||||
export function parseOpenCodeConfigContent(rawContent: string): OpenCodeConfigParseResult {
|
||||
@@ -294,7 +301,7 @@ export function parseOpenCodeConfigContent(rawContent: string): OpenCodeConfigPa
|
||||
|
||||
const content = isPlainObject(parsed) ? parsed : {}
|
||||
|
||||
const validated = OpenCodeConfigSchema.safeParse(parsed)
|
||||
const validated = validateOpenCodeConfig(parsed)
|
||||
if (validated.success) {
|
||||
return {
|
||||
content,
|
||||
@@ -302,7 +309,7 @@ export function parseOpenCodeConfigContent(rawContent: string): OpenCodeConfigPa
|
||||
}
|
||||
}
|
||||
|
||||
const validationIssues = toOpenCodeConfigValidationIssues(validated.error.issues)
|
||||
const validationIssues = validated.issues
|
||||
logger.error(`Failed to validate OpenCode config: ${validationIssues.map((issue) => `${issue.path}: ${issue.message}`).join('; ')}`)
|
||||
|
||||
return {
|
||||
@@ -402,7 +409,7 @@ export async function writeOpenCodeConfigFile(
|
||||
source?: OpenCodeConfigSourceName,
|
||||
snapshot?: OpenCodeConfigSnapshot,
|
||||
): Promise<OpenCodeConfigFile> {
|
||||
OpenCodeConfigSchema.parse(parseJsonc(rawContent))
|
||||
assertValidOpenCodeConfig(parseJsonc(rawContent))
|
||||
|
||||
const resolved = snapshot ?? await readOpenCodeConfigSnapshot()
|
||||
const targetName = source !== undefined
|
||||
@@ -526,7 +533,7 @@ export async function updateOpenCodeConfigFile(
|
||||
const mode = options.mode ?? 'replace'
|
||||
const operations = collectOpenCodeConfigPathOperations(content, snapshot.content, mode)
|
||||
|
||||
OpenCodeConfigSchema.parse(
|
||||
assertValidOpenCodeConfig(
|
||||
mode === 'merge' ? mergeOpenCodeConfigValues(snapshot.content, content, { deleteNullValues: true }) : content,
|
||||
)
|
||||
|
||||
@@ -535,7 +542,7 @@ export async function updateOpenCodeConfigFile(
|
||||
const updatedText = applyOpenCodeConfigPathOperations(originalText, operations)
|
||||
|
||||
if (updatedText !== originalText) {
|
||||
OpenCodeConfigSchema.parse(parseJsonc(updatedText))
|
||||
assertValidOpenCodeConfig(parseJsonc(updatedText))
|
||||
await writeFileAtomic(targetPath, updatedText, { mode: await existingFileMode(targetPath) })
|
||||
}
|
||||
|
||||
@@ -755,7 +762,7 @@ export async function foldLegacyConfigJsonSource(): Promise<boolean> {
|
||||
.filter((operation) => operation.value !== undefined && !hasOpenCodeConfigPath(lowestPrecedenceSource.content, operation.path))
|
||||
if (operations.length > 0) {
|
||||
const updatedText = applyOpenCodeConfigPathOperations(lowestPrecedenceSource.rawContent, operations)
|
||||
OpenCodeConfigSchema.parse(parseJsonc(updatedText))
|
||||
assertValidOpenCodeConfig(parseJsonc(updatedText))
|
||||
await writeFileAtomic(lowestPrecedenceSource.path, updatedText, { mode: await existingFileMode(lowestPrecedenceSource.path) })
|
||||
}
|
||||
await rm(legacyPath, { force: true })
|
||||
|
||||
@@ -415,15 +415,15 @@ describe('internal/opencode-config routes', () => {
|
||||
})
|
||||
|
||||
it('PUT /api/internal/opencode-config returns 409 for a shadowed removal', async () => {
|
||||
const lower = '{"theme":"light","model":"a"}'
|
||||
const target = '{"model":"b"}'
|
||||
const lower = '{"theme":"light","model":"test/a"}'
|
||||
const target = '{"model":"test/b"}'
|
||||
await writeOpenCodeConfigFile(target, 'opencode.jsonc')
|
||||
await writeFile(configPath('opencode.json'), lower, 'utf8')
|
||||
|
||||
const res = await app.request('/api/internal/opencode-config', {
|
||||
method: 'PUT',
|
||||
headers: { 'content-type': 'application/json', ...authHeaders() },
|
||||
body: JSON.stringify({ content: { model: 'b' } }),
|
||||
body: JSON.stringify({ content: { model: 'test/b' } }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(409)
|
||||
@@ -445,6 +445,24 @@ describe('internal/opencode-config routes', () => {
|
||||
})
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
const body = await res.json() as { error: string; validationIssues: Array<{ path: string; message: string }> }
|
||||
expect(body.error).toBe('Invalid config data')
|
||||
expect(body.validationIssues.map((issue) => issue.path)).toEqual(['model'])
|
||||
})
|
||||
|
||||
it('PUT /api/internal/opencode-config returns 400 with validationIssues for invalid raw content', async () => {
|
||||
await writeOpenCodeConfigFile(OPENCODE_CONFIG_SEED, 'opencode.jsonc')
|
||||
|
||||
const res = await app.request('/api/internal/opencode-config', {
|
||||
method: 'PUT',
|
||||
headers: { 'content-type': 'application/json', ...authHeaders() },
|
||||
body: JSON.stringify({ content: '{"model": 5}' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
const body = await res.json() as { error: string; validationIssues: Array<{ path: string; message: string }> }
|
||||
expect(body.error).toBe('Invalid config data')
|
||||
expect(body.validationIssues.map((issue) => issue.path)).toEqual(['model'])
|
||||
})
|
||||
|
||||
it('PUT /api/internal/opencode-config returns 400 for an invalid JSON body', async () => {
|
||||
|
||||
@@ -3,7 +3,6 @@ import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'fs/promises'
|
||||
import { tmpdir } from 'os'
|
||||
import path from 'path'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { ZodError } from 'zod'
|
||||
|
||||
const paths = vi.hoisted(() => ({ config: '', configDir: '', configHome: '', healthWatch: '' }))
|
||||
|
||||
@@ -48,6 +47,7 @@ import {
|
||||
OPENCODE_CONFIG_SEED,
|
||||
OpenCodeConfigConflictError,
|
||||
OpenCodeConfigSourceInvalidError,
|
||||
OpenCodeConfigValidationError,
|
||||
readOpenCodeConfigFile,
|
||||
writeOpenCodeConfigFile,
|
||||
} from '../../src/services/opencode-config-file'
|
||||
@@ -231,7 +231,7 @@ describe('opencode-config-apply', () => {
|
||||
source: 'opencode.json',
|
||||
settingsService,
|
||||
openCodeClient,
|
||||
})).rejects.toBeInstanceOf(ZodError)
|
||||
})).rejects.toBeInstanceOf(OpenCodeConfigValidationError)
|
||||
|
||||
await expect(readFile(sourcePath('opencode.json'), 'utf8')).resolves.toBe(previous)
|
||||
expect(markRestartPendingMock).not.toHaveBeenCalled()
|
||||
|
||||
@@ -2,7 +2,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { access, 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: '', configDir: '', configHome: '', healthWatch: '' }))
|
||||
|
||||
@@ -79,6 +78,7 @@ import {
|
||||
OpenCodeConfigRedactedValueError,
|
||||
OpenCodeConfigShadowedRemovalError,
|
||||
OpenCodeConfigSnapshotError,
|
||||
OpenCodeConfigValidationError,
|
||||
archiveBrokenOpenCodeConfigFile,
|
||||
deleteOpenCodeConfigFile,
|
||||
foldLegacyConfigJsonSource,
|
||||
@@ -88,7 +88,6 @@ import {
|
||||
restoreLegacyOpenCodeConfigBackup,
|
||||
restoreOpenCodeConfigSnapshot,
|
||||
serializeOpenCodeConfigSnapshot,
|
||||
toOpenCodeConfigValidationIssues,
|
||||
updateOpenCodeConfigFile,
|
||||
writeHealthWatchArtifact,
|
||||
writeOpenCodeConfigFile,
|
||||
@@ -166,10 +165,10 @@ describe('opencode-config-file', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects invalid content with a ZodError and leaves the previous file untouched', async () => {
|
||||
it('rejects invalid content with a validation error and leaves the previous file untouched', async () => {
|
||||
await writeOpenCodeConfigFile(OPENCODE_CONFIG_SEED)
|
||||
|
||||
await expect(writeOpenCodeConfigFile('{"model": 5}')).rejects.toBeInstanceOf(ZodError)
|
||||
await expect(writeOpenCodeConfigFile('{"model": 5}')).rejects.toBeInstanceOf(OpenCodeConfigValidationError)
|
||||
await expect(readFile(sourcePath('opencode.jsonc'), 'utf8')).resolves.toBe(OPENCODE_CONFIG_SEED)
|
||||
})
|
||||
|
||||
@@ -236,16 +235,13 @@ describe('opencode-config-file', () => {
|
||||
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
|
||||
it('maps validation issues to dotted paths with a root fallback', async () => {
|
||||
await writeFile(sourcePath('opencode.json'), JSON.stringify({ agents: { a: { mode: 'boss' } } }), 'utf8')
|
||||
|
||||
expect(toOpenCodeConfigValidationIssues(issues)).toEqual([
|
||||
{ path: 'model', message: 'Invalid model' },
|
||||
{ path: 'root', message: 'Invalid root' },
|
||||
])
|
||||
const file = await readOpenCodeConfigFile()
|
||||
|
||||
expect(file?.isValid).toBe(false)
|
||||
expect(file?.validationIssues?.[0]?.path).toBe('agents.a.mode')
|
||||
})
|
||||
|
||||
it('modifies only changed paths in the preferred source and preserves comments and untouched fields', async () => {
|
||||
@@ -338,14 +334,14 @@ describe('opencode-config-file', () => {
|
||||
const raw = '{"theme":"dark"}'
|
||||
await writeFile(sourcePath('opencode.json'), raw, 'utf8')
|
||||
|
||||
await expect(updateOpenCodeConfigFile({ model: 5 }, { mode: 'merge' })).rejects.toBeInstanceOf(ZodError)
|
||||
await expect(updateOpenCodeConfigFile({ model: 5 }, { mode: 'merge' })).rejects.toBeInstanceOf(OpenCodeConfigValidationError)
|
||||
|
||||
await expect(readFile(sourcePath('opencode.json'), 'utf8')).resolves.toBe(raw)
|
||||
})
|
||||
|
||||
it('rejects a merge patch that removes a value only a lower-priority source defines', async () => {
|
||||
const lower = '{"theme":"light"}'
|
||||
const target = '{"model":"b"}'
|
||||
const target = '{"model":"test/b"}'
|
||||
await writeFile(sourcePath('opencode.json'), lower, 'utf8')
|
||||
await writeFile(sourcePath('opencode.jsonc'), target, 'utf8')
|
||||
|
||||
@@ -360,7 +356,7 @@ describe('opencode-config-file', () => {
|
||||
|
||||
it('merges into an existing nested object while deleting sibling keys with null', async () => {
|
||||
const raw = JSON.stringify({
|
||||
mcp: { servers: { linear: { url: 'https://linear.example.com', headers: { Authorization: 'Bearer old', 'X-Keep': '1' } } } },
|
||||
mcp: { servers: { linear: { type: 'remote', url: 'https://linear.example.com', headers: { Authorization: 'Bearer old', 'X-Keep': '1' } } } },
|
||||
})
|
||||
await writeFile(sourcePath('opencode.json'), raw, 'utf8')
|
||||
|
||||
@@ -370,7 +366,7 @@ describe('opencode-config-file', () => {
|
||||
)
|
||||
|
||||
expect(updated.content).toEqual({
|
||||
mcp: { servers: { linear: { url: 'https://linear.example.com', headers: { 'X-Keep': '1' } } } },
|
||||
mcp: { servers: { linear: { type: 'remote', url: 'https://linear.example.com', headers: { 'X-Keep': '1' } } } },
|
||||
})
|
||||
const onDisk = JSON.parse(await readFile(sourcePath('opencode.json'), 'utf8')) as Record<string, unknown>
|
||||
expect(onDisk).toEqual(updated.content)
|
||||
@@ -380,13 +376,13 @@ describe('opencode-config-file', () => {
|
||||
await writeFile(sourcePath('opencode.json'), '{"theme":"dark"}', 'utf8')
|
||||
|
||||
const updated = await updateOpenCodeConfigFile(
|
||||
{ mcp: { servers: { linear: { url: 'https://linear.example.com', headers: { Authorization: null, 'X-Trace': 'on' } } } } },
|
||||
{ mcp: { servers: { linear: { type: 'remote', url: 'https://linear.example.com', headers: { Authorization: null, 'X-Trace': 'on' } } } } },
|
||||
{ mode: 'merge' },
|
||||
)
|
||||
|
||||
expect(updated.content).toEqual({
|
||||
theme: 'dark',
|
||||
mcp: { servers: { linear: { url: 'https://linear.example.com', headers: { 'X-Trace': 'on' } } } },
|
||||
mcp: { servers: { linear: { type: 'remote', url: 'https://linear.example.com', headers: { 'X-Trace': 'on' } } } },
|
||||
})
|
||||
const onDisk = await readFile(sourcePath('opencode.json'), 'utf8')
|
||||
expect(onDisk).not.toContain('null')
|
||||
@@ -436,25 +432,25 @@ describe('opencode-config-file', () => {
|
||||
})
|
||||
|
||||
it('removes an override from the target source only and reveals inherited values', async () => {
|
||||
const lower = JSON.stringify({ theme: 'light', model: 'a' })
|
||||
const lower = JSON.stringify({ theme: 'light', model: 'test/a' })
|
||||
await writeFile(sourcePath('opencode.json'), lower, 'utf8')
|
||||
await writeFile(sourcePath('opencode.jsonc'), '{\n "theme": "dark"\n}\n', 'utf8')
|
||||
|
||||
await updateOpenCodeConfigFile({ model: 'a' })
|
||||
await updateOpenCodeConfigFile({ model: 'test/a' })
|
||||
|
||||
await expect(readFile(sourcePath('opencode.json'), 'utf8')).resolves.toBe(lower)
|
||||
const revealed = await readOpenCodeConfigFile()
|
||||
expect(revealed?.content).toEqual({ theme: 'light', model: 'a' })
|
||||
expect(revealed?.content).toEqual({ theme: 'light', model: 'test/a' })
|
||||
})
|
||||
|
||||
it('rejects a removal of a value that only a lower-priority source defines and writes nothing', async () => {
|
||||
const lower = '{\n "theme": "light",\n "model": "a"\n}\n'
|
||||
const target = '{\n "model": "b"\n}\n'
|
||||
const lower = '{\n "theme": "light",\n "model": "test/a"\n}\n'
|
||||
const target = '{\n "model": "test/b"\n}\n'
|
||||
await writeFile(sourcePath('opencode.json'), lower, 'utf8')
|
||||
await writeFile(sourcePath('opencode.jsonc'), target, 'utf8')
|
||||
const targetStats = await stat(sourcePath('opencode.jsonc'))
|
||||
|
||||
const error = await updateOpenCodeConfigFile({ model: 'b' }).catch((caught: unknown) => caught)
|
||||
const error = await updateOpenCodeConfigFile({ model: 'test/b' }).catch((caught: unknown) => caught)
|
||||
|
||||
expect(error).toBeInstanceOf(OpenCodeConfigShadowedRemovalError)
|
||||
expect((error as OpenCodeConfigShadowedRemovalError).paths).toEqual(['theme'])
|
||||
@@ -465,12 +461,12 @@ describe('opencode-config-file', () => {
|
||||
})
|
||||
|
||||
it('rejects a mixed shadowed removal and legitimate change without writing anything', async () => {
|
||||
const lower = '{\n "theme": "light",\n "model": "a"\n}\n'
|
||||
const target = '{\n "model": "b"\n}\n'
|
||||
const lower = '{\n "theme": "light",\n "model": "test/a"\n}\n'
|
||||
const target = '{\n "model": "test/b"\n}\n'
|
||||
await writeFile(sourcePath('opencode.json'), lower, 'utf8')
|
||||
await writeFile(sourcePath('opencode.jsonc'), target, 'utf8')
|
||||
|
||||
const error = await updateOpenCodeConfigFile({ model: 'b', plugin: ['x'] }).catch((caught: unknown) => caught)
|
||||
const error = await updateOpenCodeConfigFile({ model: 'test/b', plugin: ['x'] }).catch((caught: unknown) => caught)
|
||||
|
||||
expect(error).toBeInstanceOf(OpenCodeConfigShadowedRemovalError)
|
||||
expect((error as OpenCodeConfigShadowedRemovalError).paths).toEqual(['theme'])
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { validateOpenCodeConfig } from '@opencode-manager/shared/opencode/config-validation'
|
||||
|
||||
describe('validateOpenCodeConfig', () => {
|
||||
it('accepts a valid v2 config document', () => {
|
||||
expect(
|
||||
validateOpenCodeConfig({
|
||||
$schema: 'https://opencode.ai/config.json',
|
||||
model: 'anthropic/claude-sonnet-4',
|
||||
share: 'manual',
|
||||
agents: { assistant: { mode: 'primary' } },
|
||||
}),
|
||||
).toEqual({ success: true })
|
||||
})
|
||||
|
||||
it('accepts v2-only fields', () => {
|
||||
expect(
|
||||
validateOpenCodeConfig({
|
||||
shell: '/bin/zsh',
|
||||
lsp: true,
|
||||
timezone: 'Europe/Madrid',
|
||||
policies: [{ action: 'tool.use', resource: 'bash', effect: 'deny' }],
|
||||
}),
|
||||
).toEqual({ success: true })
|
||||
})
|
||||
|
||||
it('rejects invalid nested values with dotted paths', () => {
|
||||
const result = validateOpenCodeConfig({ agents: { a: { mode: 'boss' } } })
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
if (result.success) return
|
||||
expect(result.issues.map((issue) => issue.path)).toContain('agents.a.mode')
|
||||
})
|
||||
|
||||
it('rejects invalid enum values', () => {
|
||||
const result = validateOpenCodeConfig({ share: 'sometimes' })
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
if (result.success) return
|
||||
expect(result.issues).toEqual([
|
||||
expect.objectContaining({ path: 'share' }),
|
||||
])
|
||||
})
|
||||
|
||||
it('accepts v1-only keys because unknown keys are ignored', () => {
|
||||
expect(
|
||||
validateOpenCodeConfig({
|
||||
agent: { build: { mode: 'primary' } },
|
||||
command: { deploy: { template: 'ship it' } },
|
||||
provider: { openai: { options: {} } },
|
||||
permission: { edit: 'allow' },
|
||||
}),
|
||||
).toEqual({ success: true })
|
||||
})
|
||||
})
|
||||
@@ -86,8 +86,8 @@ describe('opencode-import service', () => {
|
||||
const jsoncPath = path.join(os.homedir(), '.config', 'opencode', 'opencode.jsonc')
|
||||
mockExistsSync.mockImplementation((candidate: string) => [jsonPath, jsoncPath].includes(candidate))
|
||||
mockFileExists.mockResolvedValue(false)
|
||||
const rawJson = '{"model":"lower"}'
|
||||
const rawJsonc = '{\n// keep\n"model":"higher"\n}'
|
||||
const rawJson = '{"model":"test/lower"}'
|
||||
const rawJsonc = '{\n// keep\n"model":"test/higher"\n}'
|
||||
mockReadFileContent.mockImplementation(async (candidate: string) => candidate === jsoncPath ? rawJsonc : rawJson)
|
||||
|
||||
const result = await syncOpenCodeImport({})
|
||||
@@ -115,7 +115,7 @@ describe('opencode-import service', () => {
|
||||
const legacyPath = path.join(os.homedir(), '.config', 'opencode', 'config.json')
|
||||
mockExistsSync.mockImplementation((candidate: string) => [jsonPath, legacyPath].includes(candidate))
|
||||
mockFileExists.mockResolvedValue(false)
|
||||
const rawJson = '{"model":"lower"}'
|
||||
const rawJson = '{"model":"test/lower"}'
|
||||
const rawLegacy = '{"theme":"dark"}'
|
||||
mockReadFileContent.mockImplementation(async (candidate: string) =>
|
||||
candidate === legacyPath ? rawLegacy : rawJson)
|
||||
|
||||
@@ -155,9 +155,14 @@ describe('OpenCodeConfigEditor', () => {
|
||||
expect(scrollTopSets).toBeGreaterThanOrEqual(2)
|
||||
})
|
||||
|
||||
it('lists schema validation issues as line jumps', async () => {
|
||||
it('lists backend validation issues as line jumps', async () => {
|
||||
const onUpdate = vi.fn().mockRejectedValue(
|
||||
new FetchError('Invalid config data', 400, undefined, undefined, {
|
||||
validationIssues: [{ path: 'theme', message: 'Expected string' }],
|
||||
}),
|
||||
)
|
||||
renderEditor({ onUpdate })
|
||||
const user = userEvent.setup()
|
||||
renderEditor()
|
||||
const textarea = screen.getByLabelText('Config content') as HTMLTextAreaElement
|
||||
setContent(textarea, '{\n "theme": 42\n}')
|
||||
await user.click(screen.getByRole('button', { name: 'Update' }))
|
||||
@@ -169,16 +174,22 @@ describe('OpenCodeConfigEditor', () => {
|
||||
expect(row).toHaveAttribute('data-line', '2')
|
||||
})
|
||||
|
||||
it('does not call onUpdate when local validation fails', async () => {
|
||||
const { onUpdate } = renderEditor()
|
||||
it('sends content the browser cannot validate to the backend instead of rejecting it locally', async () => {
|
||||
const onUpdate = vi.fn().mockRejectedValue(
|
||||
new FetchError('Invalid config data', 400, undefined, undefined, {
|
||||
validationIssues: [{ path: 'theme', message: 'Expected string' }],
|
||||
}),
|
||||
)
|
||||
renderEditor({ onUpdate })
|
||||
const user = userEvent.setup()
|
||||
const textarea = screen.getByLabelText('Config content') as HTMLTextAreaElement
|
||||
setContent(textarea, '{\n "theme": 42\n}')
|
||||
const invalid = '{\n "theme": 42\n}'
|
||||
setContent(textarea, invalid)
|
||||
await user.click(screen.getByRole('button', { name: 'Update' }))
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/Configuration validation failed/)).toBeInTheDocument()
|
||||
expect(onUpdate).toHaveBeenCalledWith({ content: invalid, source: 'opencode.json', expectedRevision: 'rev-1' })
|
||||
})
|
||||
expect(onUpdate).not.toHaveBeenCalled()
|
||||
expect(await screen.findByText(/theme: Expected string/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('saves the raw text including comments', async () => {
|
||||
@@ -348,14 +359,19 @@ describe('OpenCodeConfigEditor', () => {
|
||||
expect(onUpdate).toHaveBeenCalledWith({ content: RAW, source: 'opencode.json', expectedRevision: 'rev-1' })
|
||||
})
|
||||
|
||||
it('resolves a validation issue under a dotted provider key to its line', async () => {
|
||||
it('resolves a nested backend validation issue to its line', async () => {
|
||||
const onUpdate = vi.fn().mockRejectedValue(
|
||||
new FetchError('Invalid config data', 400, undefined, undefined, {
|
||||
validationIssues: [{ path: 'agents.assistant.mode', message: 'Expected a known mode' }],
|
||||
}),
|
||||
)
|
||||
renderEditor({ onUpdate })
|
||||
const user = userEvent.setup()
|
||||
renderEditor()
|
||||
const textarea = screen.getByLabelText('Config content') as HTMLTextAreaElement
|
||||
const dotted = '{\n "provider": {\n "api.example.com": {\n "key": 123\n }\n }\n}'
|
||||
setContent(textarea, dotted)
|
||||
const nested = '{\n "agents": {\n "assistant": {\n "mode": 42\n }\n }\n}'
|
||||
setContent(textarea, nested)
|
||||
await user.click(screen.getByRole('button', { name: 'Update' }))
|
||||
const issueButton = await screen.findByRole('button', { name: /api\.example\.com/i })
|
||||
const issueButton = await screen.findByRole('button', { name: /agents\.assistant\.mode/i })
|
||||
expect(issueButton).toBeInTheDocument()
|
||||
await user.click(issueButton)
|
||||
const activeLine = document.body.querySelector('[data-active-line]')
|
||||
|
||||
@@ -12,7 +12,6 @@ import { useMobile } from '@/hooks/useMobile'
|
||||
import { useFindInText } from '@/lib/useFindInText'
|
||||
import { parseJsonc, parseJsoncErrorLine, resolveJsoncIssueLine } from '@/lib/jsonc'
|
||||
import { FetchError } from '@/api/fetchWrapper'
|
||||
import { OpenCodeConfigSchema } from '@opencode-manager/shared'
|
||||
import {
|
||||
downloadOpenCodeConfigSource,
|
||||
getOpenCodeConfigSources,
|
||||
@@ -143,14 +142,7 @@ export function OpenCodeConfigEditor({
|
||||
|
||||
try {
|
||||
resetErrors()
|
||||
const parsedConfig = parseJsonc<Record<string, unknown>>(editConfigContent)
|
||||
const validationResult = OpenCodeConfigSchema.safeParse(parsedConfig)
|
||||
if (!validationResult.success) {
|
||||
const issues = resolveIssues(validationResult.error.issues)
|
||||
setValidationIssues(issues)
|
||||
setEditError(`Configuration validation failed: ${issues.map(getIssueText).join('; ')}`)
|
||||
return
|
||||
}
|
||||
parseJsonc<Record<string, unknown>>(editConfigContent)
|
||||
|
||||
setIsSaving(true)
|
||||
await onUpdate({ content: editConfigContent, source: draftSource.name, expectedRevision: draftRevision })
|
||||
|
||||
Generated
+4
-1
@@ -352,6 +352,9 @@ importers:
|
||||
'@opencode/schema':
|
||||
specifier: 2.2.1
|
||||
version: 2.2.1
|
||||
effect:
|
||||
specifier: 4.0.1
|
||||
version: 4.0.1
|
||||
jsonc-parser:
|
||||
specifier: ^3.3.1
|
||||
version: 3.3.1
|
||||
@@ -8113,7 +8116,7 @@ snapshots:
|
||||
sirv: 3.0.2
|
||||
tinyglobby: 0.2.15
|
||||
tinyrainbow: 2.0.0
|
||||
vitest: 3.2.4(@types/debug@4.1.12)(@types/node@22.19.19)(@vitest/ui@3.2.4)(jiti@2.6.1)(jsdom@27.4.0)(lightningcss@1.30.2)(terser@5.46.0)(yaml@2.9.0)
|
||||
vitest: 3.2.4(@types/debug@4.1.12)(@types/node@24.10.4)(@vitest/ui@3.2.4)(jiti@2.6.1)(jsdom@27.4.0)(lightningcss@1.30.2)(terser@5.46.0)(yaml@2.9.0)
|
||||
|
||||
'@vitest/utils@3.2.4':
|
||||
dependencies:
|
||||
|
||||
@@ -18,11 +18,13 @@
|
||||
"./notifications": "./src/notifications/index.ts",
|
||||
"./project-id": "./src/project-id-resolver.ts",
|
||||
"./opencode": "./src/opencode/index.ts",
|
||||
"./opencode/config-validation": "./src/opencode/config-validation.ts",
|
||||
"./themes": "./src/themes/index.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@opencode/client": "2.2.1",
|
||||
"@opencode/schema": "2.2.1",
|
||||
"effect": "4.0.1",
|
||||
"jsonc-parser": "^3.3.1",
|
||||
"zod": "^4.1.12"
|
||||
},
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { Info } from '@opencode/schema/config'
|
||||
import { Schema } from 'effect'
|
||||
|
||||
export interface OpenCodeConfigValidationIssue {
|
||||
path: string
|
||||
message: string
|
||||
}
|
||||
|
||||
export type OpenCodeConfigValidationResult =
|
||||
| { success: true }
|
||||
| { success: false; issues: OpenCodeConfigValidationIssue[] }
|
||||
|
||||
const standardSchema = Schema.toStandardSchemaV1(Info, {
|
||||
parseOptions: { errors: 'all', onExcessProperty: 'ignore' },
|
||||
})
|
||||
|
||||
function toIssuePath(path: ReadonlyArray<PropertyKey | { readonly key: PropertyKey }> | undefined): string {
|
||||
if (!path || path.length === 0) return 'root'
|
||||
return path
|
||||
.map((segment) => String(typeof segment === 'object' ? segment.key : segment))
|
||||
.join('.')
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates a parsed OpenCode config document against the v2 `Config.Info` schema, ignoring
|
||||
* unknown keys so v1-only fields in existing files stay loadable.
|
||||
*/
|
||||
export function validateOpenCodeConfig(value: unknown): OpenCodeConfigValidationResult {
|
||||
const result = standardSchema['~standard'].validate(value)
|
||||
if (result instanceof Promise) {
|
||||
throw new Error('OpenCode config validation must be synchronous')
|
||||
}
|
||||
if (!result.issues) return { success: true }
|
||||
return {
|
||||
success: false,
|
||||
issues: result.issues.map((issue) => ({
|
||||
path: toIssuePath(issue.path),
|
||||
message: issue.message,
|
||||
})),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { ConfigEntry } from '@opencode/client'
|
||||
|
||||
export type OpenCodeConfigInfo = Extract<ConfigEntry, { type: 'document' }>['info']
|
||||
|
||||
export type OpenCodeAgentConfig = NonNullable<OpenCodeConfigInfo['agents']>[string]
|
||||
|
||||
export type OpenCodeCommandConfig = NonNullable<OpenCodeConfigInfo['commands']>[string]
|
||||
|
||||
export type OpenCodeProviderConfig = NonNullable<OpenCodeConfigInfo['providers']>[string]
|
||||
|
||||
export type OpenCodeProviderModelConfig = NonNullable<OpenCodeProviderConfig['models']>[string]
|
||||
|
||||
export type OpenCodePermissionRule = NonNullable<OpenCodeConfigInfo['permissions']>[number]
|
||||
@@ -22,6 +22,7 @@ export type {
|
||||
ModelInfo,
|
||||
ModelRef,
|
||||
PermissionRequest,
|
||||
PermissionReply,
|
||||
PromptAgentAttachment,
|
||||
PromptFileAttachment,
|
||||
PromptMention,
|
||||
@@ -51,6 +52,15 @@ export { ClientError, isIntegrationNotFoundError, isMcpServerNotFoundError, isSe
|
||||
|
||||
export { assistantText, sessionIDFromEvent, toolContentText } from './content'
|
||||
|
||||
export type {
|
||||
OpenCodeAgentConfig,
|
||||
OpenCodeCommandConfig,
|
||||
OpenCodeConfigInfo,
|
||||
OpenCodePermissionRule,
|
||||
OpenCodeProviderConfig,
|
||||
OpenCodeProviderModelConfig,
|
||||
} from './config'
|
||||
|
||||
export {
|
||||
GOAL_CHANGED_EVENT_TYPE,
|
||||
GOAL_COMMAND_NAME,
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
import type { ConfigEntry, McpServer } from '@opencode/client'
|
||||
import type { McpServer } from '@opencode/client'
|
||||
import type { OpenCodeConfigInfo } from './config'
|
||||
import { isRecord } from '../utils/record'
|
||||
|
||||
export const MCP_OAUTH_CALLBACK_PATH = '/api/mcp-oauth-proxy/callback'
|
||||
|
||||
type ConfigDocumentInfo = Extract<ConfigEntry, { type: 'document' }>['info']
|
||||
|
||||
type McpConfig = NonNullable<ConfigDocumentInfo['mcp']>
|
||||
type McpConfig = NonNullable<OpenCodeConfigInfo['mcp']>
|
||||
|
||||
export type McpServerConfig = NonNullable<McpConfig['servers']>[string]
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { ConfigEntry, ModelRef } from '@opencode/client'
|
||||
import type { OpenCodeConfigInfo } from './config'
|
||||
|
||||
type ConfigDocumentModel = Extract<ConfigEntry, { type: 'document' }>['info']['model']
|
||||
type ConfigDocumentModel = OpenCodeConfigInfo['model']
|
||||
|
||||
export function parseOpenCodeModelRef(model: string): ModelRef | undefined {
|
||||
const providerEnd = model.indexOf('/')
|
||||
|
||||
Reference in new issue
Block a user