section 16: Phase 16: Documentation, container ports and full repository checks

This commit is contained in:
Chris Scott committed 2026-10-03 04:07:44 -04:00
1 parent 81a9f0c8ef
commit a383e57bc5
55 files changed
+4095 -59

No files matched your search

@@ -14,7 +14,7 @@ describe('buildMoreItems', () => {
it('returns repo-specific items for /repos/:id', () => {
const items = buildMoreItems('/repos/42')
expect(items).toHaveLength(11)
expect(items).toHaveLength(12)
expect(items[0].key).toBe('home')
expect(items[1].key).toBe('files')
expect(items[1].dialog).toBe('files')
@@ -33,13 +33,15 @@ describe('buildMoreItems', () => {
expect(items[7].dialog).toBe('terminal')
expect(items[8].key).toBe('actions')
expect(items[8].dialog).toBe('actions')
expect(items[9].key).toBe('settings')
expect(items[10].key).toBe('logout')
expect(items[9].key).toBe('preview')
expect(items[9].dialog).toBe('preview')
expect(items[10].key).toBe('settings')
expect(items[11].key).toBe('logout')
})
it('returns session-specific items for /repos/:id/sessions/:sid', () => {
const items = buildMoreItems('/repos/42/sessions/abc')
expect(items).toHaveLength(11)
expect(items).toHaveLength(12)
expect(items[0].key).toBe('home')
expect(items[1].key).toBe('files')
expect(items[2].key).toBe('mcp')
@@ -52,8 +54,10 @@ describe('buildMoreItems', () => {
expect(items[7].dialog).toBe('terminal')
expect(items[8].key).toBe('actions')
expect(items[8].dialog).toBe('actions')
expect(items[9].key).toBe('settings')
expect(items[10].key).toBe('logout')
expect(items[9].key).toBe('preview')
expect(items[9].dialog).toBe('preview')
expect(items[10].key).toBe('settings')
expect(items[11].key).toBe('logout')
})
it('returns assistant workspace items for /repos/:id/assistant', () => {
@@ -1,5 +1,5 @@
import type { LucideIcon } from 'lucide-react'
import { Plug, Sparkles, ShieldOff, CalendarClock, GitCommitHorizontal, SquareTerminal, Settings, LogOut, Bot, Folder, Home, Play } from 'lucide-react'
import { Plug, Sparkles, ShieldOff, CalendarClock, GitCommitHorizontal, SquareTerminal, Settings, LogOut, Bot, Folder, Home, Play, Globe } from 'lucide-react'
import { getAssistantPath, isAssistantPath } from '@/lib/navigation'
export interface MoreDrawerItem {
@@ -60,6 +60,7 @@ function buildRouteNavModel(pathname: string): NavModel {
{ 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' },
{ key: 'preview', label: 'Preview', icon: Globe, dialog: 'preview' },
...baseItems,
]
@@ -80,6 +81,7 @@ function buildRouteNavModel(pathname: string): NavModel {
{ 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' },
{ key: 'preview', label: 'Preview', icon: Globe, dialog: 'preview' },
...baseItems,
]
@@ -0,0 +1,224 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter } from 'react-router-dom'
import type { CreatePreviewSessionResponse } from '@opencode-manager/shared/types'
import { createPreviewSession, usePreviewPorts } from '@/api/preview'
import { PreviewPanel } from './PreviewPanel'
vi.mock('@/api/preview', () => ({
usePreviewPorts: vi.fn(),
createPreviewSession: vi.fn(),
}))
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' }],
}
let portsState: PreviewPortsResult['data'] = portsData
const DEFAULT_ENTRY = '/repos/1?dialog=preview&previewPort=5173'
function deferred<T>() {
let resolve!: (value: T) => void
let reject!: (reason?: unknown) => void
const promise = new Promise<T>((res, rej) => {
resolve = res
reject = rej
})
return { promise, resolve, reject }
}
function panelElement(initialEntry: string) {
return (
<MemoryRouter initialEntries={[initialEntry]}>
<PreviewPanel isOpen onClose={vi.fn()} directory="/repo" />
</MemoryRouter>
)
}
function renderPanel(initialEntry = DEFAULT_ENTRY) {
const result = render(panelElement(initialEntry))
return {
...result,
refresh: () => result.rerender(panelElement(initialEntry)),
}
}
describe('PreviewPanel', () => {
beforeEach(() => {
vi.resetAllMocks()
portsState = portsData
vi.mocked(usePreviewPorts).mockImplementation(
() =>
({
data: portsState,
isLoading: false,
refetch: vi.fn(),
}) as unknown as PreviewPortsResult,
)
vi.mocked(createPreviewSession).mockResolvedValue({ token: 'tok', previewPort: 5004, publicUrl: null })
})
it('renders the iframe with the start URL and sandbox for a listed port', async () => {
renderPanel()
const iframe = await screen.findByTitle('Preview')
expect(iframe).toHaveAttribute('src', 'http://localhost:5004/__ocm_preview/start?token=tok&path=%2F')
expect(iframe.getAttribute('sandbox')).toContain('allow-scripts')
expect(iframe.getAttribute('sandbox')).toContain('allow-same-origin')
})
it('creates a session and renders the iframe when a port is selected', async () => {
const user = userEvent.setup()
renderPanel('/repos/1?dialog=preview')
await user.click(screen.getByRole('button', { name: /:5173/ }))
const iframe = await screen.findByTitle('Preview')
expect(iframe).toHaveAttribute('src', 'http://localhost:5004/__ocm_preview/start?token=tok&path=%2F')
expect(createPreviewSession).toHaveBeenCalledWith(5173)
})
it('refuses to render an iframe when the preview origin is the manager origin', async () => {
vi.mocked(createPreviewSession).mockResolvedValue({
token: 'tok',
previewPort: 5004,
publicUrl: 'http://localhost',
})
renderPanel()
expect(await screen.findByRole('alert')).toHaveTextContent(/different origin/i)
expect(screen.queryByTitle('Preview')).not.toBeInTheDocument()
})
it('shows a waiting state for a port that is not listening', () => {
renderPanel('/repos/1?dialog=preview&previewPort=6000')
expect(screen.getByText(/Waiting for port 6000/)).toBeInTheDocument()
expect(createPreviewSession).not.toHaveBeenCalled()
})
it('renders the disabled state', () => {
portsState = { enabled: false, ports: [] }
renderPanel('/repos/1?dialog=preview')
expect(screen.getByText(/Preview is disabled/)).toBeInTheDocument()
})
it('badges ports that run inside the directory', () => {
renderPanel('/repos/1?dialog=preview')
expect(screen.getByText('this repo')).toBeInTheDocument()
})
it('mints a fresh session when a listed port disappears and comes back', async () => {
const first = deferred<CreatePreviewSessionResponse>()
const second = deferred<CreatePreviewSessionResponse>()
vi.mocked(createPreviewSession).mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise)
const panel = renderPanel()
first.resolve({ token: 'tok-1', previewPort: 5004, publicUrl: null })
expect((await screen.findByTitle('Preview')).getAttribute('src')).toContain('token=tok-1')
portsState = { enabled: true, ports: [] }
panel.refresh()
expect(screen.queryByTitle('Preview')).not.toBeInTheDocument()
expect(screen.getByText(/Waiting for port 5173/)).toBeInTheDocument()
portsState = portsData
panel.refresh()
second.resolve({ token: 'tok-2', previewPort: 5004, publicUrl: null })
expect((await screen.findByTitle('Preview')).getAttribute('src')).toContain('token=tok-2')
expect(createPreviewSession).toHaveBeenCalledTimes(2)
})
it('does not render the old token while a same-port path change is pending', async () => {
const user = userEvent.setup()
const first = deferred<CreatePreviewSessionResponse>()
const second = deferred<CreatePreviewSessionResponse>()
vi.mocked(createPreviewSession).mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise)
renderPanel('/repos/1?dialog=preview&previewPort=5173&previewPath=%2F')
first.resolve({ token: 'tok-1', previewPort: 5004, publicUrl: null })
expect(await screen.findByTitle('Preview')).toBeInTheDocument()
const pathInput = screen.getByLabelText('Preview path')
await user.clear(pathInput)
await user.type(pathInput, '/foo')
await user.click(screen.getByRole('button', { name: 'Go' }))
expect(screen.queryByTitle('Preview')).not.toBeInTheDocument()
second.resolve({ token: 'tok-2', previewPort: 5004, publicUrl: null })
const iframe = await screen.findByTitle('Preview')
expect(iframe.getAttribute('src')).toContain('token=tok-2')
expect(iframe.getAttribute('src')).toContain('path=%2Ffoo')
})
it('does not replay the old token while a reload is pending', async () => {
const user = userEvent.setup()
const first = deferred<CreatePreviewSessionResponse>()
const second = deferred<CreatePreviewSessionResponse>()
vi.mocked(createPreviewSession).mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise)
renderPanel()
first.resolve({ token: 'tok-1', previewPort: 5004, publicUrl: null })
expect(await screen.findByTitle('Preview')).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Reload preview' }))
expect(screen.queryByTitle('Preview')).not.toBeInTheDocument()
second.resolve({ token: 'tok-2', previewPort: 5004, publicUrl: null })
expect((await screen.findByTitle('Preview')).getAttribute('src')).toContain('token=tok-2')
})
it('keeps the newest session when responses resolve out of order for the same port', async () => {
const user = userEvent.setup()
const first = deferred<CreatePreviewSessionResponse>()
const second = deferred<CreatePreviewSessionResponse>()
const third = deferred<CreatePreviewSessionResponse>()
vi.mocked(createPreviewSession)
.mockReturnValueOnce(first.promise)
.mockReturnValueOnce(second.promise)
.mockReturnValueOnce(third.promise)
renderPanel()
first.resolve({ token: 'tok-1', previewPort: 5004, publicUrl: null })
await screen.findByTitle('Preview')
await user.click(screen.getByRole('button', { name: 'Reload preview' }))
await user.click(screen.getByRole('button', { name: 'Reload preview' }))
third.resolve({ token: 'tok-3', previewPort: 5004, publicUrl: null })
second.resolve({ token: 'tok-2', previewPort: 5004, publicUrl: null })
const iframe = await screen.findByTitle('Preview')
expect(iframe.getAttribute('src')).toContain('token=tok-3')
expect(iframe.getAttribute('src')).not.toContain('token=tok-2')
})
it('does not mint extra sessions when the port list refetches unchanged', async () => {
const first = deferred<CreatePreviewSessionResponse>()
vi.mocked(createPreviewSession).mockReturnValueOnce(first.promise)
const panel = renderPanel()
first.resolve({ token: 'tok-1', previewPort: 5004, publicUrl: null })
await screen.findByTitle('Preview')
panel.refresh()
panel.refresh()
expect(createPreviewSession).toHaveBeenCalledTimes(1)
})
})
@@ -0,0 +1,353 @@
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
import type { CreatePreviewSessionResponse } from '@opencode-manager/shared/types'
import { ExternalLink, Globe, Loader2, Monitor, RefreshCw, Smartphone, Tablet, X } from 'lucide-react'
import { createPreviewSession, usePreviewPorts } from '@/api/preview'
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 { cn } from '@/lib/utils'
interface PreviewPanelProps {
isOpen: boolean
onClose: () => void
directory: string | undefined
}
type ViewportPreset = 'mobile' | 'tablet' | 'full'
const VIEWPORT_WIDTHS: Record<ViewportPreset, number | null> = {
mobile: 390,
tablet: 820,
full: null,
}
const VIEWPORT_PRESETS: Array<{ preset: ViewportPreset; label: string; icon: typeof Monitor }> = [
{ preset: 'mobile', label: 'Mobile viewport', icon: Smartphone },
{ preset: 'tablet', label: 'Tablet viewport', icon: Tablet },
{ preset: 'full', label: 'Full width viewport', icon: Monitor },
]
const PORT_WAIT_TIMEOUT_MS = 60_000
interface ActiveSession {
targetPort: number
path: string
renderKey: number
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
}, [searchParams])
const requestedPath = searchParams.get('previewPath') || '/'
const [pathDraft, setPathDraft] = useState(requestedPath)
const [viewport, setViewport] = useState<ViewportPreset>('full')
const [session, setSession] = useState<ActiveSession | null>(null)
const [sessionError, setSessionError] = useState<string | null>(null)
const [waitExpired, setWaitExpired] = useState(false)
const [retryNonce, setRetryNonce] = useState(0)
const sessionPortRef = useRef<number | null>(null)
const activePathRef = useRef<string | null>(null)
const requestIdRef = useRef(0)
const portsQuery = usePreviewPorts(directory, {
enabled: isOpen,
refetchInterval: isOpen ? 2000 : false,
})
const ports = useMemo(() => portsQuery.data?.ports ?? [], [portsQuery.data])
const enabled = portsQuery.data?.enabled ?? true
const portListed = requestedPort !== undefined && ports.some((entry) => entry.port === requestedPort)
useEffect(() => {
setPathDraft(requestedPath)
}, [requestedPath])
useEffect(() => {
if (!isOpen) {
requestIdRef.current += 1
sessionPortRef.current = null
activePathRef.current = null
setSession(null)
setSessionError(null)
}
}, [isOpen])
useEffect(() => {
if (portListed) return
requestIdRef.current += 1
sessionPortRef.current = null
activePathRef.current = null
setSession(null)
}, [portListed])
useEffect(() => {
if (!isOpen || !requestedPort || !enabled || portListed) {
setWaitExpired(false)
return
}
setWaitExpired(false)
const timer = setTimeout(() => setWaitExpired(true), PORT_WAIT_TIMEOUT_MS)
return () => clearTimeout(timer)
}, [isOpen, requestedPort, enabled, portListed, retryNonce])
const startSession = useCallback((port: number, path: string) => {
const requestId = requestIdRef.current + 1
requestIdRef.current = requestId
sessionPortRef.current = port
activePathRef.current = path
setSessionError(null)
setSession(null)
return createPreviewSession(port)
.then((data) => {
if (requestIdRef.current !== requestId) return
setSession({ targetPort: port, path, renderKey: requestId, data })
})
.catch((error: unknown) => {
if (requestIdRef.current !== requestId) return
sessionPortRef.current = null
activePathRef.current = null
setSessionError(errorMessage(error, 'Failed to start preview'))
})
}, [])
useEffect(() => {
if (!isOpen || !requestedPort || !enabled || !portListed) return
if (sessionPortRef.current === requestedPort && activePathRef.current === requestedPath) return
void startSession(requestedPort, requestedPath)
}, [isOpen, requestedPort, requestedPath, enabled, portListed, startSession])
const selectPort = useCallback((port: number) => {
updateParams((params) => {
params.set('previewPort', String(port))
params.delete('previewPath')
}, 'replace')
}, [updateParams])
const reload = useCallback(() => {
if (!requestedPort) return
void startSession(requestedPort, requestedPath)
}, [requestedPort, requestedPath, startSession])
const handleGo = useCallback(() => {
const nextPath = pathDraft.trim() || '/'
updateParams((params) => {
params.set('previewPath', nextPath)
}, 'replace')
if (requestedPort) {
void startSession(requestedPort, nextPath)
}
}, [pathDraft, requestedPort, updateParams, startSession])
const handleOpenInNewTab = useCallback(() => {
if (!requestedPort) return
createPreviewSession(requestedPort)
.then((data) => {
window.open(buildPreviewStartUrl(data, requestedPath), '_blank', 'noopener,noreferrer')
})
.catch((error: unknown) => {
setSessionError(errorMessage(error, 'Failed to open preview'))
})
}, [requestedPort, requestedPath])
const retry = useCallback(() => {
if (portListed && requestedPort) {
void startSession(requestedPort, requestedPath)
return
}
setWaitExpired(false)
setRetryNonce((nonce) => nonce + 1)
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]
const renderMessage = (message: ReactNode, options: { retry?: boolean; alert?: boolean } = {}) => (
<div className="flex h-full flex-col items-center justify-center gap-3 p-6 text-center text-sm text-muted-foreground">
<div role={options.alert ? 'alert' : undefined} className="flex items-center gap-2">
{message}
</div>
{options.retry && (
<Button size="sm" variant="outline" onClick={retry}>
Retry
</Button>
)}
</div>
)
const body = () => {
if (!enabled) {
return renderMessage('Preview is disabled (PREVIEW_PORT=0)')
}
if (!requestedPort) {
return renderMessage('Select a port to preview')
}
if (!portListed) {
if (waitExpired) {
return renderMessage(`Port ${requestedPort} is not listening`, { retry: true, alert: true })
}
return renderMessage(
<>
<Loader2 className="h-4 w-4 animate-spin" />
Waiting for port {requestedPort}…
</>,
)
}
if (sessionError) {
return renderMessage(sessionError, { retry: true, alert: true })
}
if (activeSession) {
if (sameOrigin) {
return renderMessage('Preview must run on a different origin than OpenCode Manager.', { alert: true })
}
return (
<div className="flex h-full justify-center overflow-hidden">
<iframe
key={activeSession.renderKey}
title="Preview"
src={buildPreviewStartUrl(activeSession.data, activeSession.path)}
sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-modals allow-downloads"
className="h-full border-0 bg-white"
style={{ width: viewportWidth ?? '100%', maxWidth: '100%' }}
/>
</div>
)
}
return renderMessage(
<>
<Loader2 className="h-4 w-4 animate-spin" />
Starting preview…
</>,
)
}
return (
<Dialog open={isOpen} onOpenChange={(open) => { if (!open) onClose() }}>
<DialogContent
mobileFullscreen
hideCloseButton={isMobile}
className={cn(
'p-0 flex flex-col bg-card border-border gap-0',
isMobile ? 'h-full' : 'w-[90vw] sm:max-w-6xl h-[90vh] sm:pb-0',
)}
>
<DialogHeader className={cn('px-4 py-2 border-b border-border flex-shrink-0', isMobile && 'relative')}>
<DialogTitle className="flex items-center gap-2">
<Globe className="w-5 h-5" />
Preview
</DialogTitle>
{isMobile && (
<Button
variant="ghost"
size="sm"
onClick={onClose}
aria-label="Close preview panel"
className="absolute right-2 top-1/2 -translate-y-1/2 h-10 w-10 p-0"
>
<X className="h-6 w-6" />
</Button>
)}
</DialogHeader>
<div className="flex items-center gap-2 border-b border-border px-3 py-2 flex-shrink-0">
<input
aria-label="Preview path"
value={pathDraft}
onChange={(event) => setPathDraft(event.target.value)}
onKeyDown={(event) => { if (event.key === 'Enter') handleGo() }}
className="h-8 min-w-0 flex-1 rounded-md border border-border bg-background px-2 text-sm"
placeholder="/"
/>
<Button size="sm" variant="outline" onClick={handleGo} disabled={!requestedPort}>
Go
</Button>
<Button
size="sm"
variant="ghost"
onClick={reload}
disabled={!requestedPort}
aria-label="Reload preview"
className="h-8 w-8 p-0"
>
<RefreshCw className="h-4 w-4" />
</Button>
<Button
size="sm"
variant="ghost"
onClick={handleOpenInNewTab}
disabled={!requestedPort}
aria-label="Open preview in new tab"
className="h-8 w-8 p-0"
>
<ExternalLink className="h-4 w-4" />
</Button>
<div className="ml-auto flex items-center gap-1">
{VIEWPORT_PRESETS.map(({ preset, label, icon: Icon }) => (
<Button
key={preset}
size="sm"
variant={viewport === preset ? 'secondary' : 'ghost'}
onClick={() => setViewport(preset)}
aria-label={label}
aria-pressed={viewport === preset}
className="h-8 w-8 p-0"
>
<Icon className="h-4 w-4" />
</Button>
))}
</div>
</div>
{enabled && ports.length > 0 && (
<div className="flex flex-wrap items-center gap-1 border-b border-border px-3 py-2 flex-shrink-0">
{ports.map((entry) => (
<button
key={entry.port}
type="button"
onClick={() => selectPort(entry.port)}
title={entry.cwd ?? undefined}
className={cn(
'flex items-center gap-1.5 rounded-md border px-2 py-1 text-xs transition-colors',
entry.port === requestedPort
? 'border-primary text-foreground'
: 'border-border text-muted-foreground hover:text-foreground',
)}
>
<span className="font-medium">:{entry.port}</span>
{entry.command && <span className="truncate">{entry.command}</span>}
{isInsideDirectory(entry.cwd, directory) && (
<span className="rounded bg-muted px-1.5 py-0.5 text-[10px]">this repo</span>
)}
</button>
))}
</div>
)}
<div className="relative flex-1 min-h-0">{body()}</div>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,138 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import type { Repo } from '@/api/types'
import { CreateWorktreeDialog } from './CreateWorktreeDialog'
const mocks = vi.hoisted(() => ({
createRepo: vi.fn(),
listBranches: vi.fn(),
navigate: vi.fn(),
showToastSuccess: vi.fn(),
showToastInfo: vi.fn(),
showToastWarning: vi.fn(),
invalidateRepoGitCaches: vi.fn(),
}))
vi.mock('@/api/repos', () => ({
createRepo: mocks.createRepo,
listBranches: mocks.listBranches,
}))
vi.mock('@/lib/toast', () => ({
showToast: {
success: mocks.showToastSuccess,
info: mocks.showToastInfo,
warning: mocks.showToastWarning,
error: vi.fn(),
},
}))
vi.mock('@/lib/queryInvalidation', () => ({
invalidateRepoGitCaches: mocks.invalidateRepoGitCaches,
}))
vi.mock('react-router-dom', async () => {
const actual = await vi.importActual('react-router-dom')
return {
...actual,
useNavigate: () => mocks.navigate,
}
})
function createWorktreeRepo(overrides: Partial<Repo> = {}): Repo {
return {
id: 42,
localPath: 'repos/feature-x',
fullPath: '/tmp/repos/feature-x',
defaultBranch: 'main',
cloneStatus: 'ready',
clonedAt: 1,
...overrides,
}
}
function renderDialog() {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
return render(
<QueryClientProvider client={queryClient}>
<CreateWorktreeDialog
open
onOpenChange={() => {}}
repoId={1}
repoUrl="https://github.com/test/repo"
defaultBaseBranch="main"
/>
</QueryClientProvider>,
)
}
async function submitCreate() {
const user = userEvent.setup()
await user.type(screen.getByPlaceholderText('feature/my-branch'), 'feature/x')
await user.click(screen.getByRole('button', { name: 'Create Worktree' }))
}
describe('CreateWorktreeDialog', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.listBranches.mockResolvedValue({
branches: [{ name: 'main', type: 'local', current: true }],
status: { ahead: 0, behind: 0 },
})
})
it('navigates to the setup terminal when the worktree setup starts', async () => {
mocks.createRepo.mockResolvedValue(
createWorktreeRepo({
worktreeSetup: {
status: 'started',
terminal: {
id: 'pty-1',
title: 'Worktree setup',
kind: 'setup',
cwd: '/tmp/repos/feature-x',
status: 'running',
},
repoCommandsSkipped: false,
},
}),
)
renderDialog()
await submitCreate()
await waitFor(() =>
expect(mocks.navigate).toHaveBeenCalledWith('/repos/42?dialog=terminal&terminal=pty-1'),
)
})
it('warns without navigating when the worktree setup fails', async () => {
mocks.createRepo.mockResolvedValue(
createWorktreeRepo({ worktreeSetup: { status: 'failed', error: 'spawn failed' } }),
)
renderDialog()
await submitCreate()
await waitFor(() => expect(mocks.showToastWarning).toHaveBeenCalled())
expect(mocks.navigate).not.toHaveBeenCalled()
})
it('informs about skipped repository commands when the setup is skipped', async () => {
mocks.createRepo.mockResolvedValue(
createWorktreeRepo({ worktreeSetup: { status: 'skipped', reason: 'untrusted' } }),
)
renderDialog()
await submitCreate()
await waitFor(() =>
expect(mocks.showToastInfo).toHaveBeenCalledWith(
'Repository setup commands were skipped until trusted in Actions',
),
)
expect(mocks.navigate).not.toHaveBeenCalled()
})
})
@@ -1,5 +1,6 @@
import { useState, useEffect } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useNavigate } from 'react-router-dom'
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
@@ -7,6 +8,7 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@
import { AlertCircle, GitBranch, Loader2 } from 'lucide-react'
import { createRepo, listBranches } from '@/api/repos'
import { showToast } from '@/lib/toast'
import { notifyWorktreeSetup } from '@/lib/worktreeSetup'
import { invalidateRepoGitCaches } from '@/lib/queryInvalidation'
interface CreateWorktreeDialogProps {
@@ -27,6 +29,7 @@ export function CreateWorktreeDialog({
onCreated,
}: CreateWorktreeDialogProps) {
const queryClient = useQueryClient()
const navigate = useNavigate()
const [branchName, setBranchName] = useState('')
const [baseBranch, setBaseBranch] = useState<string>('')
const [error, setError] = useState<string | null>(null)
@@ -66,11 +69,15 @@ export function CreateWorktreeDialog({
useWorktree: true,
baseBranch: payload.base,
}),
onSuccess: () => {
onSuccess: (repo) => {
invalidateRepoGitCaches(queryClient, repoId)
showToast.success('Worktree created')
onCreated?.()
onOpenChange(false)
notifyWorktreeSetup(repo.worktreeSetup)
if (repo.worktreeSetup?.status === 'started') {
navigate(`/repos/${repo.id}?dialog=terminal&terminal=${encodeURIComponent(repo.worktreeSetup.terminal.id)}`)
}
},
onError: (err) => {
setError(err instanceof Error ? err.message : 'Failed to create worktree')
@@ -0,0 +1,298 @@
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter } from 'react-router-dom'
import type { TerminalInfo } from '@opencode-manager/shared/types'
import type { ProjectConfigResponse } from '@opencode-manager/shared/types'
import { FetchError } from '@opencode-manager/shared'
import { LocationCatcher } from '@/test/test-utils'
import { ProjectActionsMenu } from './ProjectActionsMenu'
const mocks = vi.hoisted(() => ({
useProjectConfig: vi.fn(),
useTerminals: vi.fn(),
getProjectConfig: vi.fn(),
runMutate: vi.fn(),
removeMutate: vi.fn(),
trustMutate: vi.fn(),
openUrlFromManager: vi.fn(),
showToastError: vi.fn(),
}))
vi.mock('@/api/projectConfig', () => ({
getProjectConfig: mocks.getProjectConfig,
useProjectConfig: mocks.useProjectConfig,
useRunProjectAction: () => ({ mutate: mocks.runMutate, isPending: false }),
useTrustRepoConfig: () => ({ mutate: mocks.trustMutate, isPending: false }),
}))
vi.mock('@/api/terminals', () => ({
useTerminals: mocks.useTerminals,
useRemoveTerminal: () => ({ mutate: mocks.removeMutate, isPending: false }),
}))
vi.mock('@/lib/open-url', () => ({
openUrlFromManager: mocks.openUrlFromManager,
}))
vi.mock('@/lib/toast', () => ({
showToast: { error: mocks.showToastError, success: vi.fn() },
}))
const HASH = 'a'.repeat(64)
const OTHER_HASH = 'b'.repeat(64)
const devAction: ProjectConfigResponse['actions'][number] = {
id: 'dev',
name: 'Dev server',
command: 'pnpm dev',
autoOpenUrl: false,
source: 'personal',
}
const repoAction: ProjectConfigResponse['actions'][number] = {
...devAction,
source: 'repo',
}
const runningTerminal: TerminalInfo = {
id: 'term-1',
title: 'Dev server',
kind: 'action',
actionId: 'dev',
cwd: '/repo',
status: 'running',
}
function makeConfig(
actions: ProjectConfigResponse['actions'],
hash: string | null = null,
): ProjectConfigResponse {
return {
actions,
worktreeSetup: [],
repoFile: { path: '.ocm/project.json', exists: hash !== null, trusted: true, hash, warnings: [] },
}
}
function untrustedError(hash: string): FetchError {
return new FetchError('Repository commands are not trusted', 409, 'REPO_CONFIG_UNTRUSTED', undefined, {
details: { hash },
})
}
function menuTree(directory: string, capturedSearch: { current: string }) {
return (
<MemoryRouter initialEntries={['/repos/1']}>
<LocationCatcher capturedSearch={capturedSearch} />
<ProjectActionsMenu repoId={1} directory={directory} />
</MemoryRouter>
)
}
function renderMenu(directory = '/repo') {
const capturedSearch: { current: string } = { current: '' }
const result = render(menuTree(directory, capturedSearch))
return { ...result, capturedSearch }
}
describe('ProjectActionsMenu', () => {
beforeAll(() => {
Element.prototype.hasPointerCapture ??= () => false
Element.prototype.setPointerCapture ??= () => {}
Element.prototype.releasePointerCapture ??= () => {}
Element.prototype.scrollIntoView ??= () => {}
})
beforeEach(() => {
vi.clearAllMocks()
mocks.useProjectConfig.mockReturnValue({ data: makeConfig([devAction]), isLoading: false, error: null })
mocks.useTerminals.mockReturnValue({ data: [] })
mocks.getProjectConfig.mockResolvedValue(makeConfig([devAction]))
})
it('opens the terminal panel on the run terminal when an action succeeds', async () => {
mocks.runMutate.mockImplementation((_actionId, options) => {
options.onSuccess({ terminal: runningTerminal, alreadyRunning: false, autoOpenUrl: false })
})
const user = userEvent.setup()
const { capturedSearch } = renderMenu()
await user.click(screen.getByRole('button', { name: 'Project actions' }))
await user.click(await screen.findByRole('menuitem', { name: /dev server/i }))
await waitFor(() => expect(capturedSearch.current).toContain('dialog=terminal'))
expect(capturedSearch.current).toContain('terminal=term-1')
})
it('shows a running dot and a Stop item that removes the running terminal', async () => {
mocks.useTerminals.mockReturnValue({ data: [runningTerminal] })
const user = userEvent.setup()
renderMenu()
await user.click(screen.getByRole('button', { name: 'Project actions' }))
expect(await screen.findByTestId('action-running-dot')).toBeInTheDocument()
await user.click(await screen.findByRole('menuitem', { name: /stop/i }))
expect(mocks.removeMutate).toHaveBeenCalledWith(
{ ptyID: 'term-1', directory: '/repo' },
expect.any(Object),
)
})
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))
let runCalls = 0
mocks.runMutate.mockImplementation((_actionId, options) => {
runCalls += 1
if (runCalls === 1) {
options.onError(untrustedError(HASH))
return
}
options.onSuccess({ terminal: runningTerminal, alreadyRunning: false, autoOpenUrl: false })
})
mocks.trustMutate.mockImplementation((_vars, options) => options.onSuccess())
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('pnpm dev')).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: /trust and run/i }))
await waitFor(() => expect(mocks.runMutate).toHaveBeenCalledTimes(2))
expect(mocks.trustMutate).toHaveBeenCalledWith(
{ hash: HASH, directory: '/repo' },
expect.any(Object),
)
})
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.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('pnpm dev')).toBeInTheDocument()
expect(screen.queryByText('pnpm dev:stale')).not.toBeInTheDocument()
})
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.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('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.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('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.runMutate.mockImplementation((_actionId, options) => options.onError(untrustedError(HASH)))
const user = userEvent.setup()
const capturedSearch: { current: string } = { current: '' }
const { rerender } = render(menuTree('/repo', capturedSearch))
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()
rerender(menuTree('/other', capturedSearch))
await waitFor(() =>
expect(screen.queryByText('Trust repository actions')).not.toBeInTheDocument(),
)
expect(mocks.trustMutate).not.toHaveBeenCalled()
})
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.runMutate.mockImplementation((_actionId, options) => options.onError(untrustedError(HASH)))
let trustOptions: { onSuccess: () => void } | undefined
mocks.trustMutate.mockImplementation((_vars, options) => {
trustOptions = options
})
const user = userEvent.setup()
const capturedSearch: { current: string } = { current: '' }
const { rerender } = render(menuTree('/repo', capturedSearch))
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()
await user.click(screen.getByRole('button', { name: /trust and run/i }))
expect(mocks.runMutate).toHaveBeenCalledTimes(1)
rerender(menuTree('/other', capturedSearch))
await waitFor(() =>
expect(screen.queryByText('Trust repository actions')).not.toBeInTheDocument(),
)
await act(async () => {
trustOptions?.onSuccess()
})
expect(mocks.runMutate).toHaveBeenCalledTimes(1)
})
it('opens the resolved URL when the action opts into auto-open', async () => {
mocks.runMutate.mockImplementation((_actionId, options) => {
options.onSuccess({
terminal: runningTerminal,
alreadyRunning: false,
resolvedUrl: 'http://localhost:3000',
autoOpenUrl: true,
})
})
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.openUrlFromManager).toHaveBeenCalledWith('http://localhost:3000', expect.any(Object)),
)
})
it('shows the empty state and manage entry when no actions are configured', async () => {
mocks.useProjectConfig.mockReturnValue({ data: makeConfig([]), isLoading: false, error: null })
const user = userEvent.setup()
renderMenu()
await user.click(screen.getByRole('button', { name: 'Project actions' }))
expect(await screen.findByText('No actions configured')).toBeInTheDocument()
expect(screen.getByRole('menuitem', { name: /manage actions/i })).toBeInTheDocument()
})
})
@@ -0,0 +1,252 @@
import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import type { TerminalInfo } from '@opencode-manager/shared/types'
import { FetchError } from '@opencode-manager/shared'
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 {
getProjectConfig,
useProjectConfig,
useRunProjectAction,
useTrustRepoConfig,
} from '@/api/projectConfig'
import { useRemoveTerminal, useTerminals } from '@/api/terminals'
import { Button } from '@/components/ui/button'
import { ConfirmDestructiveDialog } from '@/components/ui/confirm-destructive-dialog'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { openDialogParam } from '@/hooks/useDialogParam'
import { useOpenPreview } from '@/hooks/useOpenPreview'
import { useUrlParams } from '@/hooks/useUrlParams'
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,
}
interface ProjectActionsMenuProps {
repoId: number
directory: string | undefined
}
interface PendingTrust {
actionId: string
hash: string
directory: string
command: string
}
function untrustedHash(error: unknown): string | null {
if (!(error instanceof FetchError) || error.code !== 'REPO_CONFIG_UNTRUSTED') return null
const details = error.details
if (details && typeof details === 'object' && typeof (details as { hash?: unknown }).hash === 'string') {
return (details as { hash: string }).hash
}
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 configQuery = useProjectConfig(repoId, directory, menuOpen && !!directory)
const terminalsQuery = useTerminals(repoId, directory, {
enabled: menuOpen && !!directory,
refetchInterval: menuOpen ? 5000 : false,
})
const runAction = useRunProjectAction(repoId, directory)
const removeTerminal = useRemoveTerminal(repoId)
const trustConfig = useTrustRepoConfig(repoId)
const [pendingTrust, setPendingTrust] = useState<PendingTrust | null>(null)
const scopeRef = useRef({ repoId, directory })
useEffect(() => {
scopeRef.current = { repoId, directory }
setPendingTrust(null)
}, [repoId, directory])
const actions = useMemo<ProjectConfigResponse['actions']>(
() => configQuery.data?.actions ?? [],
[configQuery.data],
)
const runningByAction = useMemo(() => {
const map = new Map<string, TerminalInfo>()
for (const terminal of terminalsQuery.data ?? []) {
if (terminal.kind === 'action' && terminal.actionId && terminal.status === 'running') {
map.set(terminal.actionId, terminal)
}
}
return map
}, [terminalsQuery.data])
const handleRunSuccess = useCallback((result: RunProjectActionResponse) => {
updateParams((params) => {
params.set('dialog', 'terminal')
params.set('terminal', result.terminal.id)
params.delete('mobileTab')
}, 'push')
if (result.autoOpenUrl && result.resolvedUrl) {
openUrlFromManager(result.resolvedUrl, { openPreview })
}
}, [updateParams, openPreview])
const requestTrustConfirmation = useCallback(async (actionId: string, hash: string) => {
const requestDirectory = directory
if (!requestDirectory) return
let snapshot: ProjectConfigResponse
try {
snapshot = await getProjectConfig(repoId, requestDirectory)
} catch (error) {
showToast.error(errorMessage(error, 'Failed to verify repository actions'))
return
}
const scope = scopeRef.current
if (scope.repoId !== repoId || scope.directory !== requestDirectory) return
const repoAction = snapshot.actions.find(
(action) => action.id === actionId && action.source === 'repo',
)
if (snapshot.repoFile.hash !== hash || !repoAction) {
showToast.error('Repository actions changed. Reopen the menu to review them.')
return
}
setPendingTrust({ actionId, hash, directory: requestDirectory, command: repoAction.command })
}, [directory, repoId])
const startRun = useCallback((actionId: string) => {
runAction.mutate(actionId, {
onSuccess: handleRunSuccess,
onError: (error) => {
const hash = untrustedHash(error)
if (hash) {
void requestTrustConfirmation(actionId, hash)
return
}
showToast.error(errorMessage(error, 'Failed to run action'))
},
})
}, [runAction, handleRunSuccess, requestTrustConfirmation])
const handleConfirmTrust = useCallback(() => {
if (!pendingTrust) return
const { actionId, hash, directory: trustDirectory } = pendingTrust
const origin = { repoId, directory: trustDirectory }
trustConfig.mutate({ hash, directory: trustDirectory }, {
onSuccess: () => {
const scope = scopeRef.current
if (scope.repoId !== origin.repoId || scope.directory !== origin.directory) return
setPendingTrust(null)
startRun(actionId)
},
onError: (error) => showToast.error(errorMessage(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')),
})
}, [removeTerminal, directory])
const handleManage = useCallback(() => {
openDialogParam(updateParams, 'actions')
}, [updateParams])
if (!directory) return null
return (
<>
<DropdownMenu open={menuOpen} onOpenChange={setMenuOpen}>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="icon"
aria-label="Project actions"
className="h-8 w-8 text-muted-foreground hover:text-foreground"
>
<Play className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-56">
{actions.length === 0 ? (
<DropdownMenuLabel className="font-normal text-muted-foreground">
No actions configured
</DropdownMenuLabel>
) : (
actions.map((action) => {
const Icon = ACTION_ICONS[action.icon ?? 'play']
const running = runningByAction.get(action.id)
return (
<Fragment key={action.id}>
<DropdownMenuItem disabled={runAction.isPending} onSelect={() => startRun(action.id)}>
<Icon className="mr-2 h-4 w-4" />
<span className="truncate">{action.name}</span>
{running && (
<span
data-testid="action-running-dot"
className="ml-auto h-2 w-2 rounded-full bg-primary"
/>
)}
</DropdownMenuItem>
{running && (
<DropdownMenuItem onSelect={() => handleStop(running)}>
<Square className="mr-2 h-4 w-4" />
Stop
</DropdownMenuItem>
)}
</Fragment>
)
})
)}
<DropdownMenuSeparator />
<DropdownMenuItem onSelect={handleManage}>Manage actions…</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<ConfirmDestructiveDialog
open={pendingTrust !== null}
onOpenChange={(open) => { if (!open) setPendingTrust(null) }}
onConfirm={handleConfirmTrust}
onCancel={() => setPendingTrust(null)}
title="Trust repository actions"
description="This repository defines commands that run on your machine."
warning={pendingTrust?.command}
confirmLabel="Trust and run"
pendingLabel="Trusting…"
isPending={trustConfig.isPending}
/>
</>
)
}
@@ -6,7 +6,9 @@ import { Button } from '@/components/ui/button'
import { ConfirmDestructiveDialog } from '@/components/ui/confirm-destructive-dialog'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { useMobile } from '@/hooks/useMobile'
import { useOpenPreview } from '@/hooks/useOpenPreview'
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'
@@ -22,6 +24,7 @@ interface TerminalPanelProps {
export function TerminalPanel({ repoId, directory, isOpen, onClose, onOpenLink }: TerminalPanelProps) {
const isMobile = useMobile()
const { searchParams, updateParams } = useUrlParams()
const openPreview = useOpenPreview()
const { data, isLoading, isSuccess, refetch } = useTerminals(repoId, directory, {
enabled: isOpen && !!directory,
refetchInterval: isOpen ? 5000 : false,
@@ -97,6 +100,10 @@ export function TerminalPanel({ repoId, directory, isOpen, onClose, onOpenLink }
const handleToggleCtrl = useCallback(() => setCtrlArmed((armed) => !armed), [])
const handleCtrlConsumed = useCallback(() => setCtrlArmed(false), [])
const handleOpenLink = useCallback((uri: string) => {
openUrlFromManager(uri, { openPreview })
}, [openPreview])
return (
<Dialog open={isOpen} onOpenChange={(open) => { if (!open) onClose() }}>
<DialogContent
@@ -189,7 +196,7 @@ export function TerminalPanel({ repoId, directory, isOpen, onClose, onOpenLink }
active={terminal.id === activeTerminalId}
ctrlArmed={ctrlArmed}
onCtrlConsumed={handleCtrlConsumed}
onOpenLink={onOpenLink}
onOpenLink={onOpenLink ?? handleOpenLink}
onExited={() => { void refetch() }}
/>
))