fix: apply CodeRabbit auto-fixes

This commit is contained in:
Chris Scott committed 2026-11-03 08:29:59 -05:00
1 parent 3e6ebbd1dc
commit 8d92f86142
10 files changed
+262 -28

No files matched your search

+1 -1
View File
@@ -233,6 +233,6 @@ async function applyUpdate(
if (error instanceof SyntaxError) {
return c.json({ error: 'Invalid config data', details: error.message }, 400)
}
return c.json({ error: 'Failed to update OpenCode config' }, 500)
return toClientReadErrorResponse(c, error, 'Failed to update OpenCode config')
}
}
@@ -15,7 +15,7 @@ import {
withOpenCodeConfigLock,
} from './opencode-config-file'
import { readManagedOpenCodeConfig } from './opencode-config-effective'
import { restoreOpenCodeConfigReferences } from './opencode-config-references'
import { patchNamesOpenCodeConfigEntities, restoreOpenCodeConfigReferences } from './opencode-config-references'
import { opencodeServerManager } from './opencode-single-server'
import { reloadOpenCodeConfig } from './opencode-restart'
import type { OpenCodeClient } from './opencode/client'
@@ -106,13 +106,9 @@ async function keepOpenCodeConfigReferences(
snapshot: OpenCodeConfigSnapshot,
openCodeClient: OpenCodeClient,
): Promise<Record<string, unknown>> {
try {
const resolved = await readManagedOpenCodeConfig(openCodeClient.api, snapshot.sources)
return restoreOpenCodeConfigReferences(patch, resolved as Record<string, unknown>, snapshot.content)
} catch (error) {
logger.warn('Could not read the resolved OpenCode config; saving the patch without reference restoration:', error)
return patch
}
if (!patchNamesOpenCodeConfigEntities(patch)) return patch
const resolved = await readManagedOpenCodeConfig(openCodeClient.api, snapshot.sources)
return restoreOpenCodeConfigReferences(patch, resolved as Record<string, unknown>, snapshot.content)
}
export async function applyOpenCodeConfigUpdate(
@@ -136,6 +136,11 @@ function setValueAtPath(target: Record<string, unknown>, path: readonly string[]
}
}
/** Whether a merge patch names an agent, command, provider or MCP server, the only places references are restored. */
export function patchNamesOpenCodeConfigEntities(patch: Record<string, unknown>): boolean {
return V1_ENTITY_PATHS.some((mapping) => mapping.named && isRecord(readConfigValueAtPath(patch, mapping.v2Path)))
}
/**
* Keeps `{env:…}` and `{file:…}` references in a merge patch of named config entities.
*
+13
View File
@@ -611,6 +611,19 @@ describe('Settings Routes - OpenCode Upgrade', () => {
})
})
it('returns 503 from a PATCH entity save when OpenCode cannot be read', async () => {
mockApplyOpenCodeConfigUpdate.mockRejectedValueOnce(new ClientError('Transport'))
const res = await settingsApp.fetch(new Request('http://localhost/opencode-config', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ patch: { agents: { reviewer: { description: 'new' } } } }),
}))
expect(res.status).toBe(503)
expect(await res.json()).toEqual({ error: 'OpenCode server unavailable' })
})
it('refuses a PATCH entity save with 409 while an OpenCode restart is pending', async () => {
vi.mocked(opencodeServerManager.isRestartPending).mockReturnValueOnce(true)
@@ -158,6 +158,34 @@ describe('opencode-config-apply', () => {
expect(written).not.toContain('secret')
})
it('refuses an entity merge patch without writing when the resolved config cannot be read', async () => {
const original = '{\n "providers": { "acme": { "settings": { "apiKey": "{env:ACME_KEY}" } } }\n}\n'
await writeFile(sourcePath('opencode.json'), original, 'utf8')
await expect(applyOpenCodeConfigUpdate({
content: { providers: { acme: { name: 'Acme', settings: { apiKey: 'secret' } } } },
mode: 'merge',
settingsService,
openCodeClient,
})).rejects.toThrow('OpenCode unavailable')
expect(await readFile(sourcePath('opencode.json'), 'utf8')).toBe(original)
})
it('saves a merge patch without named entities while OpenCode is unavailable', async () => {
await writeFile(sourcePath('opencode.json'), '{"theme":"dark"}', 'utf8')
await applyOpenCodeConfigUpdate({
content: { theme: 'light' },
mode: 'merge',
settingsService,
openCodeClient,
})
expect(configGetMock).not.toHaveBeenCalled()
expect(JSON.parse(await readFile(sourcePath('opencode.json'), 'utf8'))).toEqual({ theme: 'light' })
})
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'))
@@ -1,5 +1,14 @@
import { describe, expect, it } from 'vitest'
import { restoreOpenCodeConfigReferences } from '../../src/services/opencode-config-references'
import { patchNamesOpenCodeConfigEntities, restoreOpenCodeConfigReferences } from '../../src/services/opencode-config-references'
describe('patchNamesOpenCodeConfigEntities', () => {
it('is true only when a patch names agents, commands, providers or MCP servers', () => {
expect(patchNamesOpenCodeConfigEntities({ agents: { reviewer: { description: 'x' } } })).toBe(true)
expect(patchNamesOpenCodeConfigEntities({ mcp: { servers: { docs: null } } })).toBe(true)
expect(patchNamesOpenCodeConfigEntities({ theme: 'dark', permissions: [] })).toBe(false)
expect(patchNamesOpenCodeConfigEntities({ mcp: { timeout: 5 } })).toBe(false)
})
})
describe('restoreOpenCodeConfigReferences', () => {
it('keeps unchanged references of a v2 entity and writes edited values', () => {
@@ -1,4 +1,4 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { describe, it, expect, vi, beforeEach, beforeAll } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { AgentDialog } from './AgentDialog'
@@ -29,7 +29,14 @@ const providers: Provider[] = [
},
]
describe('AgentDialog model field', () => {
describe('AgentDialog', () => {
beforeAll(() => {
Element.prototype.hasPointerCapture ??= () => false
Element.prototype.setPointerCapture ??= () => {}
Element.prototype.releasePointerCapture ??= () => {}
Element.prototype.scrollIntoView ??= () => {}
})
beforeEach(() => {
vi.clearAllMocks()
mocks.useProviders.mockReturnValue({ data: { providers, models: [] } })
@@ -198,13 +205,116 @@ describe('AgentDialog model field', () => {
body: { temperature: 0.2, top_p: 0.5, reasoning_effort: 'high' },
})
expect(agent.permissions).toEqual([
{ action: 'edit', resource: 'src/**', effect: 'ask' },
{ action: 'edit', resource: '*', effect: 'allow' },
{ action: 'shell', resource: '*', effect: 'deny' },
{ action: 'edit', resource: 'src/**', effect: 'ask' },
{ action: 'webfetch', resource: '*', effect: 'allow' },
])
expect(agent.hidden).toBe(true)
expect(agent.color).toBe('#fff')
expect(agent.steps).toBe(7)
})
it('keeps a wildcard rule before a specific rule and writes the form effect in place', 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: 'edit', resource: '*', effect: 'deny' },
{ action: 'edit', resource: 'src/**', effect: 'allow' },
],
},
}}
/>,
)
await user.click(screen.getByRole('combobox', { name: 'Edit' }))
await user.click(screen.getByRole('option', { name: 'Ask' }))
await user.click(screen.getByRole('button', { name: 'Update' }))
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 () => {
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: 'edit', resource: 'src/**', effect: 'deny' },
{ action: 'shell', resource: 'git status', effect: 'ask' },
],
},
}}
/>,
)
await user.click(screen.getByRole('button', { name: 'Update' }))
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('shows the last matching wildcard effect and applies the form effect to every occurrence', 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: 'edit', resource: '*', effect: 'allow' },
{ action: 'edit', resource: '*', effect: 'deny' },
],
},
}}
/>,
)
expect(screen.getByRole('combobox', { name: 'Edit' })).toHaveTextContent('Deny')
await user.click(screen.getByRole('combobox', { name: 'Edit' }))
await user.click(screen.getByRole('option', { name: 'Ask' }))
await user.click(screen.getByRole('button', { name: 'Update' }))
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' },
])
})
})
@@ -20,14 +20,51 @@ type ManagedPermissionAction = typeof MANAGED_PERMISSION_ACTIONS[number]
type PermissionEffect = OpenCodePermissionRule['effect']
const isManagedWildcardRule = (rule: OpenCodePermissionRule): boolean =>
rule.resource === '*' && MANAGED_PERMISSION_ACTIONS.includes(rule.action as ManagedPermissionAction)
const lastMatchingRule = (
permissions: OpenCodePermissionRule[] | undefined,
matches: (rule: OpenCodePermissionRule) => boolean,
): OpenCodePermissionRule | undefined => {
let match: OpenCodePermissionRule | undefined
for (const rule of permissions ?? []) {
if (matches(rule)) {
match = rule
}
}
return match
}
const permissionEffect = (
permissions: OpenCodePermissionRule[] | undefined,
action: ManagedPermissionAction,
): PermissionEffect => {
const rule = permissions?.find((entry) => entry.action === action && entry.resource === '*')
const rule = lastMatchingRule(permissions, (entry) => entry.action === action && entry.resource === '*')
return rule?.effect ?? 'allow'
}
/**
* 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.
*/
const withManagedPermissionEffects = (
permissions: OpenCodePermissionRule[] | undefined,
effects: Record<ManagedPermissionAction, PermissionEffect>,
): OpenCodePermissionRule[] => {
const updated = (permissions ?? []).map((rule) =>
isManagedWildcardRule(rule)
? { ...rule, effect: effects[rule.action as ManagedPermissionAction] }
: rule,
)
const actionsWithWildcard = new Set(updated.filter(isManagedWildcardRule).map((rule) => rule.action))
const fallbacks = MANAGED_PERMISSION_ACTIONS
.filter((action) => !actionsWithWildcard.has(action))
.map((action) => ({ action, resource: '*', effect: effects[action] }))
return [...fallbacks, ...updated]
}
const requestBodyNumber = (agent: OpenCodeAgentConfig | undefined, key: string): number | undefined => {
const value = agent?.request?.body?.[key]
return typeof value === 'number' ? value : undefined
@@ -87,9 +124,6 @@ export function AgentDialog({ open, onOpenChange, onSubmit, editingAgent }: Agen
const handleSubmit = (values: AgentFormValues) => {
const previous = editingAgent?.agent
const preservedPermissions = (previous?.permissions ?? []).filter(
(rule) => rule.resource !== '*' || !MANAGED_PERMISSION_ACTIONS.includes(rule.action as ManagedPermissionAction),
)
const agent: OpenCodeAgentPatch = {
...previous,
system: values.prompt,
@@ -97,12 +131,11 @@ export function AgentDialog({ open, onOpenChange, onSubmit, editingAgent }: Agen
mode: values.mode,
model: values.model?.trim() || null,
disabled: values.disable,
permissions: [
...preservedPermissions,
{ action: 'edit', resource: '*', effect: values.editPermission },
{ action: 'shell', resource: '*', effect: values.shellPermission },
{ action: 'webfetch', resource: '*', effect: values.webfetchPermission },
],
permissions: withManagedPermissionEffects(previous?.permissions, {
edit: values.editPermission,
shell: values.shellPermission,
webfetch: values.webfetchPermission,
}),
request: {
...previous?.request,
body: {
+11 -5
View File
@@ -5,7 +5,6 @@ import { homedir, networkInterfaces, type NetworkInterfaceInfo } from 'node:os'
import { join } from 'node:path'
import { renderUnicodeCompact } from 'uqr'
import {
ClientError,
buildOpenCodeBasicAuth,
createOpenCodeApi,
encryptOpenCodePairingCredentials,
@@ -187,20 +186,27 @@ export async function probeOpenCodeServer(
credentials: PairingCredentials,
timeoutMs = 3000,
): Promise<OpenCodeServerProbe> {
let responseStatus: number | undefined
const api = createOpenCodeApi({
baseUrl: trimUrlTrailingSlashes(baseUrl),
headers: { authorization: buildOpenCodeBasicAuth(credentials.password, credentials.username) },
fetch: Object.assign(
async (input: RequestInfo | URL, init?: RequestInit) => {
const response = await fetch(input, init)
responseStatus = response.status
return response
},
{ preconnect: fetch.preconnect },
),
})
try {
const info = await api.server.info({ signal: AbortSignal.timeout(timeoutMs) })
return { status: 'ok', version: info.version ?? null }
} catch (error) {
if (openCodeErrorStatus(error) === 401) return { status: 'unauthorized' }
if (responseStatus === 401 || openCodeErrorStatus(error) === 401) return { status: 'unauthorized' }
const status = error instanceof ClientError
? (error.cause as { status?: number } | undefined)?.status
: undefined
const status = responseStatus !== undefined && responseStatus >= 400 ? responseStatus : undefined
return {
status: 'unreachable',
message: status === undefined ? messageOf(error) : `HTTP ${status}`,
+34
View File
@@ -362,6 +362,28 @@ describe('probeOpenCodeServer', () => {
})
})
it('reports unauthorized when the server rejects the credentials with an empty body', async () => {
const server = await startProbeServer((_request, response) => {
response.writeHead(401, { 'content-type': 'text/plain' })
response.end()
})
await expect(probeOpenCodeServer(server.baseUrl, CREDENTIALS, 1000)).resolves.toEqual({
status: 'unauthorized',
})
})
it('reports unauthorized when the server rejects the credentials with a plain text body', async () => {
const server = await startProbeServer((_request, response) => {
response.writeHead(401, { 'content-type': 'text/plain' })
response.end('unauthorized')
})
await expect(probeOpenCodeServer(server.baseUrl, CREDENTIALS, 1000)).resolves.toEqual({
status: 'unauthorized',
})
})
it('reports unreachable with the HTTP status for an unexpected response', async () => {
const server = await startProbeServer((_request, response) => {
response.writeHead(500, { 'content-type': 'application/json' })
@@ -374,6 +396,18 @@ describe('probeOpenCodeServer', () => {
})
})
it('reports unreachable with the HTTP status for an unexpected plain text response', async () => {
const server = await startProbeServer((_request, response) => {
response.writeHead(500, { 'content-type': 'text/plain' })
response.end('boom')
})
await expect(probeOpenCodeServer(server.baseUrl, CREDENTIALS, 1000)).resolves.toEqual({
status: 'unreachable',
message: 'HTTP 500',
})
})
it('reports unreachable when the server refuses the connection', async () => {
const server = await startProbeServer(() => {})
const baseUrl = server.baseUrl