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:
Chris Scott committed 2026-10-04 00:10:17 -04:00
commit cf9fa61118
135 files changed
+12726 -492

No files matched your search

+36
View File
@@ -0,0 +1,36 @@
import { useQuery } from '@tanstack/react-query'
import type { CreatePreviewSessionResponse, PreviewPortsResponse } from '@opencode-manager/shared/types'
import { API_BASE_URL } from '@/config'
import { fetchWrapper } from './fetchWrapper'
function previewPortsQueryKey(directory: string | undefined) {
return ['previewPorts', directory ?? null] as const
}
function listPreviewPorts(directory?: string): Promise<PreviewPortsResponse> {
return fetchWrapper(`${API_BASE_URL}/api/preview/ports`, {
params: { directory },
})
}
export function createPreviewSession(port: number): Promise<CreatePreviewSessionResponse> {
return fetchWrapper(`${API_BASE_URL}/api/preview/sessions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ port }),
})
}
export interface UsePreviewPortsOptions {
enabled: boolean
refetchInterval?: number | false
}
export function usePreviewPorts(directory: string | undefined, options: UsePreviewPortsOptions) {
return useQuery({
queryKey: previewPortsQueryKey(directory),
queryFn: () => listPreviewPorts(directory),
enabled: options.enabled,
refetchInterval: options.refetchInterval,
})
}
+136
View File
@@ -0,0 +1,136 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import type {
MoveProjectItemRequest,
ProjectAction,
ProjectConfigResponse,
RunProjectActionResponse,
TrustRepoConfigRequest,
} from '@opencode-manager/shared/types'
import { API_BASE_URL } from '@/config'
import { fetchWrapper } from './fetchWrapper'
function projectConfigQueryKey(repoId: number, directory: string | undefined) {
return ['projectConfig', repoId, directory ?? null] as const
}
export function getProjectConfig(repoId: number, directory?: string): Promise<ProjectConfigResponse> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/project-config`, {
params: { directory },
})
}
function updateProjectActions(
repoId: number,
actions: ProjectAction[],
directory?: string,
): Promise<ProjectConfigResponse> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/project-config/actions`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ actions }),
params: { directory },
})
}
function updateWorktreeSetup(
repoId: number,
commands: string[],
directory?: string,
): Promise<ProjectConfigResponse> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/project-config/worktree-setup`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ commands }),
params: { directory },
})
}
function trustRepoConfig(repoId: number, request: TrustRepoConfigRequest): Promise<ProjectConfigResponse> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/project-config/trust`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(request),
})
}
function moveProjectItem(repoId: number, request: MoveProjectItemRequest): Promise<ProjectConfigResponse> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/project-config/move`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(request),
})
}
function runProjectAction(
repoId: number,
actionId: string,
directory?: string,
): Promise<RunProjectActionResponse> {
return fetchWrapper(
`${API_BASE_URL}/api/repos/${repoId}/project-config/actions/${encodeURIComponent(actionId)}/run`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ directory }),
},
)
}
export function useProjectConfig(repoId: number, directory: string | undefined, enabled: boolean) {
return useQuery({
queryKey: projectConfigQueryKey(repoId, directory),
queryFn: () => getProjectConfig(repoId, directory),
enabled,
})
}
export function useUpdateProjectActions(repoId: number, directory: string | undefined) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: (actions: ProjectAction[]) => updateProjectActions(repoId, actions, directory),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: projectConfigQueryKey(repoId, directory) })
},
})
}
export function useUpdateWorktreeSetup(repoId: number, directory: string | undefined) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: (commands: string[]) => updateWorktreeSetup(repoId, commands, directory),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: projectConfigQueryKey(repoId, directory) })
},
})
}
export function useTrustRepoConfig(repoId: number) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: (request: TrustRepoConfigRequest) => trustRepoConfig(repoId, request),
onSuccess: (_data, request) => {
queryClient.invalidateQueries({ queryKey: projectConfigQueryKey(repoId, request.directory) })
},
})
}
export function useMoveProjectItem(repoId: number) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: (request: MoveProjectItemRequest) => moveProjectItem(repoId, request),
onSuccess: (_data, request) => {
queryClient.invalidateQueries({ queryKey: projectConfigQueryKey(repoId, request.directory) })
},
})
}
export function useRunProjectAction(repoId: number, directory: string | undefined) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: (actionId: string) => runProjectAction(repoId, actionId, directory),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: projectConfigQueryKey(repoId, directory) })
queryClient.invalidateQueries({ queryKey: ['terminals', repoId] })
},
})
}
+2 -2
View File
@@ -2,7 +2,7 @@ import type { Repo } from './types'
import { FetchError, fetchWrapper, fetchWrapperVoid, fetchWrapperBlob } from './fetchWrapper'
import { API_BASE_URL } from '@/config'
import { saveFile } from '@/lib/download'
import type { DiscoverReposResponse, AssistantModeStatus, AssistantModeInitRequest, DeleteRepoRequest, DeleteRepoResult, RepoGitIdentity } from '@opencode-manager/shared/types'
import type { DiscoverReposResponse, AssistantModeStatus, AssistantModeInitRequest, DeleteRepoRequest, DeleteRepoResult, RepoGitIdentity, WorktreeSetupResult } from '@opencode-manager/shared/types'
export interface CreateRepoOptions {
repoUrl?: string
@@ -63,7 +63,7 @@ export async function deleteRepoWorkspace(repoId: number, directory: string): Pr
})
}
export async function createRepoWorkspace(repoId: number): Promise<RepoWorktree> {
export async function createRepoWorkspace(repoId: number): Promise<RepoWorktree & { worktreeSetup?: WorktreeSetupResult }> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/workspaces`, {
method: 'POST',
})
+82
View File
@@ -0,0 +1,82 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import type { CreateTerminalRequest, ResizeTerminalRequest, TerminalInfo } from '@opencode-manager/shared/types'
import { API_BASE_URL } from '@/config'
import { fetchWrapper, fetchWrapperVoid } from './fetchWrapper'
function terminalsQueryKey(repoId: number, directory: string | undefined) {
return ['terminals', repoId, directory ?? null] as const
}
function terminalsRepoQueryKey(repoId: number) {
return ['terminals', repoId] as const
}
async function listTerminals(repoId: number, directory?: string): Promise<TerminalInfo[]> {
const data = await fetchWrapper<{ terminals: TerminalInfo[] }>(
`${API_BASE_URL}/api/repos/${repoId}/terminals`,
{ params: { directory } },
)
return data.terminals
}
async function createTerminal(repoId: number, body: CreateTerminalRequest): Promise<TerminalInfo> {
return fetchWrapper<TerminalInfo>(`${API_BASE_URL}/api/repos/${repoId}/terminals`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
}
export async function resizeTerminal(repoId: number, ptyID: string, body: ResizeTerminalRequest): Promise<void> {
return fetchWrapperVoid(`${API_BASE_URL}/api/repos/${repoId}/terminals/${encodeURIComponent(ptyID)}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
}
async function removeTerminal(repoId: number, ptyID: string, directory?: string): Promise<void> {
return fetchWrapperVoid(`${API_BASE_URL}/api/repos/${repoId}/terminals/${encodeURIComponent(ptyID)}`, {
method: 'DELETE',
params: { directory },
})
}
interface UseTerminalsOptions {
enabled: boolean
refetchInterval?: number | false
}
export function useTerminals(repoId: number, directory: string | undefined, options: UseTerminalsOptions) {
return useQuery({
queryKey: terminalsQueryKey(repoId, directory),
queryFn: () => listTerminals(repoId, directory),
enabled: options.enabled,
refetchInterval: options.refetchInterval,
})
}
export function useCreateTerminal(repoId: number) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: (body: CreateTerminalRequest) => createTerminal(repoId, body),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: terminalsRepoQueryKey(repoId) })
},
})
}
interface RemoveTerminalVariables {
ptyID: string
directory?: string
}
export function useRemoveTerminal(repoId: number) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: ({ ptyID, directory }: RemoveTerminalVariables) => removeTerminal(repoId, ptyID, directory),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: terminalsRepoQueryKey(repoId) })
},
})
}
+4 -2
View File
@@ -1,3 +1,6 @@
import type { SessionInfo } from '@opencode-manager/shared/opencode'
import type { WorktreeSetupResult } from '@opencode-manager/shared/types'
export interface Repo {
id: number
name?: string
@@ -15,10 +18,9 @@ export interface Repo {
gitCredentialId?: string
isWorktree?: boolean
isLocal?: boolean
worktreeSetup?: WorktreeSetupResult
}
import type { SessionInfo } from '@opencode-manager/shared/opencode'
export type Session = SessionInfo
export type PermissionResponse = 'once' | 'always' | 'reject'
@@ -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'
+46 -2
View File
@@ -1,8 +1,8 @@
import { useEffect, useRef, useState } from 'react'
import { renderHook, act, render, screen } from '@testing-library/react'
import { MemoryRouter, useNavigate } from 'react-router-dom'
import { useDialogParam } from './useDialogParam'
import { describe, it, expect } from 'vitest'
import { dialogSearch, openDialogParam, useDialogParam } from './useDialogParam'
import { describe, it, expect, vi } from 'vitest'
describe('useDialogParam', () => {
const createWrapper = (initialEntries?: string[]) => {
@@ -114,4 +114,48 @@ describe('useDialogParam', () => {
act(() => { screen.getByText('back').click() })
expect(screen.getByTestId('dialog-state').textContent).toBe('closed')
})
it('openDialogParam sets the dialog and extra params in one push while clearing mobileTab', () => {
const updateParams = vi.fn()
openDialogParam(updateParams, 'terminal', { terminal: 'pty-1' })
expect(updateParams).toHaveBeenCalledTimes(1)
const [updater, mode] = updateParams.mock.calls[0]
expect(mode).toBe('push')
const params = new URLSearchParams('mobileTab=more&keep=1')
updater(params)
expect(params.get('dialog')).toBe('terminal')
expect(params.get('terminal')).toBe('pty-1')
expect(params.get('keep')).toBe('1')
expect(params.has('mobileTab')).toBe(false)
})
it('openDialogParam without extra params only sets the dialog', () => {
const updateParams = vi.fn()
openDialogParam(updateParams, 'mcp')
const [updater] = updateParams.mock.calls[0]
const params = new URLSearchParams()
updater(params)
expect(params.get('dialog')).toBe('mcp')
expect([...params.keys()]).toEqual(['dialog'])
})
it('dialogSearch builds a query string from the dialog name and extra params', () => {
expect(dialogSearch('terminal')).toBe('?dialog=terminal')
expect(dialogSearch('terminal', { terminal: 'pty-1' })).toBe('?dialog=terminal&terminal=pty-1')
expect(dialogSearch('preview', { previewPort: '5173', previewPath: '/' })).toBe(
'?dialog=preview&previewPort=5173&previewPath=%2F',
)
})
it('dialogSearch URL-encodes extra params and omits mobileTab', () => {
const search = dialogSearch('terminal', { terminal: 'pty 1/2' })
expect(search).toBe('?dialog=terminal&terminal=pty+1%2F2')
expect(search).not.toContain('mobileTab')
})
})
+21 -1
View File
@@ -1,12 +1,32 @@
import { useCallback } from 'react'
import { useUrlParams } from './useUrlParams'
function setDialogParams(
params: URLSearchParams,
name: string,
extraParams?: Record<string, string>,
): void {
params.set('dialog', name)
if (extraParams) {
for (const [key, value] of Object.entries(extraParams)) {
params.set(key, value)
}
}
}
export function dialogSearch(name: string, extraParams?: Record<string, string>): string {
const params = new URLSearchParams()
setDialogParams(params, name, extraParams)
return `?${params.toString()}`
}
export function openDialogParam(
updateParams: ReturnType<typeof useUrlParams>['updateParams'],
name: string,
extraParams?: Record<string, string>,
): void {
updateParams((p) => {
p.set('dialog', name)
setDialogParams(p, name, extraParams)
p.delete('mobileTab')
}, 'push')
}
+17
View File
@@ -0,0 +1,17 @@
import { useCallback } from 'react'
import { openDialogParam } from './useDialogParam'
import { useUrlParams } from './useUrlParams'
export function useOpenPreview(): (port: number, path?: string) => void {
const { updateParams } = useUrlParams()
return useCallback(
(port: number, path = '/') => {
openDialogParam(updateParams, 'preview', {
previewPort: String(port),
previewPath: path,
})
},
[updateParams],
)
}
@@ -0,0 +1,38 @@
import { describe, it, expect } from 'vitest'
import { act } from '@testing-library/react'
import { renderHookWithRouterAndLocation } from '@/test/test-utils'
import { useOpenTerminal } from './useOpenTerminal'
describe('useOpenTerminal', () => {
it('opens the terminal dialog with the terminal id', () => {
const { result, capturedSearch } = renderHookWithRouterAndLocation(
() => useOpenTerminal(),
['/repos/1'],
)
act(() => {
result.current('pty-1')
})
const params = new URLSearchParams(capturedSearch.current)
expect(params.get('dialog')).toBe('terminal')
expect(params.get('terminal')).toBe('pty-1')
})
it('merges extra params and clears mobileTab in the same navigation', () => {
const { result, capturedSearch } = renderHookWithRouterAndLocation(
() => useOpenTerminal(),
['/repos/1?mobileTab=more'],
)
act(() => {
result.current('pty-2', { repoTab: 'workspaces' })
})
const params = new URLSearchParams(capturedSearch.current)
expect(params.get('dialog')).toBe('terminal')
expect(params.get('terminal')).toBe('pty-2')
expect(params.get('repoTab')).toBe('workspaces')
expect(params.has('mobileTab')).toBe(false)
})
})
+17
View File
@@ -0,0 +1,17 @@
import { useCallback } from 'react'
import { openDialogParam } from './useDialogParam'
import { useUrlParams } from './useUrlParams'
export function useOpenTerminal(): (
terminalId: string,
extraParams?: Record<string, string>,
) => void {
const { updateParams } = useUrlParams()
return useCallback(
(terminalId: string, extraParams?: Record<string, string>) => {
openDialogParam(updateParams, 'terminal', { terminal: terminalId, ...extraParams })
},
[updateParams],
)
}
@@ -0,0 +1,204 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, renderHook } from '@testing-library/react'
import { useTerminalSocket } from './useTerminalSocket'
class FakeWebSocket {
static CONNECTING = 0
static OPEN = 1
static CLOSING = 2
static CLOSED = 3
static instances: FakeWebSocket[] = []
url: string
binaryType = 'blob'
readyState = FakeWebSocket.CONNECTING
sent: string[] = []
onopen: ((event: Event) => void) | null = null
onmessage: ((event: MessageEvent) => void) | null = null
onclose: ((event: CloseEvent) => void) | null = null
onerror: ((event: Event) => void) | null = null
constructor(url: string) {
this.url = url
FakeWebSocket.instances.push(this)
}
send(data: string) {
this.sent.push(data)
}
close() {
this.readyState = FakeWebSocket.CLOSED
}
open() {
this.readyState = FakeWebSocket.OPEN
this.onopen?.(new Event('open'))
}
message(data: string | ArrayBuffer) {
this.onmessage?.({ data } as MessageEvent)
}
serverClose(code: number) {
this.readyState = FakeWebSocket.CLOSED
this.onclose?.({ code } as CloseEvent)
}
}
function metaFrame(cursor: number): ArrayBuffer {
const payload = new TextEncoder().encode(JSON.stringify({ cursor }))
const bytes = new Uint8Array(payload.length + 1)
bytes[0] = 0x00
bytes.set(payload, 1)
return bytes.buffer
}
function renderSocket(overrides: Partial<Parameters<typeof useTerminalSocket>[0]> = {}) {
return renderHook(() =>
useTerminalSocket({
repoId: 1,
directory: '/work/repo',
ptyID: 'pty-1',
onOutput: vi.fn(),
onExit: vi.fn(),
enabled: true,
...overrides,
}),
)
}
describe('useTerminalSocket', () => {
beforeEach(() => {
FakeWebSocket.instances = []
vi.stubGlobal('WebSocket', FakeWebSocket)
vi.useFakeTimers()
})
afterEach(() => {
vi.useRealTimers()
vi.unstubAllGlobals()
})
it('includes the directory in the connection url', () => {
renderSocket()
const url = new URL(FakeWebSocket.instances[0].url)
expect(url.pathname).toBe('/api/repos/1/terminals/pty-1/connect')
expect(url.searchParams.get('directory')).toBe('/work/repo')
})
it('accumulates the cursor and sends it when reconnecting after 1006', () => {
renderSocket()
const first = FakeWebSocket.instances[0]
act(() => {
first.open()
first.message(metaFrame(5))
first.message('abc')
})
act(() => {
first.serverClose(1006)
})
expect(FakeWebSocket.instances).toHaveLength(1)
act(() => {
vi.advanceTimersByTime(1000)
})
expect(FakeWebSocket.instances).toHaveLength(2)
const second = new URL(FakeWebSocket.instances[1].url)
expect(second.searchParams.get('cursor')).toBe('8')
expect(second.searchParams.get('directory')).toBe('/work/repo')
})
it('calls onExit without reconnecting on close code 4404', () => {
const onExit = vi.fn()
renderSocket({ onExit })
act(() => {
FakeWebSocket.instances[0].serverClose(4404)
})
act(() => {
vi.advanceTimersByTime(60000)
})
expect(onExit).toHaveBeenCalledTimes(1)
expect(FakeWebSocket.instances).toHaveLength(1)
})
it('exhausts the retry budget when upstream connections keep failing after open', () => {
const { result } = renderSocket()
const delays = [1000, 2000, 5000, 5000, 5000]
for (const delay of delays) {
const socket = FakeWebSocket.instances[FakeWebSocket.instances.length - 1]
act(() => {
socket.open()
socket.serverClose(1011)
})
expect(result.current.status).toBe('reconnecting')
act(() => {
vi.advanceTimersByTime(delay)
})
}
const finalSocket = FakeWebSocket.instances[FakeWebSocket.instances.length - 1]
act(() => {
finalSocket.open()
finalSocket.serverClose(1011)
})
expect(result.current.status).toBe('closed')
expect(FakeWebSocket.instances).toHaveLength(6)
act(() => {
vi.advanceTimersByTime(60000)
})
expect(FakeWebSocket.instances).toHaveLength(6)
})
it('resets the retry budget only after a healthy upstream session', () => {
const { result } = renderSocket()
act(() => {
FakeWebSocket.instances[0].open()
FakeWebSocket.instances[0].message(metaFrame(0))
FakeWebSocket.instances[0].serverClose(1011)
})
act(() => {
vi.advanceTimersByTime(1000)
})
expect(FakeWebSocket.instances).toHaveLength(2)
act(() => {
FakeWebSocket.instances[1].open()
FakeWebSocket.instances[1].serverClose(1011)
})
expect(result.current.status).toBe('reconnecting')
act(() => {
vi.advanceTimersByTime(2000)
})
expect(FakeWebSocket.instances).toHaveLength(3)
})
it('forwards send to the open socket', () => {
const { result } = renderSocket()
const socket = FakeWebSocket.instances[0]
act(() => {
socket.open()
})
act(() => {
result.current.send('ls\n')
})
expect(socket.sent).toContain('ls\n')
})
it('does not connect when disabled', () => {
renderSocket({ enabled: false })
expect(FakeWebSocket.instances).toHaveLength(0)
})
})
+135
View File
@@ -0,0 +1,135 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import { TerminalFrameDecoder } from '@/lib/terminal-protocol'
import { toWebSocketUrl } from '@/lib/websocket-url'
export type TerminalSocketStatus = 'connecting' | 'open' | 'reconnecting' | 'closed'
export interface UseTerminalSocketOptions {
repoId: number
directory: string | undefined
ptyID: string
onOutput: (text: string) => void
onExit: () => void
enabled: boolean
}
const RECONNECT_DELAYS_MS = [1000, 2000, 5000, 5000, 5000]
const TERMINAL_CLOSE_CODES = new Set([1000, 4404])
function buildSocketUrl(
repoId: number,
ptyID: string,
directory: string | undefined,
cursor: number | undefined,
): string {
const params = new URLSearchParams()
if (directory !== undefined) params.set('directory', directory)
if (cursor !== undefined) params.set('cursor', String(cursor))
const query = params.toString()
return toWebSocketUrl(
`/api/repos/${repoId}/terminals/${encodeURIComponent(ptyID)}/connect${query ? `?${query}` : ''}`,
)
}
export function useTerminalSocket({
repoId,
directory,
ptyID,
onOutput,
onExit,
enabled,
}: UseTerminalSocketOptions) {
const socketRef = useRef<WebSocket | null>(null)
const cursorRef = useRef<number | undefined>(undefined)
const onOutputRef = useRef(onOutput)
const onExitRef = useRef(onExit)
onOutputRef.current = onOutput
onExitRef.current = onExit
const [status, setStatus] = useState<TerminalSocketStatus>(enabled ? 'connecting' : 'closed')
const send = useCallback((data: string) => {
const socket = socketRef.current
if (socket && socket.readyState === WebSocket.OPEN) {
socket.send(data)
}
}, [])
useEffect(() => {
if (!enabled) {
setStatus('closed')
return
}
let disposed = false
let attempt = 0
let reconnectTimer: ReturnType<typeof setTimeout> | null = null
const decoder = new TerminalFrameDecoder()
cursorRef.current = undefined
const connect = () => {
if (disposed) return
setStatus(attempt === 0 ? 'connecting' : 'reconnecting')
const socket = new WebSocket(buildSocketUrl(repoId, ptyID, directory, cursorRef.current))
socket.binaryType = 'arraybuffer'
socketRef.current = socket
socket.onopen = () => {
if (disposed || socketRef.current !== socket) return
setStatus('open')
}
socket.onmessage = (event) => {
if (disposed || socketRef.current !== socket) return
const frame = decoder.decode(event.data as string | ArrayBuffer)
if (frame.type === 'cursor') {
attempt = 0
cursorRef.current = frame.cursor
return
}
cursorRef.current = (cursorRef.current ?? 0) + frame.text.length
onOutputRef.current(frame.text)
}
socket.onclose = (event) => {
if (disposed || socketRef.current !== socket) return
socketRef.current = null
if (TERMINAL_CLOSE_CODES.has(event.code)) {
setStatus('closed')
onExitRef.current()
return
}
if (attempt >= RECONNECT_DELAYS_MS.length) {
setStatus('closed')
return
}
const delay = RECONNECT_DELAYS_MS[attempt]
attempt += 1
setStatus('reconnecting')
reconnectTimer = setTimeout(connect, delay)
}
}
connect()
return () => {
disposed = true
if (reconnectTimer) clearTimeout(reconnectTimer)
const socket = socketRef.current
socketRef.current = null
if (socket) {
socket.onopen = null
socket.onmessage = null
socket.onclose = null
socket.onerror = null
socket.close()
}
}
}, [repoId, directory, ptyID, enabled])
return { send, status }
}
+34
View File
@@ -0,0 +1,34 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { openUrlFromManager } from './open-url'
describe('openUrlFromManager', () => {
afterEach(() => {
vi.restoreAllMocks()
})
it('opens an external URL in a new tab with noopener', () => {
const open = vi.spyOn(window, 'open').mockImplementation(() => null)
openUrlFromManager('https://example.com/docs', {})
expect(open).toHaveBeenCalledWith('https://example.com/docs', '_blank', 'noopener,noreferrer')
})
it('routes a local dev URL to the preview handler', () => {
const open = vi.spyOn(window, 'open').mockImplementation(() => null)
const openPreview = vi.fn()
openUrlFromManager('http://localhost:5173/app?x=1', { openPreview })
expect(openPreview).toHaveBeenCalledWith(5173, '/app?x=1')
expect(open).not.toHaveBeenCalled()
})
it('falls back to a new tab for a local URL without a preview handler', () => {
const open = vi.spyOn(window, 'open').mockImplementation(() => null)
openUrlFromManager('http://localhost:5173', {})
expect(open).toHaveBeenCalledWith('http://localhost:5173', '_blank', 'noopener,noreferrer')
})
})
+14
View File
@@ -0,0 +1,14 @@
import { parseLocalDevUrl } from './preview-url'
export interface OpenUrlHandlers {
openPreview?: (port: number, path: string) => void
}
export function openUrlFromManager(url: string, handlers: OpenUrlHandlers): void {
const localDevUrl = parseLocalDevUrl(url)
if (localDevUrl && handlers.openPreview) {
handlers.openPreview(localDevUrl.port, localDevUrl.path)
return
}
window.open(url, '_blank', 'noopener,noreferrer')
}
+82
View File
@@ -0,0 +1,82 @@
import { describe, expect, it } from 'vitest'
import {
buildPreviewStartUrl,
getPreviewOrigin,
isSameOriginAsManager,
parseLocalDevUrl,
parsePort,
} from './preview-url'
const managerLocation = {
protocol: 'http:',
hostname: 'manager.local',
origin: 'http://manager.local:5003',
} as Location
describe('parsePort', () => {
it.each([
['5173', 5173],
['1', 1],
['65535', 65535],
])('parses %s', (value, port) => {
expect(parsePort(value)).toBe(port)
})
it.each(['', '0', '65536', 'abc', '-1', '5173.5'])('rejects %s', (value) => {
expect(parsePort(value)).toBeNull()
})
})
describe('parseLocalDevUrl', () => {
it.each([
['http://localhost:5173', 5173, '/'],
['http://localhost:5173/app?x=1#top', 5173, '/app?x=1#top'],
['https://127.0.0.1:3000/', 3000, '/'],
['http://0.0.0.0:8080/foo', 8080, '/foo'],
['http://[::1]:4000/bar', 4000, '/bar'],
])('parses %s', (url, port, path) => {
expect(parseLocalDevUrl(url)).toEqual({ port, path })
})
it.each([
'http://example.com:5173',
'http://localhost',
'ftp://localhost:5173',
'not a url',
])('rejects %s', (url) => {
expect(parseLocalDevUrl(url)).toBeNull()
})
})
describe('getPreviewOrigin', () => {
it('uses the public URL origin when set', () => {
expect(
getPreviewOrigin({ previewPort: 5004, publicUrl: 'https://preview.example.com/base' }, managerLocation),
).toBe('https://preview.example.com')
})
it('falls back to the manager host and preview port', () => {
expect(
getPreviewOrigin({ previewPort: 5004, publicUrl: null }, managerLocation),
).toBe('http://manager.local:5004')
})
})
describe('buildPreviewStartUrl', () => {
it('encodes the token and path against the preview origin', () => {
const url = buildPreviewStartUrl(
{ token: 'tok en', previewPort: 5004, publicUrl: null },
'/a b?x=1',
managerLocation,
)
expect(url).toBe('http://manager.local:5004/__ocm_preview/start?token=tok+en&path=%2Fa+b%3Fx%3D1')
})
})
describe('isSameOriginAsManager', () => {
it('matches the manager origin and rejects another port', () => {
expect(isSameOriginAsManager('http://manager.local:5003', managerLocation)).toBe(true)
expect(isSameOriginAsManager('http://manager.local:5004', managerLocation)).toBe(false)
})
})
+59
View File
@@ -0,0 +1,59 @@
import type { CreatePreviewSessionResponse } from '@opencode-manager/shared/types'
const LOCAL_DEV_HOSTS = new Set(['localhost', '127.0.0.1', '0.0.0.0', '[::1]'])
export interface LocalDevUrl {
port: number
path: string
}
export interface PreviewOriginInput {
previewPort: number
publicUrl: string | null
}
export function parsePort(value: string): number | null {
if (!value) return null
const port = Number(value)
if (!Number.isInteger(port) || port < 1 || port > 65535) return null
return port
}
export function parseLocalDevUrl(url: string): LocalDevUrl | null {
let parsed: URL
try {
parsed = new URL(url)
} catch {
return null
}
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null
if (!LOCAL_DEV_HOSTS.has(parsed.hostname)) return null
const port = parsePort(parsed.port)
if (port === null) return null
return { port, path: `${parsed.pathname}${parsed.search}${parsed.hash}` }
}
export function getPreviewOrigin(input: PreviewOriginInput, location: Location = window.location): string {
if (input.publicUrl) {
return new URL(input.publicUrl, location.origin).origin
}
return `${location.protocol}//${location.hostname}:${input.previewPort}`
}
export function buildPreviewStartUrl(
session: CreatePreviewSessionResponse,
path: string,
location: Location = window.location,
): string {
const origin = getPreviewOrigin(session, location)
const query = new URLSearchParams({ token: session.token, path })
return `${origin}/__ocm_preview/start?${query.toString()}`
}
export function isSameOriginAsManager(origin: string, location: Location = window.location): boolean {
try {
return new URL(origin).origin === location.origin
} catch {
return false
}
}
@@ -0,0 +1,47 @@
import { describe, expect, it } from 'vitest'
import { TerminalFrameDecoder, applyCtrlModifier } from './terminal-protocol'
function metaFrame(cursor: number): ArrayBuffer {
const payload = new TextEncoder().encode(JSON.stringify({ cursor }))
const bytes = new Uint8Array(payload.length + 1)
bytes[0] = 0x00
bytes.set(payload, 1)
return bytes.buffer
}
describe('TerminalFrameDecoder', () => {
it('decodes the meta frame into a cursor', () => {
const decoder = new TerminalFrameDecoder()
expect(decoder.decode(metaFrame(42))).toEqual({ type: 'cursor', cursor: 42 })
})
it('decodes split multibyte UTF-8 across binary frames', () => {
const decoder = new TerminalFrameDecoder()
const encoded = new TextEncoder().encode('→')
const first = encoded.slice(0, 1)
const second = encoded.slice(1)
expect(decoder.decode(first.buffer)).toEqual({ type: 'output', text: '' })
expect(decoder.decode(second.buffer)).toEqual({ type: 'output', text: '→' })
})
it('passes string frames through', () => {
const decoder = new TerminalFrameDecoder()
expect(decoder.decode('plain text')).toEqual({ type: 'output', text: 'plain text' })
})
})
describe('applyCtrlModifier', () => {
it('maps a letter to its control code', () => {
expect(applyCtrlModifier('c')).toBe('\x03')
})
it('maps a control symbol to its control code', () => {
expect(applyCtrlModifier('[')).toBe('\x1b')
})
it('returns non-letter input unchanged', () => {
expect(applyCtrlModifier('1')).toBe('1')
expect(applyCtrlModifier('ab')).toBe('ab')
})
})
+54
View File
@@ -0,0 +1,54 @@
const META_FRAME_PREFIX = 0x00
const CTRL_SYMBOLS: Record<string, string> = {
'@': '\x00',
'[': '\x1b',
'\\': '\x1c',
']': '\x1d',
'^': '\x1e',
'_': '\x1f',
}
export type TerminalFrame =
| { type: 'output'; text: string }
| { type: 'cursor'; cursor: number }
export class TerminalFrameDecoder {
private readonly decoder = new TextDecoder('utf-8')
decode(data: string | ArrayBuffer): TerminalFrame {
if (typeof data === 'string') {
return { type: 'output', text: data }
}
const bytes = new Uint8Array(data)
if (bytes.length > 0 && bytes[0] === META_FRAME_PREFIX) {
return this.decodeMetaFrame(bytes.subarray(1))
}
return { type: 'output', text: this.decoder.decode(bytes, { stream: true }) }
}
private decodeMetaFrame(payload: Uint8Array): TerminalFrame {
try {
const parsed = JSON.parse(new TextDecoder('utf-8').decode(payload)) as { cursor?: unknown }
if (typeof parsed.cursor === 'number' && Number.isSafeInteger(parsed.cursor)) {
return { type: 'cursor', cursor: parsed.cursor }
}
} catch {
return { type: 'output', text: '' }
}
return { type: 'output', text: '' }
}
}
export function applyCtrlModifier(data: string): string {
if (data.length !== 1) return data
const upper = data.toUpperCase()
if (upper >= 'A' && upper <= 'Z') {
return String.fromCharCode(upper.charCodeAt(0) - 64)
}
return CTRL_SYMBOLS[data] ?? data
}
+70
View File
@@ -0,0 +1,70 @@
import type { ITheme } from '@xterm/xterm'
const BASE_TOKENS = {
background: 'background',
foreground: 'foreground',
cursor: 'primary',
selectionBackground: 'accent',
} as const
const ANSI_TOKENS = {
black: 'muted',
red: 'destructive',
green: 'success',
yellow: 'warning',
blue: 'info',
magenta: 'highlight',
cyan: 'syntax-property',
white: 'foreground',
} as const
type AnsiName = keyof typeof ANSI_TOKENS
function collectTokenColors(root: HTMLElement): Map<string, string> {
const tokens = new Set<string>([
...Object.values(BASE_TOKENS),
...Object.values(ANSI_TOKENS),
])
const probes = new Map<string, HTMLSpanElement>()
for (const token of tokens) {
const probe = document.createElement('span')
probe.style.color = `var(--color-${token})`
probe.style.position = 'absolute'
probe.style.width = '0'
probe.style.height = '0'
probe.style.overflow = 'hidden'
probe.style.opacity = '0'
probe.style.pointerEvents = 'none'
root.appendChild(probe)
probes.set(token, probe)
}
const colors = new Map<string, string>()
for (const [token, probe] of probes) {
colors.set(token, getComputedStyle(probe).color)
root.removeChild(probe)
}
return colors
}
function ansiTheme(colors: Map<string, string>): Record<AnsiName | `bright${Capitalize<AnsiName>}`, string | undefined> {
const theme = {} as Record<AnsiName | `bright${Capitalize<AnsiName>}`, string | undefined>
for (const name of Object.keys(ANSI_TOKENS) as AnsiName[]) {
const color = colors.get(ANSI_TOKENS[name])
theme[name] = color
theme[`bright${name[0].toUpperCase()}${name.slice(1)}` as `bright${Capitalize<AnsiName>}`] = color
}
return theme
}
export function resolveTerminalTheme(root: HTMLElement): ITheme {
const colors = collectTokenColors(root)
return {
background: colors.get(BASE_TOKENS.background),
foreground: colors.get(BASE_TOKENS.foreground),
cursor: colors.get(BASE_TOKENS.cursor),
selectionBackground: colors.get(BASE_TOKENS.selectionBackground),
...ansiTheme(colors),
}
}
+40
View File
@@ -0,0 +1,40 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { toWebSocketUrl } from './websocket-url'
const state = vi.hoisted(() => ({ apiBaseUrl: '' }))
vi.mock('@/config', () => ({
get API_BASE_URL() {
return state.apiBaseUrl
},
}))
describe('toWebSocketUrl', () => {
afterEach(() => {
state.apiBaseUrl = ''
})
it('uses the page origin over http when no API base url is configured', () => {
expect(toWebSocketUrl('/api/repos/1/terminals/t/connect')).toBe(
'ws://localhost/api/repos/1/terminals/t/connect',
)
})
it('uses the page origin over https when no API base url is configured', () => {
const original = window.location
Object.defineProperty(window, 'location', {
configurable: true,
value: new URL('https://example.com'),
})
try {
expect(toWebSocketUrl('/api/x')).toBe('wss://example.com/api/x')
} finally {
Object.defineProperty(window, 'location', { configurable: true, value: original })
}
})
it('uses an absolute API base url and preserves the query', () => {
state.apiBaseUrl = 'https://api.example.com'
expect(toWebSocketUrl('/api/x?directory=%2Ftmp')).toBe('wss://api.example.com/api/x?directory=%2Ftmp')
})
})
+8
View File
@@ -0,0 +1,8 @@
import { API_BASE_URL } from '@/config'
export function toWebSocketUrl(pathWithQuery: string): string {
const base = API_BASE_URL || window.location.origin
const url = new URL(pathWithQuery, base)
url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'
return url.toString()
}
+13
View File
@@ -0,0 +1,13 @@
import type { WorktreeSetupResult } from '@opencode-manager/shared/types'
import { showToast } from '@/lib/toast'
export function notifyWorktreeSetup(setup: WorktreeSetupResult | undefined): void {
if (!setup) return
if (setup.status === 'failed') {
showToast.warning('Worktree setup failed to start')
return
}
if (setup.status === 'skipped' || (setup.status === 'started' && setup.repoCommandsSkipped)) {
showToast.info('Repository setup commands were skipped until trusted in Actions')
}
}
+6
View File
@@ -12,6 +12,8 @@ import { FileBrowserSheet } from "@/components/file-browser/FileBrowserSheet"
import { RepoMcpDialog } from "@/components/repo/RepoMcpDialog"
import { RepoSkillsDialog } from "@/components/repo/RepoSkillsDialog"
import { SourceControlPanel } from "@/components/source-control"
import { TerminalPanel } from "@/components/terminal/TerminalPanel"
import { PreviewPanel } from "@/components/preview/PreviewPanel"
import { ResetPermissionsDialog } from "@/components/repo/ResetPermissionsDialog"
import { PendingActionsGroup } from "@/components/notifications/PendingActionsGroup"
import { Plus } from "lucide-react"
@@ -23,6 +25,8 @@ export function AssistantRedirect() {
const [mcpDialogOpen, setMcpDialogOpen] = useDialogParam('mcp')
const [skillsDialogOpen, setSkillsDialogOpen] = useDialogParam('skills')
const [sourceControlOpen, setSourceControlOpen] = useDialogParam('sourceControl')
const [terminalOpen, setTerminalOpen] = useDialogParam('terminal')
const [previewOpen, setPreviewOpen] = useDialogParam('preview')
const [resetPermissionsOpen, setResetPermissionsOpen] = useDialogParam('resetPermissions')
const { data: repo, isLoading: repoLoading, error: repoError } = useQuery({
@@ -92,6 +96,8 @@ export function AssistantRedirect() {
/>
)}
<SourceControlPanel repoId={repoId} isOpen={sourceControlOpen} onClose={() => setSourceControlOpen(false)} currentBranch={repo?.currentBranch || repo?.branch || "main"} repoName="Assistant" />
<TerminalPanel repoId={0} directory={assistantDirectory} isOpen={terminalOpen} onClose={() => setTerminalOpen(false)} />
<PreviewPanel isOpen={previewOpen} onClose={() => setPreviewOpen(false)} directory={assistantDirectory} />
<ResetPermissionsDialog open={resetPermissionsOpen} onOpenChange={setResetPermissionsOpen} repoId={repoId} />
</>
)}
+38 -1
View File
@@ -6,14 +6,19 @@ import { SessionList } from "@/components/session/SessionList";
import { FileBrowserSheet } from "@/components/file-browser/FileBrowserSheet";
import { Header } from "@/components/ui/header";
import { RepoMcpDialog } from "@/components/repo/RepoMcpDialog";
import { ProjectActionsMenu } from "@/components/repo/ProjectActionsMenu";
import { RepoActionsDialog } from "@/components/repo/RepoActionsDialog";
import { RepoSkillsDialog } from "@/components/repo/RepoSkillsDialog";
import { MultiRunDialog } from "@/components/repo/MultiRunDialog";
import { SourceControlPanel } from "@/components/source-control";
import { TerminalPanel } from "@/components/terminal/TerminalPanel";
import { PreviewPanel } from "@/components/preview/PreviewPanel";
import { useCreateSession } from "@/hooks/useOpenCode";
import { useRepoActivity } from "@/hooks/useRepoActivity";
import { useCreateRepoWorkspace, useDeleteRepoWorkspaces, useRepoSiblings } from "@/hooks/useRepoSiblings";
import { useSSE } from "@/hooks/useSSE";
import { useDialogParam } from "@/hooks/useDialogParam";
import { useOpenTerminal } from "@/hooks/useOpenTerminal";
import { useWorktreeTab } from "@/hooks/useWorktreeTab";
import { WorktreeTabs } from "@/components/repo/WorktreeTabs";
import { WorkspaceManager } from "@/components/repo/WorkspaceManager";
@@ -24,6 +29,7 @@ import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, D
import { ResetPermissionsDialog } from "@/components/repo/ResetPermissionsDialog";
import { PendingActionsGroup } from "@/components/notifications/PendingActionsGroup";
import { getRepoDisplayName } from "@/lib/utils";
import { notifyWorktreeSetup } from "@/lib/worktreeSetup";
import { isWorktreeSibling } from "@opencode-manager/shared/utils";
export function RepoDetail() {
@@ -34,12 +40,16 @@ export function RepoDetail() {
const [mcpDialogOpen, setMcpDialogOpen] = useDialogParam('mcp');
const [skillsDialogOpen, setSkillsDialogOpen] = useDialogParam('skills');
const [sourceControlOpen, setSourceControlOpen] = useDialogParam('sourceControl');
const [terminalOpen, setTerminalOpen] = useDialogParam('terminal');
const [actionsDialogOpen, setActionsDialogOpen] = useDialogParam('actions');
const [previewOpen, setPreviewOpen] = useDialogParam('preview');
const [resetPermissionsOpen, setResetPermissionsOpen] = useDialogParam('resetPermissions');
const [multiRunOpen, setMultiRunOpen] = useDialogParam('multiRun');
const [createWorkspaceOpen, setCreateWorkspaceOpen] = useState(false);
const [workspaceSelectorOpen, setWorkspaceSelectorOpen] = useState(false);
const [activeWorkspaceDirectory, setActiveWorkspaceDirectory] = useState<string | undefined>();
const { activeTab, setActiveTab } = useWorktreeTab();
const openTerminal = useOpenTerminal();
const { data: repo, isLoading: repoLoading } = useQuery({
queryKey: ["repo", repoId],
@@ -131,8 +141,14 @@ export function RepoDetail() {
if (workspace.directory) {
setActiveWorkspaceDirectory(workspace.directory);
}
setActiveTab('workspaces');
setCreateWorkspaceOpen(false);
notifyWorktreeSetup(workspace.worktreeSetup);
if (workspace.worktreeSetup?.status === 'started') {
const terminalId = workspace.worktreeSetup.terminal.id;
openTerminal(terminalId, { repoTab: 'workspaces' });
return;
}
setActiveTab('workspaces');
};
const handleOpenWorkspaceSelector = () => {
@@ -202,6 +218,7 @@ export function RepoDetail() {
</div>
<Header.Actions>
<div className="flex items-center gap-1">
<ProjectActionsMenu repoId={repoId} directory={composerDirectory} />
<PendingActionsGroup />
</div>
<Button
@@ -289,6 +306,13 @@ export function RepoDetail() {
directory={composerDirectory}
/>
<RepoActionsDialog
repoId={repoId}
directory={composerDirectory}
open={actionsDialogOpen}
onOpenChange={setActionsDialogOpen}
/>
<RepoSkillsDialog
open={skillsDialogOpen}
onOpenChange={setSkillsDialogOpen}
@@ -303,6 +327,19 @@ export function RepoDetail() {
repoName={repoName}
/>
<TerminalPanel
repoId={repoId}
directory={composerDirectory}
isOpen={terminalOpen}
onClose={() => setTerminalOpen(false)}
/>
<PreviewPanel
isOpen={previewOpen}
onClose={() => setPreviewOpen(false)}
directory={composerDirectory}
/>
<ResetPermissionsDialog
open={resetPermissionsOpen}
onOpenChange={setResetPermissionsOpen}
+32
View File
@@ -39,6 +39,8 @@ import { showToast } from "@/lib/toast";
import { getWorkspaceFilePath } from "@/lib/markdownLinks";
import { getRepoDisplayName } from "@/lib/utils";
import { RepoMcpDialog } from "@/components/repo/RepoMcpDialog";
import { ProjectActionsMenu } from "@/components/repo/ProjectActionsMenu";
import { RepoActionsDialog } from "@/components/repo/RepoActionsDialog";
import { ResetPermissionsDialog } from "@/components/repo/ResetPermissionsDialog";
import { RepoSkillsDialog } from "@/components/repo/RepoSkillsDialog";
import { compactSession, forkSession, listSessionMessages } from "@/api/opencode";
@@ -51,6 +53,8 @@ import { FormPrompt } from "@/components/session/FormPrompt";
import { MinimizedFormIndicator } from "@/components/session/MinimizedFormIndicator";
import { PendingActionsGroup } from "@/components/notifications/PendingActionsGroup";
import { SourceControlPanel } from "@/components/source-control";
import { TerminalPanel } from "@/components/terminal/TerminalPanel";
import { PreviewPanel } from "@/components/preview/PreviewPanel";
import { SessionSendErrorBanner } from "@/components/session/SessionSendErrorBanner";
import { BackgroundWorkBar } from "@/components/session/BackgroundWorkBar";
import { SessionGoalBar } from "@/components/session/SessionGoalBar";
@@ -119,6 +123,9 @@ export function SessionDetail() {
const [mcpDialogOpen, setMcpDialogOpen] = useDialogParam('mcp');
const [skillsDialogOpen, setSkillsDialogOpen] = useDialogParam('skills');
const [sourceControlOpen, setSourceControlOpen] = useDialogParam('sourceControl');
const [terminalOpen, setTerminalOpen] = useDialogParam('terminal');
const [actionsDialogOpen, setActionsDialogOpen] = useDialogParam('actions');
const [previewOpen, setPreviewOpen] = useDialogParam('preview');
const [resetPermissionsOpen, setResetPermissionsOpen] = useDialogParam('resetPermissions');
const [selectedFilePath, setSelectedFilePath] = useState<string | undefined>();
const [showScrollButton, setShowScrollButton] = useState(false);
@@ -679,6 +686,9 @@ export function SessionDetail() {
</div>
<Header.Actions className="gap-2 sm:gap-4">
<div className="flex items-center gap-1">
{!isAssistantSession && (
<ProjectActionsMenu repoId={repoId} directory={sessionDirectory} />
)}
<PendingActionsGroup />
</div>
<ContextUsageIndicator
@@ -869,6 +879,15 @@ export function SessionDetail() {
directory={repoDirectory}
/>
{!isAssistantSession && (
<RepoActionsDialog
repoId={repoId}
directory={sessionDirectory}
open={actionsDialogOpen}
onOpenChange={setActionsDialogOpen}
/>
)}
<SourceControlPanel
repoId={repoId}
isOpen={sourceControlOpen}
@@ -877,6 +896,19 @@ export function SessionDetail() {
repoName={workspaceDisplayName}
/>
<TerminalPanel
repoId={repoId}
directory={sessionDirectory}
isOpen={terminalOpen}
onClose={() => setTerminalOpen(false)}
/>
<PreviewPanel
isOpen={previewOpen}
onClose={() => setPreviewOpen(false)}
directory={sessionDirectory}
/>
<ResetPermissionsDialog
open={resetPermissionsOpen}
onOpenChange={setResetPermissionsOpen}
@@ -0,0 +1,163 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter, useLocation } from 'react-router-dom'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import type { TerminalInfo } from '@opencode-manager/shared/types'
import type { Repo } from '@/api/types'
import { AssistantRedirect } from '../AssistantRedirect'
const mocks = vi.hoisted(() => ({
getRepo: vi.fn(),
useSSE: vi.fn(),
useCreateSession: vi.fn(),
useTerminals: vi.fn(),
useCreateTerminal: vi.fn(),
useRemoveTerminal: vi.fn(),
usePreviewPorts: vi.fn(),
createPreviewSession: vi.fn(),
}))
vi.mock('@/api/repos', () => ({ getRepo: mocks.getRepo }))
vi.mock('@/hooks/useSSE', () => ({ useSSE: mocks.useSSE }))
vi.mock('@/hooks/useOpenCode', () => ({ useCreateSession: mocks.useCreateSession }))
vi.mock('@/api/terminals', () => ({
useTerminals: mocks.useTerminals,
useCreateTerminal: mocks.useCreateTerminal,
useRemoveTerminal: mocks.useRemoveTerminal,
}))
vi.mock('@/api/preview', () => ({
usePreviewPorts: mocks.usePreviewPorts,
createPreviewSession: mocks.createPreviewSession,
}))
vi.mock('@/components/session/SessionList', () => ({ SessionList: () => null }))
vi.mock('@/components/file-browser/FileBrowserSheet', () => ({ FileBrowserSheet: () => null }))
vi.mock('@/components/repo/RepoMcpDialog', () => ({ RepoMcpDialog: () => null }))
vi.mock('@/components/repo/RepoSkillsDialog', () => ({ RepoSkillsDialog: () => null }))
vi.mock('@/components/repo/ResetPermissionsDialog', () => ({ ResetPermissionsDialog: () => null }))
vi.mock('@/components/source-control', () => ({ SourceControlPanel: () => null }))
vi.mock('@/components/notifications/PendingActionsGroup', () => ({ PendingActionsGroup: () => null }))
vi.mock('@/components/terminal/TerminalView', async () => {
const React = await import('react')
return {
TerminalView: React.forwardRef(function MockTerminalView(
props: { ptyID: string; onOpenLink?: (uri: string) => void },
ref: React.Ref<unknown>,
) {
React.useImperativeHandle(ref, () => ({ send: vi.fn() }))
return React.createElement(
'div',
{ 'data-testid': 'terminal-view', 'data-pty-id': props.ptyID },
React.createElement(
'button',
{ type: 'button', onClick: () => props.onOpenLink?.('http://localhost:5173/dashboard') },
'local-link',
),
React.createElement(
'button',
{ type: 'button', onClick: () => props.onOpenLink?.('https://example.com/docs') },
'external-link',
),
)
}),
}
})
const assistantDirectory = '/abs/assistant'
const baseRepo: Repo = {
id: 0,
name: 'Assistant',
localPath: 'assistant',
fullPath: assistantDirectory,
defaultBranch: 'main',
currentBranch: 'main',
branch: 'main',
cloneStatus: 'ready',
clonedAt: 1,
isWorktree: false,
}
const runningTerminal: TerminalInfo = {
id: 't1',
title: 'Terminal',
kind: 'shell',
cwd: assistantDirectory,
status: 'running',
}
function LocationProbe() {
const location = useLocation()
return <div data-testid="location">{`${location.pathname}${location.search}`}</div>
}
function renderAssistantRedirect(initialEntry = '/assistant?dialog=terminal') {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
return render(
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={[initialEntry]}>
<LocationProbe />
<AssistantRedirect />
</MemoryRouter>
</QueryClientProvider>,
)
}
describe('AssistantRedirect preview routing', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.getRepo.mockResolvedValue(baseRepo)
mocks.useSSE.mockReturnValue(undefined)
mocks.useCreateSession.mockReturnValue({ mutateAsync: vi.fn(), isPending: false })
mocks.useTerminals.mockReturnValue({
data: [runningTerminal],
isLoading: false,
isSuccess: true,
refetch: vi.fn(),
})
mocks.useCreateTerminal.mockReturnValue({ mutate: vi.fn(), isPending: false })
mocks.useRemoveTerminal.mockReturnValue({ mutate: vi.fn(), isPending: false })
mocks.usePreviewPorts.mockReturnValue({
data: {
enabled: true,
ports: [{ port: 5173, host: '127.0.0.1', pid: 10, command: 'vite', cwd: assistantDirectory, inDirectory: true }],
},
isLoading: false,
refetch: vi.fn(),
})
mocks.createPreviewSession.mockResolvedValue({ token: 'tok', previewPort: 5004, publicUrl: null })
})
it('opens the preview panel when a terminal localhost link is followed', async () => {
const user = userEvent.setup()
renderAssistantRedirect()
await user.click(await screen.findByRole('button', { name: 'local-link' }))
const iframe = await screen.findByTitle('Preview')
expect(iframe.getAttribute('src')).toContain('token=tok')
expect(iframe.getAttribute('src')).toContain('path=%2Fdashboard')
expect(mocks.createPreviewSession).toHaveBeenCalledWith(5173)
expect(screen.queryByTestId('terminal-view')).not.toBeInTheDocument()
const location = screen.getByTestId('location').textContent ?? ''
expect(location).toContain('dialog=preview')
expect(location).toContain('previewPort=5173')
expect(location).toContain('previewPath=%2Fdashboard')
})
it('opens external terminal links in a new tab without mounting the preview panel', async () => {
const user = userEvent.setup()
const openSpy = vi.spyOn(window, 'open').mockReturnValue(null)
renderAssistantRedirect()
await user.click(await screen.findByRole('button', { name: 'external-link' }))
expect(openSpy).toHaveBeenCalledWith('https://example.com/docs', '_blank', 'noopener,noreferrer')
expect(mocks.createPreviewSession).not.toHaveBeenCalled()
expect(screen.queryByTitle('Preview')).not.toBeInTheDocument()
expect(screen.getByTestId('terminal-view')).toBeInTheDocument()
expect(screen.getByTestId('location').textContent).toContain('dialog=terminal')
})
})
@@ -0,0 +1,176 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import type { Repo } from '@/api/types'
import { RepoDetail } from '../RepoDetail'
const mocks = vi.hoisted(() => ({
getRepo: vi.fn(),
useRepoSiblings: vi.fn(),
useCreateRepoWorkspace: vi.fn(),
useDeleteRepoWorkspaces: vi.fn(),
useRepoActivity: vi.fn(),
useSSE: vi.fn(),
useCreateSession: vi.fn(),
createWorkspaceMutateAsync: vi.fn(),
showToastInfo: vi.fn(),
showToastWarning: vi.fn(),
}))
vi.mock('@/api/repos', () => ({
getRepo: mocks.getRepo,
workspaceLabel: (workspace: { currentBranch?: string; branch?: string; localPath?: string }) =>
workspace.currentBranch || workspace.branch || workspace.localPath || 'workspace',
}))
vi.mock('@/lib/toast', () => ({
showToast: {
success: vi.fn(),
info: mocks.showToastInfo,
warning: mocks.showToastWarning,
error: vi.fn(),
},
}))
vi.mock('@/hooks/useRepoSiblings', () => ({
useRepoSiblings: mocks.useRepoSiblings,
useCreateRepoWorkspace: mocks.useCreateRepoWorkspace,
useDeleteRepoWorkspaces: mocks.useDeleteRepoWorkspaces,
}))
vi.mock('@/hooks/useRepoActivity', () => ({ useRepoActivity: mocks.useRepoActivity }))
vi.mock('@/hooks/useSSE', () => ({ useSSE: mocks.useSSE }))
vi.mock('@/hooks/useOpenCode', () => ({ useCreateSession: mocks.useCreateSession }))
vi.mock('@/components/repo/WorktreeTabs', () => ({
WorktreeTabs: ({ onCreateWorkspace }: { onCreateWorkspace: () => void }) => (
<button type="button" onClick={onCreateWorkspace}>New workspace</button>
),
}))
vi.mock('@/components/terminal/TerminalPanel', () => ({
TerminalPanel: ({ directory, isOpen }: { directory?: string; isOpen: boolean }) => (
<div data-testid="terminal-panel" data-directory={directory ?? ''} data-open={String(isOpen)} />
),
}))
vi.mock('@/components/session/SessionList', () => ({ SessionList: () => null }))
vi.mock('@/components/file-browser/FileBrowserSheet', () => ({ FileBrowserSheet: () => null }))
vi.mock('@/components/repo/RepoMcpDialog', () => ({ RepoMcpDialog: () => null }))
vi.mock('@/components/repo/ProjectActionsMenu', () => ({ ProjectActionsMenu: () => null }))
vi.mock('@/components/repo/RepoActionsDialog', () => ({ RepoActionsDialog: () => null }))
vi.mock('@/components/repo/RepoSkillsDialog', () => ({ RepoSkillsDialog: () => null }))
vi.mock('@/components/source-control', () => ({ SourceControlPanel: () => null }))
vi.mock('@/components/repo/WorkspaceManager', () => ({ WorkspaceManager: () => null }))
vi.mock('@/components/repo/ResetPermissionsDialog', () => ({ ResetPermissionsDialog: () => null }))
vi.mock('@/components/notifications/PendingActionsGroup', () => ({ PendingActionsGroup: () => null }))
const baseRepo: Repo = {
id: 1,
name: 'my-repo',
localPath: 'repos/my-repo',
fullPath: '/abs/repos/my-repo',
defaultBranch: 'main',
currentBranch: 'main',
branch: 'main',
cloneStatus: 'ready',
clonedAt: 1,
isWorktree: false,
}
const newWorkspaceDirectory = '/abs/repos/my-repo-ws'
const siblingsData: Repo[] = []
function LocationProbe() {
const location = useLocation()
return <div data-testid="location">{`${location.pathname}${location.search}`}</div>
}
function renderRepoDetail() {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
return render(
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={['/repos/1']}>
<LocationProbe />
<Routes>
<Route path="/repos/:id" element={<RepoDetail />} />
</Routes>
</MemoryRouter>
</QueryClientProvider>,
)
}
async function startWorkspaceCreation() {
const user = userEvent.setup()
renderRepoDetail()
await user.click(await screen.findByRole('button', { name: 'New workspace' }))
await user.click(await screen.findByRole('button', { name: 'Create Workspace' }))
}
describe('RepoDetail worktree setup', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.getRepo.mockResolvedValue(baseRepo)
mocks.useRepoSiblings.mockReturnValue({ data: siblingsData })
mocks.useDeleteRepoWorkspaces.mockReturnValue({ mutate: vi.fn(), isPending: false })
mocks.useCreateSession.mockReturnValue({ mutateAsync: vi.fn(), isPending: false })
})
it('switches to the new workspace terminal when setup starts from the repo tab', async () => {
mocks.useCreateRepoWorkspace.mockReturnValue({
mutateAsync: mocks.createWorkspaceMutateAsync,
isPending: false,
})
mocks.createWorkspaceMutateAsync.mockResolvedValue({
directory: newWorkspaceDirectory,
worktreeSetup: {
status: 'started',
terminal: {
id: 'pty-new',
title: 'Worktree setup',
kind: 'setup',
cwd: newWorkspaceDirectory,
status: 'running',
},
repoCommandsSkipped: false,
},
})
await startWorkspaceCreation()
await waitFor(() =>
expect(screen.getByTestId('location')).toHaveTextContent('repoTab=workspaces'),
)
const location = screen.getByTestId('location').textContent ?? ''
expect(location).toContain('dialog=terminal')
expect(location).toContain('terminal=pty-new')
expect(screen.getByTestId('terminal-panel')).toHaveAttribute(
'data-directory',
newWorkspaceDirectory,
)
})
it('stays on the workspace tab without a terminal when setup does not start', async () => {
mocks.useCreateRepoWorkspace.mockReturnValue({
mutateAsync: mocks.createWorkspaceMutateAsync,
isPending: false,
})
mocks.createWorkspaceMutateAsync.mockResolvedValue({
directory: newWorkspaceDirectory,
worktreeSetup: { status: 'none' },
})
await startWorkspaceCreation()
await waitFor(() =>
expect(screen.getByTestId('location')).toHaveTextContent('repoTab=workspaces'),
)
expect(screen.getByTestId('location')).not.toHaveTextContent('dialog=terminal')
expect(screen.getByTestId('terminal-panel')).toHaveAttribute(
'data-directory',
newWorkspaceDirectory,
)
})
})
@@ -146,6 +146,7 @@ vi.mock('@/components/file-browser/FileBrowserSheet', () => ({
vi.mock('@/components/repo/RepoMcpDialog', () => ({
RepoMcpDialog: vi.fn(() => null),
}))
vi.mock('@/components/repo/RepoActionsDialog', () => ({ RepoActionsDialog: vi.fn(() => null) }))
vi.mock('@/components/repo/ResetPermissionsDialog', () => ({
ResetPermissionsDialog: vi.fn(() => null),
@@ -205,6 +205,7 @@ vi.mock('@/components/session/SideQuestionDialog', () => ({ SideQuestionDialog:
vi.mock('@/components/session/SessionList', () => ({ SessionList: vi.fn(() => null) }))
vi.mock('@/components/file-browser/FileBrowserSheet', () => ({ FileBrowserSheet: vi.fn(() => null) }))
vi.mock('@/components/repo/RepoMcpDialog', () => ({ RepoMcpDialog: vi.fn(() => null) }))
vi.mock('@/components/repo/RepoActionsDialog', () => ({ RepoActionsDialog: vi.fn(() => null) }))
vi.mock('@/components/repo/ResetPermissionsDialog', () => ({ ResetPermissionsDialog: vi.fn(() => null) }))
vi.mock('@/components/repo/RepoSkillsDialog', () => ({ RepoSkillsDialog: vi.fn(() => null) }))
vi.mock('@/components/source-control', () => ({ SourceControlPanel: vi.fn(() => null) }))
@@ -170,6 +170,7 @@ vi.mock('@/components/file-browser/FileBrowserSheet', () => ({
vi.mock('@/components/repo/RepoMcpDialog', () => ({
RepoMcpDialog: vi.fn(() => null),
}))
vi.mock('@/components/repo/RepoActionsDialog', () => ({ RepoActionsDialog: vi.fn(() => null) }))
vi.mock('@/components/repo/ResetPermissionsDialog', () => ({
ResetPermissionsDialog: vi.fn(() => null),
@@ -141,6 +141,7 @@ vi.mock('@/components/session/SessionList', () => ({ SessionList: vi.fn(() => nu
vi.mock('@/components/session/PermissionModeToggle', () => ({ PermissionModeToggle: vi.fn(() => null) }))
vi.mock('@/components/file-browser/FileBrowserSheet', () => ({ FileBrowserSheet: vi.fn(() => null) }))
vi.mock('@/components/repo/RepoMcpDialog', () => ({ RepoMcpDialog: vi.fn(() => null) }))
vi.mock('@/components/repo/RepoActionsDialog', () => ({ RepoActionsDialog: vi.fn(() => null) }))
vi.mock('@/components/repo/ResetPermissionsDialog', () => ({ ResetPermissionsDialog: vi.fn(() => null) }))
vi.mock('@/components/repo/RepoSkillsDialog', () => ({ RepoSkillsDialog: vi.fn(() => null) }))
vi.mock('@/components/source-control', () => ({ SourceControlPanel: vi.fn(() => null) }))
@@ -165,6 +165,7 @@ vi.mock('@/components/file-browser/FileBrowserSheet', () => ({
vi.mock('@/components/repo/RepoMcpDialog', () => ({
RepoMcpDialog: vi.fn(() => null),
}))
vi.mock('@/components/repo/RepoActionsDialog', () => ({ RepoActionsDialog: vi.fn(() => null) }))
vi.mock('@/components/repo/ResetPermissionsDialog', () => ({
ResetPermissionsDialog: vi.fn(() => null),