feat(sandbox): route host-shell surfaces into microVM via shell wrapper

This commit is contained in:
Chris Scott committed 2026-08-14 18:26:21 -04:00
1 parent aa3fb48a62
commit ae117d6a78
57 files changed
+711 -784

No files matched your search

@@ -1,222 +0,0 @@
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,14 +29,9 @@ 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,
}))
@@ -170,14 +165,6 @@ 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,6 +1,5 @@
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'
@@ -219,8 +218,6 @@ 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({
@@ -325,12 +322,6 @@ 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
@@ -1025,11 +1016,6 @@ 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
@@ -98,7 +98,7 @@ describe('OpenCodeConfigManager', () => {
})
const user = userEvent.setup()
renderWithQuery(<OpenCodeConfigManager hideHealthStatus />)
renderWithQuery(<OpenCodeConfigManager />)
await screen.findByText('Commands')
await vi.waitFor(() => {
@@ -120,7 +120,7 @@ describe('OpenCodeConfigManager', () => {
mockUpdateOpenCodeConfig.mockResolvedValueOnce({ ...defaultConfig, restartRequired: true })
const user = userEvent.setup()
renderWithQuery(<OpenCodeConfigManager hideHealthStatus />)
renderWithQuery(<OpenCodeConfigManager />)
await screen.findByText('GPT-4o')
@@ -141,7 +141,7 @@ describe('OpenCodeConfigManager', () => {
healthState.data = { opencode: 'healthy', opencodeRestartPending: true }
const user = userEvent.setup()
renderWithQuery(<OpenCodeConfigManager hideHealthStatus />)
renderWithQuery(<OpenCodeConfigManager />)
const restartNowButton = await screen.findByRole('button', { name: /restart now/i })
await user.click(restartNowButton)
@@ -156,7 +156,7 @@ describe('OpenCodeConfigManager', () => {
mockUpdateOpenCodeConfig.mockRejectedValueOnce(new Error('boom'))
const user = userEvent.setup()
renderWithQuery(<OpenCodeConfigManager hideHealthStatus />)
renderWithQuery(<OpenCodeConfigManager />)
await screen.findByText('GPT-4o')
@@ -178,7 +178,7 @@ describe('OpenCodeConfigManager', () => {
})
it('anchors the AGENTS.md card to the settings dialog scrollport', async () => {
renderWithQuery(<OpenCodeConfigManager hideHealthStatus />)
renderWithQuery(<OpenCodeConfigManager />)
const header = await screen.findByRole('button', { name: /Global Agent Instructions/i })
const card = header.parentElement
expect(card?.className).toContain('overflow-clip')
@@ -200,7 +200,7 @@ describe('OpenCodeConfigManager', () => {
mockUpdateOpenCodeConfig.mockResolvedValue(configWithRaw)
const user = userEvent.setup()
const { container } = renderWithQuery(<OpenCodeConfigManager hideHealthStatus />)
const { container } = renderWithQuery(<OpenCodeConfigManager />)
await screen.findByText('GPT-4o')
const editIcon = container.querySelector('.lucide-square-pen') as SVGElement
@@ -1,6 +1,6 @@
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 { Loader2, Plus, Trash2, 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'
@@ -56,13 +56,9 @@ interface Agent {
[key: string]: unknown
}
interface OpenCodeConfigManagerProps {
hideHealthStatus?: boolean
}
const EXPANDED_SECTION_CONTENT_CLASS = 'p-2 sm:p-4'
export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConfigManagerProps) {
export function OpenCodeConfigManager() {
const queryClient = useQueryClient()
const { data: health } = useServerHealth()
const [configs, setConfigs] = useState<OpenCodeConfig[]>([])
@@ -85,13 +81,11 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
const [deleteConfirmConfig, setDeleteConfirmConfig] = useState<OpenCodeConfig | null>(null)
const {
restartServerMutation,
upgradeOpenCodeMutation,
confirmOpen: isRestartPromptOpen,
setConfirmOpen: setIsRestartPromptOpen,
activeSessionCount,
requestRestart,
confirmRestart,
performUpgrade,
} = useOpenCodeServerActions()
const agentsMdRef = useRef<HTMLButtonElement>(null)
@@ -335,88 +329,11 @@ 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
return (
<div className="space-y-6 min-w-0">
{!hideHealthStatus && health && (
<Card className={cn('bg-transparent border-transparent', isUnhealthy && 'border-destructive')}>
<CardContent className="p-3">
<div className="flex flex-col sm:flex-row sm:items-center items-center justify-center gap-3">
<div className="flex items-center gap-2 flex-wrap justify-center ">
<div className={`h-3 w-3 rounded-full ${isUnhealthy ? 'bg-destructive animate-pulse' : 'bg-green-500'}`} />
<p className="font-medium text-sm sm:text-base">
Server Status: {isUnhealthy ? 'Unhealthy' : 'Healthy'}
</p>
{health.error && (
<p className="text-xs text-destructive">
{health.error}
</p>
)}
{health.opencodeVersion && (
<p className="text-xs text-muted-foreground">
OpenCode v{health.opencodeVersion}
</p>
)}
{health.opencodeManagerVersion && (
<p className="text-xs text-muted-foreground">
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 || sandboxEnforced}
title={updateBlockedReason}
>
{upgradeOpenCodeMutation.isPending ? (
<Loader2 className="h-3 w-3 sm:h-4 sm:w-4 mr-1 animate-spin" />
) : (
<ArrowUpCircle className="h-3 w-3 sm:h-4 sm:w-4 mr-1" />
)}
<span className="text-xs sm:text-sm">Update</span>
</Button>
<Button
variant="outline"
size="sm"
onClick={requestRestart}
disabled={restartServerMutation.isPending}
>
{restartServerMutation.isPending ? (
<Loader2 className="h-3 w-3 sm:h-4 sm:w-4 mr-1 animate-spin" />
) : (
<RotateCcw className="h-3 w-3 sm:h-4 sm:w-4 mr-1" />
)}
<span className="text-xs sm:text-sm">Restart</span>
</Button>
<Button
variant="outline"
size="sm"
onClick={() => setIsVersionDialogOpen(true)}
>
<History className="h-3 w-3 sm:h-4 sm:w-4 mr-1" />
<span className="text-xs sm:text-sm">Versions</span>
</Button>
</div>
</div>
</CardContent>
</Card>
)}
{health?.opencodeRestartPending && (
<div className="flex flex-col gap-2 rounded-md border border-amber-500/40 bg-amber-500/10 p-3 sm:flex-row sm:items-center sm:justify-between">
<div className="flex items-center gap-2">
@@ -29,9 +29,9 @@ function mockUseSettings(overrides: Partial<ReturnType<typeof useSettings>> = {}
return { updateSettingsAsync }
}
function mockHealth(sandbox?: { available: boolean; enforced: boolean; reason?: string; msbVersion?: string }) {
function mockHealth(sandbox?: { available: boolean; enforced: boolean; reason?: string; msbVersion?: string }, opencodeRestartPending = false) {
vi.mocked(useServerHealth).mockReturnValue({
data: { sandbox },
data: { opencode: 'healthy', opencodeRestartPending, sandbox },
isLoading: false,
error: null,
refetch: vi.fn(),
@@ -57,7 +57,7 @@ describe('SandboxSettings', () => {
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 })
mockHealth({ available: true, enforced: false }, true)
render(<SandboxSettings />)
@@ -1,4 +1,3 @@
import { useState } from 'react'
import { useSettings } from '@/hooks/useSettings'
import { useServerHealth } from '@/hooks/useServerHealth'
import { Switch } from '@/components/ui/switch'
@@ -10,7 +9,6 @@ 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
@@ -19,7 +17,6 @@ export function SandboxSettings() {
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')
@@ -62,7 +59,7 @@ export function SandboxSettings() {
/>
</div>
{needsRestart && (
{health?.opencodeRestartPending && (
<Alert>
<RotateCcw className="h-4 w-4" />
<AlertDescription>
@@ -180,7 +180,7 @@ export function SettingsDialog() {
</div>
<ServerEnvVarsSettings />
<SandboxSettings />
<OpenCodeConfigManager hideHealthStatus />
<OpenCodeConfigManager />
</div>
</TabsContent>
<TabsContent key="providers" value="providers" className="mt-0"><ProviderSettings /></TabsContent>
@@ -252,7 +252,7 @@ export function SettingsDialog() {
<ManagerTokenSettings />
<ServerEnvVarsSettings />
<SandboxSettings />
<OpenCodeConfigManager hideHealthStatus />
<OpenCodeConfigManager />
</div>
)}
{mobileView === 'providers' && <div key="providers"><ProviderSettings /></div>}