From 48ca38c4e3b63f50c1d95fc546561a32c868af93 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Mon, 2 Nov 2026 10:23:14 -0500 Subject: [PATCH] section 6: Phase 6: Config.Info validation owner and v2 config types in --- backend/src/routes/opencode-config.ts | 6 +- backend/src/services/opencode-config-file.ts | 33 ++++++----- .../routes/internal-opencode-config.test.ts | 24 +++++++- .../services/opencode-config-apply.test.ts | 4 +- .../services/opencode-config-file.test.ts | 52 ++++++++---------- .../opencode-config-validation.test.ts | 55 +++++++++++++++++++ backend/test/services/opencode-import.test.ts | 6 +- .../settings/OpenCodeConfigEditor.test.tsx | 40 ++++++++++---- .../settings/OpenCodeConfigEditor.tsx | 10 +--- pnpm-lock.yaml | 5 +- shared/package.json | 2 + shared/src/opencode/config-validation.ts | 41 ++++++++++++++ shared/src/opencode/config.ts | 13 +++++ shared/src/opencode/index.ts | 10 ++++ shared/src/opencode/mcp.ts | 7 +-- shared/src/opencode/modelRef.ts | 3 +- 16 files changed, 232 insertions(+), 79 deletions(-) create mode 100644 backend/test/services/opencode-config-validation.test.ts create mode 100644 shared/src/opencode/config-validation.ts create mode 100644 shared/src/opencode/config.ts diff --git a/backend/src/routes/opencode-config.ts b/backend/src/routes/opencode-config.ts index 027a633f..1525228c 100644 --- a/backend/src/routes/opencode-config.ts +++ b/backend/src/routes/opencode-config.ts @@ -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) diff --git a/backend/src/services/opencode-config-file.ts b/backend/src/services/opencode-config-file.ts index e0044b9d..5574e6a4 100644 --- a/backend/src/services/opencode-config-file.ts +++ b/backend/src/services/opencode-config-file.ts @@ -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 isValid: boolean @@ -271,11 +280,9 @@ export function withOpenCodeConfigLock(fn: () => Promise): Promise { 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 { - 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 { .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 }) diff --git a/backend/test/routes/internal-opencode-config.test.ts b/backend/test/routes/internal-opencode-config.test.ts index 5cd6307c..55a5316d 100644 --- a/backend/test/routes/internal-opencode-config.test.ts +++ b/backend/test/routes/internal-opencode-config.test.ts @@ -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 () => { diff --git a/backend/test/services/opencode-config-apply.test.ts b/backend/test/services/opencode-config-apply.test.ts index 624ff7f8..70a64baa 100644 --- a/backend/test/services/opencode-config-apply.test.ts +++ b/backend/test/services/opencode-config-apply.test.ts @@ -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() diff --git a/backend/test/services/opencode-config-file.test.ts b/backend/test/services/opencode-config-file.test.ts index 49a417f3..d9067696 100644 --- a/backend/test/services/opencode-config-file.test.ts +++ b/backend/test/services/opencode-config-file.test.ts @@ -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 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']) diff --git a/backend/test/services/opencode-config-validation.test.ts b/backend/test/services/opencode-config-validation.test.ts new file mode 100644 index 00000000..c212802d --- /dev/null +++ b/backend/test/services/opencode-config-validation.test.ts @@ -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 }) + }) +}) diff --git a/backend/test/services/opencode-import.test.ts b/backend/test/services/opencode-import.test.ts index 756d805d..0bac4a3a 100644 --- a/backend/test/services/opencode-import.test.ts +++ b/backend/test/services/opencode-import.test.ts @@ -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) diff --git a/frontend/src/components/settings/OpenCodeConfigEditor.test.tsx b/frontend/src/components/settings/OpenCodeConfigEditor.test.tsx index 64462e6c..04f3378d 100644 --- a/frontend/src/components/settings/OpenCodeConfigEditor.test.tsx +++ b/frontend/src/components/settings/OpenCodeConfigEditor.test.tsx @@ -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]') diff --git a/frontend/src/components/settings/OpenCodeConfigEditor.tsx b/frontend/src/components/settings/OpenCodeConfigEditor.tsx index 97816e6b..d763123f 100644 --- a/frontend/src/components/settings/OpenCodeConfigEditor.tsx +++ b/frontend/src/components/settings/OpenCodeConfigEditor.tsx @@ -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>(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>(editConfigContent) setIsSaving(true) await onUpdate({ content: editConfigContent, source: draftSource.name, expectedRevision: draftRevision }) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 30d6f697..80fb8e5a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -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: diff --git a/shared/package.json b/shared/package.json index aaa65f8e..546368d3 100644 --- a/shared/package.json +++ b/shared/package.json @@ -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" }, diff --git a/shared/src/opencode/config-validation.ts b/shared/src/opencode/config-validation.ts new file mode 100644 index 00000000..c2a86b4e --- /dev/null +++ b/shared/src/opencode/config-validation.ts @@ -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 | 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, + })), + } +} diff --git a/shared/src/opencode/config.ts b/shared/src/opencode/config.ts new file mode 100644 index 00000000..7ae6373b --- /dev/null +++ b/shared/src/opencode/config.ts @@ -0,0 +1,13 @@ +import type { ConfigEntry } from '@opencode/client' + +export type OpenCodeConfigInfo = Extract['info'] + +export type OpenCodeAgentConfig = NonNullable[string] + +export type OpenCodeCommandConfig = NonNullable[string] + +export type OpenCodeProviderConfig = NonNullable[string] + +export type OpenCodeProviderModelConfig = NonNullable[string] + +export type OpenCodePermissionRule = NonNullable[number] diff --git a/shared/src/opencode/index.ts b/shared/src/opencode/index.ts index 00fef098..8298fb75 100644 --- a/shared/src/opencode/index.ts +++ b/shared/src/opencode/index.ts @@ -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, diff --git a/shared/src/opencode/mcp.ts b/shared/src/opencode/mcp.ts index 368b4634..9f14c2c7 100644 --- a/shared/src/opencode/mcp.ts +++ b/shared/src/opencode/mcp.ts @@ -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['info'] - -type McpConfig = NonNullable +type McpConfig = NonNullable export type McpServerConfig = NonNullable[string] diff --git a/shared/src/opencode/modelRef.ts b/shared/src/opencode/modelRef.ts index d1a05623..9ec275e8 100644 --- a/shared/src/opencode/modelRef.ts +++ b/shared/src/opencode/modelRef.ts @@ -1,6 +1,7 @@ import type { ConfigEntry, ModelRef } from '@opencode/client' +import type { OpenCodeConfigInfo } from './config' -type ConfigDocumentModel = Extract['info']['model'] +type ConfigDocumentModel = OpenCodeConfigInfo['model'] export function parseOpenCodeModelRef(model: string): ModelRef | undefined { const providerEnd = model.indexOf('/')