fix: keep config references on save and apply review batch 2 fixes (OM-179)

This commit is contained in:
Chris Scott committed 2026-11-02 23:21:33 -05:00
1 parent 49bb4ebd36
commit 8a6fd56e9a
17 files changed
+524 -60

No files matched your search

@@ -171,6 +171,16 @@ describe('buildSettingsSkill', () => {
expect(skill).toContain('GET /opencode-config/mcp returns `503`')
})
it('documents v1 counterpart removal, reference preservation, and both 409 causes', () => {
const skill = buildSettingsSkill()
expect(skill).toContain('also deletes its v1 counterpart')
expect(skill).toContain('`{env:…}` and `{file:…}` references')
expect(skill).toContain('OpenCodeConfigShadowedRemovalError')
expect(skill).toContain('expectedRevision')
expect(skill).not.toContain('Saving never silently drops unsupported fields')
expect(skill).not.toContain('every path you do not name is left untouched')
})
it('documents the assistant reload as rebuilding every loaded location', () => {
const skill = buildSettingsSkill()
expect(skill).toContain('rebuilding every loaded location')
@@ -866,6 +876,52 @@ describe('convertAssistantOpenCodeConfigToV2', () => {
expect(config.agents.assistant).toEqual({ mode: 'all' })
})
it('keeps the v1 permission block when the converted document has no permissions', async () => {
await ensureAssistantMode(mockRepo)
const opencodeJsonPath = path.join(ws.assistantDir, 'opencode.json')
await writeFile(opencodeJsonPath, v1Config)
const api = createConfigApi((assistantDir) => [{
type: 'document',
path: path.join(assistantDir, 'opencode.json'),
info: {
default_agent: 'assistant',
agents: { assistant: { mode: 'primary', system: 'Converted prompt' } },
},
}])
expect(await convertAssistantOpenCodeConfigToV2(api)).toBe(true)
const config = parseJsonc<Record<string, unknown>>(await readFile(opencodeJsonPath, 'utf8'))
expect(config.agents).toEqual({ assistant: { mode: 'primary', system: 'Converted prompt' } })
expect(config.permission).toEqual({ read: 'allow', shell: 'ask' })
expect(config.agent).toBeUndefined()
})
it('restores a config reference from the v1 agent definition', async () => {
await ensureAssistantMode(mockRepo)
const opencodeJsonPath = path.join(ws.assistantDir, 'opencode.json')
await writeFile(opencodeJsonPath, JSON.stringify({
default_agent: 'assistant',
agent: { assistant: { mode: 'primary', prompt: '{file:./p.md}' } },
}, null, 2))
const api = createConfigApi((assistantDir) => [{
type: 'document',
path: path.join(assistantDir, 'opencode.json'),
info: {
default_agent: 'assistant',
agents: { assistant: { mode: 'primary', system: 'Resolved prompt text' } },
},
}])
expect(await convertAssistantOpenCodeConfigToV2(api)).toBe(true)
const config = JSON.parse(await readFile(opencodeJsonPath, 'utf8'))
expect(config.agents.assistant).toEqual({ mode: 'primary', system: '{file:./p.md}' })
expect(config.agent).toBeUndefined()
})
it('leaves the file unchanged when the OpenCode client fails', async () => {
await ensureAssistantMode(mockRepo)
const opencodeJsonPath = path.join(ws.assistantDir, 'opencode.json')
@@ -11,6 +11,7 @@ vi.mock('@opencode-manager/shared/config/env', () => ({
getOpenCodeConfigFilePath: () => paths.config,
getOpenCodeConfigHome: () => paths.configHome,
getOpenCodeHealthWatchPath: () => paths.healthWatch,
getWorkspacePath: () => paths.configDir,
OPENCODE_CONFIG_SOURCE_NAMES: ['opencode.json', 'opencode.jsonc'],
}))
@@ -67,8 +68,10 @@ function parseSnapshot(snapshot: string): { version: number; sources: Array<{ na
const locationReloadMock = vi.hoisted(() => vi.fn<() => Promise<void>>())
const mcpAddMock = vi.hoisted(() => vi.fn<() => Promise<void>>())
const mcpRemoveMock = vi.hoisted(() => vi.fn<() => Promise<void>>())
const configGetMock = vi.hoisted(() => vi.fn<() => Promise<unknown[]>>())
const openCodeClient = {
api: {
config: { get: configGetMock },
location: { reload: locationReloadMock },
mcp: { add: mcpAddMock, remove: mcpRemoveMock },
},
@@ -88,6 +91,7 @@ describe('opencode-config-apply', () => {
locationReloadMock.mockReset().mockResolvedValue(undefined)
mcpAddMock.mockReset().mockResolvedValue(undefined)
mcpRemoveMock.mockReset().mockResolvedValue(undefined)
configGetMock.mockReset().mockRejectedValue(new Error('OpenCode unavailable'))
workDir = await mkdtemp(path.join(tmpdir(), 'opencode-config-apply-'))
paths.config = path.join(workDir, 'opencode.json')
paths.configDir = workDir
@@ -126,6 +130,34 @@ describe('opencode-config-apply', () => {
expect(result.config.content).toEqual(change)
})
it('keeps an unchanged {env:} reference when a merge patch resends the resolved value', async () => {
await writeFile(
sourcePath('opencode.json'),
'{\n // keep me\n "providers": { "acme": { "settings": { "apiKey": "{env:ACME_KEY}" } } }\n}\n',
'utf8',
)
configGetMock.mockResolvedValue([
{
type: 'document',
path: sourcePath('opencode.json'),
info: { providers: { acme: { settings: { apiKey: 'secret' } } } },
},
])
await applyOpenCodeConfigUpdate({
content: { providers: { acme: { name: 'Acme', settings: { apiKey: 'secret' } } } },
mode: 'merge',
settingsService,
openCodeClient,
})
const written = await readFile(sourcePath('opencode.json'), 'utf8')
expect(written).toContain('"apiKey": "{env:ACME_KEY}"')
expect(written).toContain('"name": "Acme"')
expect(written).toContain('// keep me')
expect(written).not.toContain('secret')
})
it('marks a restart pending when the reload fails', async () => {
await writeFile(sourcePath('opencode.json'), '{"theme":"dark"}', 'utf8')
locationReloadMock.mockRejectedValue(new Error('OpenCode server unavailable'))
@@ -0,0 +1,72 @@
import { describe, expect, it } from 'vitest'
import { restoreOpenCodeConfigReferences } from '../../src/services/opencode-config-references'
describe('restoreOpenCodeConfigReferences', () => {
it('keeps unchanged references of a v2 entity and writes edited values', () => {
const raw = {
agents: { reviewer: { system: '{file:./prompt.md}', description: 'old' } },
providers: { acme: { settings: { apiKey: '{env:ACME_KEY}' } } },
}
const resolved = {
agents: { reviewer: { system: 'Prompt text', description: 'old' } },
providers: { acme: { settings: { apiKey: 'secret' } } },
}
const patch = {
agents: { reviewer: { system: 'Prompt text', description: 'new' } },
providers: { acme: { settings: { apiKey: 'secret' } } },
}
expect(restoreOpenCodeConfigReferences(patch, resolved, raw)).toEqual({
agents: { reviewer: { system: '{file:./prompt.md}', description: 'new' } },
providers: { acme: { settings: { apiKey: '{env:ACME_KEY}' } } },
})
})
it('writes an edited value over a reference', () => {
const raw = { agents: { reviewer: { system: '{file:./prompt.md}' } } }
const resolved = { agents: { reviewer: { system: 'Prompt text' } } }
const patch = { agents: { reviewer: { system: 'Rewritten prompt' } } }
expect(restoreOpenCodeConfigReferences(patch, resolved, raw)).toEqual(patch)
})
it('carries references across a rename', () => {
const raw = { commands: { old: { template: '{file:./cmd.md}' } } }
const resolved = { commands: { old: { template: 'Run it' } } }
const patch = { commands: { renamed: { template: 'Run it' }, old: null } }
expect(restoreOpenCodeConfigReferences(patch, resolved, raw)).toEqual({
commands: { renamed: { template: '{file:./cmd.md}' }, old: null },
})
})
it('restores references from the v1 definition through renamed fields', () => {
const raw = {
agent: { reviewer: { prompt: '{file:./prompt.md}' } },
provider: { acme: { options: { apiKey: '{env:ACME_KEY}', headers: { Authorization: 'Bearer {env:TOKEN}' } } } },
mcp: { docs: { type: 'remote', url: 'https://x', headers: { key: '{env:MCP_KEY}' } } },
}
const resolved = {
agents: { reviewer: { system: 'Prompt text' } },
providers: { acme: { settings: { apiKey: 'secret' }, headers: { Authorization: 'Bearer t' } } },
mcp: { servers: { docs: { type: 'remote', url: 'https://x', headers: { key: 'm' } } } },
}
const patch = {
agents: { reviewer: { system: 'Prompt text', description: 'added' } },
providers: { acme: { settings: { apiKey: 'secret' }, headers: { Authorization: 'Bearer t' } } },
mcp: { servers: { docs: { type: 'remote', url: 'https://x', headers: { key: 'm' } } } },
}
expect(restoreOpenCodeConfigReferences(patch, resolved, raw)).toEqual({
agents: { reviewer: { system: '{file:./prompt.md}', description: 'added' } },
providers: { acme: { settings: { apiKey: '{env:ACME_KEY}' }, headers: { Authorization: 'Bearer {env:TOKEN}' } } },
mcp: { servers: { docs: { type: 'remote', url: 'https://x', headers: { key: '{env:MCP_KEY}' } } } },
})
})
it('leaves new entities and non-entity keys unchanged', () => {
const patch = { agents: { fresh: { system: 'x' } }, theme: 'dark' }
expect(restoreOpenCodeConfigReferences(patch, { agents: {} }, { agents: {} })).toEqual(patch)
})
})
@@ -52,4 +52,22 @@ describe('validateOpenCodeConfig', () => {
}),
).toEqual({ success: true })
})
it('reports the legacy v1 skills object with an actionable message', () => {
const result = validateOpenCodeConfig({ skills: { paths: ['/home/user/skills'] } })
expect(result.success).toBe(false)
if (result.success) return
expect(result.issues).toEqual([
{
path: 'skills',
message:
'skills must be a list of skill paths. Replace the legacy `skills: { paths: [...] }` object with `skills: [...]`.',
},
])
})
it('accepts the v2 skills array', () => {
expect(validateOpenCodeConfig({ skills: ['/home/user/skills'] })).toEqual({ success: true })
})
})
@@ -216,6 +216,41 @@ describe('subscribeOpenCodeEvents', () => {
subscription.close()
})
it('keeps reconnecting when the disconnect handler throws', async () => {
const { api, subscriptions } = createFakeApi()
const onOpen = vi.fn()
const onDisconnect = vi.fn(() => {
throw new Error('disconnect failure')
})
const subscription = subscribeOpenCodeEvents({
api: () => api,
label: 'test',
onOpen,
onEvent: () => undefined,
onDisconnect,
reconnectDelayMs: 100,
maxReconnectDelayMs: 1000,
})
subscriptions[0]!.stream.push(serverConnected)
await flush()
expect(onOpen).toHaveBeenCalledTimes(1)
subscriptions[0]!.stream.end()
await flush()
expect(onDisconnect).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(100)
expect(subscriptions).toHaveLength(2)
subscriptions[1]!.stream.push(serverConnected)
await flush()
expect(onOpen).toHaveBeenCalledTimes(2)
subscription.close()
})
it('doubles the reconnect delay after a thrown transport error and caps it', async () => {
const { api, subscriptions } = createFakeApi()
const onDisconnect = vi.fn()
@@ -206,6 +206,16 @@ describe('SSEAggregator V2 event handling', () => {
expect(sseAggregator.getActiveSessions()).toEqual({})
})
it('clears a busy session from the active set when it is deleted without going idle', () => {
emitEvent({ type: 'session.status', location: { directory: '/r' }, data: { sessionID: 'ses_deleted', status: { type: 'busy' } } })
expect(sseAggregator.getActiveSessions()).toEqual({ '/r': ['ses_deleted'] })
emitEvent({ type: 'session.deleted', location: { directory: '/r' }, data: { sessionID: 'ses_deleted' } })
expect(sseAggregator.getActiveSessions()).toEqual({})
})
it('records subagent sessions from session.created parentID and forgets deleted ones', () => {
emitEvent({
type: 'session.created',