import { useState, useRef, useId } from 'react' import { cn } from '@/lib/utils' import { Loader2, Edit, Download, RotateCcw, FileText, ChevronDown, AlertTriangle } from 'lucide-react' import { Button } from '@/components/ui/button' import { Badge } from '@/components/ui/badge' import { RestartServerDialog } from './RestartServerDialog' import { OpenCodeConfigEditor } from './OpenCodeConfigEditor' import { OpenCodeConfigSourcesNotice } from './OpenCodeConfigSourcesNotice' 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 { scrollSectionIntoView } from '@/lib/settingsScroll' 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 { useOpenCodeConfigFile, OPEN_CODE_CONFIG_QUERY_KEY } from '@/hooks/useOpenCodeConfigFile' import { useOpenCodeApplyFeedback } from '@/hooks/useOpenCodeApplyFeedback' import { showToast } from '@/lib/toast' import { invalidateConfigCaches } from '@/lib/queryInvalidation' import { getOpenCodeApiErrorMessage } from '@/lib/opencode-errors' import { mcpServersFromConfig } from '@opencode-manager/shared/opencode' import { FetchError } from '@/api/fetchWrapper' import { getPreferredOpenCodeConfigSource, downloadOpenCodeConfigSource } from '@/api/types/settings' import type { OpenCodeConfigFile, OpenCodeConfigSaveResponse, OpenCodeImportStatus } from '@/api/types/settings' interface Command { template: string description?: string agent?: string model?: string subtask?: boolean topP?: number } interface Agent { prompt?: string description?: string mode?: 'subagent' | 'primary' | 'all' temperature?: number topP?: number top_p?: number model?: string tools?: Record permission?: { edit?: 'ask' | 'allow' | 'deny' bash?: 'ask' | 'allow' | 'deny' | Record webfetch?: 'ask' | 'allow' | 'deny' } disable?: boolean [key: string]: unknown } type ConfigSectionKey = 'agentsMd' | 'commands' | 'agents' | 'skills' | 'mcp' | 'models' | 'hostImport' const SECTION_LIST_CLASS = 'divide-y divide-border/60 border-t border-border/60' const SECTION_HEADER_CLASS = 'flex w-full min-w-0 items-center justify-between gap-3 py-3 text-left transition-colors hover:bg-muted/40 focus-visible:outline-2 focus-visible:outline-ring focus-visible:outline-offset-2' const SECTION_CONTENT_CLASS = 'pb-4' const SECTION_CHEVRON_CLASS = 'h-4 w-4 shrink-0 transition-transform' const SECTION_TITLE_CLASS = 'text-sm font-medium truncate' const SECTION_META_CLASS = 'text-xs text-muted-foreground' const getConfigFileName = (path: string) => path.split(/[\\/]/).filter(Boolean).pop() ?? path export function OpenCodeConfigManager() { const sectionIdPrefix = useId() const agentsMdContentId = `${sectionIdPrefix}-agents-md` const commandsContentId = `${sectionIdPrefix}-commands` const agentsContentId = `${sectionIdPrefix}-agents` const skillsContentId = `${sectionIdPrefix}-skills` const mcpContentId = `${sectionIdPrefix}-mcp` const modelsContentId = `${sectionIdPrefix}-models` const hostImportContentId = `${sectionIdPrefix}-host-import` const queryClient = useQueryClient() const applyOpenCodeSaveFeedback = useOpenCodeApplyFeedback() const { data: health } = useServerHealth() const [expandedSections, setExpandedSections] = useState>({ agentsMd: false, commands: false, agents: false, skills: false, mcp: false, models: false, hostImport: false, }) const [isEditDialogOpen, setIsEditDialogOpen] = useState(false) const [isVersionDialogOpen, setIsVersionDialogOpen] = useState(false) const { restartServerMutation, confirmOpen: isRestartPromptOpen, setConfirmOpen: setIsRestartPromptOpen, activeSessionCount, requestRestart, confirmRestart, } = 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 hostImportRef = useRef(null) const { data: config, isLoading } = useOpenCodeConfigFile() 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 toggleSection = (section: ConfigSectionKey, ref?: React.RefObject) => { const isExpanding = !expandedSections[section] setExpandedSections(prev => ({ ...prev, [section]: !prev[section] })) if (isExpanding) { setTimeout(() => scrollSectionIntoView(ref?.current ?? null), 0) } } const syncOpenCodeImportMutation = useMutation({ mutationFn: async () => settingsApi.syncOpenCodeImport(), onSuccess: () => { 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 applyOpenCodeConfigSave = (result: OpenCodeConfigSaveResponse) => { queryClient.setQueryData(OPEN_CODE_CONFIG_QUERY_KEY, result) applyOpenCodeSaveFeedback({ appliedMessage: 'Configuration updated', restartRequired: result.restartRequired, }) } const updateConfigContent = async (newContent: Record) => { const expectedRevision = queryClient.getQueryData( OPEN_CODE_CONFIG_QUERY_KEY, )?.revision const result = await settingsApi.updateOpenCodeConfig({ content: newContent, expectedRevision, }) applyOpenCodeConfigSave(result) } const updateConfigContentSafely = (newContent: Record) => { void updateConfigContent(newContent).catch((error) => { showToast.error(getApiErrorMessage(error, 'Failed to update config')) }) } const downloadConfig = (config: OpenCodeConfigFile) => { const preferredSource = getPreferredOpenCodeConfigSource(config) if (preferredSource) { downloadOpenCodeConfigSource(preferredSource) } } if (isLoading) { return (
) } const canImportFromHost = Boolean(importStatus?.configSourcePath || importStatus?.stateSourcePath) const workspaceConfigPathsToRemove = importStatus?.workspaceConfigPathsToRemove ?? [] const hostConfigSourcePaths = importStatus?.configSourcePaths ?? [] return (
{health?.opencodeRestartPending && (

Some saved changes require a server restart to take effect.

)} {!config ? (

No OpenCode configuration file found. Restart the Manager to seed one.

) : ( <>

{getConfigFileName(config.path)}

File location and updated time

{config.path}

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

{!config.isValid && ( Invalid Config )}

Merged persisted settings. Saves write to the preferred config file; removing a value deletes its override so an inherited value can reappear. Saves are applied to the running server; a restart is only requested if applying them fails.

{!config.isValid && config.validationIssues && config.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.

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

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

)}
)} setIsEditDialogOpen(false)} onUpdate={async ({ content, source, expectedRevision }) => { const result = await settingsApi.updateOpenCodeConfig({ content, source, expectedRevision, }) applyOpenCodeConfigSave(result) }} /> )}
{config && ( <>
| undefined) ?? {}} directoryCommands={directoryCommands} onChange={(commands) => { updateConfigContentSafely({ ...config.content, command: commands }) }} />
| undefined) ?? {}} directoryAgents={directoryAgents} onChange={(agents) => { updateConfigContentSafely({ ...config.content, agent: agents }) }} />
| undefined) ?? {}} onChange={(providers) => { updateConfigContentSafely({ ...config.content, provider: providers }) }} />
)}

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'}

{!isImportStatusLoading && workspaceConfigPathsToRemove.length > 0 && (

Importing replaces the workspace configuration files. These files will be removed:{' '} {workspaceConfigPathsToRemove.map(getConfigFileName).join(', ')}. {hostConfigSourcePaths.length > 1 && ( <> Host files imported: {hostConfigSourcePaths.map(getConfigFileName).join(', ')}. )}

)}

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.

)}
setIsRestartPromptOpen(false)} onConfirm={confirmRestart} />
) }