mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
Merge forge/terminal-dev-loop integration (b13707b5b) into beta
Bring the terminal, project actions and dev server preview merge (OM-17, OM-18, OM-19) onto beta after 4a2e695ec. No conflicts; the merged CreateWorktreeDialog keeps BaseBranchSelect with origin/ remote bases and the worktree setup terminal navigation.
This commit is contained in:
commit
cf9fa61118
135 files changed
+12726
-492
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(9)
|
||||
expect(items).toHaveLength(12)
|
||||
expect(items[0].key).toBe('home')
|
||||
expect(items[1].key).toBe('files')
|
||||
expect(items[1].dialog).toBe('files')
|
||||
@@ -29,13 +29,19 @@ describe('buildMoreItems', () => {
|
||||
expect(items[5].to).toBe('/repos/42/schedules')
|
||||
expect(items[6].key).toBe('source-control')
|
||||
expect(items[6].dialog).toBe('sourceControl')
|
||||
expect(items[7].key).toBe('settings')
|
||||
expect(items[8].key).toBe('logout')
|
||||
expect(items[7].key).toBe('terminal')
|
||||
expect(items[7].dialog).toBe('terminal')
|
||||
expect(items[8].key).toBe('actions')
|
||||
expect(items[8].dialog).toBe('actions')
|
||||
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(9)
|
||||
expect(items).toHaveLength(12)
|
||||
expect(items[0].key).toBe('home')
|
||||
expect(items[1].key).toBe('files')
|
||||
expect(items[2].key).toBe('mcp')
|
||||
@@ -44,13 +50,30 @@ describe('buildMoreItems', () => {
|
||||
expect(items[5].key).toBe('schedules')
|
||||
expect(items[5].to).toBe('/repos/42/schedules')
|
||||
expect(items[6].key).toBe('source-control')
|
||||
expect(items[7].key).toBe('settings')
|
||||
expect(items[8].key).toBe('logout')
|
||||
expect(items[7].key).toBe('terminal')
|
||||
expect(items[7].dialog).toBe('terminal')
|
||||
expect(items[8].key).toBe('actions')
|
||||
expect(items[8].dialog).toBe('actions')
|
||||
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('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(9)
|
||||
expect(items).toHaveLength(11)
|
||||
expect(items[0].key).toBe('home')
|
||||
expect(items[1].key).toBe('files')
|
||||
expect(items[1].dialog).toBe('files')
|
||||
@@ -59,8 +82,12 @@ describe('buildMoreItems', () => {
|
||||
expect(items[4].key).toBe('reset-permissions')
|
||||
expect(items[5].key).toBe('schedules')
|
||||
expect(items[6].key).toBe('source-control')
|
||||
expect(items[7].key).toBe('settings')
|
||||
expect(items[8].key).toBe('logout')
|
||||
expect(items[7].key).toBe('terminal')
|
||||
expect(items[7].dialog).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 only Home + Settings + Logout for /schedules', () => {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import { Plug, Sparkles, ShieldOff, CalendarClock, GitCommitHorizontal, Settings, LogOut, Bot, Folder, Home } 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 {
|
||||
@@ -58,6 +59,9 @@ function buildRouteNavModel(pathname: string): NavModel {
|
||||
{ key: 'reset-permissions', label: 'Reset Permissions', icon: ShieldOff, dialog: 'resetPermissions', danger: true },
|
||||
{ key: 'schedules', label: 'Schedules', icon: CalendarClock, to: `/repos/${id}/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' },
|
||||
{ key: 'preview', label: 'Preview', icon: Globe, dialog: 'preview' },
|
||||
...baseItems,
|
||||
]
|
||||
|
||||
@@ -69,13 +73,20 @@ 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' },
|
||||
...(isAssistantRepo
|
||||
? []
|
||||
: [{ key: 'actions', label: 'Actions', icon: Play, dialog: 'actions' }]),
|
||||
{ key: 'preview', label: 'Preview', icon: Globe, dialog: 'preview' },
|
||||
...baseItems,
|
||||
]
|
||||
|
||||
@@ -93,6 +104,8 @@ function buildRouteNavModel(pathname: string): NavModel {
|
||||
{ key: 'reset-permissions', label: 'Reset Permissions', icon: ShieldOff, dialog: 'resetPermissions', danger: true },
|
||||
{ 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,
|
||||
]
|
||||
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
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', inDirectory: true }],
|
||||
}
|
||||
|
||||
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 unavailable/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
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>()
|
||||
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,342 @@
|
||||
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 { getOpenCodeApiErrorMessage } from '@/lib/opencode-errors'
|
||||
import { buildPreviewStartUrl, getPreviewOrigin, isSameOriginAsManager, parsePort } 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
|
||||
}
|
||||
|
||||
export function PreviewPanel({ isOpen, onClose, directory }: PreviewPanelProps) {
|
||||
const isMobile = useMobile()
|
||||
const { searchParams, updateParams } = useUrlParams()
|
||||
|
||||
const requestedPort = useMemo(() => {
|
||||
const port = parsePort(searchParams.get('previewPort') ?? '')
|
||||
return 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 activeSession = session && session.targetPort === requestedPort ? session : null
|
||||
|
||||
const portsQuery = usePreviewPorts(directory, {
|
||||
enabled: isOpen,
|
||||
refetchInterval: isOpen && !activeSession ? 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(getOpenCodeApiErrorMessage(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(getOpenCodeApiErrorMessage(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 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 unavailable')
|
||||
}
|
||||
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>}
|
||||
{entry.inDirectory && (
|
||||
<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>
|
||||
)
|
||||
}
|
||||
@@ -1,32 +1,83 @@
|
||||
import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest'
|
||||
import { beforeAll, 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'
|
||||
import { createRepo, listBranches } from '@/api/repos'
|
||||
|
||||
vi.mock('@/api/repos', () => ({
|
||||
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: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn() },
|
||||
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,
|
||||
}
|
||||
})
|
||||
|
||||
const repoUrl = 'git@example.com:org/repo.git'
|
||||
|
||||
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 }, mutations: { retry: false } },
|
||||
})
|
||||
return render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<CreateWorktreeDialog open onOpenChange={vi.fn()} repoId={1} repoUrl={repoUrl} />
|
||||
<CreateWorktreeDialog
|
||||
open
|
||||
onOpenChange={vi.fn()}
|
||||
repoId={1}
|
||||
repoUrl={repoUrl}
|
||||
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', () => {
|
||||
beforeAll(() => {
|
||||
Element.prototype.hasPointerCapture ??= () => false
|
||||
@@ -37,7 +88,7 @@ describe('CreateWorktreeDialog', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(listBranches).mockResolvedValue({
|
||||
mocks.listBranches.mockResolvedValue({
|
||||
branches: [
|
||||
{ name: 'main', type: 'local', current: true },
|
||||
{ name: 'feature', type: 'local', current: false },
|
||||
@@ -47,7 +98,7 @@ describe('CreateWorktreeDialog', () => {
|
||||
],
|
||||
status: { ahead: 0, behind: 0 },
|
||||
})
|
||||
vi.mocked(createRepo).mockResolvedValue({} as never)
|
||||
mocks.createRepo.mockResolvedValue(createWorktreeRepo())
|
||||
})
|
||||
|
||||
it('lists only non-current, non-worktree local branches and remote-only branches in existing mode', async () => {
|
||||
@@ -72,13 +123,13 @@ describe('CreateWorktreeDialog', () => {
|
||||
await user.click(screen.getByRole('option', { name: /release/ }))
|
||||
await user.click(screen.getByRole('button', { name: 'Create Worktree' }))
|
||||
|
||||
await waitFor(() => expect(createRepo).toHaveBeenCalledTimes(1))
|
||||
expect(createRepo).toHaveBeenCalledWith({ repoUrl, branch: 'release', useWorktree: true })
|
||||
expect(vi.mocked(createRepo).mock.calls[0][0]).not.toHaveProperty('baseBranch')
|
||||
await waitFor(() => expect(mocks.createRepo).toHaveBeenCalledTimes(1))
|
||||
expect(mocks.createRepo).toHaveBeenCalledWith({ repoUrl, branch: 'release', useWorktree: true })
|
||||
expect(mocks.createRepo.mock.calls[0][0]).not.toHaveProperty('baseBranch')
|
||||
})
|
||||
|
||||
it('does not offer remote-only branches from non-origin remotes', async () => {
|
||||
vi.mocked(listBranches).mockResolvedValue({
|
||||
mocks.listBranches.mockResolvedValue({
|
||||
branches: [
|
||||
{ name: 'main', type: 'local', current: true },
|
||||
{ name: 'remotes/upstream/release', type: 'remote', current: false },
|
||||
@@ -95,7 +146,7 @@ describe('CreateWorktreeDialog', () => {
|
||||
})
|
||||
|
||||
it('deduplicates remote candidates that share a short name across remotes', async () => {
|
||||
vi.mocked(listBranches).mockResolvedValue({
|
||||
mocks.listBranches.mockResolvedValue({
|
||||
branches: [
|
||||
{ name: 'main', type: 'local', current: true },
|
||||
{ name: 'remotes/origin/release', type: 'remote', current: false },
|
||||
@@ -121,8 +172,8 @@ describe('CreateWorktreeDialog', () => {
|
||||
await user.click(screen.getByRole('option', { name: /main/ }))
|
||||
await user.click(screen.getByRole('button', { name: 'Create Worktree' }))
|
||||
|
||||
await waitFor(() => expect(createRepo).toHaveBeenCalledTimes(1))
|
||||
expect(createRepo).toHaveBeenCalledWith({
|
||||
await waitFor(() => expect(mocks.createRepo).toHaveBeenCalledTimes(1))
|
||||
expect(mocks.createRepo).toHaveBeenCalledWith({
|
||||
repoUrl,
|
||||
branch: 'my-new-branch',
|
||||
useWorktree: true,
|
||||
@@ -139,8 +190,8 @@ describe('CreateWorktreeDialog', () => {
|
||||
await user.click(screen.getByRole('option', { name: /release/ }))
|
||||
await user.click(screen.getByRole('button', { name: 'Create Worktree' }))
|
||||
|
||||
await waitFor(() => expect(createRepo).toHaveBeenCalledTimes(1))
|
||||
expect(createRepo).toHaveBeenCalledWith({
|
||||
await waitFor(() => expect(mocks.createRepo).toHaveBeenCalledTimes(1))
|
||||
expect(mocks.createRepo).toHaveBeenCalledWith({
|
||||
repoUrl,
|
||||
branch: 'my-new-branch',
|
||||
useWorktree: true,
|
||||
@@ -157,4 +208,57 @@ describe('CreateWorktreeDialog', () => {
|
||||
expect(await screen.findByText('Use Existing branch instead')).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Create Worktree' })).toBeDisabled()
|
||||
})
|
||||
|
||||
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,12 +1,15 @@
|
||||
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'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { AlertCircle, GitBranch, Loader2 } from 'lucide-react'
|
||||
import { createRepo, listBranches, type CreateRepoOptions } from '@/api/repos'
|
||||
import { dialogSearch } from '@/hooks/useDialogParam'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { notifyWorktreeSetup } from '@/lib/worktreeSetup'
|
||||
import { invalidateRepoGitCaches } from '@/lib/queryInvalidation'
|
||||
import { getOriginOnlyBranchNames } from '@/lib/utils'
|
||||
import { BaseBranchSelect } from './BaseBranchSelect'
|
||||
@@ -36,6 +39,7 @@ export function CreateWorktreeDialog({
|
||||
onCreated,
|
||||
}: CreateWorktreeDialogProps) {
|
||||
const queryClient = useQueryClient()
|
||||
const navigate = useNavigate()
|
||||
const [mode, setMode] = useState<WorktreeMode>('new')
|
||||
const [branchName, setBranchName] = useState('')
|
||||
const [baseBranch, setBaseBranch] = useState<string>('')
|
||||
@@ -97,11 +101,15 @@ export function CreateWorktreeDialog({
|
||||
}
|
||||
return createRepo(options)
|
||||
},
|
||||
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}${dialogSearch('terminal', { terminal: repo.worktreeSetup.terminal.id })}`)
|
||||
}
|
||||
},
|
||||
onError: (err) => {
|
||||
setError(err instanceof Error ? err.message : 'Failed to create worktree')
|
||||
|
||||
@@ -0,0 +1,353 @@
|
||||
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 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',
|
||||
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,
|
||||
executable: ProjectConfigResponse['repoFile']['executable'] = null,
|
||||
): ProjectConfigResponse {
|
||||
return {
|
||||
actions,
|
||||
worktreeSetup: [],
|
||||
repoFile: {
|
||||
path: '.ocm/project.json',
|
||||
exists: hash !== null,
|
||||
trusted: true,
|
||||
hash,
|
||||
warnings: [],
|
||||
executable,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
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, repoExecutable), isLoading: false, error: null })
|
||||
mocks.getProjectConfig.mockResolvedValue(makeConfig([repoAction], HASH, repoExecutable))
|
||||
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('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, 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()
|
||||
|
||||
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, 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()
|
||||
|
||||
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, 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()
|
||||
|
||||
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, 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: '' }
|
||||
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, 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) => {
|
||||
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,228 @@
|
||||
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 {
|
||||
ProjectConfigResponse,
|
||||
RunProjectActionResponse,
|
||||
} from '@opencode-manager/shared/types'
|
||||
import { Play, Square } 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 { 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'
|
||||
import { TrustExecutableList } from './TrustExecutableList'
|
||||
import { actionIcon } from './projectActionIcons'
|
||||
|
||||
interface ProjectActionsMenuProps {
|
||||
repoId: number
|
||||
directory: string | undefined
|
||||
}
|
||||
|
||||
interface PendingTrust {
|
||||
actionId: string
|
||||
hash: string
|
||||
directory: string
|
||||
executable: NonNullable<ProjectConfigResponse['repoFile']['executable']>
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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,
|
||||
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.actionId && isRunningActionTerminal(terminal, terminal.actionId)) {
|
||||
map.set(terminal.actionId, terminal)
|
||||
}
|
||||
}
|
||||
return map
|
||||
}, [terminalsQuery.data])
|
||||
|
||||
const handleRunSuccess = useCallback((result: RunProjectActionResponse) => {
|
||||
openTerminal(result.terminal.id)
|
||||
if (result.autoOpenUrl && result.resolvedUrl) {
|
||||
openUrlFromManager(result.resolvedUrl, { openPreview })
|
||||
}
|
||||
}, [openTerminal, 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(getOpenCodeApiErrorMessage(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',
|
||||
)
|
||||
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, executable })
|
||||
}, [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(getOpenCodeApiErrorMessage(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(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(getOpenCodeApiErrorMessage(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 = actionIcon(action.icon)
|
||||
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 ? <TrustExecutableList executable={pendingTrust.executable} /> : undefined}
|
||||
confirmLabel="Trust and run"
|
||||
pendingLabel="Trusting…"
|
||||
isPending={trustConfig.isPending}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,472 @@
|
||||
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'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
useProjectConfig: vi.fn(),
|
||||
updateActionsMutate: vi.fn(),
|
||||
updateSetupMutate: vi.fn(),
|
||||
trustMutate: vi.fn(),
|
||||
moveMutate: vi.fn(),
|
||||
showToastError: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/projectConfig', () => ({
|
||||
useProjectConfig: mocks.useProjectConfig,
|
||||
useUpdateProjectActions: () => ({ mutate: mocks.updateActionsMutate, isPending: false }),
|
||||
useUpdateWorktreeSetup: () => ({ mutate: mocks.updateSetupMutate, isPending: false }),
|
||||
useTrustRepoConfig: () => ({ mutate: mocks.trustMutate, isPending: false }),
|
||||
useMoveProjectItem: () => ({ mutate: mocks.moveMutate, isPending: false }),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/toast', () => ({
|
||||
showToast: { error: mocks.showToastError, success: vi.fn() },
|
||||
}))
|
||||
|
||||
const HASH = 'a'.repeat(64)
|
||||
|
||||
function baseConfig(overrides: Partial<ProjectConfigResponse> = {}): ProjectConfigResponse {
|
||||
return {
|
||||
actions: [],
|
||||
worktreeSetup: [],
|
||||
repoFile: {
|
||||
path: '.ocm/project.json',
|
||||
exists: false,
|
||||
trusted: false,
|
||||
hash: null,
|
||||
warnings: [],
|
||||
executable: null,
|
||||
},
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function mockConfig(config: ProjectConfigResponse) {
|
||||
mocks.useProjectConfig.mockReturnValue({ data: config, isLoading: false, error: null })
|
||||
}
|
||||
|
||||
function renderDialog() {
|
||||
return render(
|
||||
<RepoActionsDialog repoId={1} directory="/repo" open onOpenChange={vi.fn()} />,
|
||||
)
|
||||
}
|
||||
|
||||
describe('RepoActionsDialog', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('sends the full personal list when adding an action', async () => {
|
||||
mockConfig(
|
||||
baseConfig({
|
||||
actions: [
|
||||
{ id: 'existing', name: 'Existing', command: 'echo hi', autoOpenUrl: false, source: 'personal' },
|
||||
],
|
||||
}),
|
||||
)
|
||||
const user = userEvent.setup()
|
||||
renderDialog()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /add action/i }))
|
||||
await user.type(screen.getByLabelText('Name'), 'Dev server')
|
||||
await user.type(screen.getByLabelText('Command'), 'pnpm dev')
|
||||
await user.click(screen.getByRole('button', { name: /^save$/i }))
|
||||
|
||||
await waitFor(() => expect(mocks.updateActionsMutate).toHaveBeenCalledTimes(1))
|
||||
const payload = mocks.updateActionsMutate.mock.calls[0][0]
|
||||
expect(payload).toHaveLength(2)
|
||||
expect(payload[0]).toMatchObject({ id: 'existing', name: 'Existing', command: 'echo hi' })
|
||||
expect(payload[1]).toMatchObject({ name: 'Dev server', command: 'pnpm dev' })
|
||||
})
|
||||
|
||||
it('adds an action when crypto.randomUUID is unavailable', async () => {
|
||||
vi.stubGlobal('crypto', { randomUUID: undefined })
|
||||
try {
|
||||
mockConfig(baseConfig())
|
||||
const user = userEvent.setup()
|
||||
renderDialog()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /add action/i }))
|
||||
await user.type(screen.getByLabelText('Name'), 'Dev server')
|
||||
await user.type(screen.getByLabelText('Command'), 'pnpm dev')
|
||||
await user.click(screen.getByRole('button', { name: /^save$/i }))
|
||||
|
||||
await waitFor(() => expect(mocks.updateActionsMutate).toHaveBeenCalledTimes(1))
|
||||
const payload = mocks.updateActionsMutate.mock.calls[0][0]
|
||||
expect(payload).toHaveLength(1)
|
||||
expect(payload[0].id).toMatch(/^[A-Za-z0-9_-]{1,64}$/)
|
||||
expect(payload[0]).toMatchObject({ name: 'Dev server', command: 'pnpm dev' })
|
||||
} finally {
|
||||
vi.unstubAllGlobals()
|
||||
}
|
||||
})
|
||||
|
||||
it('offers no edit button for repo items but allows moving them to personal settings', () => {
|
||||
mockConfig(
|
||||
baseConfig({
|
||||
actions: [
|
||||
{ id: 'personal-1', name: 'Personal action', command: 'echo personal', autoOpenUrl: false, source: 'personal' },
|
||||
{ id: 'repo-1', name: 'Repo action', command: 'echo repo', autoOpenUrl: false, source: 'repo' },
|
||||
],
|
||||
}),
|
||||
)
|
||||
renderDialog()
|
||||
|
||||
expect(screen.getAllByRole('button', { name: /edit/i })).toHaveLength(1)
|
||||
expect(screen.getByText('In repo')).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: /move to my settings/i })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: /move to repository/i })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows the trust banner for an untrusted repo file and sends the displayed hash', async () => {
|
||||
mockConfig(
|
||||
baseConfig({
|
||||
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: [],
|
||||
executable: {
|
||||
actions: [
|
||||
{ id: 'repo-1', name: 'Repo action', command: 'echo repo', url: null, autoOpenUrl: false },
|
||||
],
|
||||
setup: [],
|
||||
},
|
||||
},
|
||||
}),
|
||||
)
|
||||
const user = userEvent.setup()
|
||||
renderDialog()
|
||||
|
||||
expect(screen.getByText(/not trusted/i)).toBeInTheDocument()
|
||||
await user.click(screen.getByRole('button', { name: /trust these commands/i }))
|
||||
|
||||
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: [],
|
||||
executable: null,
|
||||
},
|
||||
}),
|
||||
)
|
||||
renderDialog()
|
||||
|
||||
expect(screen.queryByRole('button', { name: /trust these commands/i })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders repository config parse errors', () => {
|
||||
mockConfig(
|
||||
baseConfig({
|
||||
repoFile: {
|
||||
path: '.ocm/project.json',
|
||||
exists: true,
|
||||
trusted: false,
|
||||
hash: null,
|
||||
error: 'Invalid repository config',
|
||||
warnings: [],
|
||||
executable: null,
|
||||
},
|
||||
}),
|
||||
)
|
||||
renderDialog()
|
||||
|
||||
expect(screen.getByRole('alert')).toHaveTextContent('Invalid repository config')
|
||||
})
|
||||
|
||||
it('moves a saved personal setup command to the repository', async () => {
|
||||
mockConfig(
|
||||
baseConfig({
|
||||
worktreeSetup: [{ command: 'pnpm install', source: 'personal' }],
|
||||
}),
|
||||
)
|
||||
const user = userEvent.setup()
|
||||
renderDialog()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /move to repository/i }))
|
||||
|
||||
expect(mocks.moveMutate.mock.calls[0][0]).toEqual({
|
||||
kind: 'setup',
|
||||
command: 'pnpm install',
|
||||
to: 'repo',
|
||||
directory: '/repo',
|
||||
})
|
||||
})
|
||||
|
||||
it('disables moving a personal setup command while edits are unsaved', async () => {
|
||||
mockConfig(
|
||||
baseConfig({
|
||||
worktreeSetup: [{ command: 'pnpm install', source: 'personal' }],
|
||||
}),
|
||||
)
|
||||
const user = userEvent.setup()
|
||||
renderDialog()
|
||||
|
||||
expect(screen.getByRole('button', { name: /move to repository/i })).toBeEnabled()
|
||||
|
||||
await user.type(screen.getByLabelText('Setup command 1'), ' --frozen-lockfile')
|
||||
|
||||
expect(screen.getByRole('button', { name: /move to repository/i })).toBeDisabled()
|
||||
expect(mocks.moveMutate).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('reports a failed action save and keeps the draft', async () => {
|
||||
mockConfig(
|
||||
baseConfig({
|
||||
actions: [
|
||||
{ id: 'existing', name: 'Existing', command: 'echo hi', autoOpenUrl: false, source: 'personal' },
|
||||
],
|
||||
}),
|
||||
)
|
||||
mocks.updateActionsMutate.mockImplementation(
|
||||
(_payload: unknown, options?: { onError?: (error: unknown) => void }) => {
|
||||
options?.onError?.(new FetchError('Server rejected the action', 400))
|
||||
},
|
||||
)
|
||||
const user = userEvent.setup()
|
||||
renderDialog()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /add action/i }))
|
||||
await user.type(screen.getByLabelText('Name'), 'Dev server')
|
||||
await user.type(screen.getByLabelText('Command'), 'pnpm dev')
|
||||
await user.click(screen.getByRole('button', { name: /^save$/i }))
|
||||
|
||||
expect(mocks.showToastError).toHaveBeenCalledWith('Server rejected the action')
|
||||
expect(screen.getByLabelText('Name')).toHaveValue('Dev server')
|
||||
expect(screen.getByLabelText('Command')).toHaveValue('pnpm dev')
|
||||
})
|
||||
|
||||
it('reports a failed setup save and keeps edits', async () => {
|
||||
mockConfig(
|
||||
baseConfig({
|
||||
worktreeSetup: [{ command: 'pnpm install', source: 'personal' }],
|
||||
}),
|
||||
)
|
||||
mocks.updateSetupMutate.mockImplementation(
|
||||
(_commands: unknown, options?: { onError?: (error: unknown) => void }) => {
|
||||
options?.onError?.(new FetchError('Setup save rejected', 400))
|
||||
},
|
||||
)
|
||||
const user = userEvent.setup()
|
||||
renderDialog()
|
||||
|
||||
const input = screen.getByLabelText('Setup command 1')
|
||||
await user.clear(input)
|
||||
await user.type(input, 'pnpm ci')
|
||||
await user.click(screen.getByRole('button', { name: /save setup/i }))
|
||||
|
||||
expect(mocks.showToastError).toHaveBeenCalledWith('Setup save rejected')
|
||||
expect(screen.getByLabelText('Setup command 1')).toHaveValue('pnpm ci')
|
||||
})
|
||||
|
||||
it('reports a failed trust attempt', async () => {
|
||||
mockConfig(
|
||||
baseConfig({
|
||||
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: [],
|
||||
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 FetchError('Trust rejected', 400))
|
||||
},
|
||||
)
|
||||
const user = userEvent.setup()
|
||||
renderDialog()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /trust these commands/i }))
|
||||
|
||||
expect(mocks.showToastError).toHaveBeenCalledWith('Trust rejected')
|
||||
})
|
||||
|
||||
it('reports a failed move', async () => {
|
||||
mockConfig(
|
||||
baseConfig({
|
||||
actions: [
|
||||
{ id: 'personal-1', name: 'Personal action', command: 'echo personal', autoOpenUrl: false, source: 'personal' },
|
||||
],
|
||||
}),
|
||||
)
|
||||
mocks.moveMutate.mockImplementation(
|
||||
(_request: unknown, options?: { onError?: (error: unknown) => void }) => {
|
||||
options?.onError?.(new FetchError('Move rejected', 400))
|
||||
},
|
||||
)
|
||||
const user = userEvent.setup()
|
||||
renderDialog()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /move to repository/i }))
|
||||
|
||||
expect(mocks.showToastError).toHaveBeenCalledWith('Move rejected')
|
||||
})
|
||||
|
||||
it('preserves unsaved setup edits when unrelated config data refetches', async () => {
|
||||
mockConfig(
|
||||
baseConfig({
|
||||
actions: [
|
||||
{ id: 'existing', name: 'Existing', command: 'echo hi', autoOpenUrl: false, source: 'personal' },
|
||||
],
|
||||
worktreeSetup: [{ command: 'pnpm install', source: 'personal' }],
|
||||
}),
|
||||
)
|
||||
const user = userEvent.setup()
|
||||
const view = renderDialog()
|
||||
|
||||
await user.type(screen.getByLabelText('Setup command 1'), ' --frozen-lockfile')
|
||||
|
||||
mockConfig(
|
||||
baseConfig({
|
||||
actions: [
|
||||
{ id: 'existing', name: 'Existing', command: 'echo hi', autoOpenUrl: false, source: 'personal' },
|
||||
{ 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: [], executable: null },
|
||||
}),
|
||||
)
|
||||
view.rerender(<RepoActionsDialog repoId={1} directory="/repo" open onOpenChange={vi.fn()} />)
|
||||
|
||||
expect(screen.getByLabelText('Setup command 1')).toHaveValue('pnpm install --frozen-lockfile')
|
||||
})
|
||||
|
||||
it('reflects persisted setup commands after a setup operation', () => {
|
||||
mockConfig(
|
||||
baseConfig({
|
||||
worktreeSetup: [{ command: 'pnpm install', source: 'personal' }],
|
||||
}),
|
||||
)
|
||||
const view = renderDialog()
|
||||
|
||||
mockConfig(
|
||||
baseConfig({
|
||||
worktreeSetup: [{ command: 'pnpm ci', source: 'personal' }],
|
||||
}),
|
||||
)
|
||||
view.rerender(<RepoActionsDialog repoId={1} directory="/repo" open onOpenChange={vi.fn()} />)
|
||||
|
||||
expect(screen.getByLabelText('Setup command 1')).toHaveValue('pnpm ci')
|
||||
})
|
||||
|
||||
it('reinitializes setup commands from persisted data when the dialog reopens', async () => {
|
||||
mockConfig(
|
||||
baseConfig({
|
||||
worktreeSetup: [{ command: 'pnpm install', source: 'personal' }],
|
||||
}),
|
||||
)
|
||||
const user = userEvent.setup()
|
||||
const view = renderDialog()
|
||||
|
||||
await user.type(screen.getByLabelText('Setup command 1'), ' --frozen-lockfile')
|
||||
|
||||
view.rerender(<RepoActionsDialog repoId={1} directory="/repo" open={false} onOpenChange={vi.fn()} />)
|
||||
view.rerender(<RepoActionsDialog repoId={1} directory="/repo" open onOpenChange={vi.fn()} />)
|
||||
|
||||
expect(screen.getByLabelText('Setup command 1')).toHaveValue('pnpm install')
|
||||
})
|
||||
|
||||
it('reinitializes setup commands when the location changes', async () => {
|
||||
mockConfig(
|
||||
baseConfig({
|
||||
worktreeSetup: [{ command: 'pnpm install', source: 'personal' }],
|
||||
}),
|
||||
)
|
||||
const user = userEvent.setup()
|
||||
const view = renderDialog()
|
||||
|
||||
await user.type(screen.getByLabelText('Setup command 1'), ' --frozen-lockfile')
|
||||
|
||||
mockConfig(
|
||||
baseConfig({
|
||||
worktreeSetup: [{ command: 'pnpm ci', source: 'personal' }],
|
||||
}),
|
||||
)
|
||||
view.rerender(<RepoActionsDialog repoId={1} directory="/repo-worktree" open onOpenChange={vi.fn()} />)
|
||||
|
||||
expect(screen.getByLabelText('Setup command 1')).toHaveValue('pnpm ci')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,538 @@
|
||||
import { useEffect, useMemo, useRef, useState } from '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'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import {
|
||||
useMoveProjectItem,
|
||||
useProjectConfig,
|
||||
useTrustRepoConfig,
|
||||
useUpdateProjectActions,
|
||||
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'
|
||||
import { ACTION_ICON_OPTIONS, actionIcon } from './projectActionIcons'
|
||||
import { TrustExecutableList } from './TrustExecutableList'
|
||||
|
||||
interface ActionDraft {
|
||||
id: string
|
||||
name: string
|
||||
command: string
|
||||
icon: ProjectActionIcon
|
||||
url: string
|
||||
autoOpenUrl: boolean
|
||||
}
|
||||
|
||||
function emptyActionDraft(): ActionDraft {
|
||||
return { id: randomId(), name: '', command: '', icon: 'play', url: '', autoOpenUrl: false }
|
||||
}
|
||||
|
||||
function actionToDraft(action: ProjectAction): ActionDraft {
|
||||
return {
|
||||
id: action.id,
|
||||
name: action.name,
|
||||
command: action.command,
|
||||
icon: action.icon ?? 'play',
|
||||
url: action.url ?? '',
|
||||
autoOpenUrl: action.autoOpenUrl,
|
||||
}
|
||||
}
|
||||
|
||||
function actionToPayload(action: ProjectAction): ProjectAction {
|
||||
const payload: ProjectAction = {
|
||||
id: action.id,
|
||||
name: action.name,
|
||||
command: action.command,
|
||||
autoOpenUrl: action.autoOpenUrl,
|
||||
}
|
||||
if (action.icon) payload.icon = action.icon
|
||||
if (action.url) payload.url = action.url
|
||||
return payload
|
||||
}
|
||||
|
||||
function draftToPayload(draft: ActionDraft): ProjectAction {
|
||||
const payload: ProjectAction = {
|
||||
id: draft.id,
|
||||
name: draft.name.trim(),
|
||||
command: draft.command.trim(),
|
||||
icon: draft.icon,
|
||||
autoOpenUrl: draft.autoOpenUrl,
|
||||
}
|
||||
const url = draft.url.trim()
|
||||
if (url) payload.url = url
|
||||
return payload
|
||||
}
|
||||
|
||||
interface ActionFormProps {
|
||||
draft: ActionDraft
|
||||
isSaving: boolean
|
||||
onChange: (draft: ActionDraft) => void
|
||||
onSave: (draft: ActionDraft) => void
|
||||
onCancel: () => void
|
||||
}
|
||||
|
||||
function ActionForm({ draft, isSaving, onChange, onSave, onCancel }: ActionFormProps) {
|
||||
const canSave = draft.name.trim().length > 0 && draft.command.trim().length > 0
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="action-name">Name</Label>
|
||||
<Input
|
||||
id="action-name"
|
||||
value={draft.name}
|
||||
onChange={(event) => onChange({ ...draft, name: event.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="action-command">Command</Label>
|
||||
<Input
|
||||
id="action-command"
|
||||
value={draft.command}
|
||||
onChange={(event) => onChange({ ...draft, command: event.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="action-icon">Icon</Label>
|
||||
<Select
|
||||
value={draft.icon}
|
||||
onValueChange={(value) => onChange({ ...draft, icon: value as ProjectActionIcon })}
|
||||
>
|
||||
<SelectTrigger id="action-icon">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{ACTION_ICON_OPTIONS.map(({ value, label }) => (
|
||||
<SelectItem key={value} value={value}>
|
||||
{label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="action-url">URL template</Label>
|
||||
<Input
|
||||
id="action-url"
|
||||
placeholder="http://localhost:3000/{worktree}"
|
||||
value={draft.url}
|
||||
onChange={(event) => onChange({ ...draft, url: event.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<Label htmlFor="action-auto-open">Auto-open URL</Label>
|
||||
<Switch
|
||||
id="action-auto-open"
|
||||
checked={draft.autoOpenUrl}
|
||||
onCheckedChange={(checked) => onChange({ ...draft, autoOpenUrl: checked })}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button type="button" size="sm" variant="ghost" onClick={onCancel}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="button" size="sm" onClick={() => onSave(draft)} disabled={!canSave || isSaving}>
|
||||
Save
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
interface RepoActionsDialogProps {
|
||||
repoId: number
|
||||
directory: string | undefined
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
}
|
||||
|
||||
export function RepoActionsDialog({ repoId, directory, open, onOpenChange }: RepoActionsDialogProps) {
|
||||
const configQuery = useProjectConfig(repoId, directory, open && !!directory)
|
||||
const updateActions = useUpdateProjectActions(repoId, directory)
|
||||
const updateSetup = useUpdateWorktreeSetup(repoId, directory)
|
||||
const trustConfig = useTrustRepoConfig(repoId)
|
||||
const moveItem = useMoveProjectItem(repoId)
|
||||
|
||||
const [draft, setDraft] = useState<ActionDraft | null>(null)
|
||||
const [setupCommands, setSetupCommands] = useState<string[]>([])
|
||||
|
||||
const config = configQuery.data
|
||||
|
||||
const personalActions = useMemo(
|
||||
() => (config?.actions ?? []).filter((action) => action.source === 'personal'),
|
||||
[config],
|
||||
)
|
||||
const repoActions = useMemo(
|
||||
() => (config?.actions ?? []).filter((action) => action.source === 'repo'),
|
||||
[config],
|
||||
)
|
||||
const repoSetup = useMemo(
|
||||
() => (config?.worktreeSetup ?? []).filter((item) => item.source === 'repo'),
|
||||
[config],
|
||||
)
|
||||
const personalSetup = useMemo(
|
||||
() => (config?.worktreeSetup ?? []).filter((item) => item.source === 'personal').map((item) => item.command),
|
||||
[config],
|
||||
)
|
||||
const personalSetupBaseline = useMemo(() => JSON.stringify(personalSetup), [personalSetup])
|
||||
const setupSyncKey = useRef<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !config) {
|
||||
setupSyncKey.current = null
|
||||
return
|
||||
}
|
||||
const syncKey = `${directory ?? ''}\u0000${personalSetupBaseline}`
|
||||
if (setupSyncKey.current === syncKey) return
|
||||
setupSyncKey.current = syncKey
|
||||
setSetupCommands(personalSetup)
|
||||
}, [open, config, directory, personalSetup, personalSetupBaseline])
|
||||
|
||||
const setupDirty = useMemo(
|
||||
() =>
|
||||
setupCommands.length !== personalSetup.length ||
|
||||
setupCommands.some((command, index) => command !== personalSetup[index]),
|
||||
[setupCommands, personalSetup],
|
||||
)
|
||||
|
||||
const handleSaveAction = (nextDraft: ActionDraft) => {
|
||||
const payload = draftToPayload(nextDraft)
|
||||
const exists = personalActions.some((action) => action.id === payload.id)
|
||||
const next = exists
|
||||
? personalActions.map((action) => (action.id === payload.id ? payload : actionToPayload(action)))
|
||||
: [...personalActions.map(actionToPayload), payload]
|
||||
updateActions.mutate(next, {
|
||||
onSuccess: () => setDraft(null),
|
||||
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(getOpenCodeApiErrorMessage(error, 'Failed to delete action')),
|
||||
})
|
||||
}
|
||||
|
||||
const handleSaveSetup = () => {
|
||||
updateSetup.mutate(setupCommands.map((command) => command.trim()), {
|
||||
onError: (error) => showToast.error(getOpenCodeApiErrorMessage(error, 'Failed to save setup commands')),
|
||||
})
|
||||
}
|
||||
|
||||
const handleTrust = () => {
|
||||
if (!config?.repoFile.hash) return
|
||||
trustConfig.mutate(
|
||||
{ hash: config.repoFile.hash, directory },
|
||||
{ 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(getOpenCodeApiErrorMessage(error, 'Failed to move action')) },
|
||||
)
|
||||
}
|
||||
|
||||
const moveSetup = (command: string, to: ProjectItemSource) => {
|
||||
moveItem.mutate(
|
||||
{ kind: 'setup', command, to, directory },
|
||||
{ onError: (error) => showToast.error(getOpenCodeApiErrorMessage(error, 'Failed to move setup command')) },
|
||||
)
|
||||
}
|
||||
|
||||
const isAddingAction = draft !== null && !personalActions.some((action) => action.id === draft.id)
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent
|
||||
mobileFullscreen
|
||||
className="sm:fixed sm:left-1/2 sm:top-1/2 sm:-translate-x-1/2 sm:-translate-y-1/2 sm:w-[520px] sm:max-w-[520px] sm:h-auto sm:max-h-[85vh] flex flex-col gap-0 pb-safe"
|
||||
>
|
||||
<DialogHeader className="px-4 sm:px-6 pt-4 sm:pt-6 pb-2 sm:pb-3 shrink-0">
|
||||
<DialogTitle>Project Actions</DialogTitle>
|
||||
<DialogDescription>Commands and setup steps for this location.</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex-1 overflow-y-auto px-4 sm:px-6 pb-4 sm:pb-6 space-y-6">
|
||||
{configQuery.isLoading ? (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Loader2 className="h-4 w-4 animate-spin text-primary" />
|
||||
</div>
|
||||
) : !config ? (
|
||||
<p className="text-sm text-destructive">
|
||||
{configQuery.error instanceof Error ? configQuery.error.message : 'No configuration available.'}
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<section className="space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-sm font-semibold">Actions</h3>
|
||||
<Button type="button" size="sm" variant="outline" onClick={() => setDraft(emptyActionDraft())}>
|
||||
<Plus className="h-4 w-4 mr-1" />
|
||||
Add action
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{personalActions.length === 0 && repoActions.length === 0 && (
|
||||
<p className="text-sm text-muted-foreground">No actions configured.</p>
|
||||
)}
|
||||
|
||||
{personalActions.map((action) => {
|
||||
const Icon = actionIcon(action.icon)
|
||||
const isEditing = draft?.id === action.id
|
||||
return (
|
||||
<div key={action.id} className="rounded-lg border border-border bg-card p-3 space-y-2">
|
||||
{isEditing && draft ? (
|
||||
<ActionForm
|
||||
draft={draft}
|
||||
isSaving={updateActions.isPending}
|
||||
onChange={setDraft}
|
||||
onSave={handleSaveAction}
|
||||
onCancel={() => setDraft(null)}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<div className="flex items-center gap-2">
|
||||
<Icon className="h-4 w-4 text-muted-foreground shrink-0" />
|
||||
<span className="text-sm font-medium truncate">{action.name}</span>
|
||||
</div>
|
||||
<p className="font-mono text-xs text-muted-foreground truncate">{action.command}</p>
|
||||
{action.url && (
|
||||
<p className="text-xs text-muted-foreground truncate">{action.url}</p>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => setDraft(actionToDraft(action))}
|
||||
>
|
||||
<Pencil className="h-3 w-3 mr-1" />
|
||||
Edit
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => moveAction(action, 'repo')}
|
||||
disabled={moveItem.isPending}
|
||||
>
|
||||
Move to repository
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => handleDeleteAction(action.id)}
|
||||
disabled={updateActions.isPending}
|
||||
>
|
||||
<Trash2 className="h-3 w-3 mr-1" />
|
||||
Delete
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
|
||||
{repoActions.map((action) => {
|
||||
const Icon = actionIcon(action.icon)
|
||||
return (
|
||||
<div key={action.id} className="rounded-lg border border-border bg-card p-3 space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Icon className="h-4 w-4 text-muted-foreground shrink-0" />
|
||||
<span className="text-sm font-medium truncate">{action.name}</span>
|
||||
<Badge variant="secondary">In repo</Badge>
|
||||
</div>
|
||||
<p className="font-mono text-xs text-muted-foreground truncate">{action.command}</p>
|
||||
{action.url && (
|
||||
<p className="text-xs text-muted-foreground truncate">{action.url}</p>
|
||||
)}
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => moveAction(action, 'personal')}
|
||||
disabled={moveItem.isPending}
|
||||
>
|
||||
Move to my settings
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
|
||||
{isAddingAction && draft && (
|
||||
<div className="rounded-lg border border-border bg-card p-3">
|
||||
<ActionForm
|
||||
draft={draft}
|
||||
isSaving={updateActions.isPending}
|
||||
onChange={setDraft}
|
||||
onSave={handleSaveAction}
|
||||
onCancel={() => setDraft(null)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section className="space-y-3">
|
||||
<div>
|
||||
<h3 className="text-sm font-semibold">Worktree setup</h3>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
Commands run after a new worktree is created. Use{' '}
|
||||
<code className="font-mono">$ROOT_PROJECT_PATH</code> to reference the main checkout.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{setupCommands.length === 0 && repoSetup.length === 0 && (
|
||||
<p className="text-sm text-muted-foreground">No setup commands.</p>
|
||||
)}
|
||||
|
||||
{setupCommands.map((command, index) => (
|
||||
<div key={index} className="rounded-lg border border-border bg-card p-3 space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
aria-label={`Setup command ${index + 1}`}
|
||||
value={command}
|
||||
onChange={(event) =>
|
||||
setSetupCommands((current) =>
|
||||
current.map((item, itemIndex) => (itemIndex === index ? event.target.value : item)),
|
||||
)
|
||||
}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
aria-label="Move up"
|
||||
disabled={index === 0}
|
||||
onClick={() => setSetupCommands((current) => arrayMove(current, index, index - 1))}
|
||||
>
|
||||
<ArrowUp className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
aria-label="Move down"
|
||||
disabled={index === setupCommands.length - 1}
|
||||
onClick={() => setSetupCommands((current) => arrayMove(current, index, index + 1))}
|
||||
>
|
||||
<ArrowDown className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
aria-label="Remove command"
|
||||
onClick={() => setSetupCommands((current) => current.filter((_, itemIndex) => itemIndex !== index))}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<div className="flex justify-end">
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => moveSetup(command, 'repo')}
|
||||
disabled={setupDirty || moveItem.isPending}
|
||||
>
|
||||
Move to repository
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{repoSetup.map((item) => (
|
||||
<div
|
||||
key={item.command}
|
||||
className="flex items-center justify-between gap-2 rounded-lg border border-border bg-card p-3"
|
||||
>
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<span className="font-mono text-xs truncate">{item.command}</span>
|
||||
<Badge variant="secondary">In repo</Badge>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => moveSetup(item.command, 'personal')}
|
||||
disabled={moveItem.isPending}
|
||||
>
|
||||
Move to my settings
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => setSetupCommands((current) => [...current, ''])}
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-1" />
|
||||
Add command
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
onClick={handleSaveSetup}
|
||||
disabled={setupCommands.some((command) => !command.trim()) || updateSetup.isPending}
|
||||
>
|
||||
Save setup
|
||||
</Button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="space-y-2">
|
||||
{config.repoFile.error && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{config.repoFile.error}
|
||||
</p>
|
||||
)}
|
||||
{config.repoFile.warnings.map((warning) => (
|
||||
<p key={warning} className="text-xs text-warning">
|
||||
{warning}
|
||||
</p>
|
||||
))}
|
||||
{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>
|
||||
)}
|
||||
</section>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
interface TerminalKeyBarProps {
|
||||
onSend: (data: string) => void
|
||||
ctrlArmed: boolean
|
||||
onToggleCtrl: () => void
|
||||
}
|
||||
|
||||
interface SpecialKey {
|
||||
label: string
|
||||
data: string
|
||||
ariaLabel?: string
|
||||
}
|
||||
|
||||
const ESCAPE_KEY = '\x1b'
|
||||
const TAB_KEY = '\t'
|
||||
|
||||
const ARROW_KEYS: SpecialKey[] = [
|
||||
{ label: '↑', data: '\x1b[A', ariaLabel: 'Arrow up' },
|
||||
{ label: '↓', data: '\x1b[B', ariaLabel: 'Arrow down' },
|
||||
{ label: '←', data: '\x1b[D', ariaLabel: 'Arrow left' },
|
||||
{ label: '→', data: '\x1b[C', ariaLabel: 'Arrow right' },
|
||||
]
|
||||
|
||||
const SYMBOL_KEYS: SpecialKey[] = [
|
||||
{ label: '|', data: '|' },
|
||||
{ label: '~', data: '~' },
|
||||
{ label: '/', data: '/' },
|
||||
]
|
||||
|
||||
export function TerminalKeyBar({ onSend, ctrlArmed, onToggleCtrl }: TerminalKeyBarProps) {
|
||||
const renderKey = (key: SpecialKey) => (
|
||||
<Button
|
||||
key={key.label}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 min-w-8 flex-shrink-0 px-2 font-mono text-xs"
|
||||
aria-label={key.ariaLabel}
|
||||
onMouseDown={(event) => event.preventDefault()}
|
||||
onClick={() => onSend(key.data)}
|
||||
>
|
||||
{key.label}
|
||||
</Button>
|
||||
)
|
||||
|
||||
return (
|
||||
<div
|
||||
className="flex flex-shrink-0 items-center gap-1 overflow-x-auto border-t border-border bg-card px-2 py-1.5"
|
||||
data-testid="terminal-key-bar"
|
||||
>
|
||||
{renderKey({ label: 'Esc', data: ESCAPE_KEY })}
|
||||
{renderKey({ label: 'Tab', data: TAB_KEY })}
|
||||
<Button
|
||||
type="button"
|
||||
variant={ctrlArmed ? 'default' : 'ghost'}
|
||||
size="sm"
|
||||
className={cn('h-8 min-w-8 flex-shrink-0 px-2 font-mono text-xs', ctrlArmed && 'bg-primary text-primary-foreground')}
|
||||
aria-pressed={ctrlArmed}
|
||||
onMouseDown={(event) => event.preventDefault()}
|
||||
onClick={onToggleCtrl}
|
||||
>
|
||||
Ctrl
|
||||
</Button>
|
||||
{ARROW_KEYS.map(renderKey)}
|
||||
{SYMBOL_KEYS.map(renderKey)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
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'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
import { TerminalPanel } from './TerminalPanel'
|
||||
|
||||
vi.mock('@/api/terminals', () => ({
|
||||
useTerminals: vi.fn(),
|
||||
useCreateTerminal: vi.fn(),
|
||||
useRemoveTerminal: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useMobile', async () => {
|
||||
const actual = await vi.importActual<typeof import('@/hooks/useMobile')>('@/hooks/useMobile')
|
||||
return { ...actual, useMobile: vi.fn(() => false) }
|
||||
})
|
||||
|
||||
vi.mock('./TerminalView', async () => {
|
||||
const React = await import('react')
|
||||
return {
|
||||
TerminalView: React.forwardRef(function MockTerminalView(
|
||||
props: { ptyID: string; active: boolean },
|
||||
ref: React.Ref<unknown>,
|
||||
) {
|
||||
React.useImperativeHandle(ref, () => ({ send: vi.fn() }))
|
||||
return React.createElement('div', {
|
||||
'data-testid': 'terminal-view',
|
||||
'data-pty-id': props.ptyID,
|
||||
'data-active': String(props.active),
|
||||
})
|
||||
}),
|
||||
}
|
||||
})
|
||||
|
||||
const runningTerminal: TerminalInfo = {
|
||||
id: 't1',
|
||||
title: 'Terminal',
|
||||
kind: 'shell',
|
||||
cwd: '/repo',
|
||||
status: 'running',
|
||||
}
|
||||
|
||||
const exitedTerminal: TerminalInfo = {
|
||||
id: 't2',
|
||||
title: 'Build',
|
||||
kind: 'action',
|
||||
actionId: 'build',
|
||||
cwd: '/repo',
|
||||
status: 'exited',
|
||||
exitCode: 0,
|
||||
}
|
||||
|
||||
const createMutate = vi.fn()
|
||||
const removeMutate = vi.fn()
|
||||
const refetch = vi.fn()
|
||||
|
||||
function mockTerminalHooks(
|
||||
terminals: TerminalInfo[] | undefined,
|
||||
options: { isLoading?: boolean; isSuccess?: boolean } = {},
|
||||
) {
|
||||
vi.mocked(useTerminals).mockReturnValue({
|
||||
data: terminals,
|
||||
isLoading: options.isLoading ?? false,
|
||||
isSuccess: options.isSuccess ?? terminals !== undefined,
|
||||
refetch,
|
||||
} as unknown as ReturnType<typeof useTerminals>)
|
||||
vi.mocked(useCreateTerminal).mockReturnValue({
|
||||
mutate: createMutate,
|
||||
isPending: false,
|
||||
} as unknown as ReturnType<typeof useCreateTerminal>)
|
||||
vi.mocked(useRemoveTerminal).mockReturnValue({
|
||||
mutate: removeMutate,
|
||||
isPending: false,
|
||||
} as unknown as ReturnType<typeof useRemoveTerminal>)
|
||||
}
|
||||
|
||||
function renderPanel(initialEntry = '/repos/1?dialog=terminal', onClose = vi.fn()) {
|
||||
return render(
|
||||
<MemoryRouter initialEntries={[initialEntry]}>
|
||||
<TerminalPanel repoId={1} directory="/repo" isOpen onClose={onClose} />
|
||||
</MemoryRouter>,
|
||||
)
|
||||
}
|
||||
|
||||
describe('TerminalPanel', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(useMobile).mockReturnValue(false)
|
||||
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()
|
||||
|
||||
expect(createMutate).toHaveBeenCalledTimes(1)
|
||||
expect(createMutate).toHaveBeenCalledWith({ directory: '/repo' }, expect.any(Object))
|
||||
})
|
||||
|
||||
it('does not auto-create while the list request is unresolved or failed', () => {
|
||||
mockTerminalHooks(undefined, { isSuccess: false })
|
||||
renderPanel()
|
||||
|
||||
expect(createMutate).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('auto-creates once the list resolves successfully empty', () => {
|
||||
mockTerminalHooks(undefined, { isSuccess: false })
|
||||
const { rerender } = renderPanel()
|
||||
expect(createMutate).not.toHaveBeenCalled()
|
||||
|
||||
mockTerminalHooks([], { isSuccess: true })
|
||||
rerender(
|
||||
<MemoryRouter initialEntries={['/repos/1?dialog=terminal']}>
|
||||
<TerminalPanel repoId={1} directory="/repo" isOpen onClose={vi.fn()} />
|
||||
</MemoryRouter>,
|
||||
)
|
||||
|
||||
expect(createMutate).toHaveBeenCalledTimes(1)
|
||||
expect(createMutate).toHaveBeenCalledWith({ directory: '/repo' }, expect.any(Object))
|
||||
})
|
||||
|
||||
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', async () => {
|
||||
mockTerminalHooks([runningTerminal, exitedTerminal])
|
||||
renderPanel('/repos/1?dialog=terminal&terminal=t2')
|
||||
|
||||
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')
|
||||
|
||||
expect(active).toHaveAttribute('data-active', 'true')
|
||||
expect(inactive).toHaveAttribute('data-active', 'false')
|
||||
})
|
||||
|
||||
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', async () => {
|
||||
mockTerminalHooks([runningTerminal])
|
||||
renderPanel()
|
||||
await screen.findAllByTestId('terminal-view')
|
||||
|
||||
fireEvent.click(screen.getByLabelText('Close Terminal'))
|
||||
|
||||
expect(screen.getByText('Stop the running process?')).toBeInTheDocument()
|
||||
expect(removeMutate).not.toHaveBeenCalled()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Stop' }))
|
||||
|
||||
expect(removeMutate).toHaveBeenCalledWith({ ptyID: 't1', directory: '/repo' }, expect.any(Object))
|
||||
})
|
||||
|
||||
it('removes an exited terminal without confirmation', async () => {
|
||||
mockTerminalHooks([exitedTerminal])
|
||||
renderPanel()
|
||||
await screen.findAllByTestId('terminal-view')
|
||||
|
||||
fireEvent.click(screen.getByLabelText('Close Build'))
|
||||
|
||||
expect(screen.queryByText('Stop the running process?')).not.toBeInTheDocument()
|
||||
expect(removeMutate).toHaveBeenCalledWith({ ptyID: 't2', directory: '/repo' }, expect.any(Object))
|
||||
})
|
||||
|
||||
it('renders the key bar only on mobile', async () => {
|
||||
mockTerminalHooks([runningTerminal])
|
||||
|
||||
vi.mocked(useMobile).mockReturnValue(false)
|
||||
const first = renderPanel()
|
||||
await screen.findAllByTestId('terminal-view')
|
||||
expect(screen.queryByTestId('terminal-key-bar')).not.toBeInTheDocument()
|
||||
|
||||
first.unmount()
|
||||
|
||||
vi.mocked(useMobile).mockReturnValue(true)
|
||||
renderPanel()
|
||||
await screen.findAllByTestId('terminal-view')
|
||||
expect(screen.getByTestId('terminal-key-bar')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,238 @@
|
||||
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'
|
||||
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 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
|
||||
}
|
||||
|
||||
export function TerminalPanel({ repoId, directory, isOpen, onClose }: 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,
|
||||
})
|
||||
const { mutate: createTerminal, isPending: isCreating } = useCreateTerminal(repoId)
|
||||
const { mutate: removeTerminal, isPending: isRemoving } = useRemoveTerminal(repoId)
|
||||
|
||||
const [ctrlArmed, setCtrlArmed] = useState(false)
|
||||
const [pendingClose, setPendingClose] = useState<TerminalInfo | null>(null)
|
||||
const viewHandlesRef = useRef(new Map<string, TerminalViewHandle>())
|
||||
const autoCreatedDirectoryRef = useRef<string | null>(null)
|
||||
|
||||
const terminals = useMemo(() => data ?? [], [data])
|
||||
|
||||
const selectTerminal = useCallback((id: string) => {
|
||||
updateParams((params) => {
|
||||
params.set('terminal', id)
|
||||
}, 'replace')
|
||||
}, [updateParams])
|
||||
|
||||
const requestedTerminalId = searchParams.get('terminal')
|
||||
const activeTerminalId = requestedTerminalId && terminals.some((terminal) => terminal.id === requestedTerminalId)
|
||||
? requestedTerminalId
|
||||
: terminals[0]?.id
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen || !directory) {
|
||||
autoCreatedDirectoryRef.current = null
|
||||
return
|
||||
}
|
||||
if (!isSuccess || terminals.length > 0) return
|
||||
if (autoCreatedDirectoryRef.current === directory) return
|
||||
autoCreatedDirectoryRef.current = directory
|
||||
createTerminal(
|
||||
{ directory },
|
||||
{ onSuccess: (terminal) => selectTerminal(terminal.id) },
|
||||
)
|
||||
}, [isOpen, directory, isSuccess, terminals.length, createTerminal, selectTerminal])
|
||||
|
||||
const handleCreate = useCallback(() => {
|
||||
createTerminal(
|
||||
{ directory },
|
||||
{ onSuccess: (terminal) => selectTerminal(terminal.id) },
|
||||
)
|
||||
}, [createTerminal, directory, selectTerminal])
|
||||
|
||||
const performRemove = useCallback((terminal: TerminalInfo) => {
|
||||
removeTerminal(
|
||||
{ ptyID: terminal.id, directory },
|
||||
{
|
||||
onSuccess: () => {
|
||||
updateParams((params) => {
|
||||
if (params.get('terminal') === terminal.id) params.delete('terminal')
|
||||
}, 'replace')
|
||||
},
|
||||
},
|
||||
)
|
||||
}, [removeTerminal, directory, updateParams])
|
||||
|
||||
const handleCloseTab = useCallback((terminal: TerminalInfo) => {
|
||||
if (terminal.status === 'running') {
|
||||
setPendingClose(terminal)
|
||||
return
|
||||
}
|
||||
performRemove(terminal)
|
||||
}, [performRemove])
|
||||
|
||||
const handleKeySend = useCallback((input: string) => {
|
||||
if (!activeTerminalId) return
|
||||
viewHandlesRef.current.get(activeTerminalId)?.send(input)
|
||||
}, [activeTerminalId])
|
||||
|
||||
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
|
||||
mobileFullscreen
|
||||
hideCloseButton={isMobile}
|
||||
className={cn(
|
||||
'p-0 flex flex-col bg-card border-border gap-0',
|
||||
isMobile ? 'h-full' : 'w-[90vw] sm:max-w-5xl 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">
|
||||
<SquareTerminal className="w-5 h-5" />
|
||||
Terminal
|
||||
</DialogTitle>
|
||||
{isMobile && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onClose}
|
||||
aria-label="Close terminal 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-1 border-b border-border flex-shrink-0 overflow-x-auto px-1">
|
||||
{terminals.map((terminal) => (
|
||||
<div
|
||||
key={terminal.id}
|
||||
className={cn(
|
||||
'flex items-center gap-1 rounded-t-md border-b-2 px-2 py-1.5 text-sm transition-colors flex-shrink-0',
|
||||
terminal.id === activeTerminalId
|
||||
? 'border-primary text-foreground'
|
||||
: 'border-transparent text-muted-foreground hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => selectTerminal(terminal.id)}
|
||||
className="flex max-w-[12rem] items-center gap-1.5"
|
||||
>
|
||||
<span className="truncate">{terminal.title}</span>
|
||||
{terminal.status === 'exited' && (
|
||||
<span className="rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground">
|
||||
{terminal.exitCode !== undefined ? `exited (${terminal.exitCode})` : 'exited'}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleCloseTab(terminal)}
|
||||
aria-label={`Close ${terminal.title}`}
|
||||
className="rounded p-0.5 text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={handleCreate}
|
||||
disabled={!directory || isCreating}
|
||||
aria-label="New terminal"
|
||||
className="h-7 w-7 p-0 flex-shrink-0"
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="relative flex-1 min-h-0">
|
||||
{terminals.length === 0 ? (
|
||||
<div className="flex h-full items-center justify-center text-sm text-muted-foreground">
|
||||
{isLoading || isCreating ? 'Starting terminal...' : 'No terminals'}
|
||||
</div>
|
||||
) : (
|
||||
<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>
|
||||
|
||||
{isMobile && terminals.length > 0 && (
|
||||
<TerminalKeyBar onSend={handleKeySend} ctrlArmed={ctrlArmed} onToggleCtrl={handleToggleCtrl} />
|
||||
)}
|
||||
|
||||
<ConfirmDestructiveDialog
|
||||
open={pendingClose !== null}
|
||||
onOpenChange={(open) => { if (!open) setPendingClose(null) }}
|
||||
onConfirm={() => {
|
||||
if (pendingClose) performRemove(pendingClose)
|
||||
setPendingClose(null)
|
||||
}}
|
||||
onCancel={() => setPendingClose(null)}
|
||||
title="Close Terminal"
|
||||
description="Stop the running process?"
|
||||
confirmLabel="Stop"
|
||||
pendingLabel="Stopping..."
|
||||
isPending={isRemoving}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
import { createRef, type ComponentProps } from 'react'
|
||||
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(() => {
|
||||
const onDataHandlers: Array<(data: string) => void> = []
|
||||
return {
|
||||
onDataHandlers,
|
||||
write: vi.fn(),
|
||||
focus: vi.fn(),
|
||||
dispose: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
const socket = vi.hoisted(() => ({ send: vi.fn() }))
|
||||
|
||||
vi.mock('@xterm/xterm', () => ({
|
||||
Terminal: vi.fn().mockImplementation(() => ({
|
||||
loadAddon: vi.fn(),
|
||||
open: vi.fn(),
|
||||
write: xterm.write,
|
||||
focus: xterm.focus,
|
||||
dispose: xterm.dispose,
|
||||
onData: (handler: (data: string) => void) => {
|
||||
xterm.onDataHandlers.push(handler)
|
||||
return { dispose: vi.fn() }
|
||||
},
|
||||
options: {},
|
||||
cols: 80,
|
||||
rows: 24,
|
||||
})),
|
||||
}))
|
||||
|
||||
vi.mock('@xterm/addon-fit', () => ({
|
||||
FitAddon: vi.fn().mockImplementation(() => ({ fit: vi.fn() })),
|
||||
}))
|
||||
|
||||
vi.mock('@xterm/addon-web-links', () => ({
|
||||
WebLinksAddon: vi.fn().mockImplementation(() => ({})),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/terminals', () => ({
|
||||
resizeTerminal: vi.fn().mockResolvedValue(undefined),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/terminal-theme', () => ({
|
||||
resolveTerminalTheme: vi.fn(() => ({})),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useTerminalSocket', () => ({
|
||||
useTerminalSocket: () => ({ send: socket.send, status: 'open' }),
|
||||
}))
|
||||
|
||||
function renderView(overrides: Partial<ComponentProps<typeof TerminalView>> = {}) {
|
||||
const ref = createRef<TerminalViewHandle>()
|
||||
const onCtrlConsumed = vi.fn()
|
||||
const element = (
|
||||
<TerminalView
|
||||
ref={ref}
|
||||
repoId={1}
|
||||
directory="/repo"
|
||||
ptyID="t1"
|
||||
active
|
||||
ctrlArmed={false}
|
||||
onCtrlConsumed={onCtrlConsumed}
|
||||
onOpenLink={vi.fn()}
|
||||
onExited={vi.fn()}
|
||||
{...overrides}
|
||||
/>
|
||||
)
|
||||
const view = render(element)
|
||||
return { ref, onCtrlConsumed, view }
|
||||
}
|
||||
|
||||
describe('TerminalView input handling', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
xterm.onDataHandlers.length = 0
|
||||
})
|
||||
|
||||
it('applies the ctrl modifier and consumes it for imperative key-bar sends', () => {
|
||||
const { ref, onCtrlConsumed } = renderView({ ctrlArmed: true })
|
||||
|
||||
act(() => {
|
||||
ref.current?.send('c')
|
||||
})
|
||||
|
||||
expect(socket.send).toHaveBeenCalledWith('\x03')
|
||||
expect(onCtrlConsumed).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('applies the ctrl modifier to keyboard input while armed', () => {
|
||||
const { onCtrlConsumed } = renderView({ ctrlArmed: true })
|
||||
|
||||
act(() => {
|
||||
xterm.onDataHandlers[0]('c')
|
||||
})
|
||||
|
||||
expect(socket.send).toHaveBeenCalledWith('\x03')
|
||||
expect(onCtrlConsumed).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('consumes ctrl exactly once so subsequent keyboard input is unmodified', () => {
|
||||
const ref = createRef<TerminalViewHandle>()
|
||||
const onCtrlConsumed = vi.fn()
|
||||
const props: ComponentProps<typeof TerminalView> = {
|
||||
repoId: 1,
|
||||
directory: '/repo',
|
||||
ptyID: 't1',
|
||||
active: true,
|
||||
ctrlArmed: true,
|
||||
onCtrlConsumed,
|
||||
onOpenLink: vi.fn(),
|
||||
onExited: vi.fn(),
|
||||
}
|
||||
|
||||
const { rerender } = render(<TerminalView ref={ref} {...props} />)
|
||||
|
||||
act(() => {
|
||||
ref.current?.send('c')
|
||||
})
|
||||
expect(socket.send).toHaveBeenLastCalledWith('\x03')
|
||||
expect(onCtrlConsumed).toHaveBeenCalledTimes(1)
|
||||
|
||||
rerender(<TerminalView ref={ref} {...props} ctrlArmed={false} />)
|
||||
|
||||
act(() => {
|
||||
xterm.onDataHandlers[xterm.onDataHandlers.length - 1]('c')
|
||||
})
|
||||
|
||||
expect(socket.send).toHaveBeenLastCalledWith('c')
|
||||
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()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,206 @@
|
||||
import { forwardRef, useCallback, useEffect, useImperativeHandle, useRef } from 'react'
|
||||
import { Terminal } from '@xterm/xterm'
|
||||
import { FitAddon } from '@xterm/addon-fit'
|
||||
import { WebLinksAddon } from '@xterm/addon-web-links'
|
||||
import '@xterm/xterm/css/xterm.css'
|
||||
import { resizeTerminal } from '@/api/terminals'
|
||||
import { applyCtrlModifier } from '@/lib/terminal-protocol'
|
||||
import { resolveTerminalTheme } from '@/lib/terminal-theme'
|
||||
import { useTerminalSocket } from '@/hooks/useTerminalSocket'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
const RESIZE_DEBOUNCE_MS = 150
|
||||
|
||||
const MONOSPACE_FONT = 'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace'
|
||||
|
||||
export interface TerminalViewHandle {
|
||||
send: (data: string) => void
|
||||
}
|
||||
|
||||
interface TerminalViewProps {
|
||||
repoId: number
|
||||
directory: string | undefined
|
||||
ptyID: string
|
||||
active: boolean
|
||||
ctrlArmed: boolean
|
||||
onCtrlConsumed: () => void
|
||||
onOpenLink: (uri: string) => void
|
||||
onExited: () => void
|
||||
}
|
||||
|
||||
export const TerminalView = forwardRef<TerminalViewHandle, TerminalViewProps>(function TerminalView({
|
||||
repoId,
|
||||
directory,
|
||||
ptyID,
|
||||
active,
|
||||
ctrlArmed,
|
||||
onCtrlConsumed,
|
||||
onOpenLink,
|
||||
onExited,
|
||||
}, ref) {
|
||||
const containerRef = useRef<HTMLDivElement | null>(null)
|
||||
const terminalRef = useRef<Terminal | null>(null)
|
||||
const fitAddonRef = useRef<FitAddon | null>(null)
|
||||
const sendRef = useRef<(data: string) => void>(() => {})
|
||||
const ctrlArmedRef = useRef(ctrlArmed)
|
||||
const onCtrlConsumedRef = useRef(onCtrlConsumed)
|
||||
const onOpenLinkRef = useRef(onOpenLink)
|
||||
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)
|
||||
}, [])
|
||||
|
||||
const handleInput = useCallback((data: string) => {
|
||||
if (ctrlArmedRef.current) {
|
||||
sendRef.current(applyCtrlModifier(data))
|
||||
onCtrlConsumedRef.current()
|
||||
return
|
||||
}
|
||||
sendRef.current(data)
|
||||
}, [])
|
||||
|
||||
const handleExit = useCallback(() => {
|
||||
terminalRef.current?.write('\r\n[process exited]\r\n')
|
||||
onExitedRef.current()
|
||||
}, [])
|
||||
|
||||
const { send } = useTerminalSocket({
|
||||
repoId,
|
||||
directory,
|
||||
ptyID,
|
||||
onOutput: handleOutput,
|
||||
onExit: handleExit,
|
||||
enabled: true,
|
||||
})
|
||||
sendRef.current = send
|
||||
|
||||
useImperativeHandle(ref, () => ({ send: handleInput }), [handleInput])
|
||||
|
||||
useEffect(() => {
|
||||
const container = containerRef.current
|
||||
if (!container) return
|
||||
|
||||
const terminal = new Terminal({
|
||||
cursorBlink: true,
|
||||
scrollback: 5000,
|
||||
fontFamily: MONOSPACE_FONT,
|
||||
fontSize: isMobileRef.current ? 12 : 13,
|
||||
theme: resolveTerminalTheme(document.documentElement),
|
||||
})
|
||||
const fitAddon = new FitAddon()
|
||||
terminal.loadAddon(fitAddon)
|
||||
terminal.loadAddon(
|
||||
new WebLinksAddon((_event, uri) => {
|
||||
onOpenLinkRef.current(uri)
|
||||
}),
|
||||
)
|
||||
terminal.open(container)
|
||||
|
||||
terminalRef.current = terminal
|
||||
fitAddonRef.current = fitAddon
|
||||
|
||||
const dataDisposable = terminal.onData((data) => {
|
||||
handleInput(data)
|
||||
})
|
||||
|
||||
return () => {
|
||||
dataDisposable.dispose()
|
||||
terminal.dispose()
|
||||
terminalRef.current = null
|
||||
fitAddonRef.current = null
|
||||
}
|
||||
}, [handleInput])
|
||||
|
||||
useEffect(() => {
|
||||
const terminal = terminalRef.current
|
||||
if (!terminal) return
|
||||
terminal.options.fontSize = isMobile ? 12 : 13
|
||||
try {
|
||||
fitAddonRef.current?.fit()
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
}, [isMobile])
|
||||
|
||||
useEffect(() => {
|
||||
const root = document.documentElement
|
||||
const applyTheme = () => {
|
||||
const terminal = terminalRef.current
|
||||
if (!terminal) return
|
||||
terminal.options.theme = resolveTerminalTheme(root)
|
||||
}
|
||||
const observer = new MutationObserver(applyTheme)
|
||||
observer.observe(root, { attributes: true, attributeFilter: ['class', 'style'] })
|
||||
return () => observer.disconnect()
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
const container = containerRef.current
|
||||
if (!container) return
|
||||
|
||||
let timer: ReturnType<typeof setTimeout> | null = null
|
||||
|
||||
const scheduleResize = () => {
|
||||
if (timer) clearTimeout(timer)
|
||||
timer = setTimeout(() => {
|
||||
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
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
const observer = new ResizeObserver(scheduleResize)
|
||||
observer.observe(container)
|
||||
scheduleResize()
|
||||
|
||||
return () => {
|
||||
observer.disconnect()
|
||||
if (timer) clearTimeout(timer)
|
||||
}
|
||||
}, [repoId, directory, ptyID])
|
||||
|
||||
useEffect(() => {
|
||||
if (!active) return
|
||||
try {
|
||||
fitAddonRef.current?.fit()
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
terminalRef.current?.focus()
|
||||
}, [active])
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
className={cn('h-full w-full overflow-hidden', !active && 'hidden')}
|
||||
data-terminal-id={ptyID}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
TerminalView.displayName = 'TerminalView'
|
||||
Reference in new issue
Block a user