feat(ui): preview port menu, terminal auto-start, and project actions tabs

This commit is contained in:
Chris Scott committed 2026-10-04 01:34:57 -04:00
1 parent cf9fa61118
commit 62e36eb3b2
31 files changed
+1332 -489

No files matched your search

@@ -19,6 +19,7 @@ const portsData = {
}
let portsState: PreviewPortsResult['data'] = portsData
const refetchPorts = vi.fn()
const DEFAULT_ENTRY = '/repos/1?dialog=preview&previewPort=5173'
@@ -57,7 +58,7 @@ describe('PreviewPanel', () => {
({
data: portsState,
isLoading: false,
refetch: vi.fn(),
refetch: refetchPorts,
}) as unknown as PreviewPortsResult,
)
vi.mocked(createPreviewSession).mockResolvedValue({ token: 'tok', previewPort: 5004, publicUrl: null })
@@ -109,20 +110,84 @@ describe('PreviewPanel', () => {
expect(screen.getByText(/Preview is unavailable/)).toBeInTheDocument()
})
it('badges ports marked as inside the directory', () => {
it('lists the dev servers of this repo when no port is selected', () => {
portsState = {
enabled: true,
ports: [
{ port: 5173, host: '127.0.0.1', pid: 10, command: 'vite', cwd: '/repo', inDirectory: true },
{ port: 9000, host: '127.0.0.1', pid: 11, command: 'Discord', cwd: '/', inDirectory: false },
{ port: 9001, host: '127.0.0.1', pid: 12, command: 'figma_agent', cwd: null, inDirectory: false },
],
}
renderPanel('/repos/1?dialog=preview')
expect(screen.getByText('this repo')).toBeInTheDocument()
expect(screen.getByRole('heading', { name: 'Dev servers in this repo' })).toBeInTheDocument()
expect(screen.getByRole('button', { name: /:5173 vite/ })).toBeInTheDocument()
expect(screen.queryByRole('button', { name: /:9000/ })).not.toBeInTheDocument()
expect(screen.getByText(/2 other ports are listening elsewhere/)).toBeInTheDocument()
})
it('does not badge ports marked as outside the directory', () => {
it('points to the port menu when no listening port belongs to this repo', () => {
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()
expect(screen.queryByRole('heading', { name: 'Dev servers in this repo' })).not.toBeInTheDocument()
expect(screen.getByText(/1 port is listening\. Choose one from the port menu above\./)).toBeInTheDocument()
})
it('explains how to start a dev server when no port is listening', () => {
portsState = { enabled: true, ports: [] }
renderPanel('/repos/1?dialog=preview')
expect(screen.getByText('No dev server is listening')).toBeInTheDocument()
})
it('groups repo ports first in the port menu and starts a session for the picked port', async () => {
const user = userEvent.setup()
portsState = {
enabled: true,
ports: [
{ port: 5173, host: '127.0.0.1', pid: 10, command: 'vite', cwd: '/repo', inDirectory: true },
{ port: 9000, host: '127.0.0.1', pid: 11, command: 'python3.12', cwd: '/srv/apps/demo/site', inDirectory: false },
],
}
renderPanel('/repos/1?dialog=preview')
await user.click(screen.getByRole('combobox', { name: 'Preview port' }))
const groups = screen.getAllByText(/^(This repo|Other ports)$/).map((element) => element.textContent)
expect(groups).toEqual(['This repo', 'Other ports'])
expect(screen.getByText('/.../apps/demo/site')).toBeInTheDocument()
await user.type(screen.getByRole('combobox', { name: 'Preview port' }), 'python')
expect(screen.queryByText('This repo')).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: /:9000 python3\.12/ }))
expect(await screen.findByTitle('Preview')).toBeInTheDocument()
expect(createPreviewSession).toHaveBeenCalledWith(9000)
expect(screen.getByRole('combobox', { name: 'Preview port' })).toHaveValue(':9000 python3.12')
})
it('keeps the port menu closed when the dialog opens', () => {
renderPanel('/repos/1?dialog=preview')
expect(screen.getByRole('combobox', { name: 'Preview port' })).not.toHaveFocus()
expect(screen.getAllByRole('button', { name: /:5173/ })).toHaveLength(1)
expect(refetchPorts).not.toHaveBeenCalled()
})
it('refreshes the port list when the port menu opens', async () => {
const user = userEvent.setup()
renderPanel()
await screen.findByTitle('Preview')
refetchPorts.mockClear()
await user.click(screen.getByRole('combobox', { name: 'Preview port' }))
expect(refetchPorts).toHaveBeenCalledTimes(1)
})
it('polls the port list while no preview session is active', () => {
+147 -74
View File
@@ -1,14 +1,16 @@
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
import type { CreatePreviewSessionResponse } from '@opencode-manager/shared/types'
import type { CreatePreviewSessionResponse, PreviewPort } 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 { Combobox, type ComboboxOption } from '@/components/ui/combobox'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
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'
import { cn, shortenPath } from '@/lib/utils'
interface PreviewPanelProps {
isOpen: boolean
@@ -32,6 +34,24 @@ const VIEWPORT_PRESETS: Array<{ preset: ViewportPreset; label: string; icon: typ
const PORT_WAIT_TIMEOUT_MS = 60_000
function formatPortLabel(entry: PreviewPort): string {
return entry.command ? `:${entry.port} ${entry.command}` : `:${entry.port}`
}
function toPortOptions(ports: PreviewPort[]): ComboboxOption[] {
const hasRepoPorts = ports.some((entry) => entry.inDirectory)
return ports.map((entry) => ({
value: String(entry.port),
label: formatPortLabel(entry),
description: entry.cwd ? shortenPath(entry.cwd) : undefined,
group: hasRepoPorts ? (entry.inDirectory ? 'This repo' : 'Other ports') : undefined,
}))
}
function describeListeningPorts(count: number, qualifier = ''): string {
return count === 1 ? `1 ${qualifier}port is listening` : `${count} ${qualifier}ports are listening`
}
interface ActiveSession {
targetPort: number
path: string
@@ -58,6 +78,7 @@ export function PreviewPanel({ isOpen, onClose, directory }: PreviewPanelProps)
const sessionPortRef = useRef<number | null>(null)
const activePathRef = useRef<string | null>(null)
const requestIdRef = useRef(0)
const contentRef = useRef<HTMLDivElement>(null)
const activeSession = session && session.targetPort === requestedPort ? session : null
@@ -66,6 +87,8 @@ export function PreviewPanel({ isOpen, onClose, directory }: PreviewPanelProps)
refetchInterval: isOpen && !activeSession ? 2000 : false,
})
const ports = useMemo(() => portsQuery.data?.ports ?? [], [portsQuery.data])
const portOptions = useMemo(() => toPortOptions(ports), [ports])
const repoPorts = useMemo(() => ports.filter((entry) => entry.inDirectory), [ports])
const enabled = portsQuery.data?.enabled ?? true
const portListed = requestedPort !== undefined && ports.some((entry) => entry.port === requestedPort)
@@ -134,6 +157,11 @@ export function PreviewPanel({ isOpen, onClose, directory }: PreviewPanelProps)
}, 'replace')
}, [updateParams])
const handlePortChange = useCallback((value: string) => {
const port = parsePort(value)
if (port) selectPort(port)
}, [selectPort])
const reload = useCallback(() => {
if (!requestedPort) return
void startSession(requestedPort, requestedPath)
@@ -187,12 +215,64 @@ export function PreviewPanel({ isOpen, onClose, directory }: PreviewPanelProps)
</div>
)
const renderPortChooser = () => {
if (ports.length === 0) {
return renderMessage(
<div className="space-y-1">
<p className="font-medium text-foreground">No dev server is listening</p>
<p>Start one in the Terminal or from Actions. It appears here automatically.</p>
</div>,
)
}
if (repoPorts.length === 0) {
return renderMessage(
<div className="space-y-1">
<p className="font-medium text-foreground">Select a port to preview</p>
<p>{describeListeningPorts(ports.length)}. Choose one from the port menu above.</p>
</div>,
)
}
const otherPortCount = ports.length - repoPorts.length
return (
<div className="flex h-full flex-col items-center justify-center p-6">
<div className="w-full max-w-lg space-y-3">
<h3 className="text-sm font-medium text-foreground">Dev servers in this repo</h3>
<ul className="divide-y divide-border overflow-hidden rounded-md border border-border">
{repoPorts.map((entry) => (
<li key={entry.port}>
<button
type="button"
onClick={() => selectPort(entry.port)}
aria-label={formatPortLabel(entry)}
className="flex w-full items-center gap-3 px-3 py-2.5 text-left text-sm transition-colors hover:bg-accent focus-visible:bg-accent focus-visible:outline-none"
>
<span className="font-mono font-medium tabular-nums text-foreground">:{entry.port}</span>
<span className="min-w-0 flex-1 truncate text-muted-foreground">{entry.command}</span>
{entry.cwd && (
<span className="max-w-[45%] truncate text-xs text-muted-foreground" title={entry.cwd}>
{shortenPath(entry.cwd)}
</span>
)}
</button>
</li>
))}
</ul>
{otherPortCount > 0 && (
<p className="text-xs text-muted-foreground">
{describeListeningPorts(otherPortCount, 'other ')} elsewhere. Choose one from the port menu above.
</p>
)}
</div>
</div>
)
}
const body = () => {
if (!enabled) {
return renderMessage('Preview is unavailable')
}
if (!requestedPort) {
return renderMessage('Select a port to preview')
return renderPortChooser()
}
if (!portListed) {
if (waitExpired) {
@@ -236,10 +316,15 @@ export function PreviewPanel({ isOpen, onClose, directory }: PreviewPanelProps)
return (
<Dialog open={isOpen} onOpenChange={(open) => { if (!open) onClose() }}>
<DialogContent
ref={contentRef}
mobileFullscreen
hideCloseButton={isMobile}
onOpenAutoFocus={(event) => {
event.preventDefault()
contentRef.current?.focus()
}}
className={cn(
'p-0 flex flex-col bg-card border-border gap-0',
'p-0 flex flex-col bg-card border-border gap-0 focus:outline-none',
isMobile ? 'h-full' : 'w-[90vw] sm:max-w-6xl h-[90vh] sm:pb-0',
)}
>
@@ -261,80 +346,68 @@ export function PreviewPanel({ isOpen, onClose, directory }: PreviewPanelProps)
)}
</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="/"
<div className="flex flex-col gap-2 border-b border-border px-3 py-2 flex-shrink-0 sm:flex-row sm:items-center">
<Combobox
value={requestedPort ? String(requestedPort) : ''}
onChange={handlePortChange}
options={portOptions}
placeholder="Select port"
disabled={!enabled}
allowCustomValue={false}
ariaLabel="Preview port"
onOpen={() => { void portsQuery.refetch() }}
className="sm:w-72 sm:flex-shrink-0"
/>
<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 className="flex min-w-0 flex-1 items-center gap-2">
<Input
aria-label="Preview path"
value={pathDraft}
onChange={(event) => setPathDraft(event.target.value)}
onKeyDown={(event) => { if (event.key === 'Enter') handleGo() }}
className="h-9 min-w-0 flex-1 bg-transparent px-3 py-1"
placeholder="/"
/>
<Button size="sm" variant="outline" onClick={handleGo} disabled={!requestedPort} className="h-9">
Go
</Button>
<Button
size="sm"
variant="ghost"
onClick={reload}
disabled={!requestedPort}
aria-label="Reload preview"
className="h-9 w-9 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-9 w-9 p-0"
>
<ExternalLink className="h-4 w-4" />
</Button>
<div className="ml-auto hidden items-center gap-1 sm:flex">
{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-9 w-9 p-0"
>
<Icon className="h-4 w-4" />
</Button>
))}
</div>
</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,6 +1,6 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { render, screen, waitFor, within } from '@testing-library/react'
import userEvent, { type UserEvent } from '@testing-library/user-event'
import { FetchError } from '@opencode-manager/shared'
import { RepoActionsDialog } from './RepoActionsDialog'
import type { ProjectConfigResponse } from '@opencode-manager/shared/types'
@@ -54,6 +54,25 @@ function renderDialog() {
)
}
async function openSetupTab(user: UserEvent) {
await user.click(screen.getByRole('tab', { name: /worktree setup/i }))
}
async function openRowMenu(user: UserEvent, label: string) {
await user.click(screen.getByRole('button', { name: label }))
return screen.findByRole('menu')
}
async function closeRowMenu(user: UserEvent) {
await user.keyboard('{Escape}')
await waitFor(() => expect(screen.queryByRole('menu')).not.toBeInTheDocument())
}
async function openTrustReview(user: UserEvent) {
await user.click(screen.getByRole('button', { name: /^review$/i }))
return screen.findByRole('dialog', { name: /trust repository commands/i })
}
describe('RepoActionsDialog', () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -104,7 +123,7 @@ describe('RepoActionsDialog', () => {
}
})
it('offers no edit button for repo items but allows moving them to personal settings', () => {
it('offers no edit button for repo items but allows moving them to personal settings', async () => {
mockConfig(
baseConfig({
actions: [
@@ -113,12 +132,38 @@ describe('RepoActionsDialog', () => {
],
}),
)
const user = userEvent.setup()
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()
const repoMenu = await openRowMenu(user, 'Actions for Repo action')
expect(within(repoMenu).getByRole('menuitem', { name: /move to my settings/i })).toBeInTheDocument()
expect(within(repoMenu).queryByRole('menuitem', { name: /delete/i })).not.toBeInTheDocument()
await closeRowMenu(user)
const personalMenu = await openRowMenu(user, 'Actions for Personal action')
expect(within(personalMenu).getByRole('menuitem', { name: /move to repository/i })).toBeInTheDocument()
expect(within(personalMenu).getByRole('menuitem', { name: /delete/i })).toBeInTheDocument()
})
it('moves a repo action to personal settings from its row menu', async () => {
mockConfig(
baseConfig({
actions: [
{ id: 'repo-1', name: 'Repo action', command: 'echo repo', autoOpenUrl: false, source: 'repo' },
],
}),
)
const user = userEvent.setup()
renderDialog()
const menu = await openRowMenu(user, 'Actions for Repo action')
await user.click(within(menu).getByRole('menuitem', { name: /move to my settings/i }))
await waitFor(() => expect(mocks.moveMutate).toHaveBeenCalledTimes(1))
expect(mocks.moveMutate.mock.calls[0][0]).toEqual({ kind: 'action', id: 'repo-1', to: 'personal', directory: '/repo' })
})
it('shows the trust banner for an untrusted repo file and sends the displayed hash', async () => {
@@ -146,12 +191,13 @@ describe('RepoActionsDialog', () => {
renderDialog()
expect(screen.getByText(/not trusted/i)).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: /trust these commands/i }))
const review = await openTrustReview(user)
await user.click(within(review).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', () => {
it('lists every executable action and setup command, including shadowed actions', async () => {
mockConfig(
baseConfig({
actions: [
@@ -172,15 +218,17 @@ describe('RepoActionsDialog', () => {
},
}),
)
const user = userEvent.setup()
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()
const review = await openTrustReview(user)
expect(within(review).getByText('Actions')).toBeInTheDocument()
expect(within(review).getByText('Repo action')).toBeInTheDocument()
expect(within(review).getByText('echo repo')).toBeInTheDocument()
expect(within(review).getByText('https://example.com')).toBeInTheDocument()
expect(within(review).getByText('Opens URL automatically')).toBeInTheDocument()
expect(within(review).getByText('Worktree setup commands')).toBeInTheDocument()
expect(within(review).getByText('pnpm install')).toBeInTheDocument()
})
it('does not offer trust when the repo file has no executable commands', () => {
@@ -192,7 +240,7 @@ describe('RepoActionsDialog', () => {
renderDialog()
expect(screen.queryByText(/not trusted/i)).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: /trust these commands/i })).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: /^review$/i })).not.toBeInTheDocument()
})
it('uses the shared action icon map', () => {
@@ -223,7 +271,8 @@ describe('RepoActionsDialog', () => {
)
renderDialog()
expect(screen.queryByRole('button', { name: /trust these commands/i })).not.toBeInTheDocument()
expect(screen.queryByText(/not trusted/i)).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: /^review$/i })).not.toBeInTheDocument()
})
it('renders repository config parse errors', () => {
@@ -254,8 +303,11 @@ describe('RepoActionsDialog', () => {
const user = userEvent.setup()
renderDialog()
await user.click(screen.getByRole('button', { name: /move to repository/i }))
await openSetupTab(user)
const menu = await openRowMenu(user, 'Actions for setup command 1')
await user.click(within(menu).getByRole('menuitem', { name: /move to repository/i }))
await waitFor(() => expect(mocks.moveMutate).toHaveBeenCalledTimes(1))
expect(mocks.moveMutate.mock.calls[0][0]).toEqual({
kind: 'setup',
command: 'pnpm install',
@@ -273,14 +325,47 @@ describe('RepoActionsDialog', () => {
const user = userEvent.setup()
renderDialog()
expect(screen.getByRole('button', { name: /move to repository/i })).toBeEnabled()
await openSetupTab(user)
let menu = await openRowMenu(user, 'Actions for setup command 1')
expect(within(menu).getByRole('menuitem', { name: /move to repository/i })).not.toHaveAttribute('aria-disabled')
await closeRowMenu(user)
await user.type(screen.getByLabelText('Setup command 1'), ' --frozen-lockfile')
await user.tab()
expect(screen.getByRole('button', { name: /move to repository/i })).toBeDisabled()
menu = await openRowMenu(user, 'Actions for setup command 1')
expect(within(menu).getByRole('menuitem', { name: /move to repository/i })).toHaveAttribute('aria-disabled', 'true')
await closeRowMenu(user)
expect(mocks.moveMutate).not.toHaveBeenCalled()
})
it('enables saving setup only after an edit and pins the save button outside the scrolling list', async () => {
mockConfig(
baseConfig({
worktreeSetup: [{ command: 'pnpm install', source: 'personal' }],
}),
)
const user = userEvent.setup()
renderDialog()
await openSetupTab(user)
const save = screen.getByRole('button', { name: /save setup/i })
expect(save).toBeDisabled()
expect(screen.queryByText('Unsaved changes')).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: /add command/i }))
expect(screen.getByLabelText('Setup command 2')).toHaveFocus()
expect(save).toBeDisabled()
await user.type(screen.getByLabelText('Setup command 2'), 'pnpm build')
expect(save).toBeEnabled()
expect(screen.getByText('Unsaved changes')).toBeInTheDocument()
expect(save.closest('.overflow-y-auto')).toBeNull()
await user.click(save)
expect(mocks.updateSetupMutate.mock.calls[0][0]).toEqual(['pnpm install', 'pnpm build'])
})
it('reports a failed action save and keeps the draft', async () => {
mockConfig(
baseConfig({
@@ -321,6 +406,7 @@ describe('RepoActionsDialog', () => {
const user = userEvent.setup()
renderDialog()
await openSetupTab(user)
const input = screen.getByLabelText('Setup command 1')
await user.clear(input)
await user.type(input, 'pnpm ci')
@@ -359,7 +445,8 @@ describe('RepoActionsDialog', () => {
const user = userEvent.setup()
renderDialog()
await user.click(screen.getByRole('button', { name: /trust these commands/i }))
const review = await openTrustReview(user)
await user.click(within(review).getByRole('button', { name: /trust these commands/i }))
expect(mocks.showToastError).toHaveBeenCalledWith('Trust rejected')
})
@@ -380,9 +467,10 @@ describe('RepoActionsDialog', () => {
const user = userEvent.setup()
renderDialog()
await user.click(screen.getByRole('button', { name: /move to repository/i }))
const menu = await openRowMenu(user, 'Actions for Personal action')
await user.click(within(menu).getByRole('menuitem', { name: /move to repository/i }))
expect(mocks.showToastError).toHaveBeenCalledWith('Move rejected')
await waitFor(() => expect(mocks.showToastError).toHaveBeenCalledWith('Move rejected'))
})
it('preserves unsaved setup edits when unrelated config data refetches', async () => {
@@ -397,6 +485,7 @@ describe('RepoActionsDialog', () => {
const user = userEvent.setup()
const view = renderDialog()
await openSetupTab(user)
await user.type(screen.getByLabelText('Setup command 1'), ' --frozen-lockfile')
mockConfig(
@@ -414,13 +503,15 @@ describe('RepoActionsDialog', () => {
expect(screen.getByLabelText('Setup command 1')).toHaveValue('pnpm install --frozen-lockfile')
})
it('reflects persisted setup commands after a setup operation', () => {
it('reflects persisted setup commands after a setup operation', async () => {
mockConfig(
baseConfig({
worktreeSetup: [{ command: 'pnpm install', source: 'personal' }],
}),
)
const user = userEvent.setup()
const view = renderDialog()
await openSetupTab(user)
mockConfig(
baseConfig({
@@ -441,10 +532,12 @@ describe('RepoActionsDialog', () => {
const user = userEvent.setup()
const view = renderDialog()
await openSetupTab(user)
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()} />)
await openSetupTab(user)
expect(screen.getByLabelText('Setup command 1')).toHaveValue('pnpm install')
})
@@ -458,6 +551,7 @@ describe('RepoActionsDialog', () => {
const user = userEvent.setup()
const view = renderDialog()
await openSetupTab(user)
await user.type(screen.getByLabelText('Setup command 1'), ' --frozen-lockfile')
mockConfig(
+348 -282
View File
@@ -1,13 +1,16 @@
import { useEffect, useMemo, useRef, useState } from 'react'
import { ArrowDown, ArrowUp, Loader2, Pencil, Plus, ShieldAlert, Trash2 } from 'lucide-react'
import { ArrowDown, ArrowUp, Loader2, Pencil, Plus, ShieldAlert } 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 { ConfirmDestructiveDialog } from '@/components/ui/confirm-destructive-dialog'
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 { SettingsList, SettingsListRow, SettingsListRowActionsMenu } from '@/components/ui/settings-list'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import {
useMoveProjectItem,
useProjectConfig,
@@ -21,6 +24,7 @@ import { randomId } from '@/lib/utils'
import type {
ProjectAction,
ProjectActionIcon,
ProjectConfigResponse,
ProjectItemSource,
} from '@opencode-manager/shared/types'
import { ACTION_ICON_OPTIONS, actionIcon } from './projectActionIcons'
@@ -85,16 +89,41 @@ interface ActionFormProps {
function ActionForm({ draft, isSaving, onChange, onSave, onCancel }: ActionFormProps) {
const canSave = draft.name.trim().length > 0 && draft.command.trim().length > 0
const formRef = useRef<HTMLDivElement>(null)
useEffect(() => {
formRef.current?.scrollIntoView({ block: 'nearest' })
}, [])
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 ref={formRef} className="space-y-3 bg-card p-3">
<div className="grid gap-3 sm:grid-cols-[minmax(0,1fr)_9rem]">
<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-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>
<div className="space-y-1">
<Label htmlFor="action-command">Command</Label>
@@ -104,24 +133,6 @@ function ActionForm({ draft, isSaving, onChange, onSave, onCancel }: ActionFormP
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
@@ -151,6 +162,35 @@ function ActionForm({ draft, isSaving, onChange, onSave, onCancel }: ActionFormP
)
}
type RepoFileExecutable = NonNullable<ProjectConfigResponse['repoFile']['executable']>
interface TrustReview {
hash: string
directory: string | undefined
executable: RepoFileExecutable
}
const COMPACT_ROW_CLASS = 'flex-row items-center gap-3 py-2.5'
function ActionTitle({ action }: { action: ProjectAction }) {
const Icon = actionIcon(action.icon)
return (
<>
<Icon className="mr-2 inline h-4 w-4 align-[-3px] text-muted-foreground" />
{action.name}
</>
)
}
function ActionUrl({ url }: { url: string | undefined }) {
if (!url) return null
return <p className="mt-0.5 truncate text-xs text-muted-foreground">{url}</p>
}
function TabCount({ count }: { count: number }) {
return <span className="ml-1.5 text-xs tabular-nums text-muted-foreground">{count}</span>
}
interface RepoActionsDialogProps {
repoId: number
directory: string | undefined
@@ -167,8 +207,11 @@ export function RepoActionsDialog({ repoId, directory, open, onOpenChange }: Rep
const [draft, setDraft] = useState<ActionDraft | null>(null)
const [setupCommands, setSetupCommands] = useState<string[]>([])
const [focusSetupIndex, setFocusSetupIndex] = useState<number | null>(null)
const [trustReview, setTrustReview] = useState<TrustReview | null>(null)
const config = configQuery.data
const repoFile = config?.repoFile
const personalActions = useMemo(
() => (config?.actions ?? []).filter((action) => action.source === 'personal'),
@@ -192,12 +235,14 @@ export function RepoActionsDialog({ repoId, directory, open, onOpenChange }: Rep
useEffect(() => {
if (!open || !config) {
setupSyncKey.current = null
setTrustReview(null)
return
}
const syncKey = `${directory ?? ''}\u0000${personalSetupBaseline}`
if (setupSyncKey.current === syncKey) return
setupSyncKey.current = syncKey
setSetupCommands(personalSetup)
setFocusSetupIndex(null)
}, [open, config, directory, personalSetup, personalSetupBaseline])
const setupDirty = useMemo(
@@ -206,6 +251,7 @@ export function RepoActionsDialog({ repoId, directory, open, onOpenChange }: Rep
setupCommands.some((command, index) => command !== personalSetup[index]),
[setupCommands, personalSetup],
)
const setupValid = setupCommands.every((command) => command.trim().length > 0)
const handleSaveAction = (nextDraft: ActionDraft) => {
const payload = draftToPayload(nextDraft)
@@ -231,11 +277,26 @@ export function RepoActionsDialog({ repoId, directory, open, onOpenChange }: Rep
})
}
const addSetupCommand = () => {
setFocusSetupIndex(setupCommands.length)
setSetupCommands((current) => [...current, ''])
}
const needsTrust = Boolean(repoFile?.exists && !repoFile.trusted && repoFile.hash && repoFile.executable)
const openTrustReview = () => {
if (!repoFile?.hash || !repoFile.executable) return
setTrustReview({ hash: repoFile.hash, directory, executable: repoFile.executable })
}
const handleTrust = () => {
if (!config?.repoFile.hash) return
if (!trustReview) return
trustConfig.mutate(
{ hash: config.repoFile.hash, directory },
{ onError: (error) => showToast.error(getOpenCodeApiErrorMessage(error, 'Failed to trust repository commands')) },
{ hash: trustReview.hash, directory: trustReview.directory },
{
onSuccess: () => setTrustReview(null),
onError: (error) => showToast.error(getOpenCodeApiErrorMessage(error, 'Failed to trust repository commands')),
},
)
}
@@ -254,285 +315,290 @@ export function RepoActionsDialog({ repoId, directory, open, onOpenChange }: Rep
}
const isAddingAction = draft !== null && !personalActions.some((action) => action.id === draft.id)
const hasRepoFileStatus = Boolean(repoFile?.error) || (repoFile?.warnings.length ?? 0) > 0 || needsTrust
const renderActionForm = (current: ActionDraft) => (
<ActionForm
key={current.id}
draft={current}
isSaving={updateActions.isPending}
onChange={setDraft}
onSave={handleSaveAction}
onCancel={() => setDraft(null)}
/>
)
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>
<>
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent
mobileFullscreen
className="flex flex-col gap-0 overflow-hidden p-0 pb-safe sm:h-auto sm:max-h-[85vh] sm:max-w-[560px] sm:p-0"
>
<DialogHeader className="shrink-0 border-b border-border px-4 py-4 sm:px-6">
<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">
<p className="px-4 py-4 text-sm text-destructive sm:px-6">
{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>
{hasRepoFileStatus && (
<div className="shrink-0 space-y-2 px-4 pt-3 sm:px-6">
{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>
))}
{needsTrust && (
<div className="flex items-center gap-3 rounded-lg border border-warning/50 bg-warning/10 p-3">
<ShieldAlert className="h-4 w-4 shrink-0 text-warning" />
<div className="min-w-0 flex-1">
<p className="text-sm font-medium">Repository commands are not trusted</p>
<p className="text-xs text-muted-foreground">They won't run until you review and trust them.</p>
</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 type="button" size="sm" variant="outline" className="shrink-0" onClick={openTrustReview}>
Review
</Button>
</div>
)
})}
)}
</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>
<Tabs defaultValue="actions" className="flex min-h-0 flex-1 flex-col">
<div className="shrink-0 px-4 pt-3 sm:px-6">
<TabsList className="w-full justify-start">
<TabsTrigger value="actions">
Actions
<TabCount count={personalActions.length + repoActions.length} />
</TabsTrigger>
<TabsTrigger value="setup">
Worktree setup
<TabCount count={setupCommands.length + repoSetup.length} />
</TabsTrigger>
</TabsList>
</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>
<TabsContent value="actions" className="mt-0 flex min-h-0 flex-1 flex-col px-0">
<div className="flex shrink-0 items-center justify-between gap-3 px-4 py-3 sm:px-6">
<p className="text-xs text-muted-foreground">Start these from the actions menu in the header.</p>
<Button
type="button"
size="sm"
variant="outline"
onClick={() => moveSetup(item.command, 'personal')}
disabled={moveItem.isPending}
className="shrink-0"
onClick={() => setDraft(emptyActionDraft())}
>
Move to my settings
<Plus className="h-4 w-4 mr-1" />
Add action
</Button>
</div>
))}
<div className="min-h-0 flex-1 overflow-y-auto px-4 pb-4 sm:px-6 sm:pb-6">
<SettingsList
isEmpty={personalActions.length === 0 && repoActions.length === 0 && !isAddingAction}
emptyTitle="No actions configured"
emptyHint="Add a command you run often, like a dev server or test watcher."
maxHeightClassName="max-h-none"
>
{personalActions.map((action) =>
draft?.id === action.id ? (
renderActionForm(draft)
) : (
<SettingsListRow
key={action.id}
className={COMPACT_ROW_CLASS}
title={<ActionTitle action={action} />}
description={<span className="font-mono" title={action.command}>{action.command}</span>}
belowDescription={<ActionUrl url={action.url} />}
onClick={() => setDraft(actionToDraft(action))}
trailing={
<Button
type="button"
size="icon"
variant="ghost"
className="h-8 w-8"
aria-label={`Edit ${action.name}`}
onClick={() => setDraft(actionToDraft(action))}
>
<Pencil className="h-4 w-4" />
</Button>
}
actions={[
{
label: 'Move to repository',
onClick: () => moveAction(action, 'repo'),
disabled: moveItem.isPending,
},
{
label: 'Delete',
destructive: true,
separatorBefore: true,
onClick: () => handleDeleteAction(action.id),
disabled: updateActions.isPending,
},
]}
actionsLabel={`Actions for ${action.name}`}
/>
),
)}
{isAddingAction && draft && renderActionForm(draft)}
{repoActions.map((action) => (
<SettingsListRow
key={`repo:${action.id}`}
className={COMPACT_ROW_CLASS}
title={<ActionTitle action={action} />}
badges={<Badge variant="secondary" className="shrink-0">In repo</Badge>}
description={<span className="font-mono" title={action.command}>{action.command}</span>}
belowDescription={<ActionUrl url={action.url} />}
actions={[
{
label: 'Move to my settings',
onClick: () => moveAction(action, 'personal'),
disabled: moveItem.isPending,
},
]}
actionsLabel={`Actions for ${action.name}`}
/>
))}
</SettingsList>
</div>
</TabsContent>
<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>
<TabsContent value="setup" className="mt-0 flex min-h-0 flex-1 flex-col px-0">
<div className="flex shrink-0 items-center justify-between gap-3 px-4 py-3 sm:px-6">
<p className="text-xs text-muted-foreground">
Run in order after a new worktree is created.{' '}
<code className="font-mono">$ROOT_PROJECT_PATH</code> points to the main checkout.
</p>
<Button type="button" size="sm" variant="outline" className="shrink-0" onClick={addSetupCommand}>
<Plus className="h-4 w-4 mr-1" />
Add command
</Button>
</div>
<div className="min-h-0 flex-1 overflow-y-auto px-4 pb-4 sm:px-6">
<SettingsList
isEmpty={setupCommands.length === 0 && repoSetup.length === 0}
emptyTitle="No setup commands"
emptyHint="Add commands such as pnpm install to prepare new worktrees."
maxHeightClassName="max-h-none"
>
{setupCommands.map((command, index) => (
<div key={index} className="flex items-center gap-1 bg-card px-3 py-2">
<Input
aria-label={`Setup command ${index + 1}`}
autoFocus={index === focusSetupIndex}
value={command}
className="mr-1 h-9 min-w-0 flex-1 font-mono md:text-xs"
onChange={(event) =>
setSetupCommands((current) =>
current.map((item, itemIndex) => (itemIndex === index ? event.target.value : item)),
)
}
/>
<Button
type="button"
size="icon"
variant="ghost"
className="h-8 w-8 shrink-0"
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"
className="h-8 w-8 shrink-0"
aria-label="Move down"
disabled={index === setupCommands.length - 1}
onClick={() => setSetupCommands((current) => arrayMove(current, index, index + 1))}
>
<ArrowDown className="h-4 w-4" />
</Button>
<SettingsListRowActionsMenu
label={`Actions for setup command ${index + 1}`}
actions={[
{
label: 'Move to repository',
onClick: () => moveSetup(command, 'repo'),
disabled: setupDirty || moveItem.isPending,
},
{
label: 'Remove',
destructive: true,
separatorBefore: true,
onClick: () =>
setSetupCommands((current) => current.filter((_, itemIndex) => itemIndex !== index)),
},
]}
/>
</div>
))}
{repoSetup.map((item) => (
<SettingsListRow
key={`repo:${item.command}`}
className={COMPACT_ROW_CLASS}
title={<span title={item.command}>{item.command}</span>}
titleClassName="font-mono text-xs font-normal"
badges={<Badge variant="secondary" className="shrink-0">In repo</Badge>}
actions={[
{
label: 'Move to my settings',
onClick: () => moveSetup(item.command, 'personal'),
disabled: moveItem.isPending,
},
]}
actionsLabel={`Actions for ${item.command}`}
/>
))}
</SettingsList>
</div>
<div className="flex shrink-0 items-center justify-between gap-3 border-t border-border px-4 py-3 sm:px-6">
<p className="text-xs text-muted-foreground" aria-live="polite">
{setupDirty ? 'Unsaved changes' : ''}
</p>
<Button
type="button"
size="sm"
onClick={handleSaveSetup}
disabled={!setupDirty || !setupValid || updateSetup.isPending}
>
Save setup
</Button>
</div>
</TabsContent>
</Tabs>
</>
)}
</div>
</DialogContent>
</Dialog>
</DialogContent>
</Dialog>
<ConfirmDestructiveDialog
open={open && trustReview !== null}
onOpenChange={(next) => { if (!next) setTrustReview(null) }}
onConfirm={handleTrust}
onCancel={() => setTrustReview(null)}
title="Trust repository commands"
description="This repository defines commands that run on your machine."
warning={trustReview ? <TrustExecutableList executable={trustReview.executable} /> : undefined}
confirmLabel="Trust these commands"
pendingLabel="Trusting…"
isPending={trustConfig.isPending}
/>
</>
)
}
@@ -1,5 +1,6 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { fireEvent, render, screen } from '@testing-library/react'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { MemoryRouter } from 'react-router-dom'
import type { TerminalInfo } from '@opencode-manager/shared/types'
import { useCreateTerminal, useRemoveTerminal, useTerminals } from '@/api/terminals'
@@ -130,6 +131,84 @@ describe('TerminalPanel', () => {
expect(createMutate).toHaveBeenCalledWith({ directory: '/repo' }, expect.any(Object))
})
it('auto-creates a shell when only exited terminals exist and none is requested', () => {
mockTerminalHooks([exitedTerminal])
renderPanel()
expect(createMutate).toHaveBeenCalledTimes(1)
expect(createMutate).toHaveBeenCalledWith({ directory: '/repo' }, expect.any(Object))
})
it('decides on auto-creation once per opening, so a shell exiting later is not replaced', () => {
mockTerminalHooks([runningTerminal])
const { rerender } = renderPanel()
expect(createMutate).not.toHaveBeenCalled()
mockTerminalHooks([{ ...runningTerminal, status: 'exited', exitCode: 0 }])
rerender(
<MemoryRouter initialEntries={['/repos/1?dialog=terminal']}>
<TerminalPanel repoId={1} directory="/repo" isOpen onClose={vi.fn()} />
</MemoryRouter>,
)
expect(createMutate).not.toHaveBeenCalled()
})
it('shows a requested exited terminal without auto-creating a shell', async () => {
mockTerminalHooks([exitedTerminal])
renderPanel('/repos/1?dialog=terminal&terminal=t2')
const view = await screen.findByTestId('terminal-view')
expect(view).toHaveAttribute('data-active', 'true')
expect(createMutate).not.toHaveBeenCalled()
})
it('selects a running terminal over an exited one when none is requested', async () => {
mockTerminalHooks([exitedTerminal, runningTerminal])
renderPanel()
const views = await screen.findAllByTestId('terminal-view')
expect(views.find((view) => view.getAttribute('data-pty-id') === 't1')).toHaveAttribute('data-active', 'true')
expect(createMutate).not.toHaveBeenCalled()
})
it('opens a requested terminal without auto-creating a shell from a stale cached empty list', async () => {
const actual = await vi.importActual<typeof import('@/api/terminals')>('@/api/terminals')
vi.mocked(useTerminals).mockImplementation(actual.useTerminals)
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
queryClient.setQueryData(['terminals', 1, '/repo'], [])
let resolveList: (response: Response) => void = () => {}
const fetchMock = vi.fn(() => new Promise<Response>((resolve) => { resolveList = resolve }))
vi.stubGlobal('fetch', fetchMock)
const panel = (isOpen: boolean) => (
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={['/repos/1?dialog=terminal&terminal=t2']}>
<TerminalPanel repoId={1} directory="/repo" isOpen={isOpen} onClose={vi.fn()} />
</MemoryRouter>
</QueryClientProvider>
)
try {
const { rerender } = render(panel(false))
rerender(panel(true))
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1))
expect(createMutate).not.toHaveBeenCalled()
resolveList(new Response(JSON.stringify({ terminals: [exitedTerminal] }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
}))
const view = await screen.findByTestId('terminal-view')
expect(view).toHaveAttribute('data-pty-id', 't2')
expect(view).toHaveAttribute('data-active', 'true')
expect(createMutate).not.toHaveBeenCalled()
} finally {
vi.unstubAllGlobals()
}
})
it('exposes an accessible name for the mobile panel close control', async () => {
mockTerminalHooks([runningTerminal])
vi.mocked(useMobile).mockReturnValue(true)
@@ -28,7 +28,7 @@ export function TerminalPanel({ repoId, directory, isOpen, onClose }: TerminalPa
const isMobile = useMobile()
const { searchParams, updateParams } = useUrlParams()
const openPreview = useOpenPreview()
const { data, isLoading, isSuccess, refetch } = useTerminals(repoId, directory, {
const { data, isLoading, isSuccess, isFetching, refetch } = useTerminals(repoId, directory, {
enabled: isOpen && !!directory,
refetchInterval: isOpen ? 5000 : false,
})
@@ -38,7 +38,7 @@ export function TerminalPanel({ repoId, directory, isOpen, onClose }: TerminalPa
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 autoCreateCheckedDirectoryRef = useRef<string | null>(null)
const terminals = useMemo(() => data ?? [], [data])
@@ -49,23 +49,25 @@ export function TerminalPanel({ repoId, directory, isOpen, onClose }: TerminalPa
}, [updateParams])
const requestedTerminalId = searchParams.get('terminal')
const activeTerminalId = requestedTerminalId && terminals.some((terminal) => terminal.id === requestedTerminalId)
? requestedTerminalId
: terminals[0]?.id
const requestedTerminal = terminals.find((terminal) => terminal.id === requestedTerminalId)
const runningTerminal = terminals.find((terminal) => terminal.status === 'running')
const activeTerminalId = (requestedTerminal ?? runningTerminal ?? terminals[0])?.id
const needsShell = !requestedTerminal && !runningTerminal
useEffect(() => {
if (!isOpen || !directory) {
autoCreatedDirectoryRef.current = null
autoCreateCheckedDirectoryRef.current = null
return
}
if (!isSuccess || terminals.length > 0) return
if (autoCreatedDirectoryRef.current === directory) return
autoCreatedDirectoryRef.current = directory
if (!isSuccess || isFetching) return
if (autoCreateCheckedDirectoryRef.current === directory) return
autoCreateCheckedDirectoryRef.current = directory
if (!needsShell) return
createTerminal(
{ directory },
{ onSuccess: (terminal) => selectTerminal(terminal.id) },
)
}, [isOpen, directory, isSuccess, terminals.length, createTerminal, selectTerminal])
}, [isOpen, directory, isSuccess, isFetching, needsShell, createTerminal, selectTerminal])
const handleCreate = useCallback(() => {
createTerminal(
@@ -0,0 +1,56 @@
import { describe, expect, it, vi } from 'vitest'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { Combobox } from './combobox'
const options = [
{ value: 'builtin', label: 'Built-in Browser' },
{ value: 'external', label: 'External API' },
]
function renderCombobox(onOpen = vi.fn()) {
render(
<div>
<Combobox value="builtin" onChange={vi.fn()} options={options} allowCustomValue={false} ariaLabel="Provider" onOpen={onOpen} />
<button type="button">Outside</button>
</div>,
)
return screen.getByRole('combobox', { name: 'Provider' })
}
describe('Combobox', () => {
it('restores the selected label, not the raw value, on Escape', async () => {
const user = userEvent.setup()
const input = renderCombobox()
await user.clear(input)
await user.type(input, 'Ext')
await user.keyboard('{Escape}')
expect(input).toHaveValue('Built-in Browser')
})
it('restores the selected label, not the raw value, on an outside click', async () => {
const user = userEvent.setup()
const input = renderCombobox()
await user.clear(input)
await user.type(input, 'Ext')
await user.click(screen.getByRole('button', { name: 'Outside' }))
expect(input).toHaveValue('Built-in Browser')
})
it('calls onOpen each time the options open', async () => {
const user = userEvent.setup()
const onOpen = vi.fn()
const input = renderCombobox(onOpen)
await user.click(input)
await user.keyboard('{Escape}')
await user.click(screen.getByRole('button', { name: 'Outside' }))
await user.click(input)
expect(onOpen).toHaveBeenCalledTimes(2)
})
})
+33 -11
View File
@@ -18,6 +18,12 @@ interface ComboboxProps {
className?: string
allowCustomValue?: boolean
showClear?: boolean
ariaLabel?: string
onOpen?: () => void
}
function getOptionLabel(options: ComboboxOption[], value: string): string {
return options.find(o => o.value === value)?.label || value
}
export function Combobox({
@@ -29,12 +35,11 @@ export function Combobox({
className,
allowCustomValue = true,
showClear = false,
ariaLabel,
onOpen,
}: ComboboxProps) {
const [isOpen, setIsOpen] = useState(false)
const [inputValue, setInputValue] = useState(() => {
const selectedOption = options.find(o => o.value === value)
return selectedOption?.label || value
})
const [inputValue, setInputValue] = useState(() => getOptionLabel(options, value))
const [selectedIndex, setSelectedIndex] = useState(0)
const [isUserTyping, setIsUserTyping] = useState(false)
const inputRef = useRef<HTMLInputElement>(null)
@@ -43,11 +48,24 @@ export function Combobox({
useEffect(() => {
if (!isUserTyping) {
const selectedOption = options.find(o => o.value === value)
setInputValue(selectedOption?.label || value)
setInputValue(getOptionLabel(options, value))
}
}, [value, options, isUserTyping])
const onOpenRef = useRef(onOpen)
useEffect(() => {
onOpenRef.current = onOpen
}, [onOpen])
useEffect(() => {
if (isOpen) onOpenRef.current?.()
}, [isOpen])
const restoreSelectedLabel = useCallback(() => {
setInputValue(getOptionLabel(options, value))
setIsUserTyping(false)
}, [options, value])
const isExactMatch = options.some(o => o.value === value || o.label === inputValue)
const filteredOptions = (isExactMatch && !isUserTyping) ? options : options.filter(option =>
@@ -77,15 +95,15 @@ export function Combobox({
setIsOpen(false)
if (allowCustomValue) {
onChange(inputValue)
} else if (!options.some(o => o.value === inputValue)) {
setInputValue(value)
} else {
restoreSelectedLabel()
}
}
}
document.addEventListener('mousedown', handleClickOutside)
return () => document.removeEventListener('mousedown', handleClickOutside)
}, [isOpen, inputValue, value, onChange, options, allowCustomValue])
}, [isOpen, inputValue, onChange, allowCustomValue, restoreSelectedLabel])
useEffect(() => {
if (!isOpen || !listRef.current) return
@@ -135,7 +153,7 @@ export function Combobox({
case 'Escape':
e.preventDefault()
setIsOpen(false)
setInputValue(value)
restoreSelectedLabel()
break
case 'Tab':
setIsOpen(false)
@@ -144,7 +162,7 @@ export function Combobox({
}
break
}
}, [isOpen, selectedIndex, flatFilteredOptions, handleSelect, allowCustomValue, inputValue, value, onChange])
}, [isOpen, selectedIndex, flatFilteredOptions, handleSelect, allowCustomValue, inputValue, onChange, restoreSelectedLabel])
const handleInputChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
const newValue = e.target.value
@@ -174,6 +192,10 @@ export function Combobox({
onKeyDown={handleKeyDown}
placeholder={placeholder}
disabled={disabled}
role="combobox"
aria-label={ariaLabel}
aria-autocomplete="list"
aria-expanded={isOpen}
className={cn(
'flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-[16px] md:text-sm shadow-sm transition-colors',
'file:border-0 file:bg-transparent file:text-sm file:font-medium',
@@ -1,7 +1,9 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { useState } from "react";
import { render, screen, act, fireEvent, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { stubMatchMedia } from "@/test/test-utils";
import { Combobox } from "./combobox";
import {
Dialog,
DialogContent,
@@ -33,6 +35,29 @@ describe("DialogContent", () => {
})
})
it("closes an open combobox on Escape before closing the dialog", async () => {
const user = userEvent.setup();
const onOpenChange = vi.fn();
render(
<Dialog open onOpenChange={onOpenChange}>
<DialogContent>
<DialogTitle>Test Dialog</DialogTitle>
<Combobox value="" onChange={vi.fn()} options={[{ value: "a", label: "Alpha" }]} ariaLabel="Choice" />
</DialogContent>
</Dialog>
);
const combobox = screen.getByRole("combobox", { name: "Choice" });
await user.click(combobox);
expect(combobox).toHaveAttribute("aria-expanded", "true");
await user.keyboard("{Escape}");
expect(combobox).toHaveAttribute("aria-expanded", "false");
expect(onOpenChange).not.toHaveBeenCalled();
await user.keyboard("{Escape}");
expect(onOpenChange).toHaveBeenCalledWith(false);
});
it("applies safe-area padding when fullscreen prop is true", () => {
render(
<Dialog open>
+8 -1
View File
@@ -77,7 +77,7 @@ interface DialogContentProps
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
DialogContentProps
>(({ className, children, hideCloseButton, fullscreen, mobileFullscreen, mobileSwipeToClose, keyboardAware, canSwipeBack, onSwipeBack, overlayClassName, style, onCloseAutoFocus, ...props }, ref) => {
>(({ className, children, hideCloseButton, fullscreen, mobileFullscreen, mobileSwipeToClose, keyboardAware, canSwipeBack, onSwipeBack, overlayClassName, style, onCloseAutoFocus, onEscapeKeyDown, ...props }, ref) => {
const isMobileFullscreenMode = fullscreen || mobileFullscreen
const isDialogOpen = React.useContext(DialogOpenContext)
const returnFocus = React.useContext(DialogReturnFocusContext)
@@ -87,6 +87,12 @@ const DialogContent = React.forwardRef<
event.preventDefault()
returnFocus.focus()
}
const handleEscapeKeyDown = (event: KeyboardEvent) => {
onEscapeKeyDown?.(event)
if (event.target instanceof Element && event.target.matches('[role="combobox"][aria-expanded="true"]')) {
event.preventDefault()
}
}
const [isMobile, setIsMobile] = React.useState(() => typeof window !== 'undefined' ? window.innerWidth < 768 : false)
const shouldEnableMobileSwipe = mobileSwipeToClose !== false && isMobile && isDialogOpen
const shouldAnimateSwipe = shouldEnableMobileSwipe && isMobileFullscreenMode
@@ -150,6 +156,7 @@ const DialogContent = React.forwardRef<
style={Object.keys(mergedStyle).length > 0 ? mergedStyle : undefined}
{...props}
onCloseAutoFocus={handleCloseAutoFocus}
onEscapeKeyDown={handleEscapeKeyDown}
>
{children}
{shouldEnableMobileSwipe && (
+2 -13
View File
@@ -1,4 +1,5 @@
import { useMemo } from 'react'
import { shortenPath } from '@/lib/utils'
interface PathDisplayProps {
path: string
@@ -7,19 +8,7 @@ interface PathDisplayProps {
}
export function PathDisplay({ path, maxSegments = 3, className = '' }: PathDisplayProps) {
const displayPath = useMemo(() => {
if (!path || path === '/') return '/'
const normalizedPath = path.startsWith('/') ? path : '/' + path
const segments = normalizedPath.split('/').filter(Boolean)
if (segments.length <= maxSegments) {
return '/' + segments.join('/')
}
const visibleSegments = segments.slice(-maxSegments)
return '/.../' + visibleSegments.join('/')
}, [path, maxSegments])
const displayPath = useMemo(() => shortenPath(path, maxSegments), [path, maxSegments])
return (
<span
+34 -23
View File
@@ -94,6 +94,38 @@ export function SettingsList({
)
}
interface SettingsListRowActionsMenuProps {
actions: SettingsListRowAction[]
label?: string
}
export function SettingsListRowActionsMenu({ actions, label }: SettingsListRowActionsMenuProps) {
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button type="button" variant="ghost" size="icon" className="h-8 w-8 [[data-opencode-settings]_&]:max-sm:h-11 [[data-opencode-settings]_&]:max-sm:w-11" aria-label={label}>
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{actions.map((action, i) => (
<Fragment key={action.label}>
{action.separatorBefore && i > 0 && <DropdownMenuSeparator />}
<DropdownMenuItem
disabled={action.disabled}
onSelect={() => setTimeout(action.onClick, 0)}
className={action.destructive ? 'text-destructive focus:text-destructive' : undefined}
>
{action.icon}
{action.label}
</DropdownMenuItem>
</Fragment>
))}
</DropdownMenuContent>
</DropdownMenu>
)
}
export function SettingsListRow({
title,
titleClassName,
@@ -136,7 +168,7 @@ export function SettingsListRow({
{belowDescription}
</div>
<div
className="flex w-full shrink-0 items-center justify-end gap-1 sm:w-auto sm:justify-start [[data-opencode-settings]_&]:w-auto"
className="flex shrink-0 items-center justify-end gap-1 sm:justify-start"
onClick={(e) => e.stopPropagation()}
>
{trailing}
@@ -151,28 +183,7 @@ export function SettingsListRow({
</Button>
)}
{overflowActions && overflowActions.length > 0 && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button type="button" variant="ghost" size="icon" className="h-8 w-8 [[data-opencode-settings]_&]:max-sm:h-11 [[data-opencode-settings]_&]:max-sm:w-11" aria-label={actionsLabel}>
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{overflowActions.map((action, i) => (
<Fragment key={action.label}>
{action.separatorBefore && i > 0 && <DropdownMenuSeparator />}
<DropdownMenuItem
disabled={action.disabled}
onSelect={() => setTimeout(action.onClick, 0)}
className={action.destructive ? 'text-destructive focus:text-destructive' : undefined}
>
{action.icon}
{action.label}
</DropdownMenuItem>
</Fragment>
))}
</DropdownMenuContent>
</DropdownMenu>
<SettingsListRowActionsMenu actions={overflowActions} label={actionsLabel} />
)}
</div>
</div>