feat(sandbox): add KVM-backed agent sandboxing via microsandbox

This commit is contained in:
Chris Scott committed 2026-08-13 16:14:16 -04:00
1 parent 1d477bdee4
commit aa3fb48a62
80 files changed
+17304 -204

No files matched your search

+1
View File
@@ -198,6 +198,7 @@ export const settingsApi = {
tag: string
name: string
publishedAt: string
installable: boolean
}>
currentVersion: string | null
}> => {
+3 -1
View File
@@ -11,6 +11,7 @@ import {
type OpenCodeConfigContent,
type ModelConfig,
type ProviderConfig,
type SandboxPreferences,
type SkillFileInfo,
type CreateSkillRequest,
type UpdateSkillRequest,
@@ -20,7 +21,7 @@ import {
} from '@opencode-manager/shared'
import type { NotificationPreferences } from '@opencode-manager/shared/types'
export type { TTSConfig, STTConfig, OpenCodeConfigContent, ModelConfig, ProviderConfig, NotificationPreferences, SkillFileInfo, CreateSkillRequest, UpdateSkillRequest, SkillScope, InstallSkillFromGithubRequest, InstallSkillResponse }
export type { TTSConfig, STTConfig, OpenCodeConfigContent, ModelConfig, ProviderConfig, SandboxPreferences, NotificationPreferences, SkillFileInfo, CreateSkillRequest, UpdateSkillRequest, SkillScope, InstallSkillFromGithubRequest, InstallSkillResponse }
export { DEFAULT_TTS_CONFIG, DEFAULT_STT_CONFIG, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_USER_PREFERENCES, DEFAULT_LEADER_KEY, BLOCKED_SERVER_ENV_KEYS, DEFAULT_SERVER_ENV_VARS }
export interface CustomCommand {
@@ -71,6 +72,7 @@ export interface UserPreferences {
repoSortMode?: 'recent' | 'manual' | 'name'
serverEnvVars?: Array<{ key: string; value: string }>
disabledDefaultServerEnvVars?: string[]
sandbox?: SandboxPreferences
}
export interface SettingsResponse {
@@ -0,0 +1,222 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { PromptInput } from './PromptInput'
import { useUIState } from '@/stores/uiStateStore'
import { showToast } from '@/lib/toast'
const createTestQueryClient = () => new QueryClient({
defaultOptions: {
queries: {
retry: false,
},
},
})
const mocks = vi.hoisted(() => ({
useServerHealth: vi.fn(),
useSTT: vi.fn(),
useMobile: vi.fn(),
useSendPromptMutate: vi.fn(),
sendPromptPending: vi.fn(() => false),
useCommands: vi.fn(),
useCommandHandler: vi.fn(),
useFileSearch: vi.fn(),
useModelSelection: vi.fn(),
useVariants: vi.fn(),
useSessionAgent: vi.fn(),
useAgents: vi.fn(),
useUserBash: vi.fn(),
useSessionAgentStore: vi.fn(),
useSendErrorStore: vi.fn(),
}))
vi.mock('@/hooks/useServerHealth', () => ({
useServerHealth: mocks.useServerHealth,
}))
vi.mock('@/hooks/useSTT', () => ({
useSTT: mocks.useSTT,
}))
vi.mock('@/hooks/useMobile', () => ({
useMobile: mocks.useMobile,
}))
vi.mock('@/hooks/useOpenCode', () => ({
useSendPrompt: () => ({ mutate: mocks.useSendPromptMutate, isPending: mocks.sendPromptPending() }),
useAbortSession: () => ({ mutate: vi.fn() }),
useSendShell: () => ({ mutate: vi.fn(), isPending: false }),
useOpenCodeClient: () => ({}),
useAgents: () => ({ data: [] }),
}))
vi.mock('@/hooks/useCommands', () => ({
useCommands: mocks.useCommands,
}))
vi.mock('@/hooks/useCommandHandler', () => ({
useCommandHandler: mocks.useCommandHandler,
}))
vi.mock('@/hooks/useFileSearch', () => ({
useFileSearch: mocks.useFileSearch,
}))
vi.mock('@/hooks/useModelSelection', () => ({
useModelSelection: mocks.useModelSelection,
}))
vi.mock('@/hooks/useVariants', () => ({
useVariants: mocks.useVariants,
}))
vi.mock('@/hooks/useSessionAgent', () => ({
useSessionAgent: mocks.useSessionAgent,
}))
vi.mock('@/stores/userBashStore', () => ({
useUserBash: mocks.useUserBash,
}))
vi.mock('@/stores/sessionAgentStore', () => ({
useSessionAgentStore: mocks.useSessionAgentStore,
}))
vi.mock('@/stores/sendErrorStore', () => ({
useSendErrorStore: mocks.useSendErrorStore,
}))
vi.mock('@/contexts/EventContext', () => ({
usePermissions: () => ({
hasForSession: vi.fn().mockReturnValue(false),
setShowDialog: vi.fn(),
}),
}))
vi.mock('@/lib/toast', () => ({
showToast: { success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn(), loading: vi.fn() },
}))
vi.mock('@/components/agent/AgentQuickSelect', () => ({
AgentQuickSelect: () => <div>AgentQuickSelect</div>,
}))
vi.mock('@/components/model/ModelQuickSelect', () => ({
ModelQuickSelect: () => <div>ModelQuickSelect</div>,
}))
vi.mock('@/components/ui/session-status-indicator', () => ({
SessionStatusIndicator: () => <div>SessionStatus</div>,
}))
vi.mock('@/components/command/CommandSuggestions', () => ({
CommandSuggestions: () => <div>CommandSuggestions</div>,
}))
vi.mock('./MentionSuggestions', () => ({
MentionSuggestions: () => <div>MentionSuggestions</div>,
}))
const defaultProps = {
opcodeUrl: 'http://localhost:5551',
directory: '/test',
sessionID: 'test-session',
showScrollButton: false,
isSessionActive: false,
isStreamingResponse: false,
onScrollToBottom: vi.fn(),
}
describe('PromptInput sandbox shell-mode gating', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.useMobile.mockReturnValue(false)
mocks.useSTT.mockReturnValue({
isRecording: false,
isProcessing: false,
isSupported: false,
isEnabled: false,
interimTranscript: '',
transcript: '',
startRecording: vi.fn(),
stopRecording: vi.fn(),
abortRecording: vi.fn(),
reset: vi.fn(),
clear: vi.fn(),
})
mocks.useCommands.mockReturnValue({ filterCommands: vi.fn() })
mocks.useCommandHandler.mockReturnValue({ executeCommand: vi.fn() })
mocks.useFileSearch.mockReturnValue({ files: [] })
mocks.useModelSelection.mockReturnValue({
model: null,
modelString: 'test-model',
setModel: vi.fn(),
setActiveModel: vi.fn().mockReturnValue(false),
recentModels: [],
favoriteModels: [],
toggleFavorite: vi.fn(),
isModelStateLoading: false,
})
mocks.useVariants.mockReturnValue({
hasVariants: false,
currentVariant: null,
cycleVariant: vi.fn(),
})
mocks.useSessionAgent.mockReturnValue({ agent: 'default' })
mocks.useAgents.mockReturnValue({ data: [] })
mocks.useUserBash.mockImplementation((selector) => selector({ addUserBashCommand: vi.fn() }))
mocks.useSessionAgentStore.mockImplementation((selector) => selector({ setAgent: vi.fn() }))
mocks.useSendErrorStore.mockImplementation((selector) => selector({ errors: {} }))
useUIState.getState().clearPendingPromptCommand()
useUIState.getState().clearPendingPromptFile()
})
function mockHealth(sandbox?: { available: boolean; enforced: boolean; reason?: string }) {
mocks.useServerHealth.mockReturnValue({
data: sandbox === undefined ? undefined : { sandbox },
isLoading: false,
error: null,
refetch: vi.fn(),
restartMutation: { mutate: vi.fn(), mutateAsync: vi.fn(), isPending: false },
rollbackMutation: { mutate: vi.fn(), mutateAsync: vi.fn(), isPending: false },
})
}
const renderComponent = () => {
const queryClient = createTestQueryClient()
return render(
<QueryClientProvider client={queryClient}>
<PromptInput {...defaultProps} />
</QueryClientProvider>
)
}
it('blocks bash mode with an actionable message when the running OpenCode child is enforced', () => {
mockHealth({ available: true, enforced: true })
renderComponent()
const textarea = screen.getByPlaceholderText('Send a message...')
fireEvent.change(textarea, { target: { value: '!' } })
expect(screen.getByPlaceholderText('Send a message...')).toBeInTheDocument()
expect(screen.queryByPlaceholderText('Enter bash command...')).not.toBeInTheDocument()
expect(vi.mocked(showToast.error)).toHaveBeenCalledWith(
expect.stringContaining('shell mode is disabled'),
expect.objectContaining({ id: 'sandbox-bash-mode-disabled' }),
)
})
it('allows bash mode when enforcement is off', () => {
mockHealth({ available: true, enforced: false })
renderComponent()
const textarea = screen.getByPlaceholderText('Send a message...')
fireEvent.change(textarea, { target: { value: '!' } })
expect(screen.getByPlaceholderText('Enter bash command...')).toBeInTheDocument()
expect(vi.mocked(showToast.error)).not.toHaveBeenCalled()
})
})
@@ -29,9 +29,14 @@ const mocks = vi.hoisted(() => ({
useSessionAgentStore: vi.fn(),
useSendErrorStore: vi.fn(),
useSettings: vi.fn(),
useServerHealth: vi.fn(),
EventContext: vi.fn(),
}))
vi.mock('@/hooks/useServerHealth', () => ({
useServerHealth: mocks.useServerHealth,
}))
vi.mock('@/hooks/useSTT', () => ({
useSTT: mocks.useSTT,
}))
@@ -165,6 +170,14 @@ describe('PromptInput STT Gesture Tests', () => {
mocks.sendPromptPending.mockReturnValue(false)
mocks.useMobile.mockReturnValue(true)
mocks.useServerHealth.mockReturnValue({
data: { sandbox: { available: true, enforced: false } },
isLoading: false,
error: null,
refetch: vi.fn(),
restartMutation: { mutate: vi.fn(), mutateAsync: vi.fn(), isPending: false },
rollbackMutation: { mutate: vi.fn(), mutateAsync: vi.fn(), isPending: false },
} as ReturnType<typeof import('@/hooks/useServerHealth').useServerHealth>)
mocks.useSTT.mockReturnValue({
isRecording: false,
isProcessing: false,
@@ -1,5 +1,6 @@
import { useState, useRef, useEffect, useMemo, useImperativeHandle, forwardRef, memo, useCallback, type KeyboardEvent, type PointerEvent as ReactPointerEvent } from 'react'
import { useSendPrompt, useAbortSession, useSendShell, useAgents } from '@/hooks/useOpenCode'
import { useServerHealth } from '@/hooks/useServerHealth'
import { useCommands } from '@/hooks/useCommands'
import { useCommandHandler } from '@/hooks/useCommandHandler'
import { useFileSearch } from '@/hooks/useFileSearch'
@@ -218,6 +219,8 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
const sendPrompt = useSendPrompt(opcodeUrl, directory)
const sendShell = useSendShell(opcodeUrl, directory)
const isPromptSubmitPending = sendPrompt.isPending || sendShell.isPending
const sandboxEnforced = useServerHealth().data?.sandbox?.enforced === true
const sandboxShellModeDisabledMessage = 'Sandbox enforcement is on: `!command` shell mode is disabled because it runs in the OpenCode host process. Agent shell commands run inside the microsandbox — send a normal message instead.'
const abortSession = useAbortSession(opcodeUrl, directory, sessionID)
const { filterCommands } = useCommands(opcodeUrl)
const { executeCommand } = useCommandHandler({
@@ -322,6 +325,12 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
if (isPromptSubmitPending) return
if (isBashMode) {
if (sandboxEnforced) {
showToast.error(sandboxShellModeDisabledMessage, { id: 'sandbox-bash-mode-disabled' })
setIsBashMode(false)
setPrompt('')
return
}
const command = prompt.startsWith('!') ? prompt.slice(1) : prompt
addUserBashCommand(command)
const submittedPrompt = prompt
@@ -1016,6 +1025,11 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
const value = e.target.value
if (value === '!' && prompt === '') {
if (sandboxEnforced) {
showToast.error(sandboxShellModeDisabledMessage, { id: 'sandbox-bash-mode-disabled' })
setPrompt(value)
return
}
setIsBashMode(true)
setPrompt(value)
return
@@ -336,6 +336,10 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
}
const isUnhealthy = health?.opencode !== 'healthy'
const sandboxEnforced = health?.sandbox?.enforced === true
const updateBlockedReason = sandboxEnforced
? 'Updating the OpenCode version is disabled while agent sandboxing is enabled'
: undefined
const canImportFromHost = Boolean(importStatus?.configSourcePath || importStatus?.stateSourcePath)
const activeConfig = configs.find((c) => c.name === activeConfigName) ?? null
@@ -365,13 +369,19 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
Manager v{health.opencodeManagerVersion}
</p>
)}
{sandboxEnforced && (
<p className="text-xs text-muted-foreground">
Agent sandboxing is on; Update is disabled and only verified versions can be installed.
</p>
)}
</div>
<div className="flex flex-wrap gap-2 justify-center sm:justify-end">
<Button
variant="outline"
size="sm"
onClick={performUpgrade}
disabled={upgradeOpenCodeMutation.isPending}
disabled={upgradeOpenCodeMutation.isPending || sandboxEnforced}
title={updateBlockedReason}
>
{upgradeOpenCodeMutation.isPending ? (
<Loader2 className="h-3 w-3 sm:h-4 sm:w-4 mr-1 animate-spin" />
@@ -0,0 +1,134 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { SandboxSettings } from './SandboxSettings'
import { useSettings } from '@/hooks/useSettings'
import { useServerHealth } from '@/hooks/useServerHealth'
import { showToast } from '@/lib/toast'
vi.mock('@/hooks/useSettings')
vi.mock('@/hooks/useServerHealth')
vi.mock('@/lib/toast', () => ({
showToast: { success: vi.fn(), error: vi.fn() },
}))
function mockUseSettings(overrides: Partial<ReturnType<typeof useSettings>> = {}) {
const updateSettingsAsync = vi.fn().mockResolvedValue(undefined)
vi.mocked(useSettings).mockReturnValue({
settings: undefined,
preferences: { sandbox: { enabled: false } },
isLoading: false,
error: null,
updateSettings: vi.fn(),
updateSettingsAsync,
resetSettings: vi.fn(),
isUpdating: false,
isResetting: false,
...overrides,
})
return { updateSettingsAsync }
}
function mockHealth(sandbox?: { available: boolean; enforced: boolean; reason?: string; msbVersion?: string }) {
vi.mocked(useServerHealth).mockReturnValue({
data: { sandbox },
isLoading: false,
error: null,
refetch: vi.fn(),
restartMutation: { mutate: vi.fn(), mutateAsync: vi.fn(), isPending: false },
rollbackMutation: { mutate: vi.fn(), mutateAsync: vi.fn(), isPending: false },
} as ReturnType<typeof useServerHealth>)
}
describe('SandboxSettings', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('reflects the persisted sandbox preference', () => {
mockUseSettings({ preferences: { sandbox: { enabled: true } } })
mockHealth({ available: true, enforced: false })
render(<SandboxSettings />)
expect(screen.getByRole('switch')).toBeChecked()
})
it('writes only the sandbox preference when toggled and shows the restart notice', async () => {
const user = userEvent.setup()
const { updateSettingsAsync } = mockUseSettings()
mockHealth({ available: true, enforced: false })
render(<SandboxSettings />)
await user.click(screen.getByRole('switch'))
expect(updateSettingsAsync).toHaveBeenCalledWith({ sandbox: { enabled: true } })
expect(screen.getByText('Restart the OpenCode server to apply sandbox changes.')).toBeInTheDocument()
})
it('disables the switch with a visible reason when microVMs are unavailable', () => {
mockUseSettings()
mockHealth({ available: false, enforced: false, reason: 'KVM is not available on this host' })
render(<SandboxSettings />)
expect(screen.getByRole('switch')).toBeDisabled()
expect(screen.getByText('KVM is not available on this host')).toBeInTheDocument()
})
it('still allows disabling an already-enabled preference when microVMs become unavailable', async () => {
const user = userEvent.setup()
const { updateSettingsAsync } = mockUseSettings({ preferences: { sandbox: { enabled: true } } })
mockHealth({ available: false, enforced: false, reason: 'KVM is not available on this host' })
render(<SandboxSettings />)
const toggle = screen.getByRole('switch')
expect(toggle).toBeChecked()
expect(toggle).not.toBeDisabled()
expect(screen.getByText('KVM is not available on this host')).toBeInTheDocument()
await user.click(toggle)
expect(updateSettingsAsync).toHaveBeenCalledWith({ sandbox: { enabled: false } })
})
it('disables the switch while sandbox availability has not been reported', () => {
mockUseSettings()
vi.mocked(useServerHealth).mockReturnValue({
data: undefined,
isLoading: true,
error: null,
refetch: vi.fn(),
restartMutation: { mutate: vi.fn(), mutateAsync: vi.fn(), isPending: false },
rollbackMutation: { mutate: vi.fn(), mutateAsync: vi.fn(), isPending: false },
} as ReturnType<typeof useServerHealth>)
render(<SandboxSettings />)
expect(screen.getByRole('switch')).toBeDisabled()
expect(screen.getByText('Checking sandbox availability...')).toBeInTheDocument()
})
it('shows the reported msb version when present', () => {
mockUseSettings()
mockHealth({ available: true, enforced: false, msbVersion: '0.9.1' })
render(<SandboxSettings />)
expect(screen.getByText('msb 0.9.1')).toBeInTheDocument()
})
it('shows an error toast when saving the preference fails', async () => {
const user = userEvent.setup()
mockUseSettings({ updateSettingsAsync: vi.fn().mockRejectedValue(new Error('failed')) })
mockHealth({ available: true, enforced: false })
render(<SandboxSettings />)
await user.click(screen.getByRole('switch'))
expect(vi.mocked(showToast.error)).toHaveBeenCalledWith('Failed to update sandbox preference')
})
})
@@ -0,0 +1,76 @@
import { useState } from 'react'
import { useSettings } from '@/hooks/useSettings'
import { useServerHealth } from '@/hooks/useServerHealth'
import { Switch } from '@/components/ui/switch'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Badge } from '@/components/ui/badge'
import { Box, RotateCcw } from 'lucide-react'
import { showToast } from '@/lib/toast'
export function SandboxSettings() {
const { preferences, updateSettingsAsync, isUpdating } = useSettings()
const { data: health } = useServerHealth()
const [needsRestart, setNeedsRestart] = useState(false)
const sandbox = health?.sandbox
const isAvailable = sandbox?.available === true
const enabled = preferences?.sandbox?.enabled ?? false
const handleToggle = async (next: boolean) => {
try {
await updateSettingsAsync({ sandbox: { enabled: next } })
setNeedsRestart(true)
showToast.success(next ? 'Sandboxing enabled' : 'Sandboxing disabled')
} catch {
showToast.error('Failed to update sandbox preference')
}
}
return (
<div className="rounded-lg border bg-card overflow-hidden">
<div className="p-4 space-y-3">
<div className="flex items-center justify-between gap-3">
<div className="flex items-center gap-2 min-w-0">
<Box className="h-4 w-4 shrink-0 text-muted-foreground" />
<h3 className="text-sm font-semibold truncate">Sandbox</h3>
</div>
{sandbox?.msbVersion && (
<Badge variant="outline" className="text-xs shrink-0">
msb {sandbox.msbVersion}
</Badge>
)}
</div>
<div className="flex items-center justify-between gap-3">
<div className="min-w-0 space-y-0.5">
<p className="text-sm text-muted-foreground">
Run OpenCode agent commands inside microVMs for isolation.
</p>
{sandbox === undefined ? (
<p className="text-xs text-muted-foreground">Checking sandbox availability...</p>
) : !isAvailable && (
<p className="text-xs text-destructive">
{sandbox.reason ?? 'Sandboxing is unavailable on this host.'}
</p>
)}
</div>
<Switch
checked={enabled}
disabled={isUpdating || (!isAvailable && !enabled)}
onCheckedChange={handleToggle}
aria-label="Toggle sandbox"
/>
</div>
{needsRestart && (
<Alert>
<RotateCcw className="h-4 w-4" />
<AlertDescription>
Restart the OpenCode server to apply sandbox changes.
</AlertDescription>
</Alert>
)}
</div>
</div>
)
}
@@ -0,0 +1,102 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { ServerHealthStatus } from './ServerHealthStatus'
import { useServerHealth } from '@/hooks/useServerHealth'
import { useOpenCodeServerActions } from '@/hooks/useOpenCodeServerActions'
vi.mock('@/hooks/useServerHealth')
vi.mock('@/hooks/useOpenCodeServerActions')
vi.mock('@/components/settings/RestartServerDialog', () => ({
RestartServerDialog: () => null,
}))
const BLOCKED_REASON = 'Updating the OpenCode version is disabled while agent sandboxing is enabled'
function mockHealth(sandbox?: { available: boolean; enforced: boolean; reason?: string; msbVersion?: string }) {
vi.mocked(useServerHealth).mockReturnValue({
data: { opencode: 'healthy', opencodeVersion: '1.18.16', sandbox },
isLoading: false,
error: null,
refetch: vi.fn(),
restartMutation: { mutate: vi.fn(), mutateAsync: vi.fn(), isPending: false },
rollbackMutation: { mutate: vi.fn(), mutateAsync: vi.fn(), isPending: false },
} as ReturnType<typeof useServerHealth>)
}
function mockActions(overrides: Partial<ReturnType<typeof useOpenCodeServerActions>> = {}) {
vi.mocked(useOpenCodeServerActions).mockReturnValue({
restartServerMutation: { isPending: false },
upgradeOpenCodeMutation: { isPending: false },
confirmOpen: false,
setConfirmOpen: vi.fn(),
activeSessionCount: 0,
requestRestart: vi.fn(),
confirmRestart: vi.fn(),
performUpgrade: vi.fn(),
...overrides,
} as ReturnType<typeof useOpenCodeServerActions>)
}
describe('ServerHealthStatus', () => {
beforeEach(() => {
vi.clearAllMocks()
mockActions()
})
it('keeps Update and Versions enabled when sandboxing is off', () => {
mockHealth({ available: true, enforced: false })
render(<ServerHealthStatus />)
expect(screen.getByRole('button', { name: /Update/i })).toBeEnabled()
expect(screen.getByRole('button', { name: /Versions/i })).toBeEnabled()
})
it('disables Update but keeps Versions accessible when sandbox enforcement is on', () => {
mockHealth({ available: true, enforced: true })
render(<ServerHealthStatus />)
const update = screen.getByRole('button', { name: /Update/i })
const versions = screen.getByRole('button', { name: /Versions/i })
expect(update).toBeDisabled()
expect(update).toHaveAttribute('title', BLOCKED_REASON)
expect(versions).toBeEnabled()
expect(screen.getByText(/Agent sandboxing is on; Update is disabled and only verified versions can be installed\./)).toBeInTheDocument()
})
it('keeps Update and Versions enabled while enforcement is pending but not active', () => {
mockHealth({ available: false, enforced: false, reason: 'KVM unavailable' })
render(<ServerHealthStatus />)
expect(screen.getByRole('button', { name: /Update/i })).toBeEnabled()
expect(screen.getByRole('button', { name: /Versions/i })).toBeEnabled()
})
it('does not invoke an upgrade while the Update button is disabled', async () => {
const user = userEvent.setup()
const performUpgrade = vi.fn()
mockActions({ performUpgrade })
mockHealth({ available: true, enforced: true })
render(<ServerHealthStatus />)
await user.click(screen.getByRole('button', { name: /Update/i }))
expect(performUpgrade).not.toHaveBeenCalled()
})
it('opens the version dialog when Versions is clicked under enforcement', async () => {
const user = userEvent.setup()
const onOpenVersionDialog = vi.fn()
mockHealth({ available: true, enforced: true })
render(<ServerHealthStatus onOpenVersionDialog={onOpenVersionDialog} />)
await user.click(screen.getByRole('button', { name: /Versions/i }))
expect(onOpenVersionDialog).toHaveBeenCalled()
})
})
@@ -37,6 +37,10 @@ export function ServerHealthStatus({ onOpenVersionDialog }: ServerHealthStatusPr
}
const isUnhealthy = health.opencode !== 'healthy'
const sandboxEnforced = health.sandbox?.enforced === true
const updateBlockedReason = sandboxEnforced
? 'Updating the OpenCode version is disabled while agent sandboxing is enabled'
: undefined
return (
<Card className={cn('bg-transparent border-transparent', isUnhealthy && 'border-destructive')}>
@@ -62,13 +66,19 @@ export function ServerHealthStatus({ onOpenVersionDialog }: ServerHealthStatusPr
Manager v{health.opencodeManagerVersion}
</p>
)}
{sandboxEnforced && (
<p className="text-xs text-muted-foreground">
Agent sandboxing is on; Update is disabled and only verified versions can be installed.
</p>
)}
</div>
<div className="flex flex-wrap gap-2 justify-center sm:justify-end">
<Button
variant="outline"
size="sm"
onClick={performUpgrade}
disabled={upgradeOpenCodeMutation.isPending}
disabled={upgradeOpenCodeMutation.isPending || sandboxEnforced}
title={updateBlockedReason}
>
{upgradeOpenCodeMutation.isPending ? (
<Loader2 className="h-3 w-3 sm:h-4 sm:w-4 mr-1 animate-spin" />
@@ -6,6 +6,7 @@ import { OpenCodeConfigManager } from '@/components/settings/OpenCodeConfigManag
import { OpenCodeServerAuthSettings } from '@/components/settings/OpenCodeServerAuthSettings'
import { ManagerTokenSettings } from '@/components/settings/ManagerTokenSettings'
import { ServerEnvVarsSettings } from '@/components/settings/ServerEnvVarsSettings'
import { SandboxSettings } from '@/components/settings/SandboxSettings'
import { ServerHealthStatus } from '@/components/settings/ServerHealthStatus'
import { ProviderSettings } from '@/components/settings/ProviderSettings'
import { AccountSettings } from '@/components/settings/AccountSettings'
@@ -178,6 +179,7 @@ export function SettingsDialog() {
<ManagerTokenSettings isOpen={authSectionsOpen} onToggle={toggleAuthSections} />
</div>
<ServerEnvVarsSettings />
<SandboxSettings />
<OpenCodeConfigManager hideHealthStatus />
</div>
</TabsContent>
@@ -249,6 +251,7 @@ export function SettingsDialog() {
<OpenCodeServerAuthSettings />
<ManagerTokenSettings />
<ServerEnvVarsSettings />
<SandboxSettings />
<OpenCodeConfigManager hideHealthStatus />
</div>
)}
@@ -0,0 +1,122 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { VersionSelectDialog } from './VersionSelectDialog'
import { settingsApi } from '@/api/settings'
import { useServerHealth } from '@/hooks/useServerHealth'
vi.mock('@/api/settings', () => ({
settingsApi: {
getOpenCodeVersions: vi.fn(),
installOpenCodeVersion: vi.fn(),
},
}))
vi.mock('@/hooks/useServerHealth')
vi.mock('@/lib/toast', () => ({
showToast: { success: vi.fn(), error: vi.fn(), loading: vi.fn(), dismiss: vi.fn() },
}))
vi.mock('@/lib/queryInvalidation', () => ({
invalidateConfigCaches: vi.fn(),
updateOpenCodeVersionCaches: vi.fn(),
}))
const mockGetOpenCodeVersions = settingsApi.getOpenCodeVersions as ReturnType<typeof vi.fn>
const mockInstallOpenCodeVersion = settingsApi.installOpenCodeVersion as ReturnType<typeof vi.fn>
function renderDialog(open = true) {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
return render(
<QueryClientProvider client={queryClient}>
<VersionSelectDialog open={open} onOpenChange={vi.fn()} />
</QueryClientProvider>,
)
}
function mockHealth(enforced: boolean) {
vi.mocked(useServerHealth).mockReturnValue({
data: { sandbox: { available: true, enforced } },
isLoading: false,
error: null,
refetch: vi.fn(),
restartMutation: { mutate: vi.fn(), mutateAsync: vi.fn(), isPending: false },
rollbackMutation: { mutate: vi.fn(), mutateAsync: vi.fn(), isPending: false },
} as ReturnType<typeof useServerHealth>)
}
describe('VersionSelectDialog', () => {
beforeEach(() => {
vi.clearAllMocks()
mockGetOpenCodeVersions.mockResolvedValue({
versions: [
{ version: '1.19.0', tag: 'v1.19.0', name: '', publishedAt: '2026-01-01T00:00:00Z', installable: true },
{ version: '1.18.16', tag: 'v1.18.16', name: '', publishedAt: '2025-12-01T00:00:00Z', installable: true },
],
currentVersion: '1.18.16',
})
mockInstallOpenCodeVersion.mockResolvedValue({ success: true, message: 'ok', oldVersion: null, newVersion: '1.19.0' })
mockHealth(false)
})
it('lists versions and allows selection when sandboxing is off', async () => {
const user = userEvent.setup()
renderDialog()
expect(await screen.findByText('v1.19.0')).toBeInTheDocument()
const row = screen.getByRole('button', { name: /v1\.19\.0/ })
expect(row).toBeEnabled()
expect(screen.getByRole('button', { name: /Select version/i })).toBeDisabled()
await user.click(row)
expect(screen.getByRole('button', { name: /^Install$/i })).toBeEnabled()
})
it('keeps verified versions installable and disables unverified versions when sandbox enforcement is on', async () => {
mockHealth(true)
mockGetOpenCodeVersions.mockResolvedValue({
versions: [
{ version: '1.19.0', tag: 'v1.19.0', name: '', publishedAt: '2026-01-01T00:00:00Z', installable: false },
{ version: '1.18.16', tag: 'v1.18.16', name: '', publishedAt: '2025-12-01T00:00:00Z', installable: true },
],
currentVersion: '1.17.0',
})
renderDialog()
expect(
await screen.findByText(/only verified OpenCode versions can be installed/),
).toBeInTheDocument()
const unverifiedRow = screen.getByRole('button', { name: /v1\.19\.0/ })
const verifiedRow = screen.getByRole('button', { name: /v1\.18\.16/ })
expect(unverifiedRow).toBeDisabled()
expect(verifiedRow).toBeEnabled()
expect(screen.getByRole('button', { name: /Select version/i })).toBeDisabled()
const user = userEvent.setup()
await user.click(verifiedRow)
expect(screen.getByRole('button', { name: /^Install$/i })).toBeEnabled()
})
it('keeps the install button disabled when the only available row is unverified under enforcement', async () => {
mockHealth(true)
mockGetOpenCodeVersions.mockResolvedValue({
versions: [
{ version: '1.19.0', tag: 'v1.19.0', name: '', publishedAt: '2026-01-01T00:00:00Z', installable: false },
],
currentVersion: '1.17.0',
})
const user = userEvent.setup()
renderDialog()
expect(await screen.findByText('v1.19.0')).toBeInTheDocument()
const unverifiedRow = screen.getByRole('button', { name: /v1\.19\.0/ })
expect(unverifiedRow).toBeDisabled()
await user.click(unverifiedRow)
expect(screen.getByRole('button', { name: /Select version/i })).toBeDisabled()
})
})
@@ -6,6 +6,7 @@ import { Button } from '@/components/ui/button'
import { settingsApi } from '@/api/settings'
import { showToast } from '@/lib/toast'
import { invalidateConfigCaches, updateOpenCodeVersionCaches } from '@/lib/queryInvalidation'
import { useServerHealth } from '@/hooks/useServerHealth'
interface VersionSelectDialogProps {
open: boolean
@@ -14,6 +15,8 @@ interface VersionSelectDialogProps {
export function VersionSelectDialog({ open, onOpenChange }: VersionSelectDialogProps) {
const queryClient = useQueryClient()
const { data: health } = useServerHealth()
const sandboxEnforced = health?.sandbox?.enforced === true
const [selectedVersion, setSelectedVersion] = useState<string | null>(null)
const { data, isLoading, error } = useQuery({
@@ -23,6 +26,9 @@ export function VersionSelectDialog({ open, onOpenChange }: VersionSelectDialogP
staleTime: 60000,
})
const selectedRelease = data?.versions.find((release) => release.version === selectedVersion)
const selectedInstallable = selectedRelease?.installable === true
const installMutation = useMutation({
mutationFn: (version: string) => settingsApi.installOpenCodeVersion(version),
onSuccess: (result) => {
@@ -95,6 +101,13 @@ export function VersionSelectDialog({ open, onOpenChange }: VersionSelectDialogP
{data && (
<>
{sandboxEnforced && (
<div className="rounded-lg border border-amber-500/40 bg-amber-500/10 p-3 text-sm text-amber-600 dark:text-amber-400 mb-3">
While agent sandboxing is enabled, only verified OpenCode versions can be installed. Unverified
versions are disabled. Disable Agent Sandboxing in Settings and restart the OpenCode server to
install other versions.
</div>
)}
<div className="h-[300px] overflow-y-auto pr-2">
<div className="space-y-2">
{data.versions.map((release) => {
@@ -105,13 +118,15 @@ export function VersionSelectDialog({ open, onOpenChange }: VersionSelectDialogP
<button
key={release.version}
onClick={() => setSelectedVersion(isCurrent ? null : release.version)}
disabled={isCurrent || installMutation.isPending}
disabled={isCurrent || installMutation.isPending || !release.installable}
className={`w-full text-left p-3 rounded-lg border transition-colors ${
isSelected
? 'border-primary bg-primary/10'
: isCurrent
? 'border-green-500/50 bg-green-500/10 cursor-default'
: 'border-border hover:border-primary/50 hover:bg-muted/50'
: !release.installable
? 'border-border opacity-50 cursor-not-allowed'
: 'border-border hover:border-primary/50 hover:bg-muted/50'
}`}
>
<div className="flex items-center justify-between">
@@ -123,6 +138,11 @@ export function VersionSelectDialog({ open, onOpenChange }: VersionSelectDialogP
Current
</span>
)}
{!release.installable && (
<span className="text-xs px-1.5 py-0.5 rounded bg-muted text-muted-foreground">
Unverified
</span>
)}
</div>
<div className="text-xs text-muted-foreground mt-0.5">
{formatDate(release.publishedAt)}
@@ -146,7 +166,7 @@ export function VersionSelectDialog({ open, onOpenChange }: VersionSelectDialogP
</Button>
<Button
onClick={handleInstall}
disabled={!selectedVersion || installMutation.isPending}
disabled={!selectedVersion || installMutation.isPending || !selectedInstallable}
className="min-w-[120px]"
>
{installMutation.isPending ? (
+1
View File
@@ -23,6 +23,7 @@ interface HealthResponse {
opencodeVersionSupported: boolean
opencodeManagerVersion: string | null
opencodeRestartPending?: boolean
sandbox?: { available: boolean; enabled: boolean; enforced: boolean; reason?: string; msbVersion?: string }
error?: string
}