fix(terminal-dev-loop): address branch review findings

Security:
- Reject same-site and cross-site state-changing requests on cookie-authenticated routes unless the origin is trusted
- Drop Manager and ocm_preview Set-Cookie headers from preview responses
- Show and hash the full executable content of .ocm/project.json at trust time
- Restrict action URLs to http(s) and refuse symlinked repo config paths
- Keep the preview start redirect on the gateway origin

Lifecycle:
- Stop terminals in OpenCode workspace siblings when a repo is deleted
- Report preview as unavailable instead of crashing when the gateway port cannot be bound

Performance:
- Skip branch lookups when validating terminal and project-config directories
- Stop the /proc scan once all listening sockets are mapped and pause port polling while a preview is open
- Close slow WebSocket clients with 1013 so they reconnect with replay
- Lazy-load the xterm terminal view and skip unchanged resize requests
- Request uncompressed responses from preview targets

Cleanup:
- Share one repo directory resolver, trusted-origins parser, cookie prefix, WebSocket frame forwarder, header filter, icon map and dialog-param helper
- Remove unused props, options and exports

Docs: update terminal, preview, project actions, sandboxing, internal API and environment pages
This commit is contained in:
Chris Scott committed 2026-10-03 10:00:33 -04:00
1 parent 16b91ccf02
commit c60a9b35f2
72 files changed
+2039 -596

No files matched your search

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