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

@@ -60,9 +60,20 @@ describe('buildMoreItems', () => {
expect(items[11].key).toBe('logout')
})
it('omits the Actions item for an Assistant session', () => {
const items = buildMoreItems('/repos/0/sessions/abc')
expect(items).toHaveLength(11)
expect(items.map((item) => item.key)).not.toContain('actions')
expect(items[7].key).toBe('terminal')
expect(items[8].key).toBe('preview')
expect(items[8].dialog).toBe('preview')
expect(items[9].key).toBe('settings')
expect(items[10].key).toBe('logout')
})
it('returns assistant workspace items for /repos/:id/assistant', () => {
const items = buildMoreItems('/repos/42/assistant')
expect(items).toHaveLength(10)
expect(items).toHaveLength(11)
expect(items[0].key).toBe('home')
expect(items[1].key).toBe('files')
expect(items[1].dialog).toBe('files')
@@ -73,8 +84,10 @@ describe('buildMoreItems', () => {
expect(items[6].key).toBe('source-control')
expect(items[7].key).toBe('terminal')
expect(items[7].dialog).toBe('terminal')
expect(items[8].key).toBe('settings')
expect(items[9].key).toBe('logout')
expect(items[8].key).toBe('preview')
expect(items[8].dialog).toBe('preview')
expect(items[9].key).toBe('settings')
expect(items[10].key).toBe('logout')
})
it('returns only Home + Settings + Logout for /schedules', () => {
@@ -1,5 +1,6 @@
import type { LucideIcon } from 'lucide-react'
import { Plug, Sparkles, ShieldOff, CalendarClock, GitCommitHorizontal, SquareTerminal, Settings, LogOut, Bot, Folder, Home, Play, Globe } from 'lucide-react'
import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
import { getAssistantPath, isAssistantPath } from '@/lib/navigation'
export interface MoreDrawerItem {
@@ -72,15 +73,19 @@ function buildRouteNavModel(pathname: string): NavModel {
const sessionDetailMatch = /^\/repos\/(\d+)\/sessions\/[^/]+$/.exec(pathname)
if (sessionDetailMatch) {
const repoId = sessionDetailMatch[1]
const isAssistantRepo = repoId === String(ASSISTANT_REPO_ID)
const items: MoreDrawerItem[] = [
{ key: 'files', label: 'Files', icon: Folder, dialog: 'files' },
{ key: 'mcp', label: 'MCP', icon: Plug, dialog: 'mcp' },
{ key: 'skills', label: 'Skills', icon: Sparkles, dialog: 'skills' },
{ key: 'reset-permissions', label: 'Reset Permissions', icon: ShieldOff, dialog: 'resetPermissions', danger: true },
{ key: 'schedules', label: 'Schedules', icon: CalendarClock, to: `/repos/${sessionDetailMatch[1]}/schedules` },
{ key: 'schedules', label: 'Schedules', icon: CalendarClock, to: `/repos/${repoId}/schedules` },
{ key: 'source-control', label: 'Source Control', icon: GitCommitHorizontal, dialog: 'sourceControl' },
{ key: 'terminal', label: 'Terminal', icon: SquareTerminal, dialog: 'terminal' },
{ key: 'actions', label: 'Actions', icon: Play, dialog: 'actions' },
...(isAssistantRepo
? []
: [{ key: 'actions', label: 'Actions', icon: Play, dialog: 'actions' }]),
{ key: 'preview', label: 'Preview', icon: Globe, dialog: 'preview' },
...baseItems,
]
@@ -100,6 +105,7 @@ function buildRouteNavModel(pathname: string): NavModel {
{ key: 'schedules', label: 'Schedules', icon: CalendarClock, to: '/repos/0/schedules' },
{ key: 'source-control', label: 'Source Control', icon: GitCommitHorizontal, dialog: 'sourceControl' },
{ key: 'terminal', label: 'Terminal', icon: SquareTerminal, dialog: 'terminal' },
{ key: 'preview', label: 'Preview', icon: Globe, dialog: 'preview' },
...baseItems,
]
@@ -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>
@@ -7,6 +7,7 @@ import { Input } from '@/components/ui/input'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { AlertCircle, GitBranch, Loader2 } from 'lucide-react'
import { createRepo, listBranches } from '@/api/repos'
import { dialogSearch } from '@/hooks/useDialogParam'
import { showToast } from '@/lib/toast'
import { notifyWorktreeSetup } from '@/lib/worktreeSetup'
import { invalidateRepoGitCaches } from '@/lib/queryInvalidation'
@@ -76,7 +77,7 @@ export function CreateWorktreeDialog({
onOpenChange(false)
notifyWorktreeSetup(repo.worktreeSetup)
if (repo.worktreeSetup?.status === 'started') {
navigate(`/repos/${repo.id}?dialog=terminal&terminal=${encodeURIComponent(repo.worktreeSetup.terminal.id)}`)
navigate(`/repos/${repo.id}${dialogSearch('terminal', { terminal: repo.worktreeSetup.terminal.id })}`)
}
},
onError: (err) => {
@@ -42,6 +42,11 @@ vi.mock('@/lib/toast', () => ({
const HASH = 'a'.repeat(64)
const OTHER_HASH = 'b'.repeat(64)
const repoExecutable: NonNullable<ProjectConfigResponse['repoFile']['executable']> = {
actions: [{ id: 'dev', name: 'Dev server', command: 'pnpm dev', url: null, autoOpenUrl: false }],
setup: [],
}
const devAction: ProjectConfigResponse['actions'][number] = {
id: 'dev',
name: 'Dev server',
@@ -67,11 +72,19 @@ const runningTerminal: TerminalInfo = {
function makeConfig(
actions: ProjectConfigResponse['actions'],
hash: string | null = null,
executable: ProjectConfigResponse['repoFile']['executable'] = null,
): ProjectConfigResponse {
return {
actions,
worktreeSetup: [],
repoFile: { path: '.ocm/project.json', exists: hash !== null, trusted: true, hash, warnings: [] },
repoFile: {
path: '.ocm/project.json',
exists: hash !== null,
trusted: true,
hash,
warnings: [],
executable,
},
}
}
@@ -142,8 +155,8 @@ describe('ProjectActionsMenu', () => {
})
it('trusts the repository config after a 409 and retries the run', async () => {
mocks.useProjectConfig.mockReturnValue({ data: makeConfig([repoAction], HASH), isLoading: false, error: null })
mocks.getProjectConfig.mockResolvedValue(makeConfig([repoAction], HASH))
mocks.useProjectConfig.mockReturnValue({ data: makeConfig([repoAction], HASH, repoExecutable), isLoading: false, error: null })
mocks.getProjectConfig.mockResolvedValue(makeConfig([repoAction], HASH, repoExecutable))
let runCalls = 0
mocks.runMutate.mockImplementation((_actionId, options) => {
runCalls += 1
@@ -171,10 +184,52 @@ describe('ProjectActionsMenu', () => {
)
})
it('lists every executable action and setup command, including shadowed actions', async () => {
const executable: NonNullable<ProjectConfigResponse['repoFile']['executable']> = {
actions: [
{ id: 'dev', name: 'Dev server', command: 'pnpm dev', url: 'http://localhost:3000', autoOpenUrl: true },
{ id: 'shadowed', name: 'Shadowed action', command: 'pnpm shadowed', url: null, autoOpenUrl: false },
],
setup: ['pnpm install'],
}
mocks.useProjectConfig.mockReturnValue({ data: makeConfig([repoAction], HASH, executable), isLoading: false, error: null })
mocks.getProjectConfig.mockResolvedValue(makeConfig([repoAction], HASH, executable))
mocks.runMutate.mockImplementation((_actionId, options) => options.onError(untrustedError(HASH)))
const user = userEvent.setup()
renderMenu()
await user.click(screen.getByRole('button', { name: 'Project actions' }))
await user.click(await screen.findByRole('menuitem', { name: /dev server/i }))
expect(await screen.findByText('Trust repository actions')).toBeInTheDocument()
expect(await screen.findByText('Actions')).toBeInTheDocument()
expect(screen.getByText('Shadowed action')).toBeInTheDocument()
expect(screen.getByText('pnpm shadowed')).toBeInTheDocument()
expect(screen.getByText('http://localhost:3000')).toBeInTheDocument()
expect(screen.getByText('Opens URL automatically')).toBeInTheDocument()
expect(screen.getByText('Worktree setup commands')).toBeInTheDocument()
expect(screen.getByText('pnpm install')).toBeInTheDocument()
})
it('does not offer trust when the snapshot has no executable commands', async () => {
mocks.useProjectConfig.mockReturnValue({ data: makeConfig([repoAction], HASH), isLoading: false, error: null })
mocks.getProjectConfig.mockResolvedValue(makeConfig([repoAction], HASH))
mocks.runMutate.mockImplementation((_actionId, options) => options.onError(untrustedError(HASH)))
const user = userEvent.setup()
renderMenu()
await user.click(screen.getByRole('button', { name: 'Project actions' }))
await user.click(await screen.findByRole('menuitem', { name: /dev server/i }))
await waitFor(() => expect(mocks.showToastError).toHaveBeenCalled())
expect(screen.queryByText('Trust repository actions')).not.toBeInTheDocument()
expect(mocks.trustMutate).not.toHaveBeenCalled()
})
it('shows the freshly verified command when the cached config is stale', async () => {
const staleAction: ProjectConfigResponse['actions'][number] = { ...repoAction, command: 'pnpm dev:stale' }
mocks.useProjectConfig.mockReturnValue({ data: makeConfig([staleAction], HASH), isLoading: false, error: null })
mocks.getProjectConfig.mockResolvedValue(makeConfig([repoAction], HASH))
mocks.useProjectConfig.mockReturnValue({ data: makeConfig([staleAction], HASH, repoExecutable), isLoading: false, error: null })
mocks.getProjectConfig.mockResolvedValue(makeConfig([repoAction], HASH, repoExecutable))
mocks.runMutate.mockImplementation((_actionId, options) => options.onError(untrustedError(HASH)))
const user = userEvent.setup()
renderMenu()
@@ -187,8 +242,8 @@ describe('ProjectActionsMenu', () => {
})
it('refuses confirmation when the fresh hash differs from the 409 hash', async () => {
mocks.useProjectConfig.mockReturnValue({ data: makeConfig([repoAction], HASH), isLoading: false, error: null })
mocks.getProjectConfig.mockResolvedValue(makeConfig([repoAction], OTHER_HASH))
mocks.useProjectConfig.mockReturnValue({ data: makeConfig([repoAction], HASH, repoExecutable), isLoading: false, error: null })
mocks.getProjectConfig.mockResolvedValue(makeConfig([repoAction], OTHER_HASH, repoExecutable))
mocks.runMutate.mockImplementation((_actionId, options) => options.onError(untrustedError(HASH)))
const user = userEvent.setup()
renderMenu()
@@ -202,8 +257,8 @@ describe('ProjectActionsMenu', () => {
})
it('refuses confirmation when the action is no longer a repository action', async () => {
mocks.useProjectConfig.mockReturnValue({ data: makeConfig([repoAction], HASH), isLoading: false, error: null })
mocks.getProjectConfig.mockResolvedValue(makeConfig([devAction], HASH))
mocks.useProjectConfig.mockReturnValue({ data: makeConfig([repoAction], HASH, repoExecutable), isLoading: false, error: null })
mocks.getProjectConfig.mockResolvedValue(makeConfig([devAction], HASH, repoExecutable))
mocks.runMutate.mockImplementation((_actionId, options) => options.onError(untrustedError(HASH)))
const user = userEvent.setup()
renderMenu()
@@ -217,8 +272,8 @@ describe('ProjectActionsMenu', () => {
})
it('cancels a pending confirmation when the directory changes', async () => {
mocks.useProjectConfig.mockReturnValue({ data: makeConfig([repoAction], HASH), isLoading: false, error: null })
mocks.getProjectConfig.mockResolvedValue(makeConfig([repoAction], HASH))
mocks.useProjectConfig.mockReturnValue({ data: makeConfig([repoAction], HASH, repoExecutable), isLoading: false, error: null })
mocks.getProjectConfig.mockResolvedValue(makeConfig([repoAction], HASH, repoExecutable))
mocks.runMutate.mockImplementation((_actionId, options) => options.onError(untrustedError(HASH)))
const user = userEvent.setup()
const capturedSearch: { current: string } = { current: '' }
@@ -237,8 +292,8 @@ describe('ProjectActionsMenu', () => {
})
it('does not retry the run when the trust response arrives after switching directory', async () => {
mocks.useProjectConfig.mockReturnValue({ data: makeConfig([repoAction], HASH), isLoading: false, error: null })
mocks.getProjectConfig.mockResolvedValue(makeConfig([repoAction], HASH))
mocks.useProjectConfig.mockReturnValue({ data: makeConfig([repoAction], HASH, repoExecutable), isLoading: false, error: null })
mocks.getProjectConfig.mockResolvedValue(makeConfig([repoAction], HASH, repoExecutable))
mocks.runMutate.mockImplementation((_actionId, options) => options.onError(untrustedError(HASH)))
let trustOptions: { onSuccess: () => void } | undefined
mocks.trustMutate.mockImplementation((_vars, options) => {
@@ -1,23 +1,12 @@
import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import type { TerminalInfo } from '@opencode-manager/shared/types'
import { FetchError } from '@opencode-manager/shared'
import { isRunningActionTerminal } from '@opencode-manager/shared/utils'
import type {
ProjectActionIcon,
ProjectConfigResponse,
RunProjectActionResponse,
} from '@opencode-manager/shared/types'
import {
Bug,
CheckCircle2,
FlaskConical,
Hammer,
Play,
Rocket,
Server,
Square,
SquareTerminal,
type LucideIcon,
} from 'lucide-react'
import { Play, Square } from 'lucide-react'
import {
getProjectConfig,
useProjectConfig,
@@ -37,20 +26,13 @@ import {
} from '@/components/ui/dropdown-menu'
import { openDialogParam } from '@/hooks/useDialogParam'
import { useOpenPreview } from '@/hooks/useOpenPreview'
import { useOpenTerminal } from '@/hooks/useOpenTerminal'
import { useUrlParams } from '@/hooks/useUrlParams'
import { getOpenCodeApiErrorMessage } from '@/lib/opencode-errors'
import { openUrlFromManager } from '@/lib/open-url'
import { showToast } from '@/lib/toast'
const ACTION_ICONS: Record<ProjectActionIcon, LucideIcon> = {
play: Play,
build: Hammer,
test: FlaskConical,
lint: CheckCircle2,
terminal: SquareTerminal,
server: Server,
bug: Bug,
rocket: Rocket,
}
import { TrustExecutableList } from './TrustExecutableList'
import { actionIcon } from './projectActionIcons'
interface ProjectActionsMenuProps {
repoId: number
@@ -61,7 +43,7 @@ interface PendingTrust {
actionId: string
hash: string
directory: string
command: string
executable: NonNullable<ProjectConfigResponse['repoFile']['executable']>
}
function untrustedHash(error: unknown): string | null {
@@ -73,14 +55,11 @@ function untrustedHash(error: unknown): string | null {
return null
}
function errorMessage(error: unknown, fallback: string): string {
return error instanceof Error ? error.message : fallback
}
export function ProjectActionsMenu({ repoId, directory }: ProjectActionsMenuProps) {
const [menuOpen, setMenuOpen] = useState(false)
const { updateParams } = useUrlParams()
const openPreview = useOpenPreview()
const openTerminal = useOpenTerminal()
const configQuery = useProjectConfig(repoId, directory, menuOpen && !!directory)
const terminalsQuery = useTerminals(repoId, directory, {
enabled: menuOpen && !!directory,
@@ -105,7 +84,7 @@ export function ProjectActionsMenu({ repoId, directory }: ProjectActionsMenuProp
const runningByAction = useMemo(() => {
const map = new Map<string, TerminalInfo>()
for (const terminal of terminalsQuery.data ?? []) {
if (terminal.kind === 'action' && terminal.actionId && terminal.status === 'running') {
if (terminal.actionId && isRunningActionTerminal(terminal, terminal.actionId)) {
map.set(terminal.actionId, terminal)
}
}
@@ -113,15 +92,11 @@ export function ProjectActionsMenu({ repoId, directory }: ProjectActionsMenuProp
}, [terminalsQuery.data])
const handleRunSuccess = useCallback((result: RunProjectActionResponse) => {
updateParams((params) => {
params.set('dialog', 'terminal')
params.set('terminal', result.terminal.id)
params.delete('mobileTab')
}, 'push')
openTerminal(result.terminal.id)
if (result.autoOpenUrl && result.resolvedUrl) {
openUrlFromManager(result.resolvedUrl, { openPreview })
}
}, [updateParams, openPreview])
}, [openTerminal, openPreview])
const requestTrustConfirmation = useCallback(async (actionId: string, hash: string) => {
const requestDirectory = directory
@@ -130,7 +105,7 @@ export function ProjectActionsMenu({ repoId, directory }: ProjectActionsMenuProp
try {
snapshot = await getProjectConfig(repoId, requestDirectory)
} catch (error) {
showToast.error(errorMessage(error, 'Failed to verify repository actions'))
showToast.error(getOpenCodeApiErrorMessage(error, 'Failed to verify repository actions'))
return
}
const scope = scopeRef.current
@@ -138,11 +113,12 @@ export function ProjectActionsMenu({ repoId, directory }: ProjectActionsMenuProp
const repoAction = snapshot.actions.find(
(action) => action.id === actionId && action.source === 'repo',
)
if (snapshot.repoFile.hash !== hash || !repoAction) {
const executable = snapshot.repoFile.executable
if (snapshot.repoFile.hash !== hash || !repoAction || !executable) {
showToast.error('Repository actions changed. Reopen the menu to review them.')
return
}
setPendingTrust({ actionId, hash, directory: requestDirectory, command: repoAction.command })
setPendingTrust({ actionId, hash, directory: requestDirectory, executable })
}, [directory, repoId])
const startRun = useCallback((actionId: string) => {
@@ -154,7 +130,7 @@ export function ProjectActionsMenu({ repoId, directory }: ProjectActionsMenuProp
void requestTrustConfirmation(actionId, hash)
return
}
showToast.error(errorMessage(error, 'Failed to run action'))
showToast.error(getOpenCodeApiErrorMessage(error, 'Failed to run action'))
},
})
}, [runAction, handleRunSuccess, requestTrustConfirmation])
@@ -170,13 +146,13 @@ export function ProjectActionsMenu({ repoId, directory }: ProjectActionsMenuProp
setPendingTrust(null)
startRun(actionId)
},
onError: (error) => showToast.error(errorMessage(error, 'Failed to trust repository commands')),
onError: (error) => showToast.error(getOpenCodeApiErrorMessage(error, 'Failed to trust repository commands')),
})
}, [pendingTrust, trustConfig, startRun, repoId])
const handleStop = useCallback((terminal: TerminalInfo) => {
removeTerminal.mutate({ ptyID: terminal.id, directory }, {
onError: (error) => showToast.error(errorMessage(error, 'Failed to stop action')),
onError: (error) => showToast.error(getOpenCodeApiErrorMessage(error, 'Failed to stop action')),
})
}, [removeTerminal, directory])
@@ -206,7 +182,7 @@ export function ProjectActionsMenu({ repoId, directory }: ProjectActionsMenuProp
</DropdownMenuLabel>
) : (
actions.map((action) => {
const Icon = ACTION_ICONS[action.icon ?? 'play']
const Icon = actionIcon(action.icon)
const running = runningByAction.get(action.id)
return (
<Fragment key={action.id}>
@@ -242,7 +218,7 @@ export function ProjectActionsMenu({ repoId, directory }: ProjectActionsMenuProp
onCancel={() => setPendingTrust(null)}
title="Trust repository actions"
description="This repository defines commands that run on your machine."
warning={pendingTrust?.command}
warning={pendingTrust ? <TrustExecutableList executable={pendingTrust.executable} /> : undefined}
confirmLabel="Trust and run"
pendingLabel="Trusting…"
isPending={trustConfig.isPending}
@@ -1,6 +1,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { FetchError } from '@opencode-manager/shared'
import { RepoActionsDialog } from './RepoActionsDialog'
import type { ProjectConfigResponse } from '@opencode-manager/shared/types'
@@ -31,7 +32,14 @@ function baseConfig(overrides: Partial<ProjectConfigResponse> = {}): ProjectConf
return {
actions: [],
worktreeSetup: [],
repoFile: { path: '.ocm/project.json', exists: false, trusted: false, hash: null, warnings: [] },
repoFile: {
path: '.ocm/project.json',
exists: false,
trusted: false,
hash: null,
warnings: [],
executable: null,
},
...overrides,
}
}
@@ -119,7 +127,19 @@ describe('RepoActionsDialog', () => {
actions: [
{ id: 'repo-1', name: 'Repo action', command: 'echo repo', autoOpenUrl: false, source: 'repo' },
],
repoFile: { path: '.ocm/project.json', exists: true, trusted: false, hash: HASH, warnings: [] },
repoFile: {
path: '.ocm/project.json',
exists: true,
trusted: false,
hash: HASH,
warnings: [],
executable: {
actions: [
{ id: 'repo-1', name: 'Repo action', command: 'echo repo', url: null, autoOpenUrl: false },
],
setup: [],
},
},
}),
)
const user = userEvent.setup()
@@ -131,10 +151,74 @@ describe('RepoActionsDialog', () => {
expect(mocks.trustMutate.mock.calls[0][0]).toEqual({ hash: HASH, directory: '/repo' })
})
it('lists every executable action and setup command, including shadowed actions', () => {
mockConfig(
baseConfig({
actions: [
{ id: 'shared', name: 'My action', command: 'echo personal', autoOpenUrl: false, source: 'personal' },
],
repoFile: {
path: '.ocm/project.json',
exists: true,
trusted: false,
hash: HASH,
warnings: [],
executable: {
actions: [
{ id: 'shared', name: 'Repo action', command: 'echo repo', url: 'https://example.com', autoOpenUrl: true },
],
setup: ['pnpm install'],
},
},
}),
)
renderDialog()
expect(screen.getAllByText('Actions').length).toBeGreaterThan(1)
expect(screen.getByText('Repo action')).toBeInTheDocument()
expect(screen.getByText('echo repo')).toBeInTheDocument()
expect(screen.getByText('https://example.com')).toBeInTheDocument()
expect(screen.getByText('Opens URL automatically')).toBeInTheDocument()
expect(screen.getByText('Worktree setup commands')).toBeInTheDocument()
expect(screen.getByText('pnpm install')).toBeInTheDocument()
})
it('does not offer trust when the repo file has no executable commands', () => {
mockConfig(
baseConfig({
repoFile: { path: '.ocm/project.json', exists: true, trusted: false, hash: HASH, warnings: [], executable: null },
}),
)
renderDialog()
expect(screen.queryByText(/not trusted/i)).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: /trust these commands/i })).not.toBeInTheDocument()
})
it('uses the shared action icon map', () => {
mockConfig(
baseConfig({
actions: [
{ id: 'deploy', name: 'Deploy', command: 'pnpm deploy', icon: 'rocket', autoOpenUrl: false, source: 'personal' },
],
}),
)
const { container } = renderDialog()
expect(container.ownerDocument.querySelector('.lucide-rocket')).not.toBeNull()
})
it('hides the trust banner for a trusted repo file', () => {
mockConfig(
baseConfig({
repoFile: { path: '.ocm/project.json', exists: true, trusted: true, hash: HASH, warnings: [] },
repoFile: {
path: '.ocm/project.json',
exists: true,
trusted: true,
hash: HASH,
warnings: [],
executable: null,
},
}),
)
renderDialog()
@@ -152,6 +236,7 @@ describe('RepoActionsDialog', () => {
hash: null,
error: 'Invalid repository config',
warnings: [],
executable: null,
},
}),
)
@@ -206,7 +291,7 @@ describe('RepoActionsDialog', () => {
)
mocks.updateActionsMutate.mockImplementation(
(_payload: unknown, options?: { onError?: (error: unknown) => void }) => {
options?.onError?.(new Error('Server rejected the action'))
options?.onError?.(new FetchError('Server rejected the action', 400))
},
)
const user = userEvent.setup()
@@ -230,7 +315,7 @@ describe('RepoActionsDialog', () => {
)
mocks.updateSetupMutate.mockImplementation(
(_commands: unknown, options?: { onError?: (error: unknown) => void }) => {
options?.onError?.(new Error('Setup save rejected'))
options?.onError?.(new FetchError('Setup save rejected', 400))
},
)
const user = userEvent.setup()
@@ -251,12 +336,24 @@ describe('RepoActionsDialog', () => {
actions: [
{ id: 'repo-1', name: 'Repo action', command: 'echo repo', autoOpenUrl: false, source: 'repo' },
],
repoFile: { path: '.ocm/project.json', exists: true, trusted: false, hash: HASH, warnings: [] },
repoFile: {
path: '.ocm/project.json',
exists: true,
trusted: false,
hash: HASH,
warnings: [],
executable: {
actions: [
{ id: 'repo-1', name: 'Repo action', command: 'echo repo', url: null, autoOpenUrl: false },
],
setup: [],
},
},
}),
)
mocks.trustMutate.mockImplementation(
(_request: unknown, options?: { onError?: (error: unknown) => void }) => {
options?.onError?.(new Error('Trust rejected'))
options?.onError?.(new FetchError('Trust rejected', 400))
},
)
const user = userEvent.setup()
@@ -277,7 +374,7 @@ describe('RepoActionsDialog', () => {
)
mocks.moveMutate.mockImplementation(
(_request: unknown, options?: { onError?: (error: unknown) => void }) => {
options?.onError?.(new Error('Move rejected'))
options?.onError?.(new FetchError('Move rejected', 400))
},
)
const user = userEvent.setup()
@@ -309,7 +406,7 @@ describe('RepoActionsDialog', () => {
{ id: 'added', name: 'Added', command: 'pnpm dev', autoOpenUrl: false, source: 'personal' },
],
worktreeSetup: [{ command: 'pnpm install', source: 'personal' }],
repoFile: { path: '.ocm/project.json', exists: true, trusted: true, hash: HASH, warnings: [] },
repoFile: { path: '.ocm/project.json', exists: true, trusted: true, hash: HASH, warnings: [], executable: null },
}),
)
view.rerender(<RepoActionsDialog repoId={1} directory="/repo" open onOpenChange={vi.fn()} />)
@@ -1,22 +1,6 @@
import { useEffect, useMemo, useRef, useState } from 'react'
import {
ArrowDown,
ArrowUp,
Bug,
CheckCircle2,
FlaskConical,
Hammer,
Loader2,
Pencil,
Play,
Plus,
Rocket,
Server,
ShieldAlert,
SquareTerminal,
Trash2,
type LucideIcon,
} from 'lucide-react'
import { ArrowDown, ArrowUp, Loader2, Pencil, Plus, ShieldAlert, Trash2 } from 'lucide-react'
import { arrayMove } from '@dnd-kit/sortable'
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
@@ -32,23 +16,15 @@ import {
useUpdateWorktreeSetup,
} from '@/api/projectConfig'
import { showToast } from '@/lib/toast'
import { getOpenCodeApiErrorMessage } from '@/lib/opencode-errors'
import { randomId } from '@/lib/utils'
import type { ProjectAction, ProjectActionIcon, ProjectItemSource } from '@opencode-manager/shared/types'
const ACTION_ICON_OPTIONS: { value: ProjectActionIcon; label: string; Icon: LucideIcon }[] = [
{ value: 'play', label: 'Play', Icon: Play },
{ value: 'build', label: 'Build', Icon: Hammer },
{ value: 'test', label: 'Test', Icon: FlaskConical },
{ value: 'lint', label: 'Lint', Icon: CheckCircle2 },
{ value: 'terminal', label: 'Terminal', Icon: SquareTerminal },
{ value: 'server', label: 'Server', Icon: Server },
{ value: 'bug', label: 'Bug', Icon: Bug },
{ value: 'rocket', label: 'Rocket', Icon: Rocket },
]
function actionIcon(icon: ProjectActionIcon | undefined): LucideIcon {
return ACTION_ICON_OPTIONS.find((option) => option.value === icon)?.Icon ?? Play
}
import type {
ProjectAction,
ProjectActionIcon,
ProjectItemSource,
} from '@opencode-manager/shared/types'
import { ACTION_ICON_OPTIONS, actionIcon } from './projectActionIcons'
import { TrustExecutableList } from './TrustExecutableList'
interface ActionDraft {
id: string
@@ -99,17 +75,6 @@ function draftToPayload(draft: ActionDraft): ProjectAction {
return payload
}
function moveArrayItem<T>(items: T[], from: number, to: number): T[] {
const next = [...items]
const [item] = next.splice(from, 1)
next.splice(to, 0, item)
return next
}
function mutationErrorMessage(error: unknown, fallback: string): string {
return error instanceof Error ? error.message : fallback
}
interface ActionFormProps {
draft: ActionDraft
isSaving: boolean
@@ -250,19 +215,19 @@ export function RepoActionsDialog({ repoId, directory, open, onOpenChange }: Rep
: [...personalActions.map(actionToPayload), payload]
updateActions.mutate(next, {
onSuccess: () => setDraft(null),
onError: (error) => showToast.error(mutationErrorMessage(error, 'Failed to save action')),
onError: (error) => showToast.error(getOpenCodeApiErrorMessage(error, 'Failed to save action')),
})
}
const handleDeleteAction = (id: string) => {
updateActions.mutate(personalActions.filter((action) => action.id !== id).map(actionToPayload), {
onError: (error) => showToast.error(mutationErrorMessage(error, 'Failed to delete action')),
onError: (error) => showToast.error(getOpenCodeApiErrorMessage(error, 'Failed to delete action')),
})
}
const handleSaveSetup = () => {
updateSetup.mutate(setupCommands.map((command) => command.trim()), {
onError: (error) => showToast.error(mutationErrorMessage(error, 'Failed to save setup commands')),
onError: (error) => showToast.error(getOpenCodeApiErrorMessage(error, 'Failed to save setup commands')),
})
}
@@ -270,21 +235,21 @@ export function RepoActionsDialog({ repoId, directory, open, onOpenChange }: Rep
if (!config?.repoFile.hash) return
trustConfig.mutate(
{ hash: config.repoFile.hash, directory },
{ onError: (error) => showToast.error(mutationErrorMessage(error, 'Failed to trust repository commands')) },
{ onError: (error) => showToast.error(getOpenCodeApiErrorMessage(error, 'Failed to trust repository commands')) },
)
}
const moveAction = (action: ProjectAction, to: ProjectItemSource) => {
moveItem.mutate(
{ kind: 'action', id: action.id, to, directory },
{ onError: (error) => showToast.error(mutationErrorMessage(error, 'Failed to move action')) },
{ onError: (error) => showToast.error(getOpenCodeApiErrorMessage(error, 'Failed to move action')) },
)
}
const moveSetup = (command: string, to: ProjectItemSource) => {
moveItem.mutate(
{ kind: 'setup', command, to, directory },
{ onError: (error) => showToast.error(mutationErrorMessage(error, 'Failed to move setup command')) },
{ onError: (error) => showToast.error(getOpenCodeApiErrorMessage(error, 'Failed to move setup command')) },
)
}
@@ -454,7 +419,7 @@ export function RepoActionsDialog({ repoId, directory, open, onOpenChange }: Rep
variant="ghost"
aria-label="Move up"
disabled={index === 0}
onClick={() => setSetupCommands((current) => moveArrayItem(current, index, index - 1))}
onClick={() => setSetupCommands((current) => arrayMove(current, index, index - 1))}
>
<ArrowUp className="h-4 w-4" />
</Button>
@@ -464,7 +429,7 @@ export function RepoActionsDialog({ repoId, directory, open, onOpenChange }: Rep
variant="ghost"
aria-label="Move down"
disabled={index === setupCommands.length - 1}
onClick={() => setSetupCommands((current) => moveArrayItem(current, index, index + 1))}
onClick={() => setSetupCommands((current) => arrayMove(current, index, index + 1))}
>
<ArrowDown className="h-4 w-4" />
</Button>
@@ -545,33 +510,24 @@ export function RepoActionsDialog({ repoId, directory, open, onOpenChange }: Rep
{warning}
</p>
))}
{config.repoFile.exists && !config.repoFile.trusted && config.repoFile.hash && (
<div className="rounded-lg border border-warning/50 bg-warning/10 p-3 space-y-2">
<div className="flex items-center gap-2 text-sm font-medium">
<ShieldAlert className="h-4 w-4 text-warning" />
Repository commands are not trusted
{config.repoFile.exists &&
!config.repoFile.trusted &&
config.repoFile.hash &&
config.repoFile.executable && (
<div className="rounded-lg border border-warning/50 bg-warning/10 p-3 space-y-2">
<div className="flex items-center gap-2 text-sm font-medium">
<ShieldAlert className="h-4 w-4 text-warning" />
Repository commands are not trusted
</div>
<p className="text-xs text-muted-foreground">
This repository defines commands that run on your machine. Review and trust them to enable.
</p>
<TrustExecutableList executable={config.repoFile.executable} />
<Button type="button" size="sm" onClick={handleTrust} disabled={trustConfig.isPending}>
Trust these commands
</Button>
</div>
<p className="text-xs text-muted-foreground">
This repository defines commands that run on your machine. Review and trust them to enable.
</p>
<ul className="space-y-1">
{repoActions.map((action) => (
<li key={action.id} className="font-mono text-xs">
{action.command}
{action.url ? ` — ${action.url}` : ''}
</li>
))}
{repoSetup.map((item) => (
<li key={item.command} className="font-mono text-xs">
{item.command}
</li>
))}
</ul>
<Button type="button" size="sm" onClick={handleTrust} disabled={trustConfig.isPending}>
Trust these commands
</Button>
</div>
)}
)}
</section>
</>
)}
@@ -0,0 +1,37 @@
import type { ProjectConfigResponse } from '@opencode-manager/shared/types'
type RepoFileExecutable = NonNullable<ProjectConfigResponse['repoFile']['executable']>
export function TrustExecutableList({ executable }: { executable: RepoFileExecutable }) {
return (
<div className="max-h-64 space-y-3 overflow-y-auto">
{executable.actions.length > 0 && (
<div className="space-y-1">
<p className="text-xs font-medium">Actions</p>
<ul className="space-y-1">
{executable.actions.map((action) => (
<li key={action.id} className="space-y-0.5">
<p className="text-xs font-medium">{action.name}</p>
<p className="font-mono text-xs">{action.command}</p>
{action.url && <p className="font-mono text-xs">{action.url}</p>}
{action.autoOpenUrl && <p className="text-xs">Opens URL automatically</p>}
</li>
))}
</ul>
</div>
)}
{executable.setup.length > 0 && (
<div className="space-y-1">
<p className="text-xs font-medium">Worktree setup commands</p>
<ul className="space-y-1">
{executable.setup.map((command, index) => (
<li key={`${index}-${command}`} className="font-mono text-xs">
{command}
</li>
))}
</ul>
</div>
)}
</div>
)
}
@@ -0,0 +1,27 @@
import {
Bug,
CheckCircle2,
FlaskConical,
Hammer,
Play,
Rocket,
Server,
SquareTerminal,
type LucideIcon,
} from 'lucide-react'
import type { ProjectActionIcon } from '@opencode-manager/shared/types'
export const ACTION_ICON_OPTIONS: { value: ProjectActionIcon; label: string; Icon: LucideIcon }[] = [
{ value: 'play', label: 'Play', Icon: Play },
{ value: 'build', label: 'Build', Icon: Hammer },
{ value: 'test', label: 'Test', Icon: FlaskConical },
{ value: 'lint', label: 'Lint', Icon: CheckCircle2 },
{ value: 'terminal', label: 'Terminal', Icon: SquareTerminal },
{ value: 'server', label: 'Server', Icon: Server },
{ value: 'bug', label: 'Bug', Icon: Bug },
{ value: 'rocket', label: 'Rocket', Icon: Rocket },
]
export function actionIcon(icon: ProjectActionIcon | undefined): LucideIcon {
return ACTION_ICON_OPTIONS.find((option) => option.value === icon)?.Icon ?? Play
}
@@ -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)
}