diff --git a/frontend/src/api/settings.ts b/frontend/src/api/settings.ts index 6357bf56..c7ec8428 100644 --- a/frontend/src/api/settings.ts +++ b/frontend/src/api/settings.ts @@ -14,6 +14,8 @@ import type { InstallSkillResponse, OpenCodeDirectoryFileInfo, OpenCodeRestartResponse, + ManagedOpenCodeConfig, + UpdateOpenCodeConfigPatchRequest, } from './types/settings' import { API_BASE_URL } from '@/config' import { fetchWrapper } from './fetchWrapper' @@ -73,6 +75,20 @@ export const settingsApi = { }) }, + getManagedOpenCodeConfig: async (): Promise => { + return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-config/managed`) + }, + + patchOpenCodeConfig: async ( + request: UpdateOpenCodeConfigPatchRequest + ): Promise => { + return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-config`, { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(request), + }) + }, + discoverOpenCodeModels: async ( baseUrl: string, apiKey?: string, diff --git a/frontend/src/api/types/settings.ts b/frontend/src/api/types/settings.ts index dd20feaa..94128663 100644 --- a/frontend/src/api/types/settings.ts +++ b/frontend/src/api/types/settings.ts @@ -26,6 +26,11 @@ import { type InstallSkillResponse, type SettingsResponse as SharedSettingsResponse, } from '@opencode-manager/shared' +import type { OpenCodeConfigInfo } from '@opencode-manager/shared/opencode' +import type { + OpenCodeAgentConfig, + OpenCodeCommandConfig, +} from '@opencode-manager/shared/opencode' import type { NotificationPreferences } from '@opencode-manager/shared/types' import { saveFile } from '@/lib/download' @@ -90,3 +95,30 @@ export interface OpenCodeDirectoryFileInfo { name: string relativePath: string } + +export interface ManagedOpenCodeConfig { + revision: string | null + info: OpenCodeConfigInfo +} + +/** + * Merge-patch value for one agent: an explicit null clears the stored field, + * while an omitted field stays untouched. + */ +export type OpenCodeAgentPatch = { + [K in keyof OpenCodeAgentConfig]?: OpenCodeAgentConfig[K] | null +} + +/** + * Merge-patch value for one command: an explicit null clears the stored field, + * while an omitted field stays untouched. + */ +export type OpenCodeCommandPatch = { + [K in keyof OpenCodeCommandConfig]?: OpenCodeCommandConfig[K] | null +} + +export interface UpdateOpenCodeConfigPatchRequest { + patch: Record + source?: OpenCodeConfigSourceName + expectedRevision?: string +} diff --git a/frontend/src/components/settings/AgentDialog.test.tsx b/frontend/src/components/settings/AgentDialog.test.tsx index 0a8ae007..d3fb89c9 100644 --- a/frontend/src/components/settings/AgentDialog.test.tsx +++ b/frontend/src/components/settings/AgentDialog.test.tsx @@ -43,7 +43,7 @@ describe('AgentDialog model field', () => { open onOpenChange={vi.fn()} onSubmit={vi.fn()} - editingAgent={{ name: 'reviewer', agent: { prompt: 'Review code', model: 'openai/gpt-4o' } }} + editingAgent={{ name: 'reviewer', agent: { system: 'Review code', model: 'openai/gpt-4o' } }} />, ) @@ -58,7 +58,7 @@ describe('AgentDialog model field', () => { open onOpenChange={vi.fn()} onSubmit={onSubmit} - editingAgent={{ name: 'reviewer', agent: { prompt: 'Review code', model: 'openai/gpt-4o#high' } }} + editingAgent={{ name: 'reviewer', agent: { system: 'Review code', model: 'openai/gpt-4o#high' } }} />, ) @@ -80,7 +80,7 @@ describe('AgentDialog model field', () => { onSubmit={onSubmit} editingAgent={{ name: 'reviewer', - agent: { prompt: 'Review code', model: { providerID: 'openai', model: 'gpt-4o', variant: 'high' } }, + agent: { system: 'Review code', model: { providerID: 'openai', model: 'gpt-4o', variant: 'high' } }, }} />, ) @@ -95,7 +95,7 @@ describe('AgentDialog model field', () => { ) }) - it('submits no model when the field is empty', async () => { + it('submits null for a cleared model', async () => { const onSubmit = vi.fn() const user = userEvent.setup() render( @@ -103,14 +103,39 @@ describe('AgentDialog model field', () => { open onOpenChange={vi.fn()} onSubmit={onSubmit} - editingAgent={{ name: 'reviewer', agent: { prompt: 'Review code' } }} + editingAgent={{ name: 'reviewer', agent: { system: 'Review code' } }} />, ) await user.click(screen.getByRole('button', { name: 'Update' })) const agent = onSubmit.mock.calls[0][1] - expect(agent.model).toBeUndefined() + expect(agent.model).toBeNull() + }) + + it('sends null for cleared description and model so the merge patch deletes them', async () => { + const onSubmit = vi.fn() + const user = userEvent.setup() + render( + , + ) + + await user.clear(screen.getByLabelText('Description')) + await user.clear(screen.getByLabelText('Model')) + await user.click(screen.getByRole('button', { name: 'Update' })) + + expect(onSubmit).toHaveBeenCalledWith( + 'reviewer', + expect.objectContaining({ description: null, model: null }), + ) }) it('saves the OpenCode key of an aliased model on create', async () => { @@ -129,4 +154,57 @@ describe('AgentDialog model field', () => { expect.objectContaining({ model: 'anthropic/claude-opus-5-5-fast' }), ) }) + + it('maps v2 request body values and permission rules into the form and preserves unrelated fields on save', async () => { + const onSubmit = vi.fn() + const user = userEvent.setup() + render( + , + ) + + expect(screen.getByLabelText('Temperature')).toHaveValue(0.2) + expect(screen.getByLabelText('Top P')).toHaveValue(0.5) + expect(screen.getByText('Deny')).toBeInTheDocument() + + await user.click(screen.getByRole('button', { name: 'Update' })) + + const agent = onSubmit.mock.calls[0][1] + expect(agent.request).toEqual({ + headers: { 'x-test': '1' }, + 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: 'webfetch', resource: '*', effect: 'allow' }, + ]) + expect(agent.hidden).toBe(true) + expect(agent.color).toBe('#fff') + expect(agent.steps).toBe(7) + }) }) diff --git a/frontend/src/components/settings/AgentDialog.tsx b/frontend/src/components/settings/AgentDialog.tsx index e8772c24..54ced394 100644 --- a/frontend/src/components/settings/AgentDialog.tsx +++ b/frontend/src/components/settings/AgentDialog.tsx @@ -11,6 +11,27 @@ import { Switch } from '@/components/ui/switch' import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select' import { ModelCombobox } from '@/components/model/ModelCombobox' import { configModelRef, formatOpenCodeModelRef } from '@opencode-manager/shared/opencode' +import type { OpenCodeAgentConfig, OpenCodePermissionRule } from '@opencode-manager/shared/opencode' +import type { OpenCodeAgentPatch } from '@/api/types/settings' + +const MANAGED_PERMISSION_ACTIONS = ['edit', 'shell', 'webfetch'] as const + +type ManagedPermissionAction = typeof MANAGED_PERMISSION_ACTIONS[number] + +type PermissionEffect = OpenCodePermissionRule['effect'] + +const permissionEffect = ( + permissions: OpenCodePermissionRule[] | undefined, + action: ManagedPermissionAction, +): PermissionEffect => { + const rule = permissions?.find((entry) => entry.action === action && entry.resource === '*') + return rule?.effect ?? 'allow' +} + +const requestBodyNumber = (agent: OpenCodeAgentConfig | undefined, key: string): number | undefined => { + const value = agent?.request?.body?.[key] + return typeof value === 'number' ? value : undefined +} const agentFormSchema = z.object({ name: z.string().min(1, 'Agent name is required').regex(/^[a-z0-9-]+$/, 'Must be lowercase letters, numbers, and hyphens only'), @@ -20,70 +41,42 @@ const agentFormSchema = z.object({ temperature: z.number().min(0).max(2), topP: z.number().min(0).max(1), model: z.string().optional(), - write: z.boolean(), - edit: z.boolean(), - bash: z.boolean(), - webfetch: z.boolean(), editPermission: z.enum(['ask', 'allow', 'deny']), - bashPermission: z.enum(['ask', 'allow', 'deny']), + shellPermission: z.enum(['ask', 'allow', 'deny']), webfetchPermission: z.enum(['ask', 'allow', 'deny']), - disable: z.boolean() + disable: z.boolean(), }) type AgentFormValues = z.infer -interface Agent { - prompt?: string - description?: string - mode?: 'subagent' | 'primary' | 'all' - temperature?: number - topP?: number - top_p?: number - model?: TModel - tools?: Record - permission?: { - edit?: 'ask' | 'allow' | 'deny' - bash?: 'ask' | 'allow' | 'deny' | Record - webfetch?: 'ask' | 'allow' | 'deny' - } - disable?: boolean - [key: string]: unknown -} - -type StoredAgent = Agent - interface AgentDialogProps { open: boolean onOpenChange: (open: boolean) => void - onSubmit: (name: string, agent: Agent) => void - editingAgent?: { name: string; agent: StoredAgent } | null + onSubmit: (name: string, agent: OpenCodeAgentPatch) => void + editingAgent?: { name: string; agent: OpenCodeAgentConfig } | null } export function AgentDialog({ open, onOpenChange, onSubmit, editingAgent }: AgentDialogProps) { - const getDefaultValues = (agent?: { name: string; agent: StoredAgent } | null): AgentFormValues => { + const getDefaultValues = (agent?: { name: string; agent: OpenCodeAgentConfig } | null): AgentFormValues => { const modelRef = configModelRef(agent?.agent.model) return { name: agent?.name || '', description: agent?.agent.description || '', - prompt: agent?.agent.prompt || '', + prompt: agent?.agent.system || '', mode: agent?.agent.mode || 'subagent', - temperature: agent?.agent.temperature ?? 0.7, - topP: agent?.agent.topP ?? agent?.agent.top_p ?? 1, + temperature: requestBodyNumber(agent?.agent, 'temperature') ?? 0.7, + topP: requestBodyNumber(agent?.agent, 'top_p') ?? 1, model: modelRef ? formatOpenCodeModelRef(modelRef) : '', - write: agent?.agent.tools?.write ?? true, - edit: agent?.agent.tools?.edit ?? true, - bash: agent?.agent.tools?.bash ?? true, - webfetch: agent?.agent.tools?.webfetch ?? true, - editPermission: agent?.agent.permission?.edit ?? 'allow', - bashPermission: typeof agent?.agent.permission?.bash === 'string' ? agent.agent.permission.bash : 'allow', - webfetchPermission: agent?.agent.permission?.webfetch ?? 'allow', - disable: agent?.agent.disable ?? false + editPermission: permissionEffect(agent?.agent.permissions, 'edit'), + shellPermission: permissionEffect(agent?.agent.permissions, 'shell'), + webfetchPermission: permissionEffect(agent?.agent.permissions, 'webfetch'), + disable: agent?.agent.disabled ?? false, } } const form = useForm({ resolver: zodResolver(agentFormSchema), - defaultValues: getDefaultValues(editingAgent) + defaultValues: getDefaultValues(editingAgent), }) useEffect(() => { @@ -93,28 +86,31 @@ export function AgentDialog({ open, onOpenChange, onSubmit, editingAgent }: Agen }, [open, editingAgent, form]) const handleSubmit = (values: AgentFormValues) => { - const agent: Agent = { - prompt: values.prompt, - description: values.description || undefined, + 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, + description: values.description || null, mode: values.mode, - temperature: values.temperature, - topP: values.topP, - disable: values.disable, - tools: { - write: values.write, - edit: values.edit, - bash: values.bash, - webfetch: values.webfetch + 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 }, + ], + request: { + ...previous?.request, + body: { + ...previous?.request?.body, + temperature: values.temperature, + top_p: values.topP, + }, }, - permission: { - edit: values.editPermission, - bash: values.bashPermission, - webfetch: values.webfetchPermission - } - } - - if (values.model?.trim()) { - agent.model = values.model.trim() } onSubmit(values.name, agent) @@ -287,75 +283,6 @@ export function AgentDialog({ open, onOpenChange, onSubmit, editingAgent }: Agen )} /> -
-
Tools Configuration
-
- ( - - - - - Write - - )} - /> - - ( - - - - - Edit - - )} - /> - - ( - - - - - Bash - - )} - /> - - ( - - - - - Web Fetch - - )} - /> -
-
-
Permissions
@@ -384,10 +311,10 @@ export function AgentDialog({ open, onOpenChange, onSubmit, editingAgent }: Agen ( - Bash + Shell - field.onChange(parseFloat(e.target.value)) - } - /> - - - - )} - /> (
- Run as subtask + Run as subagent - Execute this command as a separate subtask + Execute this command in a subagent session
@@ -262,4 +246,3 @@ export function CommandDialog({ ); } - diff --git a/frontend/src/components/settings/CommandsEditor.test.tsx b/frontend/src/components/settings/CommandsEditor.test.tsx index 2b0b9e9b..fb2a8eca 100644 --- a/frontend/src/components/settings/CommandsEditor.test.tsx +++ b/frontend/src/components/settings/CommandsEditor.test.tsx @@ -54,16 +54,14 @@ describe('CommandsEditor', () => { }) it('renders empty state when no commands configured', () => { - const onChange = vi.fn() - render(, { wrapper: createWrapper() }) + render(, { wrapper: createWrapper() }) expect(screen.getByText('No commands configured')).toBeInTheDocument() expect(screen.getByText('Add your first command to get started.')).toBeInTheDocument() }) it('renders command names without a leading slash', () => { - const onChange = vi.fn() - render(, { wrapper: createWrapper() }) + render(, { wrapper: createWrapper() }) expect(screen.getByText('review')).toBeInTheDocument() expect(screen.getByText('build')).toBeInTheDocument() @@ -71,12 +69,12 @@ describe('CommandsEditor', () => { }) it('renders uploaded directory command files', () => { - const onChange = vi.fn() render( , { wrapper: createWrapper() }, ) @@ -89,8 +87,7 @@ describe('CommandsEditor', () => { it('opens CommandDialog when clicking Edit on a row', async () => { const user = userEvent.setup() - const onChange = vi.fn() - render(, { wrapper: createWrapper() }) + render(, { wrapper: createWrapper() }) const editButtons = screen.getAllByText('Edit') await user.click(editButtons[0]) @@ -101,8 +98,7 @@ describe('CommandsEditor', () => { it('opens CommandDialog when clicking row body', async () => { const user = userEvent.setup() - const onChange = vi.fn() - render(, { wrapper: createWrapper() }) + render(, { wrapper: createWrapper() }) await user.click(screen.getByText('review')) @@ -111,8 +107,7 @@ describe('CommandsEditor', () => { it('opens CommandDialog and displays Create Command text when clicking Add Command button', async () => { const user = userEvent.setup() - const onChange = vi.fn() - render(, { wrapper: createWrapper() }) + render(, { wrapper: createWrapper() }) await user.click(screen.getByText('Add Command')) @@ -120,33 +115,31 @@ describe('CommandsEditor', () => { expect(screen.getByText('Create Command')).toBeInTheDocument() }) - it('calls onChange with command removed when Delete is clicked from overflow menu', async () => { + it('calls onDelete with the command name when Delete is clicked from overflow menu', async () => { const user = userEvent.setup() - const onChange = vi.fn() - render(, { wrapper: createWrapper() }) + const onDelete = vi.fn() + render(, { wrapper: createWrapper() }) await user.click(screen.getByLabelText('Actions for review')) await user.click(screen.getByText('Delete')) - expect(onChange).toHaveBeenCalledTimes(1) - expect(onChange).toHaveBeenCalledWith({ build: mockCommands.build }) + expect(onDelete).toHaveBeenCalledTimes(1) + expect(onDelete).toHaveBeenCalledWith('review') }) it('renders agent badge when command has agent', () => { - const onChange = vi.fn() - render(, { wrapper: createWrapper() }) + render(, { wrapper: createWrapper() }) expect(screen.getByText('code-reviewer')).toBeInTheDocument() }) it('uploads only markdown files from a selected commands folder', async () => { - const onChange = vi.fn() const markdownFile = new File(['commit body'], 'commit.md', { type: 'text/markdown' }) const systemFile = new File(['metadata'], '.DS_Store') Object.defineProperty(markdownFile, 'webkitRelativePath', { value: 'commands/git/commit.md' }) Object.defineProperty(systemFile, 'webkitRelativePath', { value: 'commands/.DS_Store' }) - const { container } = render(, { wrapper: createWrapper() }) + const { container } = render(, { wrapper: createWrapper() }) const input = container.querySelector('input[type="file"]') as HTMLInputElement fireEvent.change(input, { target: { files: [markdownFile, systemFile] } }) @@ -158,11 +151,10 @@ describe('CommandsEditor', () => { }) it('shows an error when a selected commands folder has no markdown files', async () => { - const onChange = vi.fn() const systemFile = new File(['metadata'], '.DS_Store') Object.defineProperty(systemFile, 'webkitRelativePath', { value: 'commands/.DS_Store' }) - const { container } = render(, { wrapper: createWrapper() }) + const { container } = render(, { wrapper: createWrapper() }) const input = container.querySelector('input[type="file"]') as HTMLInputElement fireEvent.change(input, { target: { files: [systemFile] } }) diff --git a/frontend/src/components/settings/CommandsEditor.tsx b/frontend/src/components/settings/CommandsEditor.tsx index 721d37dc..f76e1867 100644 --- a/frontend/src/components/settings/CommandsEditor.tsx +++ b/frontend/src/components/settings/CommandsEditor.tsx @@ -1,58 +1,34 @@ import { useState } from 'react' import { Plus } from 'lucide-react' -import { Button } from '@/components/ui/button' import { Badge } from '@/components/ui/badge' +import { Button } from '@/components/ui/button' import { Dialog, DialogTrigger } from '@/components/ui/dialog' import { SettingsList, SettingsListRow } from '@/components/ui/settings-list' +import type { OpenCodeCommandConfig } from '@opencode-manager/shared/opencode' +import type { OpenCodeCommandPatch, OpenCodeDirectoryFileInfo } from '@/api/types/settings' import { CommandDialog } from './CommandDialog' import { UploadFolderButton } from './UploadFolderButton' import { DirectoryFilesList } from './DirectoryFilesList' -import type { OpenCodeDirectoryFileInfo } from '@/api/types/settings' - -interface Command { - template: string - description?: string - agent?: string - model?: string - subtask?: boolean - topP?: number -} interface CommandsEditorProps { - commands: Record + commands: Record directoryCommands?: OpenCodeDirectoryFileInfo[] - onChange: (commands: Record) => void + onSave: (name: string, command: OpenCodeCommandPatch, previousName?: string) => void + onDelete: (name: string) => void } -export function CommandsEditor({ commands, directoryCommands = [], onChange }: CommandsEditorProps) { +export function CommandsEditor({ commands, directoryCommands = [], onSave, onDelete }: CommandsEditorProps) { const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false) - const [editingCommand, setEditingCommand] = useState<{ name: string; command: Command } | null>(null) + const [editingCommand, setEditingCommand] = useState<{ name: string; command: OpenCodeCommandConfig } | null>(null) const hasCommands = Object.keys(commands).length > 0 || directoryCommands.length > 0 - const handleCommandSubmit = (name: string, command: Command) => { - if (editingCommand) { - const updatedCommands = { ...commands } - delete updatedCommands[editingCommand.name] - updatedCommands[name] = command - onChange(updatedCommands) - setEditingCommand(null) - } else { - const updatedCommands = { - ...commands, - [name]: command - } - onChange(updatedCommands) - setIsCreateDialogOpen(false) - } + const handleCommandSubmit = (name: string, command: OpenCodeCommandPatch) => { + onSave(name, command, editingCommand?.name) + setEditingCommand(null) + setIsCreateDialogOpen(false) } - const deleteCommand = (name: string) => { - const updatedCommands = { ...commands } - delete updatedCommands[name] - onChange(updatedCommands) - } - - const startEdit = (name: string, command: Command) => { + const startEdit = (name: string, command: OpenCodeCommandConfig) => { setEditingCommand({ name, command }) } @@ -91,7 +67,7 @@ export function CommandsEditor({ commands, directoryCommands = [], onChange }: C } onClick={() => startEdit(name, command)} primaryAction={{ label: 'Edit', onClick: () => startEdit(name, command) }} - actions={[{ label: 'Delete', destructive: true, onClick: () => deleteCommand(name) }]} + actions={[{ label: 'Delete', destructive: true, onClick: () => onDelete(name) }]} actionsLabel={`Actions for ${name}`} /> ))} diff --git a/frontend/src/components/settings/OpenCodeConfigManager.test.tsx b/frontend/src/components/settings/OpenCodeConfigManager.test.tsx index 844eff83..9088dcc9 100644 --- a/frontend/src/components/settings/OpenCodeConfigManager.test.tsx +++ b/frontend/src/components/settings/OpenCodeConfigManager.test.tsx @@ -3,12 +3,15 @@ import { render, screen, waitFor, fireEvent, act } from '@testing-library/react' import userEvent from '@testing-library/user-event' import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { OpenCodeConfigManager } from './OpenCodeConfigManager' +import { FetchError } from '@/api/fetchWrapper' import type { OpenCodeConfigFile } from '@/api/types/settings' import { makeOpenCodeConfigFile, makeOpenCodeConfigSource } from '@/test/fixtures/opencode-config' const { mockGetOpenCodeConfig, mockUpdateOpenCodeConfig, + mockGetManagedOpenCodeConfig, + mockPatchOpenCodeConfig, mockRestartOpenCodeServer, mockGetActiveOpenCodeSessions, mockGetOpenCodeImportStatus, @@ -19,6 +22,8 @@ const { } = vi.hoisted(() => ({ mockGetOpenCodeConfig: vi.fn(), mockUpdateOpenCodeConfig: vi.fn(), + mockGetManagedOpenCodeConfig: vi.fn(), + mockPatchOpenCodeConfig: vi.fn(), mockRestartOpenCodeServer: vi.fn(), mockGetActiveOpenCodeSessions: vi.fn(), mockGetOpenCodeImportStatus: vi.fn(), @@ -65,6 +70,8 @@ vi.mock('@/api/settings', () => ({ settingsApi: { getOpenCodeConfig: mockGetOpenCodeConfig, updateOpenCodeConfig: mockUpdateOpenCodeConfig, + getManagedOpenCodeConfig: mockGetManagedOpenCodeConfig, + patchOpenCodeConfig: mockPatchOpenCodeConfig, restartOpenCodeServer: mockRestartOpenCodeServer, getActiveOpenCodeSessions: mockGetActiveOpenCodeSessions, getOpenCodeImportStatus: mockGetOpenCodeImportStatus, @@ -76,6 +83,25 @@ vi.mock('@/api/settings', () => ({ }, })) +vi.mock('@/components/model/ModelCombobox', () => ({ ModelCombobox: () => null })) + +vi.mock('./AgentDialog', () => ({ + AgentDialog: ({ open, onSubmit, editingAgent }: { + open: boolean + onSubmit: (name: string, agent: Record) => void + editingAgent?: { name: string } | null + }) => open ? ( +
+ + +
+ ) : null, +})) + const defaultContent = { provider: { openai: { @@ -108,6 +134,8 @@ describe('OpenCodeConfigManager', () => { vi.clearAllMocks() healthState.data = { opencode: 'healthy', opencodeRestartPending: false } mockGetOpenCodeConfig.mockResolvedValue(defaultConfig) + mockGetManagedOpenCodeConfig.mockResolvedValue({ revision: 'rev-1', info: {} }) + mockPatchOpenCodeConfig.mockResolvedValue({ ...defaultConfig, revision: 'rev-2' }) mockGetOpenCodeImportStatus.mockResolvedValue({}) mockGetAgentsMd.mockResolvedValue({ content: '# Agent Instructions' }) mockListManagedSkills.mockResolvedValue([]) @@ -643,4 +671,140 @@ describe('OpenCodeConfigManager', () => { expect(notice).toHaveTextContent('Saves apply only to opencode.jsonc') expect(notice).toHaveTextContent('For simpler configuration, consolidate the settings you need into one file, then remove redundant files after verifying the result.') }) + + it('lists agents and commands from the managed config query', async () => { + mockGetManagedOpenCodeConfig.mockResolvedValue({ + revision: 'rev-1', + info: { + agents: { reviewer: { system: 'Review code', description: 'Reviews code', mode: 'subagent' } }, + commands: { deploy: { template: 'Deploy it', description: 'Deploys the app' } }, + }, + }) + + const user = userEvent.setup() + renderWithQuery() + + await screen.findByText('opencode.json') + await user.click(screen.getByRole('button', { name: /Commands/i })) + expect(await screen.findByText('deploy')).toBeInTheDocument() + + const agentsButton = screen.getAllByRole('button', { name: /Agents/i }).find(button => button.textContent?.startsWith('Agents')) + expect(agentsButton).toBeDefined() + await user.click(agentsButton!) + expect(await screen.findByText('reviewer')).toBeInTheDocument() + }) + + it('shows the unavailable notice and keeps the raw editor reachable when OpenCode is down', async () => { + mockGetManagedOpenCodeConfig.mockRejectedValue(new FetchError('OpenCode server unavailable', 503)) + + const user = userEvent.setup() + const { container } = renderWithQuery() + + await screen.findByText('opencode.json') + await user.click(screen.getByRole('button', { name: /Commands/i })) + expect(await screen.findByText(/OpenCode is not running, so the configured commands cannot be listed/)).toBeInTheDocument() + + const agentsButton = screen.getAllByRole('button', { name: /Agents/i }).find(button => button.textContent?.startsWith('Agents')) + expect(agentsButton).toBeDefined() + await user.click(agentsButton!) + expect(await screen.findByText(/OpenCode is not running, so the configured agents cannot be listed/)).toBeInTheDocument() + + const editIcon = container.querySelector('.lucide-square-pen') as SVGElement + await user.click(editIcon.closest('button') as HTMLButtonElement) + expect(await screen.findByLabelText('Config content')).toBeInTheDocument() + }) + + it('saves an agent with an entity patch through the managed config endpoint', async () => { + mockGetManagedOpenCodeConfig.mockResolvedValue({ + revision: 'rev-1', + info: { agents: { reviewer: { system: 'Review code', mode: 'subagent' } } }, + }) + + const user = userEvent.setup() + renderWithQuery() + + await screen.findByText('opencode.json') + const agentsButton = screen.getAllByRole('button', { name: /Agents/i }).find(button => button.textContent?.startsWith('Agents')) + expect(agentsButton).toBeDefined() + await user.click(agentsButton!) + await user.click(await screen.findByText('reviewer')) + await user.click(await screen.findByRole('button', { name: 'Submit Agent' })) + + await waitFor(() => expect(mockPatchOpenCodeConfig).toHaveBeenCalledWith({ + patch: { agents: { reviewer: { system: 'Updated', mode: 'subagent' } } }, + expectedRevision: 'rev-1', + })) + }) + + it('deletes the previous agent name in the same patch when renaming', async () => { + mockGetManagedOpenCodeConfig.mockResolvedValue({ + revision: 'rev-1', + info: { agents: { reviewer: { system: 'Review code', mode: 'subagent' } } }, + }) + + const user = userEvent.setup() + renderWithQuery() + + await screen.findByText('opencode.json') + const agentsButton = screen.getAllByRole('button', { name: /Agents/i }).find(button => button.textContent?.startsWith('Agents')) + expect(agentsButton).toBeDefined() + await user.click(agentsButton!) + await user.click(await screen.findByText('reviewer')) + await user.click(await screen.findByRole('button', { name: 'Submit Renamed Agent' })) + + await waitFor(() => expect(mockPatchOpenCodeConfig).toHaveBeenCalledWith({ + patch: { + agents: { + 'renamed-agent': { system: 'Renamed', mode: 'subagent' }, + reviewer: null, + }, + }, + expectedRevision: 'rev-1', + })) + }) + + it('sends null for cleared command fields and a disabled subagent', async () => { + mockGetManagedOpenCodeConfig.mockResolvedValue({ + revision: 'rev-1', + info: { + commands: { + review: { + template: 'Review this code', + description: 'Reviews changes', + agent: 'reviewer', + model: 'openai/gpt-5', + subagent: true, + }, + }, + }, + }) + + const user = userEvent.setup() + renderWithQuery() + + await screen.findByText('opencode.json') + await user.click(screen.getByRole('button', { name: /Commands/i })) + await user.click(await screen.findByText('review')) + + await user.clear(screen.getByLabelText('Description')) + await user.clear(screen.getByLabelText('Agent (optional)')) + await user.clear(screen.getByLabelText('Model (optional)')) + await user.click(screen.getByRole('switch')) + await user.click(screen.getByRole('button', { name: 'Update' })) + + await waitFor(() => expect(mockPatchOpenCodeConfig).toHaveBeenCalledWith({ + patch: { + commands: { + review: { + template: 'Review this code', + description: null, + agent: null, + model: null, + subagent: null, + }, + }, + }, + expectedRevision: 'rev-1', + })) + }) }) diff --git a/frontend/src/components/settings/OpenCodeConfigManager.tsx b/frontend/src/components/settings/OpenCodeConfigManager.tsx index e02d4852..4a455ab8 100644 --- a/frontend/src/components/settings/OpenCodeConfigManager.tsx +++ b/frontend/src/components/settings/OpenCodeConfigManager.tsx @@ -19,41 +19,15 @@ import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' import { useServerHealth } from '@/hooks/useServerHealth' import { useOpenCodeServerActions } from '@/hooks/useOpenCodeServerActions' import { useOpenCodeConfigFile, OPEN_CODE_CONFIG_QUERY_KEY } from '@/hooks/useOpenCodeConfigFile' +import { useOpenCodeManagedConfig } from '@/hooks/useOpenCodeManagedConfig' import { useOpenCodeApplyFeedback } from '@/hooks/useOpenCodeApplyFeedback' import { showToast } from '@/lib/toast' -import { invalidateConfigCaches } from '@/lib/queryInvalidation' +import { invalidateConfigCaches, OPEN_CODE_MANAGED_CONFIG_QUERY_KEY } from '@/lib/queryInvalidation' import { getOpenCodeApiErrorMessage } from '@/lib/opencode-errors' import { mcpServersFromConfig } from '@opencode-manager/shared/opencode' import { FetchError } from '@/api/fetchWrapper' import { getPreferredOpenCodeConfigSource, downloadOpenCodeConfigSource } from '@/api/types/settings' -import type { OpenCodeConfigFile, OpenCodeConfigSaveResponse, OpenCodeImportStatus } from '@/api/types/settings' - -interface Command { - template: string - description?: string - agent?: string - model?: string - subtask?: boolean - topP?: number -} - -interface Agent { - prompt?: string - description?: string - mode?: 'subagent' | 'primary' | 'all' - temperature?: number - topP?: number - top_p?: number - model?: string - tools?: Record - permission?: { - edit?: 'ask' | 'allow' | 'deny' - bash?: 'ask' | 'allow' | 'deny' | Record - webfetch?: 'ask' | 'allow' | 'deny' - } - disable?: boolean - [key: string]: unknown -} +import type { OpenCodeConfigFile, OpenCodeConfigSaveResponse, OpenCodeImportStatus, OpenCodeAgentPatch, OpenCodeCommandPatch } from '@/api/types/settings' type ConfigSectionKey = 'agentsMd' | 'commands' | 'agents' | 'skills' | 'mcp' | 'models' | 'hostImport' @@ -108,6 +82,10 @@ export function OpenCodeConfigManager() { const hostImportRef = useRef(null) const { data: config, isLoading } = useOpenCodeConfigFile() + const { data: managedConfig, error: managedConfigError } = useOpenCodeManagedConfig() + const managedAgents = managedConfig?.info.agents ?? {} + const managedCommands = managedConfig?.info.commands ?? {} + const isManagedConfigUnavailable = managedConfigError instanceof FetchError && managedConfigError.statusCode === 503 const { data: managedSkills = [] } = useQuery({ queryKey: ['managed-skills'], @@ -184,6 +162,42 @@ export function OpenCodeConfigManager() { }) } + const patchManagedConfig = async (patch: Record) => { + const expectedRevision = queryClient.getQueryData( + OPEN_CODE_CONFIG_QUERY_KEY, + )?.revision + const result = await settingsApi.patchOpenCodeConfig({ patch, expectedRevision }) + queryClient.setQueryData(OPEN_CODE_CONFIG_QUERY_KEY, result) + applyOpenCodeSaveFeedback({ + appliedMessage: 'Configuration updated', + restartRequired: result.restartRequired, + }) + queryClient.invalidateQueries({ queryKey: OPEN_CODE_MANAGED_CONFIG_QUERY_KEY }) + } + + const patchManagedConfigSafely = (patch: Record) => { + void patchManagedConfig(patch).catch((error) => { + showToast.error(getApiErrorMessage(error, 'Failed to update config')) + }) + } + + const saveManagedEntity = ( + key: 'agents' | 'commands', + name: string, + value: OpenCodeAgentPatch | OpenCodeCommandPatch, + previousName?: string, + ) => { + const entries: Record = { [name]: value } + if (previousName && previousName !== name) { + entries[previousName] = null + } + patchManagedConfigSafely({ [key]: entries }) + } + + const deleteManagedEntity = (key: 'agents' | 'commands', name: string) => { + patchManagedConfigSafely({ [key]: { [name]: null } }) + } + const downloadConfig = (config: OpenCodeConfigFile) => { const preferredSource = getPreferredOpenCodeConfigSource(config) if (preferredSource) { @@ -365,7 +379,7 @@ export function OpenCodeConfigManager() {

Commands

- {Object.keys((config.content.command as Record | undefined) ?? {}).length + directoryCommands.length} configured + {Object.keys(managedCommands).length + directoryCommands.length} configured
@@ -374,16 +388,18 @@ export function OpenCodeConfigManager() { id={commandsContentId} className={cn(SECTION_CONTENT_CLASS, expandedSections.commands ? 'block' : 'hidden')} > - | undefined) ?? {}} - directoryCommands={directoryCommands} - onChange={(commands) => { - updateConfigContentSafely({ - ...config.content, - command: commands - }) - }} - /> + {isManagedConfigUnavailable ? ( +

+ OpenCode is not running, so the configured commands cannot be listed. Use Edit to change the config file directly. +

+ ) : ( + saveManagedEntity('commands', name, command, previousName)} + onDelete={(name) => deleteManagedEntity('commands', name)} + /> + )}
@@ -399,7 +415,7 @@ export function OpenCodeConfigManager() {

Agents

- {Object.keys((config.content.agent as Record | undefined) ?? {}).length + directoryAgents.length} configured + {Object.keys(managedAgents).length + directoryAgents.length} configured
@@ -408,16 +424,18 @@ export function OpenCodeConfigManager() { id={agentsContentId} className={cn(SECTION_CONTENT_CLASS, expandedSections.agents ? 'block' : 'hidden')} > - | undefined) ?? {}} - directoryAgents={directoryAgents} - onChange={(agents) => { - updateConfigContentSafely({ - ...config.content, - agent: agents - }) - }} - /> + {isManagedConfigUnavailable ? ( +

+ OpenCode is not running, so the configured agents cannot be listed. Use Edit to change the config file directly. +

+ ) : ( + saveManagedEntity('agents', name, agent, previousName)} + onDelete={(name) => deleteManagedEntity('agents', name)} + /> + )} diff --git a/frontend/src/hooks/useOpenCodeManagedConfig.ts b/frontend/src/hooks/useOpenCodeManagedConfig.ts new file mode 100644 index 00000000..a127ad6c --- /dev/null +++ b/frontend/src/hooks/useOpenCodeManagedConfig.ts @@ -0,0 +1,11 @@ +import { useQuery } from '@tanstack/react-query' +import { settingsApi } from '@/api/settings' +import { OPEN_CODE_MANAGED_CONFIG_QUERY_KEY } from '@/lib/queryInvalidation' +import type { ManagedOpenCodeConfig } from '@/api/types/settings' + +export function useOpenCodeManagedConfig() { + return useQuery({ + queryKey: OPEN_CODE_MANAGED_CONFIG_QUERY_KEY, + queryFn: () => settingsApi.getManagedOpenCodeConfig(), + }) +} diff --git a/frontend/src/lib/queryInvalidation.ts b/frontend/src/lib/queryInvalidation.ts index dbdc5146..ec5b99fa 100644 --- a/frontend/src/lib/queryInvalidation.ts +++ b/frontend/src/lib/queryInvalidation.ts @@ -3,6 +3,8 @@ import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas' import { serverScopedKey } from '@/lib/serverScope' import type { GitStatusResponse } from '@/types/git' +export const OPEN_CODE_MANAGED_CONFIG_QUERY_KEY = ['opencode-config', 'managed'] as const + export function sessionTranscriptQueryKey(sessionID: string | null | undefined) { return ['opencode', 'transcript', sessionID] } @@ -78,6 +80,7 @@ export function invalidateConfigCaches( queryClient.invalidateQueries({ queryKey: ['opencode', 'commands'] }) if (!options.skipOpenCodeConfig) { queryClient.invalidateQueries({ queryKey: ['opencode-config'] }) + queryClient.invalidateQueries({ queryKey: OPEN_CODE_MANAGED_CONFIG_QUERY_KEY }) } queryClient.invalidateQueries({ queryKey: ['health'] }) queryClient.invalidateQueries({ queryKey: ['mcp-status'] })