import { useState, useEffect, useRef } from 'react' import { Loader2, Plus, Trash2, Edit, StarOff, Download, RotateCcw, FileText, ArrowUpCircle, History } 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 { DeleteDialog } from '@/components/ui/delete-dialog' import { CreateConfigDialog } from './CreateConfigDialog' import { OpenCodeConfigEditor } from './OpenCodeConfigEditor' import { CommandsEditor } from './CommandsEditor' import { AgentsEditor } from './AgentsEditor' import { AgentsMdEditor } from './AgentsMdEditor' import { McpManager } from './McpManager' import { VersionSelectDialog } from './VersionSelectDialog' import { settingsApi } from '@/api/settings' import { useMutation, useQueryClient } from '@tanstack/react-query' import { useServerHealth } from '@/hooks/useServerHealth' import { parseJsonc, hasJsoncComments } from '@/lib/jsonc' import { showToast } from '@/lib/toast' import { invalidateConfigCaches } from '@/lib/queryInvalidation' import type { OpenCodeConfig } from '@/api/types/settings' interface Command { template: string description?: string agent?: string model?: string subtask?: boolean topP?: number } interface Agent { prompt?: string description?: string mode?: 'subagent' | 'primary' | 'all' temperature?: number topP?: number top_p?: number model?: string tools?: Record permission?: { edit?: 'ask' | 'allow' | 'deny' bash?: 'ask' | 'allow' | 'deny' | Record webfetch?: 'ask' | 'allow' | 'deny' } disable?: boolean [key: string]: unknown } export function OpenCodeConfigManager() { const queryClient = useQueryClient() const { data: health } = useServerHealth() const [configs, setConfigs] = useState([]) const [isLoading, setIsLoading] = useState(true) const [isUpdating, setIsUpdating] = useState(false) const [editingConfig, setEditingConfig] = useState(null) const [selectedConfig, setSelectedConfig] = useState(null) const [expandedSections, setExpandedSections] = useState>({ agentsMd: false, commands: false, agents: false, mcp: false, }) const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false) const [isEditDialogOpen, setIsEditDialogOpen] = useState(false) const [isVersionDialogOpen, setIsVersionDialogOpen] = useState(false) const [deleteConfirmConfig, setDeleteConfirmConfig] = useState(null) const agentsMdRef = useRef(null) const commandsRef = useRef(null) const agentsRef = useRef(null) const mcpRef = useRef(null) const scrollToSection = (ref: React.RefObject) => { if (ref.current) { ref.current.scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'nearest' }) } } const reloadConfigMutation = useMutation({ mutationFn: async () => { return await settingsApi.reloadOpenCodeConfig() }, onSuccess: () => { invalidateConfigCaches(queryClient) }, }) const restartServerMutation = useMutation({ mutationFn: async () => { return await settingsApi.restartOpenCodeServer() }, onSuccess: () => { invalidateConfigCaches(queryClient) }, }) const upgradeOpenCodeMutation = useMutation({ mutationFn: async () => { return await settingsApi.upgradeOpenCode() }, onSuccess: (data) => { if (data.upgraded && data.newVersion) { queryClient.setQueryData(['health'], (old: Record | undefined) => { if (!old) return old return { ...old, opencodeVersion: data.newVersion } }) } invalidateConfigCaches(queryClient) if (data.upgraded) { showToast.success(`Upgraded to v${data.newVersion} and server restarted`, { id: 'upgrade-opencode' }) } else { showToast.success('OpenCode is already up to date', { id: 'upgrade-opencode' }) } }, onError: (error) => { const defaultMessage = 'Failed to upgrade OpenCode' if (error && typeof error === 'object' && 'response' in error) { const response = (error as { response?: { data?: { recovered?: boolean; recoveryMessage?: string; newVersion?: string } } }).response const data = response?.data if (data?.recovered && data.newVersion) { queryClient.setQueryData(['health'], (old: Record | undefined) => { if (!old) return old return { ...old, opencodeVersion: data.newVersion } }) showToast.success(`Upgrade failed but server recovered at v${data.newVersion}`, { id: 'upgrade-opencode' }) } else { showToast.error(data?.recoveryMessage || defaultMessage, { id: 'upgrade-opencode' }) } } else { showToast.error(defaultMessage, { id: 'upgrade-opencode' }) } invalidateConfigCaches(queryClient) }, }) const getApiErrorMessage = (error: unknown, fallback: string): string => { if (error && typeof error === 'object' && 'response' in error) { const response = (error as { response?: { data?: { details?: string; error?: string } } }).response return response?.data?.details || response?.data?.error || fallback } return fallback } const getRestartErrorMessage = (error: unknown): string => { return getApiErrorMessage(error, 'Failed to restart OpenCode server') } const fetchConfigs = async () => { try { setIsLoading(true) const data = await settingsApi.getOpenCodeConfigs() setConfigs(data.configs) } catch (error) { console.error('Failed to fetch configs:', error) } finally { setIsLoading(false) } } const updateConfigContent = async (configName: string, newContent: Record, restartServer = false) => { try { setIsUpdating(true) const previousContent = configs.find(c => c.name === configName)?.content await settingsApi.updateOpenCodeConfig(configName, { content: newContent }) setConfigs(prev => prev.map(config => config.name === configName ? { ...config, content: newContent, updatedAt: Date.now() } : config )) if (selectedConfig && selectedConfig.name === configName) { setSelectedConfig({ ...selectedConfig, content: newContent, updatedAt: Date.now() }) } const agentsChanged = JSON.stringify(previousContent?.agent) !== JSON.stringify(newContent.agent) if (restartServer || agentsChanged) { showToast.loading('Reloading server...', { id: 'update-restart' }) try { await reloadConfigMutation.mutateAsync() showToast.success('Configuration updated and server reloaded', { id: 'update-restart' }) } catch (error) { showToast.error(getRestartErrorMessage(error), { id: 'update-restart' }) throw error } } else { showToast.success('Configuration updated') invalidateConfigCaches(queryClient) } } catch (error) { console.error('Failed to update config:', error) showToast.error(getApiErrorMessage(error, 'Failed to update config'), { id: 'update-restart' }) } finally { setIsUpdating(false) } } useEffect(() => { fetchConfigs() }, []) 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>(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.`) } await settingsApi.createOpenCodeConfig({ name: name.trim(), content: rawContent, isDefault, }) setIsCreateDialogOpen(false) await fetchConfigs() if (isDefault) { showToast.loading('Reloading server...', { id: 'create-config' }) try { await reloadConfigMutation.mutateAsync() showToast.success('Configuration created and server reloaded', { id: 'create-config' }) } catch (error) { showToast.error(getRestartErrorMessage(error), { id: 'create-config' }) throw error } } 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 and reloading server...', { id: 'set-default' }) try { setIsUpdating(true) await settingsApi.setDefaultOpenCodeConfig(config.name) await fetchConfigs() await reloadConfigMutation.mutateAsync() showToast.success('Default config updated and server reloaded', { 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 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' }) const url = URL.createObjectURL(blob) const a = document.createElement('a') a.href = url a.download = `${config.name}.${extension}` a.click() URL.revokeObjectURL(url) } const startEdit = (config: OpenCodeConfig) => { setEditingConfig(config) setIsEditDialogOpen(true) } if (isLoading) { return (
) } const isUnhealthy = health?.opencode !== 'healthy' return (
{health && (

Server Status: {isUnhealthy ? 'Unhealthy' : 'Healthy'}

{health.error && (

{health.error}

)} {health.opencodeVersion && (

OpenCode v{health.opencodeVersion}

)} {health.opencodeManagerVersion && (

Manager v{health.opencodeManagerVersion}

)}
)} {configs.length === 0 ? (

No OpenCode configurations found. Create your first config to get started.

) : (
{configs .sort((a, b) => { if (a.isDefault) return -1 if (b.isDefault) return 1 return 0 }) .map((config) => (
{config.name} {config.isDefault && ( Current )}

Updated: {new Date(config.updatedAt).toLocaleString()}

Created: {new Date(config.createdAt).toLocaleString()}

))}
)} {/* Edit Dialog */} setIsEditDialogOpen(false)} onUpdate={async (rawContent) => { if (!editingConfig) return showToast.loading('Saving configuration...', { id: 'edit-config' }) try { await settingsApi.updateOpenCodeConfig(editingConfig.name, { content: rawContent }) await fetchConfigs() const successMsg = editingConfig.isDefault ? 'Configuration saved and server reloaded' : '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 } }} isUpdating={isUpdating} /> {/* Global AGENTS.md Section */}

Configure Commands, Agents & MCP Servers

Add custom commands, agents, and MCP servers to your OpenCode configurations. Select a configuration below to edit its settings.

{configs.length > 0 && (
{selectedConfig ? ( <>
| undefined) ?? {}} onChange={(commands) => { const updatedContent = { ...selectedConfig.content, command: commands } updateConfigContent(selectedConfig.name, updatedContent) }} />
| undefined) ?? {}} onChange={(agents) => { const updatedContent = { ...selectedConfig.content, agent: agents } updateConfigContent(selectedConfig.name, updatedContent) }} />
updateConfigContent(selectedConfig.name, content)} onConfigUpdate={updateConfigContent} />
) : (

Select a configuration to edit its commands, agents, and MCP servers.

)}
)}
{/* Delete Confirmation Dialog */} 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} />
) }