diff --git a/backend/src/services/assistant-mode.ts b/backend/src/services/assistant-mode.ts index 6c24b164..59d9b5f6 100644 --- a/backend/src/services/assistant-mode.ts +++ b/backend/src/services/assistant-mode.ts @@ -19,7 +19,8 @@ import type { OpenCodeAgentConfig, OpenCodeApi, OpenCodeConfigInfo } from '@open import { validateOpenCodeConfig } from '@opencode-manager/shared/opencode/config-validation' import type { Database } from 'bun:sqlite' import { ensureAssistantRepo } from '../db/queries' -import { applyOpenCodeConfigEdits, removeOpenCodeConfigProperty, type OpenCodeConfigPathOperation } from './opencode-config-file' +import { applyOpenCodeConfigEdits, removeOpenCodeConfigProperty, V1_ENTITY_PATHS, type OpenCodeConfigPathOperation } from './opencode-config-file' +import { readConfigValueAtPath, restoreOpenCodeConfigReferences } from './opencode-config-references' import { readOpenCodeConfigDocuments } from './opencode-config-effective' import { logger } from '../utils/logger' @@ -788,9 +789,9 @@ Read the merged persisted global configuration and its source files. Returns \`4 ### PATCH /opencode-config -Change only the paths the user asked for. Send a nested \`patch\` object naming those paths and the values to set; every path you do not name is left untouched, and a \`null\` value removes a path. Only changed fields are patched into the preferred existing source: JSONC, then JSON. New installations use opencode.jsonc. Unchanged inherited values and comments are preserved. +Change only the paths the user asked for. Send a nested \`patch\` object naming those paths and the values to set; a path you do not name keeps its current value, and a \`null\` value removes a path. Naming a v2 entity (\`agents.\`, \`commands.\`, \`providers.\`, \`mcp.servers.\`, or \`permissions\`) also deletes its v1 counterpart (\`agent.\`, \`command.\`, \`provider.\`, \`mcp.\`, or \`permission\`) in the same edit. \`{env:…}\` and \`{file:…}\` references in fields whose value is sent back unchanged are kept. Only changed fields are patched into the preferred existing source: JSONC, then JSON. New installations use opencode.jsonc. Unchanged inherited values and comments are preserved. -Send \`expectedRevision\` from a read. A \`409\` means the source files changed: read again and reconcile rather than retrying stale content. +Send \`expectedRevision\` from a read. A \`409\` means either \`expectedRevision\` is stale or the v1 entry to remove exists only in a lower-priority config source (the \`OpenCodeConfigShadowedRemovalError\` case): read again and reconcile rather than retrying stale content. **Request Body:** \`\`\`ts @@ -818,11 +819,11 @@ Send \`expectedRevision\` from a read. A \`409\` means the source files changed: \`\`\` **Response:** -Returns the refreshed merged configuration and source files, with secrets redacted. A semantic change is applied automatically: the Manager reloads OpenCode without restarting the server, so agents, permissions, providers, models, and plugins take effect on the next message and running sessions keep running. An \`mcp\` change is applied the same way, and only the servers whose configuration changed reconnect. Comment-only changes do nothing. Saving never silently drops unsupported fields. +Returns the refreshed merged configuration and source files, with secrets redacted. A semantic change is applied automatically: the Manager reloads OpenCode without restarting the server, so agents, permissions, providers, models, and plugins take effect on the next message and running sessions keep running. An \`mcp\` change is applied the same way, and only the servers whose configuration changed reconnect. Comment-only changes do nothing. The response adds \`restartRequired: true\` only when the automatic reload failed, for example because the OpenCode server is unavailable. -Returns \`400\` for invalid configuration or a \`\` value (\`paths\` lists them), and \`409\` for a stale revision. +Returns \`400\` for invalid configuration or a \`\` value (\`paths\` lists them), and \`409\` when \`expectedRevision\` is stale or the v1 entry to remove exists only in a lower-priority config source. ### GET /opencode-config/mcp @@ -1359,9 +1360,26 @@ function parseAssistantOpenCodeConfig(rawContent: string): Record entry.v2Path.length === v2Path.length && entry.v2Path.every((segment, index) => segment === v2Path[index]), + ) + if (mapping === undefined) { + throw new Error(`No v1 config path is defined for ${v2Path.join('.')}`) + } + return [...mapping.v1Path] +} + +const ASSISTANT_V1_AGENT_PATH = resolveV1EntityPath(['agents']) +const ASSISTANT_V1_PERMISSION_PATH = resolveV1EntityPath(['permissions']) + function hasAssistantV1OpenCodeConfig(config: Record): boolean { - if (config.permission !== undefined) return true - return isRecord(config.agent) && isRecord(config.agent.assistant) + if (readConfigValueAtPath(config, ASSISTANT_V1_PERMISSION_PATH) !== undefined) return true + const v1Agents = readConfigValueAtPath(config, ASSISTANT_V1_AGENT_PATH) + return isRecord(v1Agents) && isRecord(v1Agents[ASSISTANT_DEFAULT_AGENT_NAME]) } function assistantOpenCodeConfigNeedsRepair(config: OpenCodeConfigInfo): boolean { @@ -1377,9 +1395,7 @@ function assistantOpenCodeConfigNeedsRepair(config: OpenCodeConfigInfo): boolean } function assistantOpenCodeConfigHasGeneratedAgentPersona(config: OpenCodeConfigInfo): boolean { - const agent = config.agents?.[ASSISTANT_DEFAULT_AGENT_NAME] - if (typeof agent !== 'object' || agent === null) return false - return matchesGeneratedAssistantAgentPrompt(agent.system) + return normalizeAssistantAgent(config.agents?.[ASSISTANT_DEFAULT_AGENT_NAME]) !== undefined } function resolveValidAssistantMode(agent: unknown): 'primary' | 'all' { @@ -1387,15 +1403,24 @@ function resolveValidAssistantMode(agent: unknown): 'primary' | 'all' { return mode === 'primary' || mode === 'all' ? mode : 'primary' } +/** + * Reduces a generated assistant persona to a mode-only agent, leaving a customized persona to the caller. + */ +function normalizeAssistantAgent(agent: unknown): OpenCodeAgentConfig | undefined { + if (!isRecord(agent) || !matchesGeneratedAssistantAgentPrompt(agent.system)) return undefined + return { mode: resolveValidAssistantMode(agent) } +} + function stripGeneratedAssistantAgentPersona(config: OpenCodeConfigInfo): OpenCodeConfigInfo { const existingAssistantAgent = config.agents?.[ASSISTANT_DEFAULT_AGENT_NAME] - const validMode = resolveValidAssistantMode(existingAssistantAgent) return { ...config, agents: { ...(config.agents ?? {}), - [ASSISTANT_DEFAULT_AGENT_NAME]: { mode: validMode }, + [ASSISTANT_DEFAULT_AGENT_NAME]: normalizeAssistantAgent(existingAssistantAgent) ?? { + mode: resolveValidAssistantMode(existingAssistantAgent), + }, }, } } @@ -1404,20 +1429,10 @@ function mergeAssistantOpenCodeConfig(existing?: OpenCodeConfigInfo): OpenCodeCo const generated = buildAssistantOpenCodeConfig() const existingAssistantAgent = existing?.agents?.[ASSISTANT_DEFAULT_AGENT_NAME] const validMode = resolveValidAssistantMode(existingAssistantAgent) - - const existingIsGenerated = typeof existingAssistantAgent === 'object' && - existingAssistantAgent !== null && - matchesGeneratedAssistantAgentPrompt(existingAssistantAgent.system) - - let mergedAssistantAgent: OpenCodeAgentConfig - if (existingIsGenerated) { - mergedAssistantAgent = { mode: validMode } - } else { - mergedAssistantAgent = { - ...(typeof existingAssistantAgent === 'object' && existingAssistantAgent !== null ? existingAssistantAgent : {}), - mode: validMode, - disabled: false, - } + const mergedAssistantAgent: OpenCodeAgentConfig = normalizeAssistantAgent(existingAssistantAgent) ?? { + ...(existingAssistantAgent ?? {}), + mode: validMode, + disabled: false, } return { @@ -1432,15 +1447,20 @@ function mergeAssistantOpenCodeConfig(existing?: OpenCodeConfigInfo): OpenCodeCo } } -function buildAssistantV1ConfigRemovalPaths(config: Record): string[][] { - const v1Agent = config.agent +function buildAssistantV1ConfigRemovalPaths( + config: Record, + convertedPermissions: unknown, +): string[][] { + const v1Agent = readConfigValueAtPath(config, ASSISTANT_V1_AGENT_PATH) const removeWholeAgent = isRecord(v1Agent) && Object.keys(v1Agent).length === 1 && - isRecord(v1Agent.assistant) + isRecord(v1Agent[ASSISTANT_DEFAULT_AGENT_NAME]) - const paths: string[][] = [removeWholeAgent ? ['agent'] : ['agent', ASSISTANT_DEFAULT_AGENT_NAME]] - if (config.permission !== undefined) { - paths.push(['permission']) + const paths: string[][] = [ + removeWholeAgent ? ASSISTANT_V1_AGENT_PATH : [...ASSISTANT_V1_AGENT_PATH, ASSISTANT_DEFAULT_AGENT_NAME], + ] + if (convertedPermissions !== undefined && readConfigValueAtPath(config, ASSISTANT_V1_PERMISSION_PATH) !== undefined) { + paths.push(ASSISTANT_V1_PERMISSION_PATH) } return paths } @@ -1449,12 +1469,22 @@ function resolveConvertedAssistantAgent( agent: OpenCodeAgentConfig | undefined, v1Agent: unknown, ): OpenCodeAgentConfig { - if (agent === undefined) { - return { mode: resolveValidAssistantMode(v1Agent) } - } - return matchesGeneratedAssistantAgentPrompt(agent.system) - ? { mode: resolveValidAssistantMode(agent) } - : agent + return normalizeAssistantAgent(agent) ?? agent ?? { mode: resolveValidAssistantMode(v1Agent) } +} + +function restoreAssistantAgentReferences( + agent: OpenCodeAgentConfig, + resolved: OpenCodeConfigInfo, + raw: Record, +): OpenCodeAgentConfig { + const restored = restoreOpenCodeConfigReferences( + { agents: { [ASSISTANT_DEFAULT_AGENT_NAME]: agent } }, + resolved as Record, + raw, + ) + const restoredAgent = readConfigValueAtPath(restored, ['agents', ASSISTANT_DEFAULT_AGENT_NAME]) + if (typeof restoredAgent !== 'object' || restoredAgent === null) return agent + return restoredAgent as OpenCodeAgentConfig } /** @@ -1476,13 +1506,18 @@ export async function convertAssistantOpenCodeConfigToV2(api: OpenCodeApi): Prom const documentInfo = documents.get(path.resolve(opencodeJsonPath)) if (documentInfo === undefined) return false - const v1AssistantAgent = isRecord(rawConfig.agent) ? rawConfig.agent.assistant : undefined + const v1Assistants = readConfigValueAtPath(rawConfig, ASSISTANT_V1_AGENT_PATH) + const v1AssistantAgent = isRecord(v1Assistants) ? v1Assistants[ASSISTANT_DEFAULT_AGENT_NAME] : undefined const setOperations: OpenCodeConfigPathOperation[] = [ { path: ['agents', ASSISTANT_DEFAULT_AGENT_NAME], - value: resolveConvertedAssistantAgent( - documentInfo.agents?.[ASSISTANT_DEFAULT_AGENT_NAME], - v1AssistantAgent, + value: restoreAssistantAgentReferences( + resolveConvertedAssistantAgent( + documentInfo.agents?.[ASSISTANT_DEFAULT_AGENT_NAME], + v1AssistantAgent, + ), + documentInfo, + rawConfig, ), }, ] @@ -1491,7 +1526,7 @@ export async function convertAssistantOpenCodeConfigToV2(api: OpenCodeApi): Prom } let updatedText = applyOpenCodeConfigEdits(rawContent, setOperations) - for (const removalPath of buildAssistantV1ConfigRemovalPaths(rawConfig)) { + for (const removalPath of buildAssistantV1ConfigRemovalPaths(rawConfig, documentInfo.permissions)) { updatedText = removeOpenCodeConfigProperty(updatedText, removalPath) } diff --git a/backend/src/services/opencode-config-apply.ts b/backend/src/services/opencode-config-apply.ts index 8e14107c..e6c9bcf1 100644 --- a/backend/src/services/opencode-config-apply.ts +++ b/backend/src/services/opencode-config-apply.ts @@ -10,9 +10,12 @@ import { restoreOpenCodeConfigSnapshot, serializeOpenCodeConfigSnapshot, updateOpenCodeConfigFile, + type OpenCodeConfigSnapshot, type OpenCodeConfigUpdateMode, withOpenCodeConfigLock, } from './opencode-config-file' +import { readManagedOpenCodeConfig } from './opencode-config-effective' +import { restoreOpenCodeConfigReferences } from './opencode-config-references' import { opencodeServerManager } from './opencode-single-server' import { reloadOpenCodeConfig } from './opencode-restart' import type { OpenCodeClient } from './opencode/client' @@ -98,6 +101,20 @@ function requiresOpenCodeReload(previous: OpenCodeConfigFile | null, next: OpenC return listChangedTopLevelKeys(previous?.content ?? {}, next.content).length > 0 } +async function keepOpenCodeConfigReferences( + patch: Record, + snapshot: OpenCodeConfigSnapshot, + openCodeClient: OpenCodeClient, +): Promise> { + try { + const resolved = await readManagedOpenCodeConfig(openCodeClient.api, snapshot.sources) + return restoreOpenCodeConfigReferences(patch, resolved as Record, snapshot.content) + } catch (error) { + logger.warn('Could not read the resolved OpenCode config; saving the patch without reference restoration:', error) + return patch + } +} + export async function applyOpenCodeConfigUpdate( input: ApplyOpenCodeConfigOptions, ): Promise { @@ -106,8 +123,11 @@ export async function applyOpenCodeConfigUpdate( const snapshot = await readOpenCodeConfigSnapshot() const previous = await readOpenCodeConfigFile(snapshot) + const savedContent = mode === 'merge' && typeof content !== 'string' + ? await keepOpenCodeConfigReferences(content, snapshot, input.openCodeClient) + : content - const next = await updateOpenCodeConfigFile(content, { source, expectedRevision, snapshot, mode }) + const next = await updateOpenCodeConfigFile(savedContent, { source, expectedRevision, snapshot, mode }) if (previous?.isValid) { const snapshot = serializeOpenCodeConfigSnapshot(previous) diff --git a/backend/src/services/opencode-config-file.ts b/backend/src/services/opencode-config-file.ts index ebe6f814..ec3b3a9a 100644 --- a/backend/src/services/opencode-config-file.ts +++ b/backend/src/services/opencode-config-file.ts @@ -153,7 +153,8 @@ export interface OpenCodeConfigPathOperation { value: unknown } -interface OpenCodeConfigV1EntityPath { +/** Maps a v2 config entity container to the v1 container OpenCode converts it from. */ +export interface OpenCodeConfigV1EntityPath { v2Path: string[] v1Path: string[] named: boolean @@ -165,7 +166,7 @@ interface OpenCodeConfigV1EntityRemoval { container?: JSONPath } -const V1_ENTITY_PATHS: readonly OpenCodeConfigV1EntityPath[] = [ +export const V1_ENTITY_PATHS: readonly OpenCodeConfigV1EntityPath[] = [ { v2Path: ['agents'], v1Path: ['agent'], named: true }, { v2Path: ['commands'], v1Path: ['command'], named: true }, { v2Path: ['providers'], v1Path: ['provider'], named: true }, diff --git a/backend/src/services/opencode-config-redact.ts b/backend/src/services/opencode-config-redact.ts index 7c742d42..bc52f569 100644 --- a/backend/src/services/opencode-config-redact.ts +++ b/backend/src/services/opencode-config-redact.ts @@ -1,5 +1,5 @@ +import { isRecord } from '@opencode-manager/shared/utils' import type { OpenCodeConfigFile } from '../types/settings' -import { isRecord } from './opencode/enforcement-config' import { OPENCODE_CONFIG_REDACTED_VALUE } from './opencode-config-file' const SECRET_KEYS = new Set([ diff --git a/backend/src/services/opencode-config-references.ts b/backend/src/services/opencode-config-references.ts new file mode 100644 index 00000000..1197c1d2 --- /dev/null +++ b/backend/src/services/opencode-config-references.ts @@ -0,0 +1,156 @@ +import { isRecord } from '@opencode-manager/shared/utils' +import { V1_ENTITY_PATHS, type OpenCodeConfigV1EntityPath } from './opencode-config-file' + +const CONFIG_REFERENCE_PATTERN = /\{(?:env|file):[^}]+\}/ + +type FieldAlias = readonly [v2Prefix: readonly string[], v1Prefix: readonly string[]] + +const V1_FIELD_ALIASES: Readonly> = { + agents: [ + [['system'], ['prompt']], + [['request', 'body', 'temperature'], ['temperature']], + [['request', 'body', 'top_p'], ['top_p']], + [['request', 'body'], ['options']], + ], + providers: [ + [['settings', 'baseURL'], ['api']], + [['headers'], ['options', 'headers']], + [['body'], ['options', 'body']], + [['settings'], ['options']], + ], + 'mcp.servers': [ + [['oauth', 'client_id'], ['oauth', 'clientId']], + [['oauth', 'client_secret'], ['oauth', 'clientSecret']], + [['oauth', 'redirect_uri'], ['oauth', 'redirectUri']], + ], +} + +interface RawEntityCandidate { + entity: unknown + aliases: readonly FieldAlias[] +} + +/** Reads a nested config value by object keys and array indices, or `undefined` when absent. */ +export function readConfigValueAtPath(value: unknown, path: readonly string[]): unknown { + let current = value + for (const segment of path) { + if (Array.isArray(current)) { + current = current[Number(segment)] + continue + } + if (!isRecord(current) || !Object.prototype.hasOwnProperty.call(current, segment)) return undefined + current = current[segment] + } + return current +} + +function startsWithPath(path: readonly string[], prefix: readonly string[]): boolean { + return prefix.length <= path.length && prefix.every((segment, index) => path[index] === segment) +} + +function readRawReference(candidates: readonly RawEntityCandidate[], path: readonly string[]): string | undefined { + for (const candidate of candidates) { + const paths = [ + path, + ...candidate.aliases + .filter(([v2Prefix]) => startsWithPath(path, v2Prefix)) + .map(([v2Prefix, v1Prefix]) => [...v1Prefix, ...path.slice(v2Prefix.length)]), + ] + for (const rawPath of paths) { + const raw = readConfigValueAtPath(candidate.entity, rawPath) + if (typeof raw === 'string' && CONFIG_REFERENCE_PATTERN.test(raw)) return raw + } + } + return undefined +} + +function restoreEntityReferences( + next: unknown, + path: readonly string[], + resolvedEntity: unknown, + candidates: readonly RawEntityCandidate[], +): unknown { + if (typeof next === 'string') { + if (readConfigValueAtPath(resolvedEntity, path) !== next) return next + return readRawReference(candidates, path) ?? next + } + if (Array.isArray(next)) { + return next.map((item, index) => restoreEntityReferences(item, [...path, String(index)], resolvedEntity, candidates)) + } + if (isRecord(next)) { + return Object.fromEntries( + Object.entries(next).map(([key, value]) => [key, restoreEntityReferences(value, [...path, key], resolvedEntity, candidates)]), + ) + } + return next +} + +function findRenameSource( + patchContainer: Record, + resolvedContainer: Record, +): string | undefined { + const removed = Object.keys(patchContainer).filter( + (name) => patchContainer[name] === null && Object.prototype.hasOwnProperty.call(resolvedContainer, name), + ) + return removed.length === 1 ? removed[0] : undefined +} + +function restoreContainerReferences( + mapping: OpenCodeConfigV1EntityPath, + patchContainer: Record, + resolved: Record, + raw: Record, +): Record { + const resolvedContainer = readConfigValueAtPath(resolved, mapping.v2Path) + if (!isRecord(resolvedContainer)) return patchContainer + const rawV2Container = readConfigValueAtPath(raw, mapping.v2Path) + const rawV1Container = readConfigValueAtPath(raw, mapping.v1Path) + const aliases = V1_FIELD_ALIASES[mapping.v2Path.join('.')] ?? [] + + return Object.fromEntries( + Object.entries(patchContainer).map(([name, value]) => { + if (!isRecord(value)) return [name, value] + const sourceName = Object.prototype.hasOwnProperty.call(resolvedContainer, name) + ? name + : findRenameSource(patchContainer, resolvedContainer) + if (sourceName === undefined) return [name, value] + + const candidates: RawEntityCandidate[] = [ + { entity: isRecord(rawV2Container) ? rawV2Container[sourceName] : undefined, aliases: [] }, + ] + if (!mapping.reservedNames?.includes(sourceName)) { + candidates.push({ entity: isRecord(rawV1Container) ? rawV1Container[sourceName] : undefined, aliases }) + } + return [name, restoreEntityReferences(value, [], resolvedContainer[sourceName], candidates)] + }), + ) +} + +function setValueAtPath(target: Record, path: readonly string[], value: unknown): Record { + const [head, ...rest] = path + if (head === undefined) return target + const child = target[head] + return { + ...target, + [head]: rest.length === 0 ? value : setValueAtPath(isRecord(child) ? child : {}, rest, value), + } +} + +/** + * Keeps `{env:…}` and `{file:…}` references in a merge patch of named config entities. + * + * Settings edits entities from OpenCode's resolved config, so an untouched field arrives with its + * substituted value. A string that still equals the resolved value is replaced by the reference + * stored in the raw config: the same entity, the entity being renamed, or its v1 definition. + */ +export function restoreOpenCodeConfigReferences( + patch: Record, + resolved: Record, + raw: Record, +): Record { + return V1_ENTITY_PATHS.filter((mapping) => mapping.named).reduce((current, mapping) => { + const patchContainer = readConfigValueAtPath(current, mapping.v2Path) + if (!isRecord(patchContainer)) return current + return setValueAtPath(current, mapping.v2Path, restoreContainerReferences(mapping, patchContainer, resolved, raw)) + }, patch) +} diff --git a/backend/src/services/opencode-event-subscription.ts b/backend/src/services/opencode-event-subscription.ts index b7ff5a39..a58d3a77 100644 --- a/backend/src/services/opencode-event-subscription.ts +++ b/backend/src/services/opencode-event-subscription.ts @@ -130,14 +130,24 @@ export function subscribeOpenCodeEvents(options: OpenCodeEventSubscriptionOption if (closed || token !== loopToken) return - options.onDisconnect(stallError ?? failure) + try { + options.onDisconnect(stallError ?? failure) + } catch (error) { + logger.error(`${options.label}: disconnect handler failed`, error) + } await wait(currentDelay) if (closed || token !== loopToken) return currentDelay = nextBackoffDelay(currentDelay, maxReconnectDelayMs) } } - void run(loopToken) + const startLoop = (token: number): void => { + void run(token).catch((error) => { + logger.error(`${options.label}: subscription loop failed`, error) + }) + } + + startLoop(loopToken) return { close: () => { @@ -153,7 +163,7 @@ export function subscribeOpenCodeEvents(options: OpenCodeEventSubscriptionOption stopDelay() stopAttempt() currentDelay = reconnectDelayMs - void run(loopToken) + startLoop(loopToken) }, } } diff --git a/backend/src/services/opencode/enforcement-config.ts b/backend/src/services/opencode/enforcement-config.ts index 00fdc61b..179a6145 100644 --- a/backend/src/services/opencode/enforcement-config.ts +++ b/backend/src/services/opencode/enforcement-config.ts @@ -1,8 +1,6 @@ -export type EnforcementRemovedSections = Record +import { isRecord } from '@opencode-manager/shared/utils' -export function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} +export type EnforcementRemovedSections = Record function mergeRecordSections(target: Record, key: string, value: Record): void { const current = isRecord(target[key]) ? { ...(target[key] as Record) } : {} diff --git a/backend/src/services/sse-aggregator.ts b/backend/src/services/sse-aggregator.ts index 17cfb875..770bbacf 100644 --- a/backend/src/services/sse-aggregator.ts +++ b/backend/src/services/sse-aggregator.ts @@ -553,6 +553,7 @@ class SSEAggregator { } case 'session.deleted': { this.unmarkSubagentSession(directory, event.data.sessionID) + this.markSessionIdle(directory, event.data.sessionID) return } } diff --git a/backend/test/services/assistant-mode.test.ts b/backend/test/services/assistant-mode.test.ts index 8a14d3b0..899d75d7 100644 --- a/backend/test/services/assistant-mode.test.ts +++ b/backend/test/services/assistant-mode.test.ts @@ -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>(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') diff --git a/backend/test/services/opencode-config-apply.test.ts b/backend/test/services/opencode-config-apply.test.ts index 70a64baa..00302764 100644 --- a/backend/test/services/opencode-config-apply.test.ts +++ b/backend/test/services/opencode-config-apply.test.ts @@ -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>()) const mcpAddMock = vi.hoisted(() => vi.fn<() => Promise>()) const mcpRemoveMock = vi.hoisted(() => vi.fn<() => Promise>()) +const configGetMock = vi.hoisted(() => vi.fn<() => Promise>()) 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')) diff --git a/backend/test/services/opencode-config-references.test.ts b/backend/test/services/opencode-config-references.test.ts new file mode 100644 index 00000000..d3542205 --- /dev/null +++ b/backend/test/services/opencode-config-references.test.ts @@ -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) + }) +}) diff --git a/backend/test/services/opencode-config-validation.test.ts b/backend/test/services/opencode-config-validation.test.ts index c212802d..32b11b08 100644 --- a/backend/test/services/opencode-config-validation.test.ts +++ b/backend/test/services/opencode-config-validation.test.ts @@ -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 }) + }) }) diff --git a/backend/test/services/opencode-event-subscription.test.ts b/backend/test/services/opencode-event-subscription.test.ts index f23e0b71..c7b3faa7 100644 --- a/backend/test/services/opencode-event-subscription.test.ts +++ b/backend/test/services/opencode-event-subscription.test.ts @@ -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() diff --git a/backend/test/services/sse-aggregator.test.ts b/backend/test/services/sse-aggregator.test.ts index 7e05599b..215972f0 100644 --- a/backend/test/services/sse-aggregator.test.ts +++ b/backend/test/services/sse-aggregator.test.ts @@ -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', diff --git a/frontend/src/contexts/EventContext.test.tsx b/frontend/src/contexts/EventContext.test.tsx index d9fbb0b2..b238610b 100644 --- a/frontend/src/contexts/EventContext.test.tsx +++ b/frontend/src/contexts/EventContext.test.tsx @@ -1230,6 +1230,7 @@ describe('EventProvider permissions and forms', () => { expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'agents'] }) expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'skills'] }) expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'providers'] }) + expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode-config', 'managed'] }) }) }) @@ -3109,6 +3110,7 @@ describe('EventProvider permissions and forms', () => { expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'agents', 'srv_remote'] }) }) expect(invalidateQueries).not.toHaveBeenCalledWith({ queryKey: ['opencode', 'commands'] }) + expect(invalidateQueries).not.toHaveBeenCalledWith({ queryKey: ['opencode-config', 'managed'] }) }) it('reconciles only linked directories with active work on a remote resync', async () => { diff --git a/frontend/src/contexts/EventContext.tsx b/frontend/src/contexts/EventContext.tsx index b70c1ebe..0c18b395 100644 --- a/frontend/src/contexts/EventContext.tsx +++ b/frontend/src/contexts/EventContext.tsx @@ -42,6 +42,7 @@ import { invalidateQueryKeysDebounced, invalidateRepoGitCachesDebounced, invalidateSessionListCachesDebounced, + OPEN_CODE_MANAGED_CONFIG_QUERY_KEY, } from '@/lib/queryInvalidation' const STATUS_POLL_INTERVAL_MS = 5000 @@ -1273,7 +1274,10 @@ export function EventProvider({ children }: { children: React.ReactNode }) { void fetchInitialSessionStatuses() void syncRunningShells(directories) invalidateChildSessionCaches(queryClient) - invalidateQueryKeysDebounced(queryClient, LOCATION_CATALOG_QUERY_KEYS) + invalidateQueryKeysDebounced(queryClient, [ + ...LOCATION_CATALOG_QUERY_KEYS, + OPEN_CODE_MANAGED_CONFIG_QUERY_KEY, + ]) } const initialDirectories = [...new Set((reposRef.current ?? []).map(r => r.fullPath))] diff --git a/shared/src/opencode/config-validation.ts b/shared/src/opencode/config-validation.ts index f1978bde..65a4bd1a 100644 --- a/shared/src/opencode/config-validation.ts +++ b/shared/src/opencode/config-validation.ts @@ -1,6 +1,7 @@ import { Info } from '@opencode/schema/config' import { Schema } from 'effect' import type { OpenCodeConfigValidationIssue } from '../types' +import { isRecord } from '../utils/record' export type OpenCodeConfigValidationResult = | { success: true } @@ -10,6 +11,9 @@ const standardSchema = Schema.toStandardSchemaV1(Info, { parseOptions: { errors: 'all', onExcessProperty: 'ignore' }, }) +const LEGACY_SKILLS_MESSAGE = + 'skills must be a list of skill paths. Replace the legacy `skills: { paths: [...] }` object with `skills: [...]`.' + function toIssuePath(path: ReadonlyArray | undefined): string { if (!path || path.length === 0) return 'root' return path @@ -17,9 +21,14 @@ function toIssuePath(path: ReadonlyArray ({ - path: toIssuePath(issue.path), - message: issue.message, - })), + issues: result.issues.map((issue) => { + const path = toIssuePath(issue.path) + const isLegacySkillsIssue = legacySkillsObject && path === 'skills' + return { + path, + message: isLegacySkillsIssue ? LEGACY_SKILLS_MESSAGE : issue.message, + } + }), } }