mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
section 9: Phase 9: Settings agents and commands read managed v2 config
This commit is contained in:
1 parent
6578e11eeb
commit
81725fb345
13 files changed
+534
-373
No files matched your search
@@ -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<ManagedOpenCodeConfig> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-config/managed`)
|
||||
},
|
||||
|
||||
patchOpenCodeConfig: async (
|
||||
request: UpdateOpenCodeConfigPatchRequest
|
||||
): Promise<OpenCodeConfigSaveResponse> => {
|
||||
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,
|
||||
|
||||
@@ -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<string, unknown>
|
||||
source?: OpenCodeConfigSourceName
|
||||
expectedRevision?: string
|
||||
}
|
||||
@@ -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(
|
||||
<AgentDialog
|
||||
open
|
||||
onOpenChange={vi.fn()}
|
||||
onSubmit={onSubmit}
|
||||
editingAgent={{
|
||||
name: 'reviewer',
|
||||
agent: { system: 'Review code', description: 'Reviews changes', model: 'openai/gpt-4o' },
|
||||
}}
|
||||
/>,
|
||||
)
|
||||
|
||||
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(
|
||||
<AgentDialog
|
||||
open
|
||||
onOpenChange={vi.fn()}
|
||||
onSubmit={onSubmit}
|
||||
editingAgent={{
|
||||
name: 'reviewer',
|
||||
agent: {
|
||||
system: 'Review code',
|
||||
description: 'Reviews changes',
|
||||
mode: 'subagent',
|
||||
hidden: true,
|
||||
color: '#fff',
|
||||
steps: 7,
|
||||
request: {
|
||||
headers: { 'x-test': '1' },
|
||||
body: { temperature: 0.2, top_p: 0.5, reasoning_effort: 'high' },
|
||||
},
|
||||
permissions: [
|
||||
{ action: 'shell', resource: '*', effect: 'deny' },
|
||||
{ action: 'edit', resource: 'src/**', effect: 'ask' },
|
||||
{ action: 'webfetch', resource: '*', effect: 'allow' },
|
||||
],
|
||||
},
|
||||
}}
|
||||
/>,
|
||||
)
|
||||
|
||||
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)
|
||||
})
|
||||
})
|
||||
@@ -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<typeof agentFormSchema>
|
||||
|
||||
interface Agent<TModel = string> {
|
||||
prompt?: string
|
||||
description?: string
|
||||
mode?: 'subagent' | 'primary' | 'all'
|
||||
temperature?: number
|
||||
topP?: number
|
||||
top_p?: number
|
||||
model?: TModel
|
||||
tools?: Record<string, boolean>
|
||||
permission?: {
|
||||
edit?: 'ask' | 'allow' | 'deny'
|
||||
bash?: 'ask' | 'allow' | 'deny' | Record<string, 'ask' | 'allow' | 'deny'>
|
||||
webfetch?: 'ask' | 'allow' | 'deny'
|
||||
}
|
||||
disable?: boolean
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
type StoredAgent = Agent<string | { providerID: string; model: string; variant?: string }>
|
||||
|
||||
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<AgentFormValues>({
|
||||
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
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="text-sm font-medium">Tools Configuration</div>
|
||||
<div className="grid grid-cols-2 gap-2 text-sm">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="write"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex flex-row items-center space-x-2 space-y-0">
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormLabel className="font-normal">Write</FormLabel>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="edit"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex flex-row items-center space-x-2 space-y-0">
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormLabel className="font-normal">Edit</FormLabel>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="bash"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex flex-row items-center space-x-2 space-y-0">
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormLabel className="font-normal">Bash</FormLabel>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="webfetch"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex flex-row items-center space-x-2 space-y-0">
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormLabel className="font-normal">Web Fetch</FormLabel>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="text-sm font-medium">Permissions</div>
|
||||
<div className="grid grid-cols-3 gap-2 text-sm">
|
||||
@@ -384,10 +311,10 @@ export function AgentDialog({ open, onOpenChange, onSubmit, editingAgent }: Agen
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="bashPermission"
|
||||
name="shellPermission"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel className="text-xs">Bash</FormLabel>
|
||||
<FormLabel className="text-xs">Shell</FormLabel>
|
||||
<Select onValueChange={field.onChange} defaultValue={field.value}>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
|
||||
@@ -24,7 +24,7 @@ const mockAgents = {
|
||||
'helper': {
|
||||
description: 'General helper agent',
|
||||
mode: 'primary' as const,
|
||||
disable: true,
|
||||
disabled: true,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -34,28 +34,26 @@ describe('AgentsEditor', () => {
|
||||
})
|
||||
|
||||
it('renders empty state when no agents configured', () => {
|
||||
const onChange = vi.fn()
|
||||
render(<AgentsEditor agents={{}} onChange={onChange} />, { wrapper: createWrapper() })
|
||||
render(<AgentsEditor agents={{}} onSave={vi.fn()} onDelete={vi.fn()} />, { wrapper: createWrapper() })
|
||||
|
||||
expect(screen.getByText('No agents configured')).toBeInTheDocument()
|
||||
expect(screen.getByText('Add your first agent to get started.')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders agent names', () => {
|
||||
const onChange = vi.fn()
|
||||
render(<AgentsEditor agents={mockAgents} onChange={onChange} />, { wrapper: createWrapper() })
|
||||
render(<AgentsEditor agents={mockAgents} onSave={vi.fn()} onDelete={vi.fn()} />, { wrapper: createWrapper() })
|
||||
|
||||
expect(screen.getByText('code-reviewer')).toBeInTheDocument()
|
||||
expect(screen.getByText('helper')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders uploaded directory agent files', () => {
|
||||
const onChange = vi.fn()
|
||||
render(
|
||||
<AgentsEditor
|
||||
agents={{}}
|
||||
directoryAgents={[{ kind: 'agents', name: 'planner', relativePath: 'team/planner.md' }]}
|
||||
onChange={onChange}
|
||||
onSave={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
/>,
|
||||
{ wrapper: createWrapper() },
|
||||
)
|
||||
@@ -68,8 +66,7 @@ describe('AgentsEditor', () => {
|
||||
|
||||
it('opens AgentDialog when clicking Edit on a row', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onChange = vi.fn()
|
||||
render(<AgentsEditor agents={mockAgents} onChange={onChange} />, { wrapper: createWrapper() })
|
||||
render(<AgentsEditor agents={mockAgents} onSave={vi.fn()} onDelete={vi.fn()} />, { wrapper: createWrapper() })
|
||||
|
||||
const editButtons = screen.getAllByText('Edit')
|
||||
await user.click(editButtons[0])
|
||||
@@ -80,8 +77,7 @@ describe('AgentsEditor', () => {
|
||||
|
||||
it('opens AgentDialog when clicking row body', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onChange = vi.fn()
|
||||
render(<AgentsEditor agents={mockAgents} onChange={onChange} />, { wrapper: createWrapper() })
|
||||
render(<AgentsEditor agents={mockAgents} onSave={vi.fn()} onDelete={vi.fn()} />, { wrapper: createWrapper() })
|
||||
|
||||
await user.click(screen.getByText('code-reviewer'))
|
||||
|
||||
@@ -90,8 +86,7 @@ describe('AgentsEditor', () => {
|
||||
|
||||
it('opens AgentDialog and displays Create Agent text when clicking Add Agent button', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onChange = vi.fn()
|
||||
render(<AgentsEditor agents={{}} onChange={onChange} />, { wrapper: createWrapper() })
|
||||
render(<AgentsEditor agents={{}} onSave={vi.fn()} onDelete={vi.fn()} />, { wrapper: createWrapper() })
|
||||
|
||||
await user.click(screen.getByText('Add Agent'))
|
||||
|
||||
@@ -99,21 +94,20 @@ describe('AgentsEditor', () => {
|
||||
expect(screen.getByText('Create Agent')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('calls onChange with agent removed when Delete is clicked from overflow menu', async () => {
|
||||
it('calls onDelete with the agent name when Delete is clicked from overflow menu', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onChange = vi.fn()
|
||||
render(<AgentsEditor agents={mockAgents} onChange={onChange} />, { wrapper: createWrapper() })
|
||||
const onDelete = vi.fn()
|
||||
render(<AgentsEditor agents={mockAgents} onSave={vi.fn()} onDelete={onDelete} />, { wrapper: createWrapper() })
|
||||
|
||||
await user.click(screen.getByLabelText('Actions for code-reviewer'))
|
||||
await user.click(screen.getByText('Delete'))
|
||||
|
||||
expect(onChange).toHaveBeenCalledTimes(1)
|
||||
expect(onChange).toHaveBeenCalledWith({ helper: mockAgents.helper })
|
||||
expect(onDelete).toHaveBeenCalledTimes(1)
|
||||
expect(onDelete).toHaveBeenCalledWith('code-reviewer')
|
||||
})
|
||||
|
||||
it('renders mode and disabled badges for agents', () => {
|
||||
const onChange = vi.fn()
|
||||
render(<AgentsEditor agents={mockAgents} onChange={onChange} />, { wrapper: createWrapper() })
|
||||
render(<AgentsEditor agents={mockAgents} onSave={vi.fn()} onDelete={vi.fn()} />, { wrapper: createWrapper() })
|
||||
|
||||
expect(screen.getByText('subagent')).toBeInTheDocument()
|
||||
expect(screen.getByText('Disabled')).toBeInTheDocument()
|
||||
|
||||
@@ -1,67 +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 { OpenCodeAgentConfig } from '@opencode-manager/shared/opencode'
|
||||
import type { OpenCodeAgentPatch, OpenCodeDirectoryFileInfo } from '@/api/types/settings'
|
||||
import { AgentDialog } from './AgentDialog'
|
||||
import { UploadFolderButton } from './UploadFolderButton'
|
||||
import { DirectoryFilesList } from './DirectoryFilesList'
|
||||
import type { OpenCodeDirectoryFileInfo } from '@/api/types/settings'
|
||||
|
||||
interface Agent {
|
||||
prompt?: string
|
||||
description?: string
|
||||
mode?: 'subagent' | 'primary' | 'all'
|
||||
temperature?: number
|
||||
topP?: number
|
||||
top_p?: number
|
||||
model?: string
|
||||
tools?: Record<string, boolean>
|
||||
permission?: {
|
||||
edit?: 'ask' | 'allow' | 'deny'
|
||||
bash?: 'ask' | 'allow' | 'deny' | Record<string, 'ask' | 'allow' | 'deny'>
|
||||
webfetch?: 'ask' | 'allow' | 'deny'
|
||||
}
|
||||
disable?: boolean
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
interface AgentsEditorProps {
|
||||
agents: Record<string, Agent>
|
||||
agents: Record<string, OpenCodeAgentConfig>
|
||||
directoryAgents?: OpenCodeDirectoryFileInfo[]
|
||||
onChange: (agents: Record<string, Agent>) => void
|
||||
onSave: (name: string, agent: OpenCodeAgentPatch, previousName?: string) => void
|
||||
onDelete: (name: string) => void
|
||||
}
|
||||
|
||||
export function AgentsEditor({ agents, directoryAgents = [], onChange }: AgentsEditorProps) {
|
||||
export function AgentsEditor({ agents, directoryAgents = [], onSave, onDelete }: AgentsEditorProps) {
|
||||
const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false)
|
||||
const [editingAgent, setEditingAgent] = useState<{ name: string; agent: Agent } | null>(null)
|
||||
const [editingAgent, setEditingAgent] = useState<{ name: string; agent: OpenCodeAgentConfig } | null>(null)
|
||||
const hasAgents = Object.keys(agents).length > 0 || directoryAgents.length > 0
|
||||
|
||||
const handleAgentSubmit = (name: string, agent: Agent) => {
|
||||
if (editingAgent) {
|
||||
const updatedAgents = { ...agents }
|
||||
delete updatedAgents[editingAgent.name]
|
||||
updatedAgents[name] = agent
|
||||
onChange(updatedAgents)
|
||||
setEditingAgent(null)
|
||||
} else {
|
||||
const updatedAgents = {
|
||||
...agents,
|
||||
[name]: agent
|
||||
}
|
||||
onChange(updatedAgents)
|
||||
setIsCreateDialogOpen(false)
|
||||
}
|
||||
const handleAgentSubmit = (name: string, agent: OpenCodeAgentPatch) => {
|
||||
onSave(name, agent, editingAgent?.name)
|
||||
setEditingAgent(null)
|
||||
setIsCreateDialogOpen(false)
|
||||
}
|
||||
|
||||
const deleteAgent = (name: string) => {
|
||||
const updatedAgents = { ...agents }
|
||||
delete updatedAgents[name]
|
||||
onChange(updatedAgents)
|
||||
}
|
||||
|
||||
const startEdit = (name: string, agent: Agent) => {
|
||||
const startEdit = (name: string, agent: OpenCodeAgentConfig) => {
|
||||
setEditingAgent({ name, agent })
|
||||
}
|
||||
|
||||
@@ -98,12 +65,12 @@ export function AgentsEditor({ agents, directoryAgents = [], onChange }: AgentsE
|
||||
badges={
|
||||
<>
|
||||
{agent.mode && <Badge variant="outline" className="shrink-0">{agent.mode}</Badge>}
|
||||
{agent.disable && <Badge variant="secondary" className="shrink-0">Disabled</Badge>}
|
||||
{agent.disabled && <Badge variant="secondary" className="shrink-0">Disabled</Badge>}
|
||||
</>
|
||||
}
|
||||
onClick={() => startEdit(name, agent)}
|
||||
primaryAction={{ label: 'Edit', onClick: () => startEdit(name, agent) }}
|
||||
actions={[{ label: 'Delete', destructive: true, onClick: () => deleteAgent(name) }]}
|
||||
actions={[{ label: 'Delete', destructive: true, onClick: () => onDelete(name) }]}
|
||||
actionsLabel={`Actions for ${name}`}
|
||||
/>
|
||||
))}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { z } from "zod";
|
||||
import { useEffect } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
@@ -21,6 +22,9 @@ import {
|
||||
} from "@/components/ui/form";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { configModelRef, formatOpenCodeModelRef } from "@opencode-manager/shared/opencode";
|
||||
import type { OpenCodeCommandConfig } from "@opencode-manager/shared/opencode";
|
||||
import type { OpenCodeCommandPatch } from "@/api/types/settings";
|
||||
|
||||
const commandFormSchema = z.object({
|
||||
name: z
|
||||
@@ -34,26 +38,16 @@ const commandFormSchema = z.object({
|
||||
description: z.string().optional(),
|
||||
agent: z.string().optional(),
|
||||
model: z.string().optional(),
|
||||
subtask: z.boolean(),
|
||||
topP: z.number().min(0).max(1).optional(),
|
||||
subagent: z.boolean(),
|
||||
});
|
||||
|
||||
type CommandFormValues = z.infer<typeof commandFormSchema>;
|
||||
|
||||
interface Command {
|
||||
template: string;
|
||||
description?: string;
|
||||
agent?: string;
|
||||
model?: string;
|
||||
subtask?: boolean;
|
||||
topP?: number;
|
||||
}
|
||||
|
||||
interface CommandDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onSubmit: (name: string, command: Command) => void;
|
||||
editingCommand?: { name: string; command: Command } | null;
|
||||
onSubmit: (name: string, command: OpenCodeCommandPatch) => void;
|
||||
editingCommand?: { name: string; command: OpenCodeCommandConfig } | null;
|
||||
}
|
||||
|
||||
export function CommandDialog({
|
||||
@@ -62,27 +56,39 @@ export function CommandDialog({
|
||||
onSubmit,
|
||||
editingCommand,
|
||||
}: CommandDialogProps) {
|
||||
const getDefaultValues = (
|
||||
command?: { name: string; command: OpenCodeCommandConfig } | null,
|
||||
): CommandFormValues => {
|
||||
const modelRef = configModelRef(command?.command.model);
|
||||
return {
|
||||
name: command?.name || "",
|
||||
template: command?.command.template || "",
|
||||
description: command?.command.description || "",
|
||||
agent: command?.command.agent || "",
|
||||
model: modelRef ? formatOpenCodeModelRef(modelRef) : "",
|
||||
subagent: command?.command.subagent || false,
|
||||
};
|
||||
};
|
||||
|
||||
const form = useForm<CommandFormValues>({
|
||||
resolver: zodResolver(commandFormSchema),
|
||||
defaultValues: {
|
||||
name: editingCommand?.name || "",
|
||||
template: editingCommand?.command.template || "",
|
||||
description: editingCommand?.command.description || "",
|
||||
agent: editingCommand?.command.agent || "",
|
||||
model: editingCommand?.command.model || "",
|
||||
subtask: editingCommand?.command.subtask || false,
|
||||
topP: editingCommand?.command.topP ?? 1,
|
||||
},
|
||||
defaultValues: getDefaultValues(editingCommand),
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
form.reset(getDefaultValues(editingCommand));
|
||||
}
|
||||
}, [open, editingCommand, form]);
|
||||
|
||||
const handleSubmit = (values: CommandFormValues) => {
|
||||
const command: Command = {
|
||||
const command: OpenCodeCommandPatch = {
|
||||
...editingCommand?.command,
|
||||
template: values.template,
|
||||
description: values.description || undefined,
|
||||
agent: values.agent || undefined,
|
||||
model: values.model || undefined,
|
||||
subtask: values.subtask || undefined,
|
||||
topP: values.topP || undefined,
|
||||
description: values.description || null,
|
||||
agent: values.agent || null,
|
||||
model: values.model?.trim() || null,
|
||||
subagent: values.subagent ? true : null,
|
||||
};
|
||||
|
||||
onSubmit(values.name, command);
|
||||
@@ -171,7 +177,7 @@ export function CommandDialog({
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="flex flex-wrap sm:grid grid-cols-3 gap-4">
|
||||
<div className="flex flex-col gap-4 sm:grid sm:grid-cols-2">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="agent"
|
||||
@@ -185,28 +191,6 @@ export function CommandDialog({
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="topP"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Top P (optional)</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
{...field}
|
||||
type="number"
|
||||
min="0"
|
||||
max="1"
|
||||
step="0.1"
|
||||
onChange={(e) =>
|
||||
field.onChange(parseFloat(e.target.value))
|
||||
}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
@@ -228,13 +212,13 @@ export function CommandDialog({
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="subtask"
|
||||
name="subagent"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
|
||||
<div className="space-y-0.5">
|
||||
<FormLabel className="text-base">Run as subtask</FormLabel>
|
||||
<FormLabel className="text-base">Run as subagent</FormLabel>
|
||||
<FormDescription>
|
||||
Execute this command as a separate subtask
|
||||
Execute this command in a subagent session
|
||||
</FormDescription>
|
||||
</div>
|
||||
<FormControl>
|
||||
@@ -262,4 +246,3 @@ export function CommandDialog({
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -54,16 +54,14 @@ describe('CommandsEditor', () => {
|
||||
})
|
||||
|
||||
it('renders empty state when no commands configured', () => {
|
||||
const onChange = vi.fn()
|
||||
render(<CommandsEditor commands={{}} onChange={onChange} />, { wrapper: createWrapper() })
|
||||
render(<CommandsEditor commands={{}} onSave={vi.fn()} onDelete={vi.fn()} />, { 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(<CommandsEditor commands={mockCommands} onChange={onChange} />, { wrapper: createWrapper() })
|
||||
render(<CommandsEditor commands={mockCommands} onSave={vi.fn()} onDelete={vi.fn()} />, { 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(
|
||||
<CommandsEditor
|
||||
commands={{}}
|
||||
directoryCommands={[{ kind: 'commands', name: 'deploy', relativePath: 'project/deploy.md' }]}
|
||||
onChange={onChange}
|
||||
onSave={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
/>,
|
||||
{ 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(<CommandsEditor commands={mockCommands} onChange={onChange} />, { wrapper: createWrapper() })
|
||||
render(<CommandsEditor commands={mockCommands} onSave={vi.fn()} onDelete={vi.fn()} />, { 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(<CommandsEditor commands={mockCommands} onChange={onChange} />, { wrapper: createWrapper() })
|
||||
render(<CommandsEditor commands={mockCommands} onSave={vi.fn()} onDelete={vi.fn()} />, { 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(<CommandsEditor commands={{}} onChange={onChange} />, { wrapper: createWrapper() })
|
||||
render(<CommandsEditor commands={{}} onSave={vi.fn()} onDelete={vi.fn()} />, { 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(<CommandsEditor commands={mockCommands} onChange={onChange} />, { wrapper: createWrapper() })
|
||||
const onDelete = vi.fn()
|
||||
render(<CommandsEditor commands={mockCommands} onSave={vi.fn()} onDelete={onDelete} />, { 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(<CommandsEditor commands={mockCommands} onChange={onChange} />, { wrapper: createWrapper() })
|
||||
render(<CommandsEditor commands={mockCommands} onSave={vi.fn()} onDelete={vi.fn()} />, { 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(<CommandsEditor commands={{}} onChange={onChange} />, { wrapper: createWrapper() })
|
||||
const { container } = render(<CommandsEditor commands={{}} onSave={vi.fn()} onDelete={vi.fn()} />, { 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(<CommandsEditor commands={{}} onChange={onChange} />, { wrapper: createWrapper() })
|
||||
const { container } = render(<CommandsEditor commands={{}} onSave={vi.fn()} onDelete={vi.fn()} />, { wrapper: createWrapper() })
|
||||
const input = container.querySelector('input[type="file"]') as HTMLInputElement
|
||||
|
||||
fireEvent.change(input, { target: { files: [systemFile] } })
|
||||
|
||||
@@ -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<string, Command>
|
||||
commands: Record<string, OpenCodeCommandConfig>
|
||||
directoryCommands?: OpenCodeDirectoryFileInfo[]
|
||||
onChange: (commands: Record<string, Command>) => 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}`}
|
||||
/>
|
||||
))}
|
||||
|
||||
@@ -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<string, unknown>) => void
|
||||
editingAgent?: { name: string } | null
|
||||
}) => open ? (
|
||||
<div>
|
||||
<button onClick={() => onSubmit(editingAgent?.name ?? 'new-agent', { system: 'Updated', mode: 'subagent' })}>
|
||||
Submit Agent
|
||||
</button>
|
||||
<button onClick={() => onSubmit('renamed-agent', { system: 'Renamed', mode: 'subagent' })}>
|
||||
Submit Renamed Agent
|
||||
</button>
|
||||
</div>
|
||||
) : 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(<OpenCodeConfigManager />)
|
||||
|
||||
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(<OpenCodeConfigManager />)
|
||||
|
||||
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(<OpenCodeConfigManager />)
|
||||
|
||||
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(<OpenCodeConfigManager />)
|
||||
|
||||
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(<OpenCodeConfigManager />)
|
||||
|
||||
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',
|
||||
}))
|
||||
})
|
||||
})
|
||||
@@ -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<string, boolean>
|
||||
permission?: {
|
||||
edit?: 'ask' | 'allow' | 'deny'
|
||||
bash?: 'ask' | 'allow' | 'deny' | Record<string, 'ask' | 'allow' | 'deny'>
|
||||
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<HTMLButtonElement>(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<string, unknown>) => {
|
||||
const expectedRevision = queryClient.getQueryData<OpenCodeConfigFile>(
|
||||
OPEN_CODE_CONFIG_QUERY_KEY,
|
||||
)?.revision
|
||||
const result = await settingsApi.patchOpenCodeConfig({ patch, expectedRevision })
|
||||
queryClient.setQueryData<OpenCodeConfigFile>(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<string, unknown>) => {
|
||||
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<string, unknown> = { [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() {
|
||||
<div className="flex min-w-0 items-center gap-3">
|
||||
<h4 className={SECTION_TITLE_CLASS}>Commands</h4>
|
||||
<span className={SECTION_META_CLASS}>
|
||||
{Object.keys((config.content.command as Record<string, Command> | undefined) ?? {}).length + directoryCommands.length} configured
|
||||
{Object.keys(managedCommands).length + directoryCommands.length} configured
|
||||
</span>
|
||||
</div>
|
||||
<ChevronDown className={cn(SECTION_CHEVRON_CLASS, expandedSections.commands && 'rotate-180')} />
|
||||
@@ -374,16 +388,18 @@ export function OpenCodeConfigManager() {
|
||||
id={commandsContentId}
|
||||
className={cn(SECTION_CONTENT_CLASS, expandedSections.commands ? 'block' : 'hidden')}
|
||||
>
|
||||
<CommandsEditor
|
||||
commands={(config.content.command as Record<string, Command> | undefined) ?? {}}
|
||||
directoryCommands={directoryCommands}
|
||||
onChange={(commands) => {
|
||||
updateConfigContentSafely({
|
||||
...config.content,
|
||||
command: commands
|
||||
})
|
||||
}}
|
||||
/>
|
||||
{isManagedConfigUnavailable ? (
|
||||
<p className="py-4 text-sm text-muted-foreground">
|
||||
OpenCode is not running, so the configured commands cannot be listed. Use Edit to change the config file directly.
|
||||
</p>
|
||||
) : (
|
||||
<CommandsEditor
|
||||
commands={managedCommands}
|
||||
directoryCommands={directoryCommands}
|
||||
onSave={(name, command, previousName) => saveManagedEntity('commands', name, command, previousName)}
|
||||
onDelete={(name) => deleteManagedEntity('commands', name)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -399,7 +415,7 @@ export function OpenCodeConfigManager() {
|
||||
<div className="flex min-w-0 items-center gap-3">
|
||||
<h4 className={SECTION_TITLE_CLASS}>Agents</h4>
|
||||
<span className={SECTION_META_CLASS}>
|
||||
{Object.keys((config.content.agent as Record<string, Agent> | undefined) ?? {}).length + directoryAgents.length} configured
|
||||
{Object.keys(managedAgents).length + directoryAgents.length} configured
|
||||
</span>
|
||||
</div>
|
||||
<ChevronDown className={cn(SECTION_CHEVRON_CLASS, expandedSections.agents && 'rotate-180')} />
|
||||
@@ -408,16 +424,18 @@ export function OpenCodeConfigManager() {
|
||||
id={agentsContentId}
|
||||
className={cn(SECTION_CONTENT_CLASS, expandedSections.agents ? 'block' : 'hidden')}
|
||||
>
|
||||
<AgentsEditor
|
||||
agents={(config.content.agent as Record<string, Agent> | undefined) ?? {}}
|
||||
directoryAgents={directoryAgents}
|
||||
onChange={(agents) => {
|
||||
updateConfigContentSafely({
|
||||
...config.content,
|
||||
agent: agents
|
||||
})
|
||||
}}
|
||||
/>
|
||||
{isManagedConfigUnavailable ? (
|
||||
<p className="py-4 text-sm text-muted-foreground">
|
||||
OpenCode is not running, so the configured agents cannot be listed. Use Edit to change the config file directly.
|
||||
</p>
|
||||
) : (
|
||||
<AgentsEditor
|
||||
agents={managedAgents}
|
||||
directoryAgents={directoryAgents}
|
||||
onSave={(name, agent, previousName) => saveManagedEntity('agents', name, agent, previousName)}
|
||||
onDelete={(name) => deleteManagedEntity('agents', name)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -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<ManagedOpenCodeConfig>({
|
||||
queryKey: OPEN_CODE_MANAGED_CONFIG_QUERY_KEY,
|
||||
queryFn: () => settingsApi.getManagedOpenCodeConfig(),
|
||||
})
|
||||
}
|
||||
@@ -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'] })
|
||||
|
||||
Reference in new issue
Block a user