import { useState, useEffect, useRef } from 'react' import { cn } from '@/lib/utils' import { Loader2, Plus, Trash2, Edit, Download, RotateCcw, FileText, ArrowUpCircle, History, 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' import { AgentsMdEditor } from './AgentsMdEditor' import { McpManager } from './McpManager' import { SkillsEditor } from './SkillsEditor' import { OpenCodeModelsEditor, type ConfigProvider } from './OpenCodeModelsEditor' import { VersionSelectDialog } from './VersionSelectDialog' 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 { showToast } from '@/lib/toast' import { invalidateConfigCaches } from '@/lib/queryInvalidation' import { getOpenCodeApiErrorMessage } from '@/lib/opencode-errors' import { FetchError } from '@/api/fetchWrapper' import type { OpenCodeConfig, OpenCodeImportStatus } from '@/api/types/settings' interface Command { template: string description?: string agent?: string model?: string subtask?: boolean topP?: number } interface Agent { prompt?: string description?: string mode?: 'subagent' | 'primary' | 'all' temperature?: number topP?: number top_p?: number model?: string tools?: Record permission?: { edit?: 'ask' | 'allow' | 'deny' bash?: 'ask' | 'allow' | 'deny' | Record webfetch?: 'ask' | 'allow' | 'deny' } disable?: boolean [key: string]: unknown } interface OpenCodeConfigManagerProps { hideHealthStatus?: boolean } const EXPANDED_SECTION_CONTENT_CLASS = 'p-2 sm:p-4' export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConfigManagerProps) { 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 [activeConfigName, setActiveConfigName] = useState('') const [expandedSections, setExpandedSections] = useState>({ agentsMd: false, commands: false, agents: false, skills: false, mcp: false, models: false, }) const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false) const [isEditDialogOpen, setIsEditDialogOpen] = useState(false) const [isVersionDialogOpen, setIsVersionDialogOpen] = useState(false) const [deleteConfirmConfig, setDeleteConfirmConfig] = useState(null) const { restartServerMutation, upgradeOpenCodeMutation, confirmOpen: isRestartPromptOpen, setConfirmOpen: setIsRestartPromptOpen, activeSessionCount, requestRestart, confirmRestart, performUpgrade, } = useOpenCodeServerActions() const agentsMdRef = useRef(null) const commandsRef = useRef(null) const agentsRef = useRef(null) const skillsRef = useRef(null) const mcpRef = useRef(null) const modelsRef = useRef(null) const { data: managedSkills = [] } = useQuery({ queryKey: ['managed-skills'], queryFn: () => settingsApi.listManagedSkills(), staleTime: 5 * 60 * 1000, }) const { data: importStatus, isLoading: isImportStatusLoading } = useQuery({ queryKey: ['opencode-import-status'], queryFn: () => settingsApi.getOpenCodeImportStatus(), staleTime: 30 * 1000, }) const { data: directoryCommands = [] } = useQuery({ queryKey: ['opencode-directory-files', 'commands'], queryFn: () => settingsApi.listOpenCodeDirectoryFiles('commands'), staleTime: 30 * 1000, }) const { data: directoryAgents = [] } = useQuery({ queryKey: ['opencode-directory-files', 'agents'], queryFn: () => settingsApi.listOpenCodeDirectoryFiles('agents'), staleTime: 30 * 1000, }) const scrollToSection = (ref: React.RefObject) => { if (ref.current) { ref.current.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'nearest' }) } } const syncOpenCodeImportMutation = useMutation({ mutationFn: async () => settingsApi.syncOpenCodeImport(), onSuccess: async () => { await fetchConfigs() invalidateConfigCaches(queryClient) queryClient.invalidateQueries({ queryKey: ['opencode-import-status'] }) }, }) const getApiErrorMessage = getOpenCodeApiErrorMessage const getOpenCodeImportErrorMessage = (error: unknown): string => { if (error instanceof FetchError && error.code === 'OPENCODE_IMPORT_PROTECTED') { return error.detail || error.message } 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) => { const previousConfig = configs.find(c => c.name === configName) const previousContent = previousConfig?.content const previousSelectedConfig = selectedConfig 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 }) } try { setIsUpdating(true) const result = await settingsApi.updateOpenCodeConfig(configName, { content: newContent }) if (result.removedFields && result.removedFields.length > 0) { showToast.info(`Configuration updated after removing invalid fields: ${result.removedFields.join(', ')}`) } else if (result.restartRequired) { showToast.success('Configuration saved. Restart the server to apply changes.') } else { showToast.success('Configuration updated') } 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) } 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>(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 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' const canImportFromHost = Boolean(importStatus?.configSourcePath || importStatus?.stateSourcePath) const activeConfig = configs.find((c) => c.name === activeConfigName) ?? null return (
{!hideHealthStatus && health && (

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

{health.error && (

{health.error}

)} {health.opencodeVersion && (

OpenCode v{health.opencodeVersion}

)} {health.opencodeManagerVersion && (

Manager v{health.opencodeManagerVersion}

)}
)} {health?.opencodeRestartPending && (

Configuration changes are saved but require a server restart to take effect.

)}
Existing OpenCode Host Import

Import your standalone OpenCode config and session state into this workspace, then restart the server so existing chats can reconnect.

Config Source

{isImportStatusLoading ? 'Checking...' : importStatus?.configSourcePath || 'No importable OpenCode config found'}

State Source

{isImportStatusLoading ? 'Checking...' : importStatus?.stateSourcePath || 'No importable OpenCode state found'}

Workspace State

{importStatus?.workspaceStatePath || 'Unavailable'}

{importStatus?.workspaceStateExists ? 'A workspace session database already exists. Import is blocked to protect it from being replaced by detected host state.' : 'No workspace session database exists yet. Import will seed it from the detected host state.'}

{syncOpenCodeImportMutation.error && (

Import blocked

{getOpenCodeImportErrorMessage(syncOpenCodeImportMutation.error)}

This workspace already has OpenCode session state, so host state import was stopped to prevent accidental replacement of existing chats and history. If you want to use host state instead, clear the workspace state first and then run the import again.

)} {syncOpenCodeImportMutation.data?.relinkedRepos && (

Last Relink Result

Linked {syncOpenCodeImportMutation.data.relinkedRepos.relinkedCount} repos, matched {syncOpenCodeImportMutation.data.relinkedRepos.existingCount} existing repos, skipped {syncOpenCodeImportMutation.data.relinkedRepos.nonRepoPathCount} non-repo session paths, and ignored {syncOpenCodeImportMutation.data.relinkedRepos.duplicatePathCount} duplicate session paths.

{syncOpenCodeImportMutation.data.relinkedRepos.errors.length > 0 && (

{syncOpenCodeImportMutation.data.relinkedRepos.errors.length} repo paths could not be linked.

)}
)} {!canImportFromHost && !isImportStatusLoading && (

No host OpenCode config or state was detected. For Docker installs, bind your host OpenCode config and state into the container before using this action.

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

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

) : ( OpenCode Configurations
{activeConfig && !activeConfig.isValid && ( Invalid Config )}
Download Edit {!activeConfig?.isDefault && ( Apply as default )} Delete
{activeConfig && (

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

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

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

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 ? ( <> {!selectedConfig.isValid && selectedConfig.validationIssues && selectedConfig.validationIssues.length > 0 && (

This configuration has validation issues

OpenCode may fail to start until these fields are corrected. Open the config editor to fix the file directly.

    {selectedConfig.validationIssues.slice(0, 8).map((issue) => (
  • {issue.path}: {issue.message}
  • ))}
{selectedConfig.validationIssues.length > 8 && (

Showing 8 of {selectedConfig.validationIssues.length} issues. Open the config editor to review and fix the file.

)}
)}
| undefined) ?? {}} directoryCommands={directoryCommands} onChange={(commands) => { const updatedContent = { ...selectedConfig.content, command: commands } updateConfigContent(selectedConfig.name, updatedContent) }} />
| undefined) ?? {}} directoryAgents={directoryAgents} onChange={(agents) => { const updatedContent = { ...selectedConfig.content, agent: agents } updateConfigContent(selectedConfig.name, updatedContent) }} />
updateConfigContent(selectedConfig.name, content)} onConfigUpdate={updateConfigContent} />
| undefined) ?? {}} onChange={(providers) => { const updatedContent = { ...selectedConfig.content, provider: providers } updateConfigContent(selectedConfig.name, updatedContent) }} />
) : (

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} /> setIsRestartPromptOpen(false)} onConfirm={confirmRestart} />
) }