mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
refactor(config): make on-disk opencode.json the single source of truth (#354)
* refactor(config): make on-disk opencode.json the single source of truth Make <workspace>/.config/opencode/opencode.json the only store for the active OpenCode configuration. One owner (opencode-config-file.ts) reads, validates, writes, archives, and seeds the file; one owner (opencode-config-apply.ts) decides how an edit is applied: restart pending, or a live patch with recovery. Settings routes, the internal assistant API, the health-watch supervisor, boot, and host import all go through them, so an edit that lands on the file without going through the database is visible immediately instead of at the next Manager boot. Remove the named-config profiles. Migration 019 archives every opencode_configs row to .config/opencode-configs-archive/<name>.json, restores the default row to opencode.json when no file exists, then drops the table, its indexes, and repos.opencode_config_name. The /opencode-configs* and config/switch routes and the CreateConfigDialog/SwitchConfigDialog dialogs are gone, and the ocm tool gains GET/PUT /opencode-config backed by the same apply owner. Harden the write path: serialize and atomically write config updates while preserving the file mode, keep withFileLock usable after a rejection, route reloadConfig's cleaned-config write through the file owner, stop boot from rewriting an existing valid config when importing state, prune the health-watch directory to its newest 20 entries, resolve archive paths with realpath, and share one frontend config query across dialogs. * fix(mirror): canonicalize worktree paths before branch ownership check * refactor(config): unify opencode config apply and rollback paths - share one config route factory between public and internal mounts - capture last-known-good before every config write and restore via one helper - stop auto-restarting on save; flag restart-required fields and live-patch the rest - add CONFIG_PATCH_TIMEOUT_MS for config patch requests - extract canonicalPath helpers, health-watch artifact writer, and useProvidersWithModels hook * refactor(model-state): use OpenCode state file as model state source of truth
This commit is contained in:
1 parent
7a3c5229df
commit
295d24ced7
116 files changed
+10291
-4208
No files matched your search
@@ -0,0 +1,74 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { AddMcpServerDialog } from './AddMcpServerDialog'
|
||||
import { makeOpenCodeConfigFile } from '@/test/fixtures/opencode-config'
|
||||
|
||||
const {
|
||||
mockGetOpenCodeConfig,
|
||||
mockUpdateOpenCodeConfig,
|
||||
mockAddServerAsync,
|
||||
} = vi.hoisted(() => ({
|
||||
mockGetOpenCodeConfig: vi.fn(),
|
||||
mockUpdateOpenCodeConfig: vi.fn(),
|
||||
mockAddServerAsync: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/settings', () => ({
|
||||
settingsApi: {
|
||||
getOpenCodeConfig: mockGetOpenCodeConfig,
|
||||
updateOpenCodeConfig: mockUpdateOpenCodeConfig,
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useMcpServers', () => ({
|
||||
useMcpServers: () => ({ addServerAsync: mockAddServerAsync, isAddingServer: false }),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/toast', () => ({
|
||||
showToast: { success: vi.fn(), error: vi.fn(), info: vi.fn(), loading: vi.fn(), warning: vi.fn(), dismiss: vi.fn() },
|
||||
}))
|
||||
|
||||
const config = makeOpenCodeConfigFile()
|
||||
|
||||
function renderDialog(onUpdate: (content: Record<string, unknown>) => Promise<void>) {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
return render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<AddMcpServerDialog open onOpenChange={vi.fn()} onUpdate={onUpdate} />
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
}
|
||||
|
||||
describe('AddMcpServerDialog', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockGetOpenCodeConfig.mockResolvedValue(config)
|
||||
mockUpdateOpenCodeConfig.mockResolvedValue(config)
|
||||
mockAddServerAsync.mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('issues exactly one config update through the owner callback and never writes directly', async () => {
|
||||
const onUpdate = vi.fn<(content: Record<string, unknown>) => Promise<void>>().mockResolvedValue(undefined)
|
||||
const user = userEvent.setup()
|
||||
renderDialog(onUpdate)
|
||||
|
||||
await user.type(screen.getByLabelText('Server ID'), 'filesystem')
|
||||
await user.type(screen.getByLabelText('Command'), 'npx server-filesystem /tmp')
|
||||
await user.click(screen.getByRole('button', { name: 'Add MCP Server' }))
|
||||
|
||||
await waitFor(() => expect(onUpdate).toHaveBeenCalledTimes(1))
|
||||
expect(mockUpdateOpenCodeConfig).not.toHaveBeenCalled()
|
||||
expect(onUpdate).toHaveBeenCalledWith({
|
||||
mcp: {
|
||||
filesystem: {
|
||||
type: 'local',
|
||||
enabled: true,
|
||||
command: ['npx', 'server-filesystem', '/tmp'],
|
||||
},
|
||||
},
|
||||
})
|
||||
expect(mockAddServerAsync).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -13,8 +13,7 @@ import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
interface AddMcpServerDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
configName?: string
|
||||
onUpdate?: (configName: string, content: Record<string, unknown>) => Promise<void>
|
||||
onUpdate: (content: Record<string, unknown>) => Promise<void>
|
||||
}
|
||||
|
||||
interface EnvironmentVariable {
|
||||
@@ -40,10 +39,8 @@ export function AddMcpServerDialog({ open, onOpenChange, onUpdate }: AddMcpServe
|
||||
|
||||
const addMcpServerMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
const config = await settingsApi.getDefaultOpenCodeConfig()
|
||||
if (!config) throw new Error('No default config found')
|
||||
|
||||
const currentMcp = (config.content?.mcp as Record<string, unknown>) || {}
|
||||
const config = await settingsApi.getOpenCodeConfig()
|
||||
const currentMcp = (config.content.mcp as Record<string, unknown>) || {}
|
||||
|
||||
const mcpConfig: Record<string, unknown> = {
|
||||
type: serverType,
|
||||
@@ -93,7 +90,7 @@ export function AddMcpServerDialog({ open, onOpenChange, onUpdate }: AddMcpServe
|
||||
},
|
||||
}
|
||||
|
||||
await settingsApi.updateOpenCodeConfig(config.name, { content: updatedConfig })
|
||||
await onUpdate(updatedConfig)
|
||||
|
||||
if (enabled) {
|
||||
const buildOauthField = () => {
|
||||
@@ -126,15 +123,7 @@ export function AddMcpServerDialog({ open, onOpenChange, onUpdate }: AddMcpServe
|
||||
})
|
||||
}
|
||||
},
|
||||
onSuccess: async () => {
|
||||
if (onUpdate) {
|
||||
const config = await settingsApi.getDefaultOpenCodeConfig()
|
||||
if (config) {
|
||||
await onUpdate(config.name, config.content)
|
||||
}
|
||||
} else {
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode-config'] })
|
||||
}
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['mcp-status'] })
|
||||
handleClose()
|
||||
},
|
||||
|
||||
@@ -2,7 +2,6 @@ import { useForm } from 'react-hook-form'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { z } from 'zod'
|
||||
import { useMemo, useEffect } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
|
||||
import { Input } from '@/components/ui/input'
|
||||
@@ -11,7 +10,7 @@ import { Textarea } from '@/components/ui/textarea'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { Combobox, type ComboboxOption } from '@/components/ui/combobox'
|
||||
import { getProvidersWithModels } from '@/api/providers'
|
||||
import { useProvidersWithModels } from '@/hooks/useProvidersWithModels'
|
||||
|
||||
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'),
|
||||
@@ -66,12 +65,7 @@ interface AgentDialogProps {
|
||||
}
|
||||
|
||||
export function AgentDialog({ open, onOpenChange, onSubmit, editingAgent }: AgentDialogProps) {
|
||||
const { data: providers = [] } = useQuery({
|
||||
queryKey: ['providers-with-models'],
|
||||
queryFn: () => getProvidersWithModels(),
|
||||
enabled: open,
|
||||
staleTime: 5 * 60 * 1000,
|
||||
})
|
||||
const { data: providers } = useProvidersWithModels({ enabled: open })
|
||||
|
||||
const providerOptions: ComboboxOption[] = useMemo(() => {
|
||||
const sourceLabels: Record<string, string> = {
|
||||
|
||||
@@ -1,180 +0,0 @@
|
||||
import { useState, useRef } from 'react'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { parseJsonc } from '@/lib/jsonc'
|
||||
|
||||
interface CreateConfigDialogProps {
|
||||
isOpen: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
onCreate: (name: string, content: string, isDefault: boolean) => Promise<void>
|
||||
isUpdating: boolean
|
||||
}
|
||||
|
||||
export function CreateConfigDialog({ isOpen, onOpenChange, onCreate, isUpdating }: CreateConfigDialogProps) {
|
||||
const [name, setName] = useState('')
|
||||
const [content, setContent] = useState('')
|
||||
const [isDefault, setIsDefault] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const [errorLine, setErrorLine] = useState<number | null>(null)
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null)
|
||||
|
||||
const handleSubmit = async (event?: React.MouseEvent) => {
|
||||
event?.preventDefault()
|
||||
event?.stopPropagation()
|
||||
|
||||
if (!name.trim() || !content.trim()) return
|
||||
|
||||
try {
|
||||
await onCreate(name.trim(), content.trim(), isDefault)
|
||||
setName('')
|
||||
setContent('')
|
||||
setIsDefault(false)
|
||||
setError('')
|
||||
setErrorLine(null)
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof SyntaxError) {
|
||||
const match = error.message.match(/line (\d+)/i)
|
||||
const line = match ? parseInt(match[1]) : null
|
||||
setErrorLine(line)
|
||||
setError(`JSON Error: ${error.message}`)
|
||||
if (line && textareaRef.current) {
|
||||
highlightErrorLine(textareaRef.current, line)
|
||||
}
|
||||
} else if (error instanceof Error) {
|
||||
setError(error.message)
|
||||
setErrorLine(null)
|
||||
} else {
|
||||
setError('Failed to create configuration')
|
||||
setErrorLine(null)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const handleFileUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = event.target.files?.[0]
|
||||
if (!file) return
|
||||
|
||||
const reader = new FileReader()
|
||||
reader.onload = (e) => {
|
||||
const fileContent = e.target?.result as string
|
||||
try {
|
||||
parseJsonc(fileContent)
|
||||
setContent(fileContent)
|
||||
setName(file.name.replace('.json', '').replace('.jsonc', ''))
|
||||
setError('')
|
||||
setErrorLine(null)
|
||||
} catch (err) {
|
||||
if (err instanceof SyntaxError) {
|
||||
const match = err.message.match(/line (\d+)/i)
|
||||
const line = match ? parseInt(match[1]) : null
|
||||
setErrorLine(line)
|
||||
setError(`Invalid JSON/JSONC file: ${err.message}`)
|
||||
} else {
|
||||
setError('Invalid JSON/JSONC file')
|
||||
setErrorLine(null)
|
||||
}
|
||||
}
|
||||
}
|
||||
reader.readAsText(file)
|
||||
}
|
||||
|
||||
const highlightErrorLine = (textarea: HTMLTextAreaElement, line: number) => {
|
||||
const lines = textarea.value.split('\n')
|
||||
if (line > lines.length) return
|
||||
|
||||
let charIndex = 0
|
||||
for (let i = 0; i < line - 1; i++) {
|
||||
charIndex += lines[i].length + 1
|
||||
}
|
||||
|
||||
textarea.focus()
|
||||
textarea.setSelectionRange(charIndex, charIndex + lines[line - 1].length)
|
||||
}
|
||||
|
||||
const handleContentChange = (value: string) => {
|
||||
setContent(value)
|
||||
setError('')
|
||||
setErrorLine(null)
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={onOpenChange}>
|
||||
<DialogContent mobileFullscreen className="sm:max-w-2xl sm:max-h-[85vh] flex flex-col">
|
||||
<DialogHeader className="flex-shrink-0">
|
||||
<DialogTitle>Create OpenCode Config</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4 overflow-y-auto flex-1 pr-2">
|
||||
<div>
|
||||
<Label htmlFor="config-name" className="pb-1">Config Name</Label>
|
||||
<Input
|
||||
id="config-name"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="my-config"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="config-upload" className="pb-1">Upload JSON File</Label>
|
||||
<Input
|
||||
id="config-upload"
|
||||
type="file"
|
||||
accept=".json,.jsonc"
|
||||
onChange={handleFileUpload}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="config-content" className="pb-1">Config Content (JSON/JSONC)</Label>
|
||||
<Textarea
|
||||
id="config-content"
|
||||
ref={textareaRef}
|
||||
value={content}
|
||||
onChange={(e) => handleContentChange(e.target.value)}
|
||||
placeholder='{"$schema": "https://opencode.ai/config.json", "theme": "dark"}'
|
||||
rows={12}
|
||||
className="font-mono md:text-sm"
|
||||
/>
|
||||
{error && (
|
||||
<p className="text-sm text-red-500 mt-2">
|
||||
{error}
|
||||
{errorLine && (
|
||||
<span className="ml-2 text-xs">(Line {errorLine})</span>
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center space-x-2">
|
||||
<Switch
|
||||
id="config-default"
|
||||
checked={isDefault}
|
||||
onCheckedChange={setIsDefault}
|
||||
/>
|
||||
<Label htmlFor="config-default">Set as default configuration</Label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-row sm:flex-row justify-end gap-2 flex-shrink-0 pt-4 pb-4 border-t">
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)} className="flex-1 sm:flex-none">
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={(e) => handleSubmit(e)}
|
||||
disabled={isUpdating || !name.trim() || !content.trim()}
|
||||
className="flex-1 sm:flex-none"
|
||||
>
|
||||
{isUpdating && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
|
||||
Create
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -17,16 +17,14 @@ import { showToast } from '@/lib/toast'
|
||||
|
||||
interface McpManagerProps {
|
||||
config: {
|
||||
name: string
|
||||
content: Record<string, unknown>
|
||||
} | null
|
||||
onUpdate: (content: Record<string, unknown>) => Promise<void>
|
||||
onConfigUpdate?: (configName: string, content: Record<string, unknown>) => Promise<void>
|
||||
}
|
||||
|
||||
|
||||
|
||||
export function McpManager({ config, onUpdate, onConfigUpdate }: McpManagerProps) {
|
||||
export function McpManager({ config, onUpdate }: McpManagerProps) {
|
||||
const [isAddDialogOpen, setIsAddDialogOpen] = useState(false)
|
||||
const [deleteConfirmServer, setDeleteConfirmServer] = useState<{ id: string; name: string } | null>(null)
|
||||
const [togglingServerId, setTogglingServerId] = useState<string | null>(null)
|
||||
@@ -179,7 +177,7 @@ export function McpManager({ config, onUpdate, onConfigUpdate }: McpManagerProps
|
||||
if (!config) {
|
||||
return (
|
||||
<div className="text-center py-8">
|
||||
<p className="text-muted-foreground">Select a configuration to manage MCP servers.</p>
|
||||
<p className="text-muted-foreground">No OpenCode configuration file found.</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -219,7 +217,7 @@ export function McpManager({ config, onUpdate, onConfigUpdate }: McpManagerProps
|
||||
<AddMcpServerDialog
|
||||
open={isAddDialogOpen}
|
||||
onOpenChange={setIsAddDialogOpen}
|
||||
onUpdate={onConfigUpdate}
|
||||
onUpdate={onUpdate}
|
||||
/>
|
||||
</Dialog>
|
||||
</div>
|
||||
|
||||
@@ -2,7 +2,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { render, screen, waitFor, fireEvent } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { OpenCodeConfigEditor } from './OpenCodeConfigEditor'
|
||||
import type { OpenCodeConfig } from '@/api/types/settings'
|
||||
import { makeOpenCodeConfigFile } from '@/test/fixtures/opencode-config'
|
||||
|
||||
const RAW = `{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
@@ -10,16 +10,7 @@ const RAW = `{
|
||||
"model": "anthropic/claude-sonnet-4"
|
||||
}`
|
||||
|
||||
const config: OpenCodeConfig = {
|
||||
id: 1,
|
||||
name: 'default',
|
||||
content: {},
|
||||
rawContent: RAW,
|
||||
isValid: true,
|
||||
isDefault: true,
|
||||
createdAt: 0,
|
||||
updatedAt: 0,
|
||||
}
|
||||
const config = makeOpenCodeConfigFile({ rawContent: RAW })
|
||||
|
||||
function setContent(textarea: HTMLTextAreaElement, value: string) {
|
||||
fireEvent.change(textarea, { target: { value } })
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { useState, useEffect, useCallback, useRef } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogFooter, DialogTitle } from '@/components/ui/dialog'
|
||||
@@ -10,7 +10,7 @@ import { useFindInText } from '@/lib/useFindInText'
|
||||
import { parseJsonc, parseJsoncErrorLine, resolveJsoncIssueLine } from '@/lib/jsonc'
|
||||
import { FetchError } from '@/api/fetchWrapper'
|
||||
import { OpenCodeConfigSchema } from '@opencode-manager/shared'
|
||||
import type { OpenCodeConfig } from '@/api/types/settings'
|
||||
import type { OpenCodeConfigFile } from '@/api/types/settings'
|
||||
|
||||
type ValidationIssue = {
|
||||
path: string
|
||||
@@ -19,7 +19,7 @@ type ValidationIssue = {
|
||||
}
|
||||
|
||||
interface OpenCodeConfigEditorProps {
|
||||
config: OpenCodeConfig | null
|
||||
config: OpenCodeConfigFile | null
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
onUpdate: (content: string) => Promise<void>
|
||||
@@ -41,6 +41,7 @@ export function OpenCodeConfigEditor({
|
||||
const [removedFields, setRemovedFields] = useState<string[]>([])
|
||||
const [activeLine, setActiveLine] = useState<number | null>(null)
|
||||
const [revealNonce, setRevealNonce] = useState(0)
|
||||
const hasInitializedSessionRef = useRef(false)
|
||||
const isMobile = useMobile()
|
||||
const isDirty = editConfigContent !== initialContent
|
||||
const { query, setQuery, matches, currentMatchIndex, hasMatches, next, prev } = useFindInText(editConfigContent)
|
||||
@@ -59,14 +60,18 @@ export function OpenCodeConfigEditor({
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (config && isOpen) {
|
||||
const next = config.rawContent || JSON.stringify(config.content, null, 2)
|
||||
setEditConfigContent(next)
|
||||
setInitialContent(next)
|
||||
resetErrors()
|
||||
setIsSaving(false)
|
||||
setIsDiscardPromptOpen(false)
|
||||
if (!isOpen) {
|
||||
hasInitializedSessionRef.current = false
|
||||
return
|
||||
}
|
||||
if (hasInitializedSessionRef.current || !config) return
|
||||
hasInitializedSessionRef.current = true
|
||||
const next = config.rawContent || JSON.stringify(config.content, null, 2)
|
||||
setEditConfigContent(next)
|
||||
setInitialContent(next)
|
||||
resetErrors()
|
||||
setIsSaving(false)
|
||||
setIsDiscardPromptOpen(false)
|
||||
}, [config, isOpen])
|
||||
|
||||
const requestClose = () => {
|
||||
@@ -155,7 +160,7 @@ export function OpenCodeConfigEditor({
|
||||
>
|
||||
<DialogHeader className="flex shrink-0 flex-row items-center justify-between space-y-0 border-b p-4 sm:p-6">
|
||||
<DialogTitle className="text-lg font-semibold sm:text-xl">
|
||||
{`Edit Config: ${config.name}`}
|
||||
Edit opencode.json
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
@@ -257,7 +262,7 @@ export function OpenCodeConfigEditor({
|
||||
onOpenChange={(open) => !open && setIsDiscardPromptOpen(false)}
|
||||
onDiscard={discardAndClose}
|
||||
onKeepEditing={() => setIsDiscardPromptOpen(false)}
|
||||
itemName={config.name}
|
||||
itemName="opencode.json"
|
||||
/>
|
||||
</>
|
||||
)
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import { describe, it, expect, vi, beforeEach, beforeAll } from 'vitest'
|
||||
import { render, screen, waitFor, fireEvent } from '@testing-library/react'
|
||||
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 type { OpenCodeConfig } from '@/api/types/settings'
|
||||
import type { OpenCodeConfigFile } from '@/api/types/settings'
|
||||
import { makeOpenCodeConfigFile } from '@/test/fixtures/opencode-config'
|
||||
|
||||
const {
|
||||
mockGetOpenCodeConfigs,
|
||||
mockGetOpenCodeConfig,
|
||||
mockUpdateOpenCodeConfig,
|
||||
mockRestartOpenCodeServer,
|
||||
mockGetActiveOpenCodeSessions,
|
||||
@@ -15,7 +16,7 @@ const {
|
||||
mockListOpenCodeDirectoryFiles,
|
||||
healthState,
|
||||
} = vi.hoisted(() => ({
|
||||
mockGetOpenCodeConfigs: vi.fn(),
|
||||
mockGetOpenCodeConfig: vi.fn(),
|
||||
mockUpdateOpenCodeConfig: vi.fn(),
|
||||
mockRestartOpenCodeServer: vi.fn(),
|
||||
mockGetActiveOpenCodeSessions: vi.fn(),
|
||||
@@ -35,7 +36,7 @@ vi.mock('@/lib/toast', () => ({
|
||||
|
||||
vi.mock('@/api/settings', () => ({
|
||||
settingsApi: {
|
||||
getOpenCodeConfigs: mockGetOpenCodeConfigs,
|
||||
getOpenCodeConfig: mockGetOpenCodeConfig,
|
||||
updateOpenCodeConfig: mockUpdateOpenCodeConfig,
|
||||
restartOpenCodeServer: mockRestartOpenCodeServer,
|
||||
getActiveOpenCodeSessions: mockGetActiveOpenCodeSessions,
|
||||
@@ -47,28 +48,27 @@ vi.mock('@/api/settings', () => ({
|
||||
},
|
||||
}))
|
||||
|
||||
const defaultConfig: OpenCodeConfig = {
|
||||
id: 1,
|
||||
name: 'default',
|
||||
isDefault: true,
|
||||
isValid: true,
|
||||
createdAt: 1,
|
||||
updatedAt: 1,
|
||||
content: {
|
||||
provider: {
|
||||
openai: {
|
||||
name: 'OpenAI',
|
||||
models: {
|
||||
'gpt-4o': { name: 'GPT-4o' },
|
||||
},
|
||||
const defaultContent = {
|
||||
provider: {
|
||||
openai: {
|
||||
name: 'OpenAI',
|
||||
models: {
|
||||
'gpt-4o': { name: 'GPT-4o' },
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
const defaultConfig = makeOpenCodeConfigFile({
|
||||
path: '/workspace/.opencode/opencode.json',
|
||||
rawContent: JSON.stringify(defaultContent, null, 2),
|
||||
content: defaultContent,
|
||||
})
|
||||
|
||||
function renderWithQuery(ui: React.ReactElement) {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
return render(<QueryClientProvider client={queryClient}>{ui}</QueryClientProvider>)
|
||||
const result = render(<QueryClientProvider client={queryClient}>{ui}</QueryClientProvider>)
|
||||
return { ...result, queryClient }
|
||||
}
|
||||
|
||||
describe('OpenCodeConfigManager', () => {
|
||||
@@ -79,7 +79,7 @@ describe('OpenCodeConfigManager', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
healthState.data = { opencode: 'healthy', opencodeRestartPending: false }
|
||||
mockGetOpenCodeConfigs.mockResolvedValue({ configs: [defaultConfig] })
|
||||
mockGetOpenCodeConfig.mockResolvedValue(defaultConfig)
|
||||
mockGetOpenCodeImportStatus.mockResolvedValue({})
|
||||
mockListManagedSkills.mockResolvedValue([])
|
||||
mockListOpenCodeDirectoryFiles.mockImplementation((kind: 'agents' | 'commands') => {
|
||||
@@ -130,8 +130,7 @@ describe('OpenCodeConfigManager', () => {
|
||||
await user.click(screen.getByText('Delete'))
|
||||
|
||||
expect(mockUpdateOpenCodeConfig).toHaveBeenCalledTimes(1)
|
||||
const [configName, payload] = mockUpdateOpenCodeConfig.mock.calls[0]
|
||||
expect(configName).toBe('default')
|
||||
const [payload] = mockUpdateOpenCodeConfig.mock.calls[0]
|
||||
expect(payload.content.provider.openai.models).not.toHaveProperty('gpt-4o')
|
||||
|
||||
expect(screen.queryByText('Restart OpenCode Server?')).not.toBeInTheDocument()
|
||||
@@ -186,15 +185,15 @@ describe('OpenCodeConfigManager', () => {
|
||||
})
|
||||
|
||||
it('keeps the editor mounted while the post-save config refresh is in flight', async () => {
|
||||
const configWithRaw: OpenCodeConfig = {
|
||||
const configWithRaw: OpenCodeConfigFile = {
|
||||
...defaultConfig,
|
||||
rawContent: '{\n "theme": "system"\n}',
|
||||
}
|
||||
mockGetOpenCodeConfigs.mockResolvedValueOnce({ configs: [configWithRaw] })
|
||||
mockGetOpenCodeConfig.mockResolvedValueOnce(configWithRaw)
|
||||
let resolveRefresh!: () => void
|
||||
mockGetOpenCodeConfigs.mockReturnValueOnce(
|
||||
new Promise<{ configs: OpenCodeConfig[] }>((resolve) => {
|
||||
resolveRefresh = () => resolve({ configs: [configWithRaw] })
|
||||
mockGetOpenCodeConfig.mockReturnValueOnce(
|
||||
new Promise<OpenCodeConfigFile>((resolve) => {
|
||||
resolveRefresh = () => resolve(configWithRaw)
|
||||
}),
|
||||
)
|
||||
mockUpdateOpenCodeConfig.mockResolvedValue(configWithRaw)
|
||||
@@ -208,18 +207,116 @@ describe('OpenCodeConfigManager', () => {
|
||||
await user.click(editButton)
|
||||
|
||||
const textarea = await screen.findByLabelText('Config content') as HTMLTextAreaElement
|
||||
fireEvent.change(textarea, { target: { value: configWithRaw.rawContent! + ' ' } })
|
||||
fireEvent.change(textarea, { target: { value: configWithRaw.rawContent + ' ' } })
|
||||
await user.click(screen.getByRole('button', { name: 'Update' }))
|
||||
|
||||
await waitFor(() => expect(mockUpdateOpenCodeConfig).toHaveBeenCalledTimes(1))
|
||||
expect(screen.getByText('Edit Config: default')).toBeInTheDocument()
|
||||
expect(screen.getByText('Edit opencode.json')).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Update' })).toBeDisabled()
|
||||
|
||||
resolveRefresh()
|
||||
await waitFor(() => expect(screen.queryByText('Edit Config: default')).not.toBeInTheDocument())
|
||||
await waitFor(() => expect(screen.queryByText('Edit opencode.json')).not.toBeInTheDocument())
|
||||
})
|
||||
|
||||
it('renders host import collapsed after configurations until expanded', async () => {
|
||||
it('preserves an open draft when the config query refreshes in the background', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { container, queryClient } = renderWithQuery(<OpenCodeConfigManager />)
|
||||
|
||||
await screen.findByText('GPT-4o')
|
||||
|
||||
const editIcon = container.querySelector('.lucide-square-pen') as SVGElement
|
||||
const editButton = editIcon.closest('button') as HTMLButtonElement
|
||||
await user.click(editButton)
|
||||
|
||||
const textarea = await screen.findByLabelText('Config content') as HTMLTextAreaElement
|
||||
const draft = `${defaultConfig.rawContent}\n// draft\n`
|
||||
fireEvent.change(textarea, { target: { value: draft } })
|
||||
|
||||
const refreshedContent = { theme: 'dark' }
|
||||
const refreshedConfig: OpenCodeConfigFile = {
|
||||
...defaultConfig,
|
||||
content: refreshedContent,
|
||||
rawContent: JSON.stringify(refreshedContent, null, 2),
|
||||
updatedAt: 2,
|
||||
}
|
||||
mockGetOpenCodeConfig.mockResolvedValue(refreshedConfig)
|
||||
|
||||
await act(async () => {
|
||||
await queryClient.invalidateQueries({ queryKey: ['opencode-config', 'file'] })
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(`Updated: ${new Date(2).toLocaleString()}`)).toBeInTheDocument()
|
||||
})
|
||||
expect(mockGetOpenCodeConfig).toHaveBeenCalledTimes(2)
|
||||
expect(textarea).toHaveValue(draft)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Cancel' }))
|
||||
expect(screen.getByText('Unsaved Changes')).toBeInTheDocument()
|
||||
await user.click(screen.getByRole('button', { name: 'Keep Editing' }))
|
||||
expect(textarea).toHaveValue(draft)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Cancel' }))
|
||||
await user.click(screen.getByRole('button', { name: 'Discard' }))
|
||||
await waitFor(() => expect(screen.queryByText('Edit opencode.json')).not.toBeInTheDocument())
|
||||
|
||||
const reopenIcon = container.querySelector('.lucide-square-pen') as SVGElement
|
||||
const reopenButton = reopenIcon.closest('button') as HTMLButtonElement
|
||||
await user.click(reopenButton)
|
||||
|
||||
const reopenedTextarea = await screen.findByLabelText('Config content') as HTMLTextAreaElement
|
||||
expect(reopenedTextarea).toHaveValue(JSON.stringify(refreshedContent, null, 2))
|
||||
})
|
||||
|
||||
it('does not reset an in-flight save when the config query refreshes in the background', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { container, queryClient } = renderWithQuery(<OpenCodeConfigManager />)
|
||||
|
||||
await screen.findByText('GPT-4o')
|
||||
|
||||
const editIcon = container.querySelector('.lucide-square-pen') as SVGElement
|
||||
await user.click(editIcon.closest('button') as HTMLButtonElement)
|
||||
|
||||
const textarea = await screen.findByLabelText('Config content') as HTMLTextAreaElement
|
||||
const draft = `${defaultConfig.rawContent}\n// draft\n`
|
||||
fireEvent.change(textarea, { target: { value: draft } })
|
||||
|
||||
let resolveSave!: (value: OpenCodeConfigFile) => void
|
||||
mockUpdateOpenCodeConfig.mockReturnValueOnce(
|
||||
new Promise<OpenCodeConfigFile>((resolve) => {
|
||||
resolveSave = resolve
|
||||
}),
|
||||
)
|
||||
|
||||
const updateButton = screen.getByRole('button', { name: 'Update' })
|
||||
await user.click(updateButton)
|
||||
await waitFor(() => expect(updateButton).toBeDisabled())
|
||||
|
||||
const refreshedContent = { theme: 'dark' }
|
||||
const refreshedConfig: OpenCodeConfigFile = {
|
||||
...defaultConfig,
|
||||
content: refreshedContent,
|
||||
rawContent: JSON.stringify(refreshedContent, null, 2),
|
||||
updatedAt: 2,
|
||||
}
|
||||
mockGetOpenCodeConfig.mockResolvedValue(refreshedConfig)
|
||||
|
||||
await act(async () => {
|
||||
await queryClient.invalidateQueries({ queryKey: ['opencode-config', 'file'] })
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(`Updated: ${new Date(2).toLocaleString()}`)).toBeInTheDocument()
|
||||
})
|
||||
expect(updateButton).toBeDisabled()
|
||||
expect(textarea).toBeDisabled()
|
||||
expect(textarea).toHaveValue(draft)
|
||||
|
||||
resolveSave(refreshedConfig)
|
||||
await waitFor(() => expect(screen.queryByText('Edit opencode.json')).not.toBeInTheDocument())
|
||||
})
|
||||
|
||||
it('renders host import collapsed after the configuration card until expanded', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderWithQuery(<OpenCodeConfigManager />)
|
||||
|
||||
@@ -228,12 +325,26 @@ describe('OpenCodeConfigManager', () => {
|
||||
const importContent = document.getElementById(importToggle.getAttribute('aria-controls') ?? '')
|
||||
expect(importContent).toHaveClass('hidden')
|
||||
|
||||
const configsTitle = screen.getByText('OpenCode Configurations')
|
||||
expect(configsTitle.compareDocumentPosition(importToggle) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
|
||||
const configTitle = screen.getByText('OpenCode Configuration')
|
||||
expect(configTitle.compareDocumentPosition(importToggle) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
|
||||
|
||||
await user.click(importToggle)
|
||||
expect(importToggle).toHaveAttribute('aria-expanded', 'true')
|
||||
expect(importContent).toHaveClass('block')
|
||||
expect(await screen.findByRole('button', { name: /Import From Host/i })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows the config file path and an invalid badge when the file is invalid', async () => {
|
||||
mockGetOpenCodeConfig.mockResolvedValue({
|
||||
...defaultConfig,
|
||||
isValid: false,
|
||||
validationIssues: [{ path: 'model', message: 'Expected string' }],
|
||||
})
|
||||
|
||||
renderWithQuery(<OpenCodeConfigManager />)
|
||||
|
||||
expect(await screen.findByText('/workspace/.opencode/opencode.json')).toBeInTheDocument()
|
||||
expect(screen.getByText('Invalid Config')).toBeInTheDocument()
|
||||
expect(screen.getByText('model')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -1,15 +1,11 @@
|
||||
import { useState, useEffect, useRef, useId } from 'react'
|
||||
import { useState, useRef, useId } from 'react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { Loader2, Plus, Trash2, Edit, Download, RotateCcw, FileText, ChevronDown, AlertTriangle } from 'lucide-react'
|
||||
import { Loader2, Edit, Download, RotateCcw, FileText, ChevronDown, AlertTriangle } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
|
||||
import { DeleteDialog } from '@/components/ui/delete-dialog'
|
||||
import { RestartServerDialog } from './RestartServerDialog'
|
||||
import { CreateConfigDialog } from './CreateConfigDialog'
|
||||
import { OpenCodeConfigEditor } from './OpenCodeConfigEditor'
|
||||
import { CommandsEditor } from './CommandsEditor'
|
||||
import { AgentsEditor } from './AgentsEditor'
|
||||
@@ -22,13 +18,14 @@ import { settingsApi } from '@/api/settings'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { useServerHealth } from '@/hooks/useServerHealth'
|
||||
import { useOpenCodeServerActions } from '@/hooks/useOpenCodeServerActions'
|
||||
import { parseJsonc, hasJsoncComments } from '@/lib/jsonc'
|
||||
import { useOpenCodeConfigFile, OPEN_CODE_CONFIG_QUERY_KEY } from '@/hooks/useOpenCodeConfigFile'
|
||||
import { hasJsoncComments } from '@/lib/jsonc'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { saveFile } from '@/lib/download'
|
||||
import { invalidateConfigCaches } from '@/lib/queryInvalidation'
|
||||
import { getOpenCodeApiErrorMessage } from '@/lib/opencode-errors'
|
||||
import { FetchError } from '@/api/fetchWrapper'
|
||||
import type { OpenCodeConfig, OpenCodeImportStatus } from '@/api/types/settings'
|
||||
import type { OpenCodeConfigFile, OpenCodeImportStatus } from '@/api/types/settings'
|
||||
|
||||
interface Command {
|
||||
template: string
|
||||
@@ -63,12 +60,6 @@ export function OpenCodeConfigManager() {
|
||||
const hostImportContentId = useId()
|
||||
const queryClient = useQueryClient()
|
||||
const { data: health } = useServerHealth()
|
||||
const [configs, setConfigs] = useState<OpenCodeConfig[]>([])
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [isUpdating, setIsUpdating] = useState(false)
|
||||
const [editingConfig, setEditingConfig] = useState<OpenCodeConfig | null>(null)
|
||||
const [selectedConfig, setSelectedConfig] = useState<OpenCodeConfig | null>(null)
|
||||
const [activeConfigName, setActiveConfigName] = useState<string>('')
|
||||
const [expandedSections, setExpandedSections] = useState<Record<string, boolean>>({
|
||||
agentsMd: false,
|
||||
commands: false,
|
||||
@@ -78,10 +69,8 @@ export function OpenCodeConfigManager() {
|
||||
models: false,
|
||||
hostImport: false,
|
||||
})
|
||||
const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false)
|
||||
const [isEditDialogOpen, setIsEditDialogOpen] = useState(false)
|
||||
const [isVersionDialogOpen, setIsVersionDialogOpen] = useState(false)
|
||||
const [deleteConfirmConfig, setDeleteConfirmConfig] = useState<OpenCodeConfig | null>(null)
|
||||
const {
|
||||
restartServerMutation,
|
||||
confirmOpen: isRestartPromptOpen,
|
||||
@@ -98,6 +87,8 @@ export function OpenCodeConfigManager() {
|
||||
const mcpRef = useRef<HTMLButtonElement>(null)
|
||||
const modelsRef = useRef<HTMLButtonElement>(null)
|
||||
|
||||
const { data: config, isLoading } = useOpenCodeConfigFile()
|
||||
|
||||
const { data: managedSkills = [] } = useQuery({
|
||||
queryKey: ['managed-skills'],
|
||||
queryFn: () => settingsApi.listManagedSkills(),
|
||||
@@ -134,8 +125,7 @@ export function OpenCodeConfigManager() {
|
||||
|
||||
const syncOpenCodeImportMutation = useMutation({
|
||||
mutationFn: async () => settingsApi.syncOpenCodeImport(),
|
||||
onSuccess: async () => {
|
||||
await fetchConfigs()
|
||||
onSuccess: () => {
|
||||
invalidateConfigCaches(queryClient)
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode-import-status'] })
|
||||
},
|
||||
@@ -151,34 +141,16 @@ export function OpenCodeConfigManager() {
|
||||
return getApiErrorMessage(error, 'Failed to import existing OpenCode host data')
|
||||
}
|
||||
|
||||
const fetchConfigs = async (silent = false) => {
|
||||
try {
|
||||
if (!silent) setIsLoading(true)
|
||||
const data = await settingsApi.getOpenCodeConfigs()
|
||||
setConfigs(data.configs)
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch configs:', error)
|
||||
} finally {
|
||||
if (!silent) setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const updateConfigContent = async (configName: string, newContent: Record<string, unknown>) => {
|
||||
const previousConfig = configs.find(c => c.name === configName)
|
||||
const previousContent = previousConfig?.content
|
||||
const previousSelectedConfig = selectedConfig
|
||||
const updateConfigContent = async (newContent: Record<string, unknown>) => {
|
||||
const previousConfig = queryClient.getQueryData<OpenCodeConfigFile>(OPEN_CODE_CONFIG_QUERY_KEY)
|
||||
const now = Date.now()
|
||||
|
||||
setConfigs(prev => prev.map(config =>
|
||||
config.name === configName ? { ...config, content: newContent, updatedAt: now } : config
|
||||
))
|
||||
if (selectedConfig && selectedConfig.name === configName) {
|
||||
setSelectedConfig({ ...selectedConfig, content: newContent, updatedAt: now })
|
||||
}
|
||||
queryClient.setQueryData<OpenCodeConfigFile>(OPEN_CODE_CONFIG_QUERY_KEY, (prev) =>
|
||||
prev ? { ...prev, content: newContent, updatedAt: now } : prev
|
||||
)
|
||||
|
||||
try {
|
||||
setIsUpdating(true)
|
||||
const result = await settingsApi.updateOpenCodeConfig(configName, { content: newContent })
|
||||
const result = await settingsApi.updateOpenCodeConfig({ content: newContent })
|
||||
if (result.removedFields && result.removedFields.length > 0) {
|
||||
showToast.info(`Configuration updated after removing invalid fields: ${result.removedFields.join(', ')}`)
|
||||
} else if (result.restartRequired) {
|
||||
@@ -188,135 +160,18 @@ export function OpenCodeConfigManager() {
|
||||
}
|
||||
invalidateConfigCaches(queryClient)
|
||||
} catch (error) {
|
||||
setConfigs(prev => prev.map(config =>
|
||||
config.name === configName ? { ...config, content: previousContent ?? {}, updatedAt: previousConfig?.updatedAt ?? now } : config
|
||||
))
|
||||
if (previousSelectedConfig && previousSelectedConfig.name === configName) {
|
||||
setSelectedConfig(previousSelectedConfig)
|
||||
if (previousConfig) {
|
||||
queryClient.setQueryData(OPEN_CODE_CONFIG_QUERY_KEY, previousConfig)
|
||||
}
|
||||
console.error('Failed to update config:', error)
|
||||
showToast.error(getApiErrorMessage(error, 'Failed to update config'))
|
||||
} finally {
|
||||
setIsUpdating(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
fetchConfigs()
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (configs.length === 0) {
|
||||
setActiveConfigName('')
|
||||
return
|
||||
}
|
||||
const stillExists = configs.some((c) => c.name === activeConfigName)
|
||||
if (!stillExists) {
|
||||
const fallback = configs.find((c) => c.isDefault) ?? configs[0]
|
||||
setActiveConfigName(fallback.name)
|
||||
}
|
||||
}, [configs, activeConfigName])
|
||||
|
||||
useEffect(() => {
|
||||
if (configs.length > 0 && !selectedConfig) {
|
||||
const defaultConfig = configs.find(config => config.isDefault)
|
||||
setSelectedConfig(defaultConfig || configs[0])
|
||||
}
|
||||
}, [configs, selectedConfig])
|
||||
|
||||
const createConfig = async (name: string, rawContent: string, isDefault: boolean) => {
|
||||
showToast.loading('Creating configuration...', { id: 'create-config' })
|
||||
try {
|
||||
setIsUpdating(true)
|
||||
const parsedContent = parseJsonc<Record<string, unknown>>(rawContent)
|
||||
|
||||
const forbiddenFields = ['id', 'createdAt', 'updatedAt']
|
||||
const foundForbidden = forbiddenFields.filter(field => field in parsedContent)
|
||||
if (foundForbidden.length > 0) {
|
||||
throw new Error(`Invalid fields found: ${foundForbidden.join(', ')}. These fields are managed automatically.`)
|
||||
}
|
||||
|
||||
const result = await settingsApi.createOpenCodeConfig({
|
||||
name: name.trim(),
|
||||
content: rawContent,
|
||||
isDefault,
|
||||
})
|
||||
|
||||
setIsCreateDialogOpen(false)
|
||||
await fetchConfigs()
|
||||
|
||||
if (isDefault) {
|
||||
if (result.removedFields && result.removedFields.length > 0) {
|
||||
showToast.info(`Configuration created after removing invalid fields: ${result.removedFields.join(', ')}`, { id: 'create-config' })
|
||||
} else {
|
||||
showToast.success('Configuration created and applied', { id: 'create-config' })
|
||||
}
|
||||
} else {
|
||||
showToast.success('Configuration created', { id: 'create-config' })
|
||||
}
|
||||
|
||||
invalidateConfigCaches(queryClient)
|
||||
} catch (error) {
|
||||
console.error('Failed to create config:', error)
|
||||
showToast.error(getApiErrorMessage(error, 'Failed to create configuration'), { id: 'create-config' })
|
||||
throw error
|
||||
} finally {
|
||||
setIsUpdating(false)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
const deleteConfig = async (config: OpenCodeConfig) => {
|
||||
try {
|
||||
setIsUpdating(true)
|
||||
await settingsApi.deleteOpenCodeConfig(config.name)
|
||||
setDeleteConfirmConfig(null)
|
||||
if (selectedConfig?.id === config.id) {
|
||||
setSelectedConfig(null)
|
||||
}
|
||||
fetchConfigs()
|
||||
invalidateConfigCaches(queryClient)
|
||||
} catch (error) {
|
||||
console.error('Failed to delete config:', error)
|
||||
} finally {
|
||||
setIsUpdating(false)
|
||||
}
|
||||
}
|
||||
|
||||
const setDefaultConfig = async (config: OpenCodeConfig) => {
|
||||
showToast.loading('Setting default config...', { id: 'set-default' })
|
||||
try {
|
||||
setIsUpdating(true)
|
||||
const result = await settingsApi.setDefaultOpenCodeConfig(config.name)
|
||||
await fetchConfigs()
|
||||
if (result.removedFields && result.removedFields.length > 0) {
|
||||
showToast.info(`Default config updated after removing invalid fields: ${result.removedFields.join(', ')}`, { id: 'set-default' })
|
||||
} else {
|
||||
showToast.success('Default config updated and applied', { id: 'set-default' })
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to set default config:', error)
|
||||
showToast.error(getApiErrorMessage(error, 'Failed to set default config'), { id: 'set-default' })
|
||||
} finally {
|
||||
setIsUpdating(false)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
const downloadConfig = (config: OpenCodeConfig) => {
|
||||
const downloadConfig = (config: OpenCodeConfigFile) => {
|
||||
const content = config.rawContent || JSON.stringify(config.content, null, 2)
|
||||
const extension = config.rawContent && hasJsoncComments(config.rawContent) ? 'jsonc' : 'json'
|
||||
const blob = new Blob([content], { type: 'application/json' })
|
||||
void saveFile(blob, `${config.name}.${extension}`)
|
||||
}
|
||||
|
||||
|
||||
|
||||
const startEdit = (config: OpenCodeConfig) => {
|
||||
setEditingConfig(config)
|
||||
setIsEditDialogOpen(true)
|
||||
void saveFile(blob, `opencode.${extension}`)
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
@@ -328,7 +183,6 @@ export function OpenCodeConfigManager() {
|
||||
}
|
||||
|
||||
const canImportFromHost = Boolean(importStatus?.configSourcePath || importStatus?.stateSourcePath)
|
||||
const activeConfig = configs.find((c) => c.name === activeConfigName) ?? null
|
||||
|
||||
return (
|
||||
<div className="space-y-6 min-w-0">
|
||||
@@ -356,438 +210,315 @@ export function OpenCodeConfigManager() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
<CreateConfigDialog
|
||||
isOpen={isCreateDialogOpen}
|
||||
onOpenChange={setIsCreateDialogOpen}
|
||||
onCreate={createConfig}
|
||||
isUpdating={isUpdating}
|
||||
/>
|
||||
|
||||
<VersionSelectDialog
|
||||
open={isVersionDialogOpen}
|
||||
onOpenChange={setIsVersionDialogOpen}
|
||||
/>
|
||||
|
||||
{configs.length === 0 ? (
|
||||
{!config ? (
|
||||
<Card>
|
||||
<CardContent className="p-8 text-center">
|
||||
<p className="text-muted-foreground">No OpenCode configurations found. Create your first config to get started.</p>
|
||||
<p className="text-muted-foreground">No OpenCode configuration file found. Restart the Manager to seed one.</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-sm sm:text-base">OpenCode Configurations</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<div className="flex flex-col gap-2 sm:flex-row sm:items-center">
|
||||
<Select
|
||||
value={activeConfigName}
|
||||
onValueChange={(value) => {
|
||||
setActiveConfigName(value)
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:max-w-xs">
|
||||
<SelectValue placeholder="Select a configuration...">
|
||||
{activeConfig && (
|
||||
<>
|
||||
{activeConfig.name}
|
||||
{activeConfig.isDefault && (
|
||||
<span className="text-orange-500 dark:text-orange-400"> (Active)</span>
|
||||
)}
|
||||
{!activeConfig.isValid && ' (Invalid)'}
|
||||
</>
|
||||
)}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{configs.map((config) => (
|
||||
<SelectItem key={config.id} value={config.name}>
|
||||
{config.name}
|
||||
{config.isDefault && (
|
||||
<span className="text-orange-500 dark:text-orange-400"> (Active)</span>
|
||||
)}
|
||||
{!config.isValid && ' (Invalid)'}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<>
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-sm sm:text-base">OpenCode Configuration</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<div className="flex flex-col gap-2 sm:flex-row sm:items-center">
|
||||
<div className="min-w-0">
|
||||
<p className="truncate text-sm font-medium">{config.path}</p>
|
||||
<p className="truncate text-sm text-muted-foreground">Updated: {new Date(config.updatedAt).toLocaleString()}</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
{activeConfig && !activeConfig.isValid && (
|
||||
{!config.isValid && (
|
||||
<Badge variant="destructive">Invalid Config</Badge>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<TooltipProvider delayDuration={200}>
|
||||
<div className="flex items-center gap-1 sm:gap-1.5 sm:ml-auto">
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
disabled={!activeConfig}
|
||||
onClick={() => activeConfig && downloadConfig(activeConfig)}
|
||||
>
|
||||
<Download className="h-4 w-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom">Download</TooltipContent>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
disabled={!activeConfig}
|
||||
onClick={() => activeConfig && startEdit(activeConfig)}
|
||||
>
|
||||
<Edit className="h-4 w-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom">Edit</TooltipContent>
|
||||
</Tooltip>
|
||||
{!activeConfig?.isDefault && (
|
||||
<TooltipProvider delayDuration={200}>
|
||||
<div className="flex items-center gap-1 sm:gap-1.5 sm:ml-auto">
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
variant="default"
|
||||
disabled={!activeConfig || isUpdating}
|
||||
onClick={() => activeConfig && setDefaultConfig(activeConfig)}
|
||||
onClick={() => downloadConfig(config)}
|
||||
>
|
||||
Apply
|
||||
<Download className="h-4 w-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom">Apply as default</TooltipContent>
|
||||
<TooltipContent side="bottom">Download</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
disabled={!activeConfig}
|
||||
className="text-red-500 hover:text-red-600"
|
||||
onClick={() => activeConfig && setDeleteConfirmConfig(activeConfig)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom">Delete</TooltipContent>
|
||||
</Tooltip>
|
||||
<Button size="sm" onClick={() => setIsCreateDialogOpen(true)}>
|
||||
<Plus className="h-3 w-3 sm:h-4 sm:w-4 mr-1" />
|
||||
<span className="text-xs sm:text-sm">New Config</span>
|
||||
</Button>
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
</div>
|
||||
|
||||
{activeConfig && (
|
||||
<div className="text-sm text-muted-foreground break-words">
|
||||
<p className="truncate">Updated: {new Date(activeConfig.updatedAt).toLocaleString()}</p>
|
||||
<p className="truncate">Created: {new Date(activeConfig.createdAt).toLocaleString()}</p>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setIsEditDialogOpen(true)}
|
||||
>
|
||||
<Edit className="h-4 w-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom">Edit</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{!config.isValid && config.validationIssues && config.validationIssues.length > 0 && (
|
||||
<div className="rounded-lg border border-destructive/40 bg-destructive/5 p-4">
|
||||
<p className="font-medium text-destructive">This configuration has validation issues</p>
|
||||
<p className="mt-1 text-sm text-destructive/90">
|
||||
OpenCode may fail to start until these fields are corrected. Open the config editor to fix the file directly.
|
||||
</p>
|
||||
<ul className="mt-3 list-disc space-y-1 pl-5 text-sm text-destructive/90">
|
||||
{config.validationIssues.slice(0, 8).map((issue) => (
|
||||
<li key={`${issue.path}-${issue.message}`}>
|
||||
<span className="font-mono text-xs">{issue.path}</span>: {issue.message}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{config.validationIssues.length > 8 && (
|
||||
<p className="mt-2 text-xs text-destructive/80">
|
||||
Showing 8 of {config.validationIssues.length} issues. Open the config editor to review and fix the file.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<OpenCodeConfigEditor
|
||||
config={config}
|
||||
isOpen={isEditDialogOpen}
|
||||
onClose={() => setIsEditDialogOpen(false)}
|
||||
onUpdate={async (rawContent) => {
|
||||
await settingsApi.updateOpenCodeConfig({ content: rawContent })
|
||||
await queryClient.invalidateQueries({ queryKey: OPEN_CODE_CONFIG_QUERY_KEY })
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Edit Dialog */}
|
||||
<OpenCodeConfigEditor
|
||||
config={editingConfig}
|
||||
isOpen={isEditDialogOpen}
|
||||
onClose={() => setIsEditDialogOpen(false)}
|
||||
onUpdate={async (rawContent) => {
|
||||
if (!editingConfig) return
|
||||
showToast.loading('Saving configuration...', { id: 'edit-config' })
|
||||
try {
|
||||
const result = await settingsApi.updateOpenCodeConfig(editingConfig.name, { content: rawContent })
|
||||
await fetchConfigs(true)
|
||||
const successMsg = result.restartRequired
|
||||
? 'Configuration saved. Restart the server to apply changes.'
|
||||
: 'Configuration saved'
|
||||
showToast.success(successMsg, { id: 'edit-config' })
|
||||
invalidateConfigCaches(queryClient)
|
||||
} catch (error) {
|
||||
showToast.error(getApiErrorMessage(error, 'Failed to save configuration'), { id: 'edit-config' })
|
||||
throw error
|
||||
}
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* Global AGENTS.md Section */}
|
||||
<div className="mt-8 space-y-6">
|
||||
<div className="border-t border-border pt-6">
|
||||
<div className="bg-card border border-border rounded-lg overflow-clip min-w-0 mb-6">
|
||||
<button
|
||||
ref={agentsMdRef}
|
||||
className={cn("w-full px-4 py-3 flex items-center justify-between transition-colors min-w-0", expandedSections.agentsMd ? "bg-muted/40 hover:bg-muted/50" : "hover:bg-muted/50")}
|
||||
onClick={() => {
|
||||
const isExpanding = !expandedSections.agentsMd
|
||||
setExpandedSections(prev => ({ ...prev, agentsMd: isExpanding }))
|
||||
if (isExpanding) {
|
||||
setTimeout(() => scrollToSection(agentsMdRef), 100)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<FileText className="h-4 w-4 text-blue-500" />
|
||||
<h4 className="text-sm font-medium truncate">Global Agent Instructions (AGENTS.md)</h4>
|
||||
</div>
|
||||
<ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.agentsMd ? 'rotate-90' : ''}`} />
|
||||
</button>
|
||||
<div className={`${expandedSections.agentsMd ? 'block' : 'hidden'} border-t border-border`}>
|
||||
<div className="p-4">
|
||||
<AgentsMdEditor />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h3 className="text-base sm:text-lg font-semibold mb-4">Configure Commands, Agents & MCP Servers</h3>
|
||||
<p className="text-sm text-muted-foreground mb-6">
|
||||
Add custom commands, agents, and MCP servers to your OpenCode configurations. Select a configuration below to edit its settings.
|
||||
</p>
|
||||
|
||||
{configs.length > 0 && (
|
||||
<div className="space-y-6">
|
||||
<div className='px-1'>
|
||||
<Label className="text-sm sm:text-base font-medium">Select Configuration to Edit</Label>
|
||||
<Select
|
||||
onValueChange={(value) => {
|
||||
const config = configs.find(c => c.name === value)
|
||||
setSelectedConfig(config || null)
|
||||
<div className="mt-8 space-y-6">
|
||||
<div className="border-t border-border pt-6">
|
||||
<div className="bg-card border border-border rounded-lg overflow-clip min-w-0 mb-6">
|
||||
<button
|
||||
ref={agentsMdRef}
|
||||
className={cn("w-full px-4 py-3 flex items-center justify-between transition-colors min-w-0", expandedSections.agentsMd ? "bg-muted/40 hover:bg-muted/50" : "hover:bg-muted/50")}
|
||||
onClick={() => {
|
||||
const isExpanding = !expandedSections.agentsMd
|
||||
setExpandedSections(prev => ({ ...prev, agentsMd: isExpanding }))
|
||||
if (isExpanding) {
|
||||
setTimeout(() => scrollToSection(agentsMdRef), 100)
|
||||
}
|
||||
}}
|
||||
value={selectedConfig?.name || ""}
|
||||
>
|
||||
<SelectTrigger className="mt-2 w-full">
|
||||
<SelectValue placeholder="Select a configuration..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{configs.map(config => (
|
||||
<SelectItem key={config.id} value={config.name}>
|
||||
{config.name} {config.isDefault && '(Default)'} {!config.isValid && '(Invalid)'}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-4 pb-4 min-w-0">
|
||||
{selectedConfig ? (
|
||||
<>
|
||||
{!selectedConfig.isValid && selectedConfig.validationIssues && selectedConfig.validationIssues.length > 0 && (
|
||||
<div className="rounded-lg border border-destructive/40 bg-destructive/5 p-4">
|
||||
<p className="font-medium text-destructive">This configuration has validation issues</p>
|
||||
<p className="mt-1 text-sm text-destructive/90">
|
||||
OpenCode may fail to start until these fields are corrected. Open the config editor to fix the file directly.
|
||||
</p>
|
||||
<ul className="mt-3 list-disc space-y-1 pl-5 text-sm text-destructive/90">
|
||||
{selectedConfig.validationIssues.slice(0, 8).map((issue) => (
|
||||
<li key={`${issue.path}-${issue.message}`}>
|
||||
<span className="font-mono text-xs">{issue.path}</span>: {issue.message}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{selectedConfig.validationIssues.length > 8 && (
|
||||
<p className="mt-2 text-xs text-destructive/80">
|
||||
Showing 8 of {selectedConfig.validationIssues.length} issues. Open the config editor to review and fix the file.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="bg-card border border-border rounded-lg overflow-hidden min-w-0">
|
||||
<button
|
||||
ref={commandsRef}
|
||||
className={cn("w-full px-4 py-3 flex items-center justify-between transition-colors min-w-0", expandedSections.commands ? "bg-muted/40 hover:bg-muted/50" : "hover:bg-muted/50")}
|
||||
onClick={() => {
|
||||
const isExpanding = !expandedSections.commands
|
||||
setExpandedSections(prev => ({ ...prev, commands: isExpanding }))
|
||||
|
||||
if (isExpanding) {
|
||||
setTimeout(() => scrollToSection(commandsRef), 100)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<h4 className="text-sm font-medium truncate">Commands</h4>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{Object.keys((selectedConfig.content?.command as Record<string, Command> | undefined) ?? {}).length + directoryCommands.length} configured
|
||||
</span>
|
||||
</div>
|
||||
<ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.commands ? 'rotate-90' : ''}`} />
|
||||
</button>
|
||||
<div className={`${expandedSections.commands ? 'block' : 'hidden'} border-t border-border`}>
|
||||
<div className={EXPANDED_SECTION_CONTENT_CLASS}>
|
||||
<CommandsEditor
|
||||
commands={(selectedConfig.content?.command as Record<string, Command> | undefined) ?? {}}
|
||||
directoryCommands={directoryCommands}
|
||||
onChange={(commands) => {
|
||||
const updatedContent = {
|
||||
...selectedConfig.content,
|
||||
command: commands
|
||||
}
|
||||
updateConfigContent(selectedConfig.name, updatedContent)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-card border border-border rounded-lg overflow-hidden min-w-0">
|
||||
<button
|
||||
ref={agentsRef}
|
||||
className={cn("w-full px-4 py-3 flex items-center justify-between transition-colors min-w-0", expandedSections.agents ? "bg-muted/40 hover:bg-muted/50" : "hover:bg-muted/50")}
|
||||
onClick={() => {
|
||||
const isExpanding = !expandedSections.agents
|
||||
setExpandedSections(prev => ({ ...prev, agents: isExpanding }))
|
||||
|
||||
if (isExpanding) {
|
||||
setTimeout(() => scrollToSection(agentsRef), 100)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<h4 className="text-sm font-medium truncate">Agents</h4>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{Object.keys((selectedConfig.content?.agent as Record<string, Agent> | undefined) ?? {}).length + directoryAgents.length} configured
|
||||
</span>
|
||||
</div>
|
||||
<ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.agents ? 'rotate-90' : ''}`} />
|
||||
</button>
|
||||
<div className={`${expandedSections.agents ? 'block' : 'hidden'} border-t border-border`}>
|
||||
<div className={EXPANDED_SECTION_CONTENT_CLASS}>
|
||||
<AgentsEditor
|
||||
agents={(selectedConfig.content?.agent as Record<string, Agent> | undefined) ?? {}}
|
||||
directoryAgents={directoryAgents}
|
||||
onChange={(agents) => {
|
||||
const updatedContent = {
|
||||
...selectedConfig.content,
|
||||
agent: agents
|
||||
}
|
||||
updateConfigContent(selectedConfig.name, updatedContent)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-card border border-border rounded-lg overflow-hidden min-w-0">
|
||||
<button
|
||||
ref={skillsRef}
|
||||
className={cn("w-full px-4 py-3 flex items-center justify-between transition-colors min-w-0", expandedSections.skills ? "bg-muted/40 hover:bg-muted/50" : "hover:bg-muted/50")}
|
||||
onClick={() => {
|
||||
const isExpanding = !expandedSections.skills
|
||||
setExpandedSections(prev => ({ ...prev, skills: isExpanding }))
|
||||
if (isExpanding) {
|
||||
setTimeout(() => scrollToSection(skillsRef), 100)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<h4 className="text-sm font-medium truncate">Skills</h4>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{managedSkills.length} configured
|
||||
</span>
|
||||
</div>
|
||||
<ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.skills ? 'rotate-90' : ''}`} />
|
||||
</button>
|
||||
<div className={`${expandedSections.skills ? 'block' : 'hidden'} border-t border-border`}>
|
||||
<div className={EXPANDED_SECTION_CONTENT_CLASS}>
|
||||
<SkillsEditor
|
||||
managedSkills={managedSkills}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-card border border-border rounded-lg overflow-hidden min-w-0">
|
||||
<button
|
||||
ref={mcpRef}
|
||||
className={cn("w-full px-4 py-3 flex items-center justify-between transition-colors min-w-0", expandedSections.mcp ? "bg-muted/40 hover:bg-muted/50" : "hover:bg-muted/50")}
|
||||
onClick={() => {
|
||||
const isExpanding = !expandedSections.mcp
|
||||
setExpandedSections(prev => ({ ...prev, mcp: isExpanding }))
|
||||
|
||||
if (isExpanding) {
|
||||
setTimeout(() => scrollToSection(mcpRef), 100)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<h4 className="text-sm font-medium truncate">MCP Servers</h4>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{Object.keys((selectedConfig.content?.mcp as Record<string, unknown> | undefined) ?? {}).length} configured
|
||||
</span>
|
||||
</div>
|
||||
<ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.mcp ? 'rotate-90' : ''}`} />
|
||||
</button>
|
||||
<div className={`${expandedSections.mcp ? 'block' : 'hidden'} border-t border-border`}>
|
||||
<div className={EXPANDED_SECTION_CONTENT_CLASS}>
|
||||
<McpManager
|
||||
config={selectedConfig}
|
||||
onUpdate={(content) => updateConfigContent(selectedConfig.name, content)}
|
||||
onConfigUpdate={updateConfigContent}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-card border border-border rounded-lg overflow-hidden min-w-0">
|
||||
<button
|
||||
ref={modelsRef}
|
||||
className={cn("w-full px-4 py-3 flex items-center justify-between transition-colors min-w-0", expandedSections.models ? "bg-muted/40 hover:bg-muted/50" : "hover:bg-muted/50")}
|
||||
onClick={() => {
|
||||
const isExpanding = !expandedSections.models
|
||||
setExpandedSections(prev => ({ ...prev, models: isExpanding }))
|
||||
|
||||
if (isExpanding) {
|
||||
setTimeout(() => scrollToSection(modelsRef), 100)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<h4 className="text-sm font-medium truncate">Models</h4>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{(() => {
|
||||
const provider = selectedConfig.content?.provider as Record<string, unknown> | undefined
|
||||
if (!provider) return 0
|
||||
return Object.values(provider).reduce<number>((acc, p) => {
|
||||
const models = (p as { models?: Record<string, unknown> })?.models
|
||||
return acc + (models ? Object.keys(models).length : 0)
|
||||
}, 0)
|
||||
})()} configured
|
||||
</span>
|
||||
</div>
|
||||
<ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.models ? 'rotate-90' : ''}`} />
|
||||
</button>
|
||||
<div className={`${expandedSections.models ? 'block' : 'hidden'} border-t border-border`}>
|
||||
<div className={EXPANDED_SECTION_CONTENT_CLASS}>
|
||||
<OpenCodeModelsEditor
|
||||
providers={(selectedConfig.content?.provider as Record<string, ConfigProvider> | undefined) ?? {}}
|
||||
onChange={(providers) => {
|
||||
const updatedContent = {
|
||||
...selectedConfig.content,
|
||||
provider: providers
|
||||
}
|
||||
updateConfigContent(selectedConfig.name, updatedContent)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="bg-card border border-border rounded-lg p-6">
|
||||
<p className="text-muted-foreground text-center">Select a configuration to edit its commands, agents, and MCP servers.</p>
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<FileText className="h-4 w-4 text-blue-500" />
|
||||
<h4 className="text-sm font-medium truncate">Global Agent Instructions (AGENTS.md)</h4>
|
||||
</div>
|
||||
)}
|
||||
<ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.agentsMd ? 'rotate-90' : ''}`} />
|
||||
</button>
|
||||
<div className={`${expandedSections.agentsMd ? 'block' : 'hidden'} border-t border-border`}>
|
||||
<div className="p-4">
|
||||
<AgentsMdEditor />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<h3 className="text-base sm:text-lg font-semibold mb-4">Configure Commands, Agents & MCP Servers</h3>
|
||||
<p className="text-sm text-muted-foreground mb-6">
|
||||
Add custom commands, agents, and MCP servers to your OpenCode configuration.
|
||||
</p>
|
||||
|
||||
{config && (
|
||||
<div className="space-y-6">
|
||||
<div className="flex flex-col gap-4 pb-4 min-w-0">
|
||||
<div className="bg-card border border-border rounded-lg overflow-hidden min-w-0">
|
||||
<button
|
||||
ref={commandsRef}
|
||||
className={cn("w-full px-4 py-3 flex items-center justify-between transition-colors min-w-0", expandedSections.commands ? "bg-muted/40 hover:bg-muted/50" : "hover:bg-muted/50")}
|
||||
onClick={() => {
|
||||
const isExpanding = !expandedSections.commands
|
||||
setExpandedSections(prev => ({ ...prev, commands: isExpanding }))
|
||||
|
||||
if (isExpanding) {
|
||||
setTimeout(() => scrollToSection(commandsRef), 100)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<h4 className="text-sm font-medium truncate">Commands</h4>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{Object.keys((config.content.command as Record<string, Command> | undefined) ?? {}).length + directoryCommands.length} configured
|
||||
</span>
|
||||
</div>
|
||||
<ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.commands ? 'rotate-90' : ''}`} />
|
||||
</button>
|
||||
<div className={`${expandedSections.commands ? 'block' : 'hidden'} border-t border-border`}>
|
||||
<div className={EXPANDED_SECTION_CONTENT_CLASS}>
|
||||
<CommandsEditor
|
||||
commands={(config.content.command as Record<string, Command> | undefined) ?? {}}
|
||||
directoryCommands={directoryCommands}
|
||||
onChange={(commands) => {
|
||||
updateConfigContent({
|
||||
...config.content,
|
||||
command: commands
|
||||
})
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-card border border-border rounded-lg overflow-hidden min-w-0">
|
||||
<button
|
||||
ref={agentsRef}
|
||||
className={cn("w-full px-4 py-3 flex items-center justify-between transition-colors min-w-0", expandedSections.agents ? "bg-muted/40 hover:bg-muted/50" : "hover:bg-muted/50")}
|
||||
onClick={() => {
|
||||
const isExpanding = !expandedSections.agents
|
||||
setExpandedSections(prev => ({ ...prev, agents: isExpanding }))
|
||||
|
||||
if (isExpanding) {
|
||||
setTimeout(() => scrollToSection(agentsRef), 100)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<h4 className="text-sm font-medium truncate">Agents</h4>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{Object.keys((config.content.agent as Record<string, Agent> | undefined) ?? {}).length + directoryAgents.length} configured
|
||||
</span>
|
||||
</div>
|
||||
<ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.agents ? 'rotate-90' : ''}`} />
|
||||
</button>
|
||||
<div className={`${expandedSections.agents ? 'block' : 'hidden'} border-t border-border`}>
|
||||
<div className={EXPANDED_SECTION_CONTENT_CLASS}>
|
||||
<AgentsEditor
|
||||
agents={(config.content.agent as Record<string, Agent> | undefined) ?? {}}
|
||||
directoryAgents={directoryAgents}
|
||||
onChange={(agents) => {
|
||||
updateConfigContent({
|
||||
...config.content,
|
||||
agent: agents
|
||||
})
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-card border border-border rounded-lg overflow-hidden min-w-0">
|
||||
<button
|
||||
ref={skillsRef}
|
||||
className={cn("w-full px-4 py-3 flex items-center justify-between transition-colors min-w-0", expandedSections.skills ? "bg-muted/40 hover:bg-muted/50" : "hover:bg-muted/50")}
|
||||
onClick={() => {
|
||||
const isExpanding = !expandedSections.skills
|
||||
setExpandedSections(prev => ({ ...prev, skills: isExpanding }))
|
||||
if (isExpanding) {
|
||||
setTimeout(() => scrollToSection(skillsRef), 100)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<h4 className="text-sm font-medium truncate">Skills</h4>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{managedSkills.length} configured
|
||||
</span>
|
||||
</div>
|
||||
<ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.skills ? 'rotate-90' : ''}`} />
|
||||
</button>
|
||||
<div className={`${expandedSections.skills ? 'block' : 'hidden'} border-t border-border`}>
|
||||
<div className={EXPANDED_SECTION_CONTENT_CLASS}>
|
||||
<SkillsEditor
|
||||
managedSkills={managedSkills}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-card border border-border rounded-lg overflow-hidden min-w-0">
|
||||
<button
|
||||
ref={mcpRef}
|
||||
className={cn("w-full px-4 py-3 flex items-center justify-between transition-colors min-w-0", expandedSections.mcp ? "bg-muted/40 hover:bg-muted/50" : "hover:bg-muted/50")}
|
||||
onClick={() => {
|
||||
const isExpanding = !expandedSections.mcp
|
||||
setExpandedSections(prev => ({ ...prev, mcp: isExpanding }))
|
||||
|
||||
if (isExpanding) {
|
||||
setTimeout(() => scrollToSection(mcpRef), 100)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<h4 className="text-sm font-medium truncate">MCP Servers</h4>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{Object.keys((config.content.mcp as Record<string, unknown> | undefined) ?? {}).length} configured
|
||||
</span>
|
||||
</div>
|
||||
<ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.mcp ? 'rotate-90' : ''}`} />
|
||||
</button>
|
||||
<div className={`${expandedSections.mcp ? 'block' : 'hidden'} border-t border-border`}>
|
||||
<div className={EXPANDED_SECTION_CONTENT_CLASS}>
|
||||
<McpManager
|
||||
config={config}
|
||||
onUpdate={updateConfigContent}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-card border border-border rounded-lg overflow-hidden min-w-0">
|
||||
<button
|
||||
ref={modelsRef}
|
||||
className={cn("w-full px-4 py-3 flex items-center justify-between transition-colors min-w-0", expandedSections.models ? "bg-muted/40 hover:bg-muted/50" : "hover:bg-muted/50")}
|
||||
onClick={() => {
|
||||
const isExpanding = !expandedSections.models
|
||||
setExpandedSections(prev => ({ ...prev, models: isExpanding }))
|
||||
|
||||
if (isExpanding) {
|
||||
setTimeout(() => scrollToSection(modelsRef), 100)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<h4 className="text-sm font-medium truncate">Models</h4>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{(() => {
|
||||
const provider = config.content.provider as Record<string, unknown> | undefined
|
||||
if (!provider) return 0
|
||||
return Object.values(provider).reduce<number>((acc, p) => {
|
||||
const models = (p as { models?: Record<string, unknown> })?.models
|
||||
return acc + (models ? Object.keys(models).length : 0)
|
||||
}, 0)
|
||||
})()} configured
|
||||
</span>
|
||||
</div>
|
||||
<ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.models ? 'rotate-90' : ''}`} />
|
||||
</button>
|
||||
<div className={`${expandedSections.models ? 'block' : 'hidden'} border-t border-border`}>
|
||||
<div className={EXPANDED_SECTION_CONTENT_CLASS}>
|
||||
<OpenCodeModelsEditor
|
||||
providers={(config.content.provider as Record<string, ConfigProvider> | undefined) ?? {}}
|
||||
onChange={(providers) => {
|
||||
updateConfigContent({
|
||||
...config.content,
|
||||
provider: providers
|
||||
})
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-card border border-border rounded-lg overflow-hidden min-w-0">
|
||||
<button
|
||||
@@ -892,18 +623,6 @@ export function OpenCodeConfigManager() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Delete Confirmation Dialog */}
|
||||
<DeleteDialog
|
||||
open={!!deleteConfirmConfig}
|
||||
onOpenChange={() => setDeleteConfirmConfig(null)}
|
||||
onConfirm={() => deleteConfirmConfig && deleteConfig(deleteConfirmConfig)}
|
||||
onCancel={() => setDeleteConfirmConfig(null)}
|
||||
title="Delete Configuration"
|
||||
description="Any repositories using this configuration will continue to work but won't receive updates."
|
||||
itemName={deleteConfirmConfig?.name}
|
||||
isDeleting={isUpdating}
|
||||
/>
|
||||
|
||||
<RestartServerDialog
|
||||
open={isRestartPromptOpen}
|
||||
onOpenChange={setIsRestartPromptOpen}
|
||||
|
||||
Reference in new issue
Block a user