mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
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.
This commit is contained in:
1 parent
8d92f86142
commit
38d618be9b
5 files changed
+85
-19
No files matched your search
@@ -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)
|
||||
|
||||
@@ -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.<name>\`, \`commands.<name>\`, \`providers.<id>\`, \`mcp.servers.<name>\`, or \`permissions\`) also deletes its v1 counterpart (\`agent.<name>\`, \`command.<name>\`, \`provider.<id>\`, \`mcp.<name>\`, 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 \`<redacted>\` 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 \`<redacted>\` 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
|
||||
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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(
|
||||
<AgentDialog
|
||||
open
|
||||
onOpenChange={vi.fn()}
|
||||
onSubmit={onSubmit}
|
||||
editingAgent={{
|
||||
name: 'reviewer',
|
||||
agent: {
|
||||
system: 'Review code',
|
||||
permissions: [{ action: 'shell', resource: 'git status', effect: 'ask' }],
|
||||
},
|
||||
}}
|
||||
/>,
|
||||
)
|
||||
|
||||
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(
|
||||
<AgentDialog
|
||||
open
|
||||
onOpenChange={vi.fn()}
|
||||
onSubmit={onSubmit}
|
||||
editingAgent={{ name: 'reviewer', agent: { system: 'Review code' } }}
|
||||
/>,
|
||||
)
|
||||
|
||||
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' },
|
||||
])
|
||||
|
||||
@@ -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<ManagedPermissionAction, PermissionEffect>,
|
||||
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<typeof agentFormSchema>
|
||||
|
||||
const formPermissionEffects = (values: AgentFormValues): Record<ManagedPermissionAction, PermissionEffect> => ({
|
||||
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: {
|
||||
|
||||
Reference in new issue
Block a user