fix(terminal-dev-loop): address branch review findings

Security:
- Reject same-site and cross-site state-changing requests on cookie-authenticated routes unless the origin is trusted
- Drop Manager and ocm_preview Set-Cookie headers from preview responses
- Show and hash the full executable content of .ocm/project.json at trust time
- Restrict action URLs to http(s) and refuse symlinked repo config paths
- Keep the preview start redirect on the gateway origin

Lifecycle:
- Stop terminals in OpenCode workspace siblings when a repo is deleted
- Report preview as unavailable instead of crashing when the gateway port cannot be bound

Performance:
- Skip branch lookups when validating terminal and project-config directories
- Stop the /proc scan once all listening sockets are mapped and pause port polling while a preview is open
- Close slow WebSocket clients with 1013 so they reconnect with replay
- Lazy-load the xterm terminal view and skip unchanged resize requests
- Request uncompressed responses from preview targets

Cleanup:
- Share one repo directory resolver, trusted-origins parser, cookie prefix, WebSocket frame forwarder, header filter, icon map and dialog-param helper
- Remove unused props, options and exports

Docs: update terminal, preview, project actions, sandboxing, internal API and environment pages
This commit is contained in:
Chris Scott committed 2026-10-03 10:00:33 -04:00
1 parent 16b91ccf02
commit c60a9b35f2
72 files changed
+2039 -596

No files matched your search

@@ -15,7 +15,7 @@ type PreviewPortsResult = ReturnType<typeof usePreviewPorts>
const portsData = {
enabled: true,
ports: [{ port: 5173, host: '127.0.0.1' as const, pid: 10, command: 'vite', cwd: '/repo' }],
ports: [{ port: 5173, host: '127.0.0.1' as const, pid: 10, command: 'vite', cwd: '/repo', inDirectory: true }],
}
let portsState: PreviewPortsResult['data'] = portsData
@@ -106,15 +106,43 @@ describe('PreviewPanel', () => {
portsState = { enabled: false, ports: [] }
renderPanel('/repos/1?dialog=preview')
expect(screen.getByText(/Preview is disabled/)).toBeInTheDocument()
expect(screen.getByText(/Preview is unavailable/)).toBeInTheDocument()
})
it('badges ports that run inside the directory', () => {
it('badges ports marked as inside the directory', () => {
renderPanel('/repos/1?dialog=preview')
expect(screen.getByText('this repo')).toBeInTheDocument()
})
it('does not badge ports marked as outside the directory', () => {
portsState = {
enabled: true,
ports: [{ port: 5173, host: '127.0.0.1', pid: 10, command: 'vite', cwd: '/elsewhere', inDirectory: false }],
}
renderPanel('/repos/1?dialog=preview')
expect(screen.queryByText('this repo')).not.toBeInTheDocument()
})
it('polls the port list while no preview session is active', () => {
renderPanel('/repos/1?dialog=preview')
const lastOptions = vi.mocked(usePreviewPorts).mock.calls.at(-1)?.[1]
expect(lastOptions?.enabled).toBe(true)
expect(lastOptions?.refetchInterval).toBe(2000)
})
it('stops polling once a preview session is active', async () => {
renderPanel()
await screen.findByTitle('Preview')
const lastOptions = vi.mocked(usePreviewPorts).mock.calls.at(-1)?.[1]
expect(lastOptions?.enabled).toBe(true)
expect(lastOptions?.refetchInterval).toBe(false)
})
it('mints a fresh session when a listed port disappears and comes back', async () => {
const first = deferred<CreatePreviewSessionResponse>()
const second = deferred<CreatePreviewSessionResponse>()
@@ -6,7 +6,8 @@ import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { useMobile } from '@/hooks/useMobile'
import { useUrlParams } from '@/hooks/useUrlParams'
import { buildPreviewStartUrl, getPreviewOrigin, isSameOriginAsManager } from '@/lib/preview-url'
import { getOpenCodeApiErrorMessage } from '@/lib/opencode-errors'
import { buildPreviewStartUrl, getPreviewOrigin, isSameOriginAsManager, parsePort } from '@/lib/preview-url'
import { cn } from '@/lib/utils'
interface PreviewPanelProps {
@@ -38,26 +39,13 @@ interface ActiveSession {
data: CreatePreviewSessionResponse
}
function isInsideDirectory(cwd: string | null, directory: string | undefined): boolean {
if (!cwd || !directory) return false
if (cwd === directory) return true
const prefix = directory.endsWith('/') ? directory : `${directory}/`
return cwd.startsWith(prefix)
}
function errorMessage(error: unknown, fallback: string): string {
return error instanceof Error ? error.message : fallback
}
export function PreviewPanel({ isOpen, onClose, directory }: PreviewPanelProps) {
const isMobile = useMobile()
const { searchParams, updateParams } = useUrlParams()
const requestedPort = useMemo(() => {
const raw = searchParams.get('previewPort')
if (!raw) return undefined
const port = Number(raw)
return Number.isInteger(port) && port > 0 && port <= 65535 ? port : undefined
const port = parsePort(searchParams.get('previewPort') ?? '')
return port ?? undefined
}, [searchParams])
const requestedPath = searchParams.get('previewPath') || '/'
@@ -71,9 +59,11 @@ export function PreviewPanel({ isOpen, onClose, directory }: PreviewPanelProps)
const activePathRef = useRef<string | null>(null)
const requestIdRef = useRef(0)
const activeSession = session && session.targetPort === requestedPort ? session : null
const portsQuery = usePreviewPorts(directory, {
enabled: isOpen,
refetchInterval: isOpen ? 2000 : false,
refetchInterval: isOpen && !activeSession ? 2000 : false,
})
const ports = useMemo(() => portsQuery.data?.ports ?? [], [portsQuery.data])
const enabled = portsQuery.data?.enabled ?? true
@@ -127,7 +117,7 @@ export function PreviewPanel({ isOpen, onClose, directory }: PreviewPanelProps)
if (requestIdRef.current !== requestId) return
sessionPortRef.current = null
activePathRef.current = null
setSessionError(errorMessage(error, 'Failed to start preview'))
setSessionError(getOpenCodeApiErrorMessage(error, 'Failed to start preview'))
})
}, [])
@@ -166,7 +156,7 @@ export function PreviewPanel({ isOpen, onClose, directory }: PreviewPanelProps)
window.open(buildPreviewStartUrl(data, requestedPath), '_blank', 'noopener,noreferrer')
})
.catch((error: unknown) => {
setSessionError(errorMessage(error, 'Failed to open preview'))
setSessionError(getOpenCodeApiErrorMessage(error, 'Failed to open preview'))
})
}, [requestedPort, requestedPath])
@@ -180,7 +170,6 @@ export function PreviewPanel({ isOpen, onClose, directory }: PreviewPanelProps)
void portsQuery.refetch()
}, [portListed, requestedPort, requestedPath, startSession, portsQuery])
const activeSession = session && session.targetPort === requestedPort ? session : null
const previewOrigin = activeSession ? getPreviewOrigin(activeSession.data) : null
const sameOrigin = previewOrigin ? isSameOriginAsManager(previewOrigin) : false
const viewportWidth = VIEWPORT_WIDTHS[viewport]
@@ -200,7 +189,7 @@ export function PreviewPanel({ isOpen, onClose, directory }: PreviewPanelProps)
const body = () => {
if (!enabled) {
return renderMessage('Preview is disabled (PREVIEW_PORT=0)')
return renderMessage('Preview is unavailable')
}
if (!requestedPort) {
return renderMessage('Select a port to preview')
@@ -338,7 +327,7 @@ export function PreviewPanel({ isOpen, onClose, directory }: PreviewPanelProps)
>
<span className="font-medium">:{entry.port}</span>
{entry.command && <span className="truncate">{entry.command}</span>}
{isInsideDirectory(entry.cwd, directory) && (
{entry.inDirectory && (
<span className="rounded bg-muted px-1.5 py-0.5 text-[10px]">this repo</span>
)}
</button>