From 38d618be9b9fc5f20686a8f32a54ad11345c69fe Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Thu, 5 Nov 2026 12:43:42 -0500 Subject: [PATCH] fix: limit the restart-pending 409 to entity patches and keep inherited agent permissions (OM-179) PATCH /opencode-config refuses only patches that name an agent, command, provider or MCP server while a restart is pending; other keys still apply. The assistant API reference documents the new 409. The agent dialog adds a wildcard permission rule only for an action whose effect the user changed, so saving an agent no longer overrides an inherited global ask or deny. --- backend/src/routes/opencode-config.ts | 3 +- backend/src/services/assistant-mode.ts | 4 +- backend/test/routes/settings.test.ts | 16 +++++ .../components/settings/AgentDialog.test.tsx | 59 ++++++++++++++++--- .../src/components/settings/AgentDialog.tsx | 22 ++++--- 5 files changed, 85 insertions(+), 19 deletions(-) diff --git a/backend/src/routes/opencode-config.ts b/backend/src/routes/opencode-config.ts index 90446ed9..a35564b4 100644 --- a/backend/src/routes/opencode-config.ts +++ b/backend/src/routes/opencode-config.ts @@ -27,6 +27,7 @@ import { import { readManagedOpenCodeConfig } from '../services/opencode-config-effective' import { applyOpenCodeConfigUpdate, toOpenCodeConfigApplyResponse } from '../services/opencode-config-apply' import { redactOpenCodeConfigContent, redactOpenCodeConfigFile } from '../services/opencode-config-redact' +import { patchNamesOpenCodeConfigEntities } from '../services/opencode-config-references' import { opencodeServerManager } from '../services/opencode-single-server' import { logger } from '../utils/logger' @@ -175,7 +176,7 @@ export function createOpenCodeConfigRoutes( return c.json({ error: 'Invalid config data', details: parsed.error.issues }, 400) } - if (opencodeServerManager.isRestartPending()) { + if (opencodeServerManager.isRestartPending() && patchNamesOpenCodeConfigEntities(parsed.data.patch)) { return c.json({ error: 'OpenCode has not loaded the saved configuration yet. Restart OpenCode before editing entries.', }, 409) diff --git a/backend/src/services/assistant-mode.ts b/backend/src/services/assistant-mode.ts index 59d9b5f6..29dd52dc 100644 --- a/backend/src/services/assistant-mode.ts +++ b/backend/src/services/assistant-mode.ts @@ -791,7 +791,7 @@ Read the merged persisted global configuration and its source files. Returns \`4 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 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. +Send \`expectedRevision\` from a read. A \`409\` with \`expectedRevision\` and \`actualRevision\` means the revision is stale, and a \`409\` with \`paths\` means 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. A \`409\` with neither field means OpenCode has not loaded the saved configuration since a failed reload, so a patch naming an agent, command, provider or MCP server is refused: do not retry, and tell the user to restart the OpenCode server from Settings. Patches that name no such entity still apply. **Request Body:** \`\`\`ts @@ -823,7 +823,7 @@ Returns the refreshed merged configuration and source files, with secrets redact 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\` when \`expectedRevision\` is stale or the v1 entry to remove exists only in a lower-priority config source. +Returns \`400\` for invalid configuration or a \`\` value (\`paths\` lists them), and \`409\` when \`expectedRevision\` is stale, the v1 entry to remove exists only in a lower-priority config source, or an entity patch arrives while an OpenCode restart is pending. ### GET /opencode-config/mcp diff --git a/backend/test/routes/settings.test.ts b/backend/test/routes/settings.test.ts index f4e91bf9..0d927b9d 100644 --- a/backend/test/routes/settings.test.ts +++ b/backend/test/routes/settings.test.ts @@ -639,6 +639,22 @@ describe('Settings Routes - OpenCode Upgrade', () => { expect(mockApplyOpenCodeConfigUpdate).not.toHaveBeenCalled() }) + it('applies a PATCH that names no entity while an OpenCode restart is pending', async () => { + vi.mocked(opencodeServerManager.isRestartPending).mockReturnValueOnce(true) + mockApplyOpenCodeConfigUpdate.mockResolvedValueOnce({ status: 'applied', config: { revision: 'r2' } }) + + const res = await settingsApp.fetch(new Request('http://localhost/opencode-config', { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ patch: { theme: 'dark' } }), + })) + + expect(res.status).toBe(200) + expect(mockApplyOpenCodeConfigUpdate).toHaveBeenCalledWith( + expect.objectContaining({ content: { theme: 'dark' }, mode: 'merge' }), + ) + }) + it('returns 400 when the PUT body fails schema validation', async () => { const res = await settingsApp.fetch(new Request('http://localhost/opencode-config', { method: 'PUT', diff --git a/frontend/src/components/settings/AgentDialog.test.tsx b/frontend/src/components/settings/AgentDialog.test.tsx index 3f0f51f4..dfcd7046 100644 --- a/frontend/src/components/settings/AgentDialog.test.tsx +++ b/frontend/src/components/settings/AgentDialog.test.tsx @@ -205,7 +205,6 @@ describe('AgentDialog', () => { body: { temperature: 0.2, top_p: 0.5, reasoning_effort: 'high' }, }) expect(agent.permissions).toEqual([ - { action: 'edit', resource: '*', effect: 'allow' }, { action: 'shell', resource: '*', effect: 'deny' }, { action: 'edit', resource: 'src/**', effect: 'ask' }, { action: 'webfetch', resource: '*', effect: 'allow' }, @@ -242,14 +241,12 @@ describe('AgentDialog', () => { const agent = onSubmit.mock.calls[0][1] expect(agent.permissions).toEqual([ - { action: 'shell', resource: '*', effect: 'allow' }, - { action: 'webfetch', resource: '*', effect: 'allow' }, { action: 'edit', resource: '*', effect: 'ask' }, { action: 'edit', resource: 'src/**', effect: 'allow' }, ]) }) - it('prepends wildcard rules for managed actions that have none', async () => { + it('adds no wildcard rule for an unchanged action so it keeps inheriting the global permission', async () => { const onSubmit = vi.fn() const user = userEvent.setup() render( @@ -274,14 +271,60 @@ describe('AgentDialog', () => { const agent = onSubmit.mock.calls[0][1] expect(agent.permissions).toEqual([ - { action: 'edit', resource: '*', effect: 'allow' }, - { action: 'shell', resource: '*', effect: 'allow' }, - { action: 'webfetch', resource: '*', effect: 'allow' }, { action: 'edit', resource: 'src/**', effect: 'deny' }, { action: 'shell', resource: 'git status', effect: 'ask' }, ]) }) + it('prepends a wildcard rule only for a changed action that has none', 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: 'shell', resource: '*', effect: 'deny' }, + { action: 'shell', resource: 'git status', effect: 'ask' }, + ]) + }) + + it('writes no permissions for a prompt-only save of an agent without permission rules', async () => { + const onSubmit = vi.fn() + const user = userEvent.setup() + render( + , + ) + + await user.type(screen.getByLabelText('Prompt'), ' carefully') + await user.click(screen.getByRole('button', { name: 'Update' })) + + const agent = onSubmit.mock.calls[0][1] + expect(agent.system).toBe('Review code carefully') + expect(agent).not.toHaveProperty('permissions') + }) + it('shows the last matching wildcard effect and applies the form effect to every occurrence', async () => { const onSubmit = vi.fn() const user = userEvent.setup() @@ -311,8 +354,6 @@ describe('AgentDialog', () => { const agent = onSubmit.mock.calls[0][1] expect(agent.permissions).toEqual([ - { action: 'shell', resource: '*', effect: 'allow' }, - { action: 'webfetch', resource: '*', effect: 'allow' }, { action: 'edit', resource: '*', effect: 'ask' }, { action: 'edit', resource: '*', effect: 'ask' }, ]) diff --git a/frontend/src/components/settings/AgentDialog.tsx b/frontend/src/components/settings/AgentDialog.tsx index 8a868c32..781458e5 100644 --- a/frontend/src/components/settings/AgentDialog.tsx +++ b/frontend/src/components/settings/AgentDialog.tsx @@ -47,11 +47,13 @@ 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, and prepends a - * wildcard fallback for managed actions that have no wildcard rule yet. + * wildcard fallback only for changed actions that have no wildcard rule yet, so + * an untouched action keeps inheriting the global permission. */ const withManagedPermissionEffects = ( permissions: OpenCodePermissionRule[] | undefined, effects: Record, + changedActions: readonly ManagedPermissionAction[], ): OpenCodePermissionRule[] => { const updated = (permissions ?? []).map((rule) => isManagedWildcardRule(rule) @@ -59,7 +61,7 @@ const withManagedPermissionEffects = ( : rule, ) const actionsWithWildcard = new Set(updated.filter(isManagedWildcardRule).map((rule) => rule.action)) - const fallbacks = MANAGED_PERMISSION_ACTIONS + const fallbacks = changedActions .filter((action) => !actionsWithWildcard.has(action)) .map((action) => ({ action, resource: '*', effect: effects[action] })) return [...fallbacks, ...updated] @@ -86,6 +88,12 @@ const agentFormSchema = z.object({ type AgentFormValues = z.infer +const formPermissionEffects = (values: AgentFormValues): Record => ({ + edit: values.editPermission, + shell: values.shellPermission, + webfetch: values.webfetchPermission, +}) + interface AgentDialogProps { open: boolean onOpenChange: (open: boolean) => void @@ -124,6 +132,10 @@ export function AgentDialog({ open, onOpenChange, onSubmit, editingAgent }: Agen const handleSubmit = (values: AgentFormValues) => { const previous = editingAgent?.agent + const effects = formPermissionEffects(values) + const loadedEffects = formPermissionEffects(getDefaultValues(editingAgent)) + const changedActions = MANAGED_PERMISSION_ACTIONS.filter((action) => effects[action] !== loadedEffects[action]) + const permissions = withManagedPermissionEffects(previous?.permissions, effects, changedActions) const agent: OpenCodeAgentPatch = { ...previous, system: values.prompt, @@ -131,11 +143,7 @@ export function AgentDialog({ open, onOpenChange, onSubmit, editingAgent }: Agen mode: values.mode, model: values.model?.trim() || null, disabled: values.disable, - permissions: withManagedPermissionEffects(previous?.permissions, { - edit: values.editPermission, - shell: values.shellPermission, - webfetch: values.webfetchPermission, - }), + ...(permissions.length > 0 || previous?.permissions ? { permissions } : {}), request: { ...previous?.request, body: {