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

@@ -1,5 +1,5 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
import { fireEvent, render, screen } from '@testing-library/react'
import { MemoryRouter } from 'react-router-dom'
import type { TerminalInfo } from '@opencode-manager/shared/types'
import { useCreateTerminal, useRemoveTerminal, useTerminals } from '@/api/terminals'
@@ -91,6 +91,14 @@ describe('TerminalPanel', () => {
mockTerminalHooks([])
})
it('renders a loading fallback before the lazy terminal view resolves', async () => {
mockTerminalHooks([runningTerminal])
renderPanel()
expect(screen.getByText('Loading terminal...')).toBeInTheDocument()
expect(await screen.findAllByTestId('terminal-view')).toHaveLength(1)
})
it('auto-creates a terminal when the directory has none', () => {
mockTerminalHooks([])
renderPanel()
@@ -122,22 +130,23 @@ describe('TerminalPanel', () => {
expect(createMutate).toHaveBeenCalledWith({ directory: '/repo' }, expect.any(Object))
})
it('exposes an accessible name for the mobile panel close control', () => {
it('exposes an accessible name for the mobile panel close control', async () => {
mockTerminalHooks([runningTerminal])
vi.mocked(useMobile).mockReturnValue(true)
const onClose = vi.fn()
renderPanel('/repos/1?dialog=terminal', onClose)
await screen.findAllByTestId('terminal-view')
fireEvent.click(screen.getByRole('button', { name: 'Close terminal panel' }))
expect(onClose).toHaveBeenCalledTimes(1)
})
it('activates the terminal referenced by the terminal URL param', () => {
it('activates the terminal referenced by the terminal URL param', async () => {
mockTerminalHooks([runningTerminal, exitedTerminal])
renderPanel('/repos/1?dialog=terminal&terminal=t2')
const views = screen.getAllByTestId('terminal-view')
const views = await screen.findAllByTestId('terminal-view')
const active = views.find((view) => view.getAttribute('data-pty-id') === 't2')
const inactive = views.find((view) => view.getAttribute('data-pty-id') === 't1')
@@ -145,16 +154,18 @@ describe('TerminalPanel', () => {
expect(inactive).toHaveAttribute('data-active', 'false')
})
it('shows an exited badge with the exit code', () => {
it('shows an exited badge with the exit code', async () => {
mockTerminalHooks([exitedTerminal])
renderPanel()
await screen.findAllByTestId('terminal-view')
expect(screen.getByText('exited (0)')).toBeInTheDocument()
})
it('asks for confirmation before closing a running terminal', () => {
it('asks for confirmation before closing a running terminal', async () => {
mockTerminalHooks([runningTerminal])
renderPanel()
await screen.findAllByTestId('terminal-view')
fireEvent.click(screen.getByLabelText('Close Terminal'))
@@ -166,9 +177,10 @@ describe('TerminalPanel', () => {
expect(removeMutate).toHaveBeenCalledWith({ ptyID: 't1', directory: '/repo' }, expect.any(Object))
})
it('removes an exited terminal without confirmation', () => {
it('removes an exited terminal without confirmation', async () => {
mockTerminalHooks([exitedTerminal])
renderPanel()
await screen.findAllByTestId('terminal-view')
fireEvent.click(screen.getByLabelText('Close Build'))
@@ -176,17 +188,19 @@ describe('TerminalPanel', () => {
expect(removeMutate).toHaveBeenCalledWith({ ptyID: 't2', directory: '/repo' }, expect.any(Object))
})
it('renders the key bar only on mobile', () => {
it('renders the key bar only on mobile', async () => {
mockTerminalHooks([runningTerminal])
vi.mocked(useMobile).mockReturnValue(false)
renderPanel()
const first = renderPanel()
await screen.findAllByTestId('terminal-view')
expect(screen.queryByTestId('terminal-key-bar')).not.toBeInTheDocument()
cleanup()
first.unmount()
vi.mocked(useMobile).mockReturnValue(true)
renderPanel()
await screen.findAllByTestId('terminal-view')
expect(screen.getByTestId('terminal-key-bar')).toBeInTheDocument()
})
})
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { lazy, Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import type { TerminalInfo } from '@opencode-manager/shared/types'
import { Plus, SquareTerminal, X } from 'lucide-react'
import { useCreateTerminal, useRemoveTerminal, useTerminals } from '@/api/terminals'
@@ -11,17 +11,20 @@ import { useUrlParams } from '@/hooks/useUrlParams'
import { openUrlFromManager } from '@/lib/open-url'
import { cn } from '@/lib/utils'
import { TerminalKeyBar } from './TerminalKeyBar'
import { TerminalView, type TerminalViewHandle } from './TerminalView'
import type { TerminalViewHandle } from './TerminalView'
const TerminalView = lazy(() =>
import('./TerminalView').then((module) => ({ default: module.TerminalView })),
)
interface TerminalPanelProps {
repoId: number
directory: string | undefined
isOpen: boolean
onClose: () => void
onOpenLink?: (uri: string) => void
}
export function TerminalPanel({ repoId, directory, isOpen, onClose, onOpenLink }: TerminalPanelProps) {
export function TerminalPanel({ repoId, directory, isOpen, onClose }: TerminalPanelProps) {
const isMobile = useMobile()
const { searchParams, updateParams } = useUrlParams()
const openPreview = useOpenPreview()
@@ -183,23 +186,31 @@ export function TerminalPanel({ repoId, directory, isOpen, onClose, onOpenLink }
{isLoading || isCreating ? 'Starting terminal...' : 'No terminals'}
</div>
) : (
terminals.map((terminal) => (
<TerminalView
key={terminal.id}
ref={(handle) => {
if (handle) viewHandlesRef.current.set(terminal.id, handle)
else viewHandlesRef.current.delete(terminal.id)
}}
repoId={repoId}
directory={directory}
ptyID={terminal.id}
active={terminal.id === activeTerminalId}
ctrlArmed={ctrlArmed}
onCtrlConsumed={handleCtrlConsumed}
onOpenLink={onOpenLink ?? handleOpenLink}
onExited={() => { void refetch() }}
/>
))
<Suspense
fallback={
<div className="flex h-full items-center justify-center text-sm text-muted-foreground">
Loading terminal...
</div>
}
>
{terminals.map((terminal) => (
<TerminalView
key={terminal.id}
ref={(handle) => {
if (handle) viewHandlesRef.current.set(terminal.id, handle)
else viewHandlesRef.current.delete(terminal.id)
}}
repoId={repoId}
directory={directory}
ptyID={terminal.id}
active={terminal.id === activeTerminalId}
ctrlArmed={ctrlArmed}
onCtrlConsumed={handleCtrlConsumed}
onOpenLink={handleOpenLink}
onExited={() => { void refetch() }}
/>
))}
</Suspense>
)}
</div>
@@ -1,6 +1,7 @@
import { createRef, type ComponentProps } from 'react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, render } from '@testing-library/react'
import { resizeTerminal } from '@/api/terminals'
import { TerminalView, type TerminalViewHandle } from './TerminalView'
const xterm = vi.hoisted(() => {
@@ -64,6 +65,7 @@ function renderView(overrides: Partial<ComponentProps<typeof TerminalView>> = {}
active
ctrlArmed={false}
onCtrlConsumed={onCtrlConsumed}
onOpenLink={vi.fn()}
onExited={vi.fn()}
{...overrides}
/>
@@ -110,6 +112,7 @@ describe('TerminalView input handling', () => {
active: true,
ctrlArmed: true,
onCtrlConsumed,
onOpenLink: vi.fn(),
onExited: vi.fn(),
}
@@ -131,3 +134,84 @@ describe('TerminalView input handling', () => {
expect(onCtrlConsumed).toHaveBeenCalledTimes(1)
})
})
class TestResizeObserver {
static instances: TestResizeObserver[] = []
readonly callback: ResizeObserverCallback
constructor(callback: ResizeObserverCallback) {
this.callback = callback
TestResizeObserver.instances.push(this)
}
observe() {}
unobserve() {}
disconnect() {}
trigger() {
this.callback([], this as unknown as ResizeObserver)
}
}
function setVisibleSize(container: HTMLElement) {
Object.defineProperty(container, 'clientWidth', { value: 800, configurable: true })
Object.defineProperty(container, 'clientHeight', { value: 400, configurable: true })
}
describe('TerminalView resize', () => {
beforeEach(() => {
vi.clearAllMocks()
TestResizeObserver.instances = []
vi.stubGlobal('ResizeObserver', TestResizeObserver)
vi.useFakeTimers()
})
afterEach(() => {
vi.useRealTimers()
vi.unstubAllGlobals()
})
it('sends a resize only when the fitted size changes', () => {
const { view } = renderView()
const container = view.container.querySelector('[data-terminal-id="t1"]') as HTMLElement
setVisibleSize(container)
act(() => {
vi.advanceTimersByTime(150)
})
expect(resizeTerminal).toHaveBeenCalledTimes(1)
act(() => {
TestResizeObserver.instances[0].trigger()
vi.advanceTimersByTime(150)
})
act(() => {
TestResizeObserver.instances[0].trigger()
vi.advanceTimersByTime(150)
})
expect(resizeTerminal).toHaveBeenCalledTimes(1)
})
it('does not send a resize while the view is hidden', () => {
const { view } = renderView({ active: false })
const container = view.container.querySelector('[data-terminal-id="t1"]') as HTMLElement
setVisibleSize(container)
act(() => {
vi.advanceTimersByTime(150)
})
expect(resizeTerminal).not.toHaveBeenCalled()
})
it('does not send a resize when the container has no size', () => {
renderView()
act(() => {
vi.advanceTimersByTime(150)
})
expect(resizeTerminal).not.toHaveBeenCalled()
})
})
@@ -14,22 +14,18 @@ const RESIZE_DEBOUNCE_MS = 150
const MONOSPACE_FONT = 'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace'
function defaultOpenLink(uri: string) {
window.open(uri, '_blank', 'noopener,noreferrer')
}
export interface TerminalViewHandle {
send: (data: string) => void
}
export interface TerminalViewProps {
interface TerminalViewProps {
repoId: number
directory: string | undefined
ptyID: string
active: boolean
ctrlArmed: boolean
onCtrlConsumed: () => void
onOpenLink?: (uri: string) => void
onOpenLink: (uri: string) => void
onExited: () => void
}
@@ -53,12 +49,15 @@ export const TerminalView = forwardRef<TerminalViewHandle, TerminalViewProps>(fu
const onExitedRef = useRef(onExited)
const isMobile = useMobile()
const isMobileRef = useRef(isMobile)
const activeRef = useRef(active)
const lastSizeRef = useRef<{ cols: number; rows: number } | null>(null)
ctrlArmedRef.current = ctrlArmed
onCtrlConsumedRef.current = onCtrlConsumed
onOpenLinkRef.current = onOpenLink
onExitedRef.current = onExited
isMobileRef.current = isMobile
activeRef.current = active
const handleOutput = useCallback((text: string) => {
terminalRef.current?.write(text)
@@ -105,8 +104,7 @@ export const TerminalView = forwardRef<TerminalViewHandle, TerminalViewProps>(fu
terminal.loadAddon(fitAddon)
terminal.loadAddon(
new WebLinksAddon((_event, uri) => {
const openLink = onOpenLinkRef.current ?? defaultOpenLink
openLink(uri)
onOpenLinkRef.current(uri)
}),
)
terminal.open(container)
@@ -161,12 +159,18 @@ export const TerminalView = forwardRef<TerminalViewHandle, TerminalViewProps>(fu
const terminal = terminalRef.current
const fitAddon = fitAddonRef.current
if (!terminal || !fitAddon) return
if (!activeRef.current) return
if (container.clientWidth === 0 || container.clientHeight === 0) return
try {
fitAddon.fit()
} catch {
return
}
resizeTerminal(repoId, ptyID, { directory, cols: terminal.cols, rows: terminal.rows }).catch(() => {})
const size = { cols: terminal.cols, rows: terminal.rows }
const lastSize = lastSizeRef.current
if (lastSize && lastSize.cols === size.cols && lastSize.rows === size.rows) return
lastSizeRef.current = size
resizeTerminal(repoId, ptyID, { directory, cols: size.cols, rows: size.rows }).catch(() => {})
}, RESIZE_DEBOUNCE_MS)
}