From 64e87ba1ea11da90b92aba4c3bd28406aa9e09d5 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Thu, 5 Nov 2026 16:16:49 -0500 Subject: [PATCH] fix: guard the Assistant config conversion and place agent permission fallbacks after catch-all rules (OM-179) The Assistant v1-to-v2 conversion now skips the write when OpenCode returns no converted assistant agent for a customized v1 one, or when the converted config fails validation, and it shares a file lock with ensureAssistantMode so the two never overwrite each other. A new agent wildcard permission rule is inserted after the last catch-all * * rule instead of before it, so the catch-all cannot override it. The event subscription also counts each received event as stream activity. --- backend/src/services/assistant-mode.ts | 148 ++++++++++-------- .../services/opencode-event-subscription.ts | 1 + backend/test/services/assistant-mode.test.ts | 34 ++++ .../components/settings/AgentDialog.test.tsx | 33 ++++ .../src/components/settings/AgentDialog.tsx | 9 +- 5 files changed, 158 insertions(+), 67 deletions(-) diff --git a/backend/src/services/assistant-mode.ts b/backend/src/services/assistant-mode.ts index 29dd52dc..e456acb7 100644 --- a/backend/src/services/assistant-mode.ts +++ b/backend/src/services/assistant-mode.ts @@ -23,6 +23,7 @@ import { applyOpenCodeConfigEdits, removeOpenCodeConfigProperty, V1_ENTITY_PATHS import { readConfigValueAtPath, restoreOpenCodeConfigReferences } from './opencode-config-references' import { readOpenCodeConfigDocuments } from './opencode-config-effective' import { logger } from '../utils/logger' +import { withFileLock } from '../utils/atomic-json' const ASSISTANT_MODE_DIR = ASSISTANT_REPO_PATH @@ -1199,35 +1200,35 @@ export async function ensureAssistantMode( await writeFileContent(agentsMdPath, agentsMdContent) } - const existingOpenCodeJsonContent = opencodeJsonExists ? await readFileContent(opencodeJsonPath) : undefined - const parsedOpenCodeConfig = existingOpenCodeJsonContent === undefined - ? undefined - : parseAssistantOpenCodeConfig(existingOpenCodeJsonContent) - const hasV1OpenCodeConfig = parsedOpenCodeConfig !== undefined && hasAssistantV1OpenCodeConfig(parsedOpenCodeConfig) - const existingOpenCodeConfig = parsedOpenCodeConfig as OpenCodeConfigInfo | undefined + const opencodeJsonUpdated = await withFileLock(opencodeJsonPath, async () => { + const existingOpenCodeJsonContent = opencodeJsonExists ? await readFileContent(opencodeJsonPath) : undefined + const parsedOpenCodeConfig = existingOpenCodeJsonContent === undefined + ? undefined + : parseAssistantOpenCodeConfig(existingOpenCodeJsonContent) + const hasV1OpenCodeConfig = parsedOpenCodeConfig !== undefined && hasAssistantV1OpenCodeConfig(parsedOpenCodeConfig) + const existingOpenCodeConfig = parsedOpenCodeConfig as OpenCodeConfigInfo | undefined - let opencodeJsonUpdated = false - if (!opencodeJsonExists || overwriteOpenCodeConfig) { - await writeFileContent(opencodeJsonPath, JSON.stringify(buildAssistantOpenCodeConfig(), null, 2)) - opencodeJsonUpdated = true - } else if (!hasV1OpenCodeConfig) { - if (existingOpenCodeConfig !== undefined) { - const repairedConfig = assistantOpenCodeConfigNeedsRepair(existingOpenCodeConfig) - ? mergeAssistantOpenCodeConfig(existingOpenCodeConfig) - : existingOpenCodeConfig - const updatedConfig = assistantOpenCodeConfigHasGeneratedAgentPersona(repairedConfig) - ? stripGeneratedAssistantAgentPersona(repairedConfig) - : repairedConfig - - if (updatedConfig !== existingOpenCodeConfig) { - await writeFileContent(opencodeJsonPath, JSON.stringify(updatedConfig, null, 2)) - opencodeJsonUpdated = true - } - } else { + if (!opencodeJsonExists || overwriteOpenCodeConfig) { await writeFileContent(opencodeJsonPath, JSON.stringify(buildAssistantOpenCodeConfig(), null, 2)) - opencodeJsonUpdated = true + return true } - } + if (hasV1OpenCodeConfig) return false + if (existingOpenCodeConfig === undefined) { + await writeFileContent(opencodeJsonPath, JSON.stringify(buildAssistantOpenCodeConfig(), null, 2)) + return true + } + + const repairedConfig = assistantOpenCodeConfigNeedsRepair(existingOpenCodeConfig) + ? mergeAssistantOpenCodeConfig(existingOpenCodeConfig) + : existingOpenCodeConfig + const updatedConfig = assistantOpenCodeConfigHasGeneratedAgentPersona(repairedConfig) + ? stripGeneratedAssistantAgentPersona(repairedConfig) + : repairedConfig + if (updatedConfig === existingOpenCodeConfig) return false + + await writeFileContent(opencodeJsonPath, JSON.stringify(updatedConfig, null, 2)) + return true + }) await ensureDirectoryExists(path.join(assistantDir, ASSISTANT_OPENCODE_DIR)) await ensureDirectoryExists(path.join(assistantDir, ASSISTANT_OPENCODE_DIR, ASSISTANT_AGENTS_DIR)) @@ -1492,52 +1493,69 @@ function restoreAssistantAgentReferences( * keeping comments and formatting. The file is left untouched when OpenCode is unreachable. */ export async function convertAssistantOpenCodeConfigToV2(api: OpenCodeApi): Promise { + const assistantDir = getAssistantModeDirectory() + const opencodeJsonPath = path.join(assistantDir, ASSISTANT_OPENCODE_CONFIG_FILENAME) try { - const assistantDir = getAssistantModeDirectory() - const opencodeJsonPath = path.join(assistantDir, ASSISTANT_OPENCODE_CONFIG_FILENAME) - - if (!await fileExists(opencodeJsonPath)) return false - - const rawContent = await readFileContent(opencodeJsonPath) - const rawConfig = parseAssistantOpenCodeConfig(rawContent) - if (rawConfig === undefined || !hasAssistantV1OpenCodeConfig(rawConfig)) return false - - const documents = await readOpenCodeConfigDocuments(api, assistantDir) - const documentInfo = documents.get(path.resolve(opencodeJsonPath)) - if (documentInfo === undefined) return false - - 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: restoreAssistantAgentReferences( - resolveConvertedAssistantAgent( - documentInfo.agents?.[ASSISTANT_DEFAULT_AGENT_NAME], - v1AssistantAgent, - ), - documentInfo, - rawConfig, - ), - }, - ] - if (documentInfo.permissions !== undefined) { - setOperations.push({ path: ['permissions'], value: documentInfo.permissions }) - } - - let updatedText = applyOpenCodeConfigEdits(rawContent, setOperations) - for (const removalPath of buildAssistantV1ConfigRemovalPaths(rawConfig, documentInfo.permissions)) { - updatedText = removeOpenCodeConfigProperty(updatedText, removalPath) - } - - await writeFileContent(opencodeJsonPath, updatedText) - return true + return await withFileLock(opencodeJsonPath, () => convertAssistantOpenCodeConfigFile(api, assistantDir, opencodeJsonPath)) } catch (error) { logger.warn('Skipped the Assistant OpenCode config conversion:', error) return false } } +async function convertAssistantOpenCodeConfigFile( + api: OpenCodeApi, + assistantDir: string, + opencodeJsonPath: string, +): Promise { + if (!await fileExists(opencodeJsonPath)) return false + + const rawContent = await readFileContent(opencodeJsonPath) + const rawConfig = parseAssistantOpenCodeConfig(rawContent) + if (rawConfig === undefined || !hasAssistantV1OpenCodeConfig(rawConfig)) return false + + const documents = await readOpenCodeConfigDocuments(api, assistantDir) + const documentInfo = documents.get(path.resolve(opencodeJsonPath)) + if (documentInfo === undefined) return false + + const v1Assistants = readConfigValueAtPath(rawConfig, ASSISTANT_V1_AGENT_PATH) + const v1AssistantAgent = isRecord(v1Assistants) ? v1Assistants[ASSISTANT_DEFAULT_AGENT_NAME] : undefined + if (isRecord(v1AssistantAgent) && documentInfo.agents?.[ASSISTANT_DEFAULT_AGENT_NAME] === undefined) { + logger.warn('Skipped the Assistant OpenCode config conversion: OpenCode returned no converted assistant agent') + return false + } + const setOperations: OpenCodeConfigPathOperation[] = [ + { + path: ['agents', ASSISTANT_DEFAULT_AGENT_NAME], + value: restoreAssistantAgentReferences( + resolveConvertedAssistantAgent( + documentInfo.agents?.[ASSISTANT_DEFAULT_AGENT_NAME], + v1AssistantAgent, + ), + documentInfo, + rawConfig, + ), + }, + ] + if (documentInfo.permissions !== undefined) { + setOperations.push({ path: ['permissions'], value: documentInfo.permissions }) + } + + let updatedText = applyOpenCodeConfigEdits(rawContent, setOperations) + for (const removalPath of buildAssistantV1ConfigRemovalPaths(rawConfig, documentInfo.permissions)) { + updatedText = removeOpenCodeConfigProperty(updatedText, removalPath) + } + + const validation = validateOpenCodeConfig(parseJsonc(updatedText)) + if (!validation.success) { + logger.warn('Skipped the Assistant OpenCode config conversion: the converted config is invalid', validation.issues) + return false + } + + await writeFileContent(opencodeJsonPath, updatedText) + return true +} + export async function getAssistantModeStatus(repo: Repo): Promise { const assistantDir = getAssistantModeDirectory() diff --git a/backend/src/services/opencode-event-subscription.ts b/backend/src/services/opencode-event-subscription.ts index a58d3a77..df77d060 100644 --- a/backend/src/services/opencode-event-subscription.ts +++ b/backend/src/services/opencode-event-subscription.ts @@ -106,6 +106,7 @@ export function subscribeOpenCodeEvents(options: OpenCodeEventSubscriptionOption }) for await (const event of stream) { + lastActivityAt = Date.now() if (closed || token !== loopToken) break if (!opened && event.type === 'server.connected') { opened = true diff --git a/backend/test/services/assistant-mode.test.ts b/backend/test/services/assistant-mode.test.ts index 899d75d7..196c2718 100644 --- a/backend/test/services/assistant-mode.test.ts +++ b/backend/test/services/assistant-mode.test.ts @@ -951,6 +951,40 @@ describe('convertAssistantOpenCodeConfigToV2', () => { expect(await convertAssistantOpenCodeConfigToV2(api)).toBe(false) expect(calls).toBe(0) }) + + it('leaves a customized v1 assistant untouched when OpenCode returns no converted agent', 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', permissions: convertedPermissions }, + }]) + + expect(await convertAssistantOpenCodeConfigToV2(api)).toBe(false) + expect(await readFile(opencodeJsonPath, 'utf8')).toBe(v1Config) + }) + + it('leaves the file untouched when the converted config is invalid', 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', + permissions: [{ action: 'shell', resource: '*', effect: 'sometimes' }], + agents: { assistant: { mode: 'primary', system: 'Converted prompt' } }, + }, + }]) + + expect(await convertAssistantOpenCodeConfigToV2(api)).toBe(false) + expect(await readFile(opencodeJsonPath, 'utf8')).toBe(v1Config) + }) }) describe('assistant-mode end-to-end', () => { diff --git a/frontend/src/components/settings/AgentDialog.test.tsx b/frontend/src/components/settings/AgentDialog.test.tsx index 81fa30dc..52d3f40c 100644 --- a/frontend/src/components/settings/AgentDialog.test.tsx +++ b/frontend/src/components/settings/AgentDialog.test.tsx @@ -341,6 +341,39 @@ describe('AgentDialog', () => { ]) }) + it('places a new wildcard rule after a catch-all rule and before later exceptions', async () => { + const onSubmit = vi.fn() + const user = userEvent.setup() + render( + , + ) + + await user.click(screen.getByRole('combobox', { name: 'Shell' })) + await user.click(screen.getByRole('option', { name: 'Deny' })) + await user.click(screen.getByRole('button', { name: 'Update' })) + + const agent = onSubmit.mock.calls[0][1] + expect(agent.permissions).toEqual([ + { action: '*', resource: '*', effect: 'allow' }, + { action: 'shell', resource: '*', effect: 'deny' }, + { action: 'shell', resource: 'git status', effect: 'allow' }, + ]) + }) + it('writes no permissions for a prompt-only save of an agent without permission rules', async () => { const onSubmit = vi.fn() const user = userEvent.setup() diff --git a/frontend/src/components/settings/AgentDialog.tsx b/frontend/src/components/settings/AgentDialog.tsx index 6ea68cab..9e2157a3 100644 --- a/frontend/src/components/settings/AgentDialog.tsx +++ b/frontend/src/components/settings/AgentDialog.tsx @@ -48,7 +48,8 @@ const permissionEffect = ( * Applies the form effects to the managed wildcard rules in place, so the rule * order OpenCode resolves with last-match-wins stays unchanged. An `inherit` * effect removes the action's wildcard rules so the global permission applies; - * any other effect prepends a wildcard rule when the action has none yet. + * any other effect adds a wildcard rule when the action has none yet, placed + * after the last catch-all `* *` rule so that rule cannot override it. */ const withManagedPermissionEffects = ( permissions: OpenCodePermissionRule[] | undefined, @@ -64,7 +65,11 @@ const withManagedPermissionEffects = ( const effect = effects[action] return effect === 'inherit' || actionsWithWildcard.has(action) ? [] : [{ action, resource: '*', effect }] }) - return [...fallbacks, ...updated] + const fallbackIndex = updated.reduce( + (index, rule, currentIndex) => (rule.action === '*' && rule.resource === '*' ? currentIndex + 1 : index), + 0, + ) + return [...updated.slice(0, fallbackIndex), ...fallbacks, ...updated.slice(fallbackIndex)] } const optionalNumber = (value: string): number | undefined => {