fix(sandbox): guard enable path and harden UI rendering performance (#341)

* fix(sandbox): guard enable path and harden UI rendering performance

* chore(deps): allow esbuild postinstall in pnpm onlyBuiltDependencies

* fix(sandbox): align availability reporting and address PR review feedback

* fix(sandbox): block planning without process attestation
This commit is contained in:
Chris Scott authored and GitHub committed 2026-08-27 08:58:23 -04:00
1 parent ba8e8f4b29
commit d63198ec8a
19 files changed
+501 -82

No files matched your search

@@ -321,6 +321,82 @@ describe('MessagePart', () => {
})
})
describe('tool output clamping', () => {
const createBashPartWithOutput = (output: string): MessagePartType => ({
type: 'tool',
tool: 'bash',
sessionID: 'test-session',
state: {
status: 'completed',
input: { command: 'echo big' },
output,
time: { start: Date.now(), end: Date.now() + 100 },
},
})
const expandTool = () => {
fireEvent.click(screen.getByRole('button'))
}
it('renders small output in full without omission marker', () => {
setup()
const output = Array.from({ length: 200 }, (_, i) => `line ${i}`).join('\n')
render(<MessagePart part={createBashPartWithOutput(output)} />)
expandTool()
expect(output).not.toContain('omitted')
const pre = document.querySelector('pre')!
expect(pre.textContent).toBe(output)
expect(screen.queryByText(/omitted/)).toBeNull()
})
it('clamps very large output with a marker and keeps head and tail', () => {
setup()
const lines: string[] = []
for (let i = 0; lines.join('\n').length < 200_000; i++) {
lines.push(`line-${i} ${'x'.repeat(80)} marker-start-${i === 0 ? 'FIRST' : ''}${i === 0 ? 'FIRST-marker-end' : ''}`)
}
const output = lines.join('\n')
const startMarker = 'marker-start-FIRST'
const endContent = `line-${lines.length - 1}`
render(<MessagePart part={createBashPartWithOutput(output)} />)
expandTool()
expect(screen.queryByText(/omitted/)).not.toBeNull()
const pre = document.querySelector('pre')!
const rendered = pre.textContent ?? ''
expect(rendered).toContain('omitted — use the copy button for the full output')
expect(rendered.length).toBeLessThan(35_000)
expect(output.startsWith(rendered.split('\n')[0])).toBe(true)
expect(rendered).toContain(endContent)
expect(rendered).toContain(startMarker)
})
it('copies the full unclamped output via the copy button', async () => {
setup()
const writeText = vi.fn().mockResolvedValue(undefined)
Object.assign(navigator, { clipboard: { writeText } })
const lines: string[] = []
for (let i = 0; lines.join('\n').length < 200_000; i++) {
lines.push(`line-${i} ${'y'.repeat(80)}`)
}
const output = lines.join('\n')
render(<MessagePart part={createBashPartWithOutput(output)} />)
expandTool()
const copyButton = screen.getByTitle('Copy output')
fireEvent.click(copyButton)
await expect(vi.waitFor(() => writeText.mock.calls[0]?.[0])).resolves.toBe(output)
})
})
describe('simpleChatMode', () => {
const createToolPart = (): MessagePartType => ({
type: 'tool',
@@ -1,4 +1,4 @@
import { useState, useRef, useEffect } from 'react'
import { useState, useRef, useEffect, useMemo, memo } from 'react'
import { unwrapSandboxExecCommand } from '@opencode-manager/shared/utils'
import type { components } from '@/api/opencode-types'
import { useSettings } from '@/hooks/useSettings'
@@ -13,6 +13,33 @@ import { getToolSpecificRender } from './FileToolRender'
type ToolPart = components['schemas']['ToolPart']
const DISPLAY_LIMIT = 30_000
const DISPLAY_HEAD_LENGTH = 20_000
const DISPLAY_TAIL_LENGTH = 10_000
function formatOmittedSize(size: number): string {
return size < 1024 * 1024
? `${(size / 1024).toFixed(1)} KB`
: `${(size / (1024 * 1024)).toFixed(1)} MB`
}
function clampDisplayText(text: string): string {
if (text.length <= DISPLAY_LIMIT) return text
const headCut = text.lastIndexOf('\n', DISPLAY_HEAD_LENGTH)
const head = headCut === -1 ? text.slice(0, DISPLAY_HEAD_LENGTH) : text.slice(0, headCut)
const tailFrom = text.length - DISPLAY_TAIL_LENGTH
const tailCut = text.indexOf('\n', tailFrom)
const tail = tailCut === -1 ? text.slice(tailFrom) : text.slice(tailCut + 1)
const omitted = formatOmittedSize(text.length - head.length - tail.length)
const marker = `\n[… ${omitted} omitted — use the copy button for the full output …]\n`
return head + marker + tail
}
function BoundedPre({ content, className }: { content: string; className: string }) {
const clamped = useMemo(() => clampDisplayText(content), [content])
return <pre className={className}>{clamped}</pre>
}
interface ToolCallPartProps {
part: ToolPart
onFileClick?: (filePath: string, lineNumber?: number) => void
@@ -29,8 +56,8 @@ function getTaskSessionId(part: ToolPart): string | undefined {
}
function ClickableJson({ json, onFileClick }: { json: unknown; onFileClick?: (filePath: string) => void }) {
const jsonString = JSON.stringify(json, null, 2)
const references = detectFileReferences(jsonString)
const jsonString = useMemo(() => JSON.stringify(json, null, 2), [json])
const references = useMemo(() => detectFileReferences(jsonString), [jsonString])
if (references.length === 0) {
return <pre className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-words">{jsonString}</pre>
@@ -68,7 +95,7 @@ function ClickableJson({ json, onFileClick }: { json: unknown; onFileClick?: (fi
return <pre className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-words">{parts}</pre>
}
export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCallPartProps) {
export const ToolCallPart = memo(function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCallPartProps) {
const { preferences } = useSettings()
const { userBashCommands } = useUserBash()
const taskSessionId = part.tool === 'task' ? getTaskSessionId(part) : undefined
@@ -79,7 +106,10 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal
const rawCommand = part.tool === 'bash' && typeof part.state.input?.command === 'string'
? part.state.input.command
: undefined
const displayCommand = rawCommand === undefined ? undefined : unwrapSandboxExecCommand(rawCommand)
const displayCommand = useMemo(
() => (rawCommand === undefined ? undefined : unwrapSandboxExecCommand(rawCommand)),
[rawCommand]
)
const isSandboxedCommand = rawCommand !== undefined && (
displayCommand !== rawCommand ||
(part.state.status === 'completed' && (part.state.metadata as Record<string, unknown> | undefined)?.sandbox === true)
@@ -260,10 +290,8 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal
)}
</div>
<div className="relative">
<pre className="bg-accent p-3 rounded text-xs overflow-x-auto whitespace-pre-wrap">
{output}
</pre>
<CopyButton content={output} title="Copy output" className="absolute top-2 right-2" />
<BoundedPre content={output ?? ''} className="bg-accent p-3 rounded text-xs overflow-x-auto whitespace-pre-wrap" />
<CopyButton content={output ?? ''} title="Copy output" className="absolute top-2 right-2" />
</div>
</div>
)
@@ -401,9 +429,10 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal
<div className="text-sm">
<div className="text-muted-foreground mb-1">Output:</div>
<div className="relative">
<pre className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-all">
{part.state.status === 'completed' ? part.state.output : ''}
</pre>
<BoundedPre
content={part.state.status === 'completed' ? part.state.output ?? '' : ''}
className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-all"
/>
{part.state.status === 'completed' && part.state.output && (
<CopyButton content={part.state.output} title="Copy output" className="absolute top-1 right-1" iconSize="sm" />
)}
@@ -420,13 +449,14 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal
{part.state.status === 'error' && (
<div className="text-sm">
<div className="text-red-600 dark:text-red-400 mb-1">Error:</div>
<pre className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-words text-red-600 dark:text-red-300">
{part.state.error}
</pre>
<BoundedPre
content={part.state.error ?? ''}
className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-words text-red-600 dark:text-red-300"
/>
</div>
)}
</div>
)}
</div>
)
}
})
@@ -5,6 +5,7 @@ import { SandboxSettings } from './SandboxSettings'
import { useSettings } from '@/hooks/useSettings'
import { useServerHealth } from '@/hooks/useServerHealth'
import { showToast } from '@/lib/toast'
import { FetchError } from '@/api/fetchWrapper'
vi.mock('@/hooks/useSettings')
vi.mock('@/hooks/useServerHealth')
@@ -132,6 +133,24 @@ describe('SandboxSettings', () => {
expect(vi.mocked(showToast.error)).toHaveBeenCalledWith('Failed to update sandbox preference')
})
it('shows the backend error when enabling sandboxing is rejected', async () => {
const user = userEvent.setup()
mockUseSettings({
updateSettingsAsync: vi.fn().mockRejectedValue(
new FetchError('Cannot enable sandboxing: process identity attestation is unavailable', 400),
),
})
mockHealth({ available: true, enforced: false })
render(<SandboxSettings />)
await user.click(screen.getByRole('switch', { name: 'Toggle sandbox' }))
expect(vi.mocked(showToast.error)).toHaveBeenCalledWith(
'Cannot enable sandboxing: process identity attestation is unavailable',
)
})
it('preserves the git credential preference when the sandbox toggle changes', async () => {
const user = userEvent.setup()
const { updateSettingsAsync } = mockUseSettings({
@@ -5,6 +5,7 @@ import { Alert, AlertDescription } from '@/components/ui/alert'
import { Badge } from '@/components/ui/badge'
import { Box, RotateCcw } from 'lucide-react'
import { showToast } from '@/lib/toast'
import { FetchError } from '@/api/fetchWrapper'
export function SandboxSettings() {
const { preferences, updateSettingsAsync, isUpdating } = useSettings()
@@ -19,8 +20,8 @@ export function SandboxSettings() {
try {
await updateSettingsAsync({ sandbox: next })
showToast.success(message)
} catch {
showToast.error('Failed to update sandbox preference')
} catch (error) {
showToast.error(error instanceof FetchError ? error.message : 'Failed to update sandbox preference')
}
}
@@ -528,4 +528,49 @@ describe('EventProvider questions', () => {
expect(screen.getByTestId('healthy')).toHaveTextContent('false')
})
})
it('does not re-render consumers for health notifications that only change lastEventAt', async () => {
let onHealthChange: (state: { isConnected: boolean; isHealthy: boolean; lastEventAt: number | null; isStalled: boolean }) => void = () => {}
mocks.subscribeGlobalMonitor.mockImplementation(({ onHealthChange: handler }) => {
onHealthChange = handler
return {
dispose: vi.fn(),
updateDirectories: vi.fn(),
reconnect: vi.fn(),
reportVisibility: vi.fn(),
}
})
let renderCount = 0
const Probe = () => {
renderCount += 1
const { isConnected } = useSSEHealth()
return <div data-testid="probe-connected">{String(isConnected)}</div>
}
render(<Probe />, { wrapper: createWrapper() })
await waitFor(() => {
expect(screen.getByTestId('probe-connected')).toHaveTextContent('false')
})
const initialRenderCount = renderCount
act(() => {
onHealthChange({ isConnected: true, isHealthy: true, lastEventAt: 1, isStalled: false })
})
await waitFor(() => {
expect(screen.getByTestId('probe-connected')).toHaveTextContent('true')
})
const afterBooleanChange = renderCount
act(() => {
onHealthChange({ isConnected: true, isHealthy: true, lastEventAt: 2, isStalled: false })
onHealthChange({ isConnected: true, isHealthy: true, lastEventAt: 3, isStalled: false })
})
expect(afterBooleanChange).toBe(initialRenderCount + 1)
expect(renderCount).toBe(afterBooleanChange)
})
})
+18 -5
View File
@@ -13,6 +13,7 @@ import { invalidateRepoGitCachesDebounced } from '@/lib/queryInvalidation'
type PermissionsBySession = Record<string, PermissionRequest[]>
type QuestionsBySession = Record<string, QuestionRequest[]>
type SSEHealthState = Pick<EventStreamHealthState, 'isConnected' | 'isHealthy' | 'isStalled'>
type SessionScopedItem = { id: string; sessionID: string }
@@ -163,7 +164,7 @@ interface EventContextValue {
navigateToCurrent: () => void
syncForSession: (directory: string, sessionID: string) => Promise<void>
}
sseHealth: EventStreamHealthState
sseHealth: SSEHealthState
getRepoIdForSession: (sessionID: string) => number | null
getClient: (sessionID: string) => OpenCodeClient | null
}
@@ -175,7 +176,10 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
const navigate = useNavigate()
const [sshHostKeyRequest, setSSHHostKeyRequest] = useState<SSHHostKeyRequest | null>(null)
const [sseHealth, setSseHealth] = useState<EventStreamHealthState>(() => openCodeEventStream.getHealth())
const [sseHealth, setSseHealth] = useState<SSEHealthState>(() => {
const { isConnected, isHealthy, isStalled } = openCodeEventStream.getHealth()
return { isConnected, isHealthy, isStalled }
})
const respondToSSHHostKey = useCallback(async (requestId: string, approved: boolean) => {
try {
@@ -187,6 +191,15 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
}
}, [])
const handleHealthChange = useCallback((next: EventStreamHealthState) => {
setSseHealth((prev) => {
if (prev.isConnected === next.isConnected && prev.isHealthy === next.isHealthy && prev.isStalled === next.isStalled) {
return prev
}
return { isConnected: next.isConnected, isHealthy: next.isHealthy, isStalled: next.isStalled }
})
}, [])
const [permissionsBySession, setPermissionsBySession] = useState<PermissionsBySession>({})
const [questionsBySession, setQuestionsBySession] = useState<QuestionsBySession>({})
const [showPermissionDialog, setShowPermissionDialog] = useState(true)
@@ -552,7 +565,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
directories: initialDirectories,
onEvent: handleSSEMessage,
onStatusChange: handleStatusChange,
onHealthChange: setSseHealth,
onHealthChange: handleHealthChange,
})
subscriptionRef.current = subscription
@@ -560,7 +573,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
subscription.dispose()
subscriptionRef.current = null
}
}, [addPermission, removePermission, addQuestion, removeQuestion, rememberSessionDirectory, fetchInitialPendingData, queryClient, setSseHealth])
}, [addPermission, removePermission, addQuestion, removeQuestion, rememberSessionDirectory, fetchInitialPendingData, queryClient, handleHealthChange])
useEffect(() => {
reposRef.current = repos
@@ -658,6 +671,6 @@ export function useQuestions() {
return questions
}
export function useSSEHealth(): EventStreamHealthState {
export function useSSEHealth(): SSEHealthState {
return useEventContext().sseHealth
}