section 9: Phase 9: Project actions settings dialog

This commit is contained in:
Chris Scott committed 2026-10-03 02:32:44 -04:00
1 parent d6aeafeae9
commit 81a9f0c8ef
12 files changed
+1106 -7

No files matched your search

+136
View File
@@ -0,0 +1,136 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import type {
MoveProjectItemRequest,
ProjectAction,
ProjectConfigResponse,
RunProjectActionResponse,
TrustRepoConfigRequest,
} from '@opencode-manager/shared/types'
import { API_BASE_URL } from '@/config'
import { fetchWrapper } from './fetchWrapper'
function directoryQuery(directory: string | undefined): string {
return directory ? `?${new URLSearchParams({ directory }).toString()}` : ''
}
export function projectConfigQueryKey(repoId: number, directory: string | undefined) {
return ['projectConfig', repoId, directory ?? null] as const
}
export function getProjectConfig(repoId: number, directory?: string): Promise<ProjectConfigResponse> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/project-config${directoryQuery(directory)}`)
}
export function updateProjectActions(
repoId: number,
actions: ProjectAction[],
directory?: string,
): Promise<ProjectConfigResponse> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/project-config/actions${directoryQuery(directory)}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ actions }),
})
}
export function updateWorktreeSetup(
repoId: number,
commands: string[],
directory?: string,
): Promise<ProjectConfigResponse> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/project-config/worktree-setup${directoryQuery(directory)}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ commands }),
})
}
export function trustRepoConfig(repoId: number, request: TrustRepoConfigRequest): Promise<ProjectConfigResponse> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/project-config/trust`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(request),
})
}
export function moveProjectItem(repoId: number, request: MoveProjectItemRequest): Promise<ProjectConfigResponse> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/project-config/move`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(request),
})
}
export function runProjectAction(
repoId: number,
actionId: string,
directory?: string,
): Promise<RunProjectActionResponse> {
return fetchWrapper(
`${API_BASE_URL}/api/repos/${repoId}/project-config/actions/${encodeURIComponent(actionId)}/run`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ directory }),
},
)
}
export function useProjectConfig(repoId: number, directory: string | undefined, enabled: boolean) {
return useQuery({
queryKey: projectConfigQueryKey(repoId, directory),
queryFn: () => getProjectConfig(repoId, directory),
enabled,
})
}
export function useUpdateProjectActions(repoId: number, directory: string | undefined) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: (actions: ProjectAction[]) => updateProjectActions(repoId, actions, directory),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['projectConfig', repoId] })
},
})
}
export function useUpdateWorktreeSetup(repoId: number, directory: string | undefined) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: (commands: string[]) => updateWorktreeSetup(repoId, commands, directory),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['projectConfig', repoId] })
},
})
}
export function useTrustRepoConfig(repoId: number) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: (request: TrustRepoConfigRequest) => trustRepoConfig(repoId, request),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['projectConfig', repoId] })
},
})
}
export function useMoveProjectItem(repoId: number) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: (request: MoveProjectItemRequest) => moveProjectItem(repoId, request),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['projectConfig', repoId] })
},
})
}
export function useRunProjectAction(repoId: number, directory: string | undefined) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: (actionId: string) => runProjectAction(repoId, actionId, directory),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['projectConfig', repoId] })
queryClient.invalidateQueries({ queryKey: ['terminals', repoId] })
},
})
}
@@ -14,7 +14,7 @@ describe('buildMoreItems', () => {
it('returns repo-specific items for /repos/:id', () => {
const items = buildMoreItems('/repos/42')
expect(items).toHaveLength(10)
expect(items).toHaveLength(11)
expect(items[0].key).toBe('home')
expect(items[1].key).toBe('files')
expect(items[1].dialog).toBe('files')
@@ -31,13 +31,15 @@ describe('buildMoreItems', () => {
expect(items[6].dialog).toBe('sourceControl')
expect(items[7].key).toBe('terminal')
expect(items[7].dialog).toBe('terminal')
expect(items[8].key).toBe('settings')
expect(items[9].key).toBe('logout')
expect(items[8].key).toBe('actions')
expect(items[8].dialog).toBe('actions')
expect(items[9].key).toBe('settings')
expect(items[10].key).toBe('logout')
})
it('returns session-specific items for /repos/:id/sessions/:sid', () => {
const items = buildMoreItems('/repos/42/sessions/abc')
expect(items).toHaveLength(10)
expect(items).toHaveLength(11)
expect(items[0].key).toBe('home')
expect(items[1].key).toBe('files')
expect(items[2].key).toBe('mcp')
@@ -48,8 +50,10 @@ describe('buildMoreItems', () => {
expect(items[6].key).toBe('source-control')
expect(items[7].key).toBe('terminal')
expect(items[7].dialog).toBe('terminal')
expect(items[8].key).toBe('settings')
expect(items[9].key).toBe('logout')
expect(items[8].key).toBe('actions')
expect(items[8].dialog).toBe('actions')
expect(items[9].key).toBe('settings')
expect(items[10].key).toBe('logout')
})
it('returns assistant workspace items for /repos/:id/assistant', () => {
@@ -1,5 +1,5 @@
import type { LucideIcon } from 'lucide-react'
import { Plug, Sparkles, ShieldOff, CalendarClock, GitCommitHorizontal, SquareTerminal, Settings, LogOut, Bot, Folder, Home } from 'lucide-react'
import { Plug, Sparkles, ShieldOff, CalendarClock, GitCommitHorizontal, SquareTerminal, Settings, LogOut, Bot, Folder, Home, Play } from 'lucide-react'
import { getAssistantPath, isAssistantPath } from '@/lib/navigation'
export interface MoreDrawerItem {
@@ -59,6 +59,7 @@ function buildRouteNavModel(pathname: string): NavModel {
{ key: 'schedules', label: 'Schedules', icon: CalendarClock, to: `/repos/${id}/schedules` },
{ key: 'source-control', label: 'Source Control', icon: GitCommitHorizontal, dialog: 'sourceControl' },
{ key: 'terminal', label: 'Terminal', icon: SquareTerminal, dialog: 'terminal' },
{ key: 'actions', label: 'Actions', icon: Play, dialog: 'actions' },
...baseItems,
]
@@ -78,6 +79,7 @@ function buildRouteNavModel(pathname: string): NavModel {
{ key: 'schedules', label: 'Schedules', icon: CalendarClock, to: `/repos/${sessionDetailMatch[1]}/schedules` },
{ key: 'source-control', label: 'Source Control', icon: GitCommitHorizontal, dialog: 'sourceControl' },
{ key: 'terminal', label: 'Terminal', icon: SquareTerminal, dialog: 'terminal' },
{ key: 'actions', label: 'Actions', icon: Play, dialog: 'actions' },
...baseItems,
]
@@ -0,0 +1,353 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { RepoActionsDialog } from './RepoActionsDialog'
import type { ProjectConfigResponse } from '@opencode-manager/shared/types'
const mocks = vi.hoisted(() => ({
useProjectConfig: vi.fn(),
updateActionsMutate: vi.fn(),
updateSetupMutate: vi.fn(),
trustMutate: vi.fn(),
moveMutate: vi.fn(),
showToastError: vi.fn(),
}))
vi.mock('@/api/projectConfig', () => ({
useProjectConfig: mocks.useProjectConfig,
useUpdateProjectActions: () => ({ mutate: mocks.updateActionsMutate, isPending: false }),
useUpdateWorktreeSetup: () => ({ mutate: mocks.updateSetupMutate, isPending: false }),
useTrustRepoConfig: () => ({ mutate: mocks.trustMutate, isPending: false }),
useMoveProjectItem: () => ({ mutate: mocks.moveMutate, isPending: false }),
}))
vi.mock('@/lib/toast', () => ({
showToast: { error: mocks.showToastError, success: vi.fn() },
}))
const HASH = 'a'.repeat(64)
function baseConfig(overrides: Partial<ProjectConfigResponse> = {}): ProjectConfigResponse {
return {
actions: [],
worktreeSetup: [],
repoFile: { path: '.ocm/project.json', exists: false, trusted: false, hash: null, warnings: [] },
...overrides,
}
}
function mockConfig(config: ProjectConfigResponse) {
mocks.useProjectConfig.mockReturnValue({ data: config, isLoading: false, error: null })
}
function renderDialog() {
return render(
<RepoActionsDialog repoId={1} directory="/repo" open onOpenChange={vi.fn()} />,
)
}
describe('RepoActionsDialog', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('sends the full personal list when adding an action', async () => {
mockConfig(
baseConfig({
actions: [
{ id: 'existing', name: 'Existing', command: 'echo hi', autoOpenUrl: false, source: 'personal' },
],
}),
)
const user = userEvent.setup()
renderDialog()
await user.click(screen.getByRole('button', { name: /add action/i }))
await user.type(screen.getByLabelText('Name'), 'Dev server')
await user.type(screen.getByLabelText('Command'), 'pnpm dev')
await user.click(screen.getByRole('button', { name: /^save$/i }))
await waitFor(() => expect(mocks.updateActionsMutate).toHaveBeenCalledTimes(1))
const payload = mocks.updateActionsMutate.mock.calls[0][0]
expect(payload).toHaveLength(2)
expect(payload[0]).toMatchObject({ id: 'existing', name: 'Existing', command: 'echo hi' })
expect(payload[1]).toMatchObject({ name: 'Dev server', command: 'pnpm dev' })
})
it('offers no edit button for repo items but allows moving them to personal settings', () => {
mockConfig(
baseConfig({
actions: [
{ id: 'personal-1', name: 'Personal action', command: 'echo personal', autoOpenUrl: false, source: 'personal' },
{ id: 'repo-1', name: 'Repo action', command: 'echo repo', autoOpenUrl: false, source: 'repo' },
],
}),
)
renderDialog()
expect(screen.getAllByRole('button', { name: /edit/i })).toHaveLength(1)
expect(screen.getByText('In repo')).toBeInTheDocument()
expect(screen.getByRole('button', { name: /move to my settings/i })).toBeInTheDocument()
expect(screen.getByRole('button', { name: /move to repository/i })).toBeInTheDocument()
})
it('shows the trust banner for an untrusted repo file and sends the displayed hash', async () => {
mockConfig(
baseConfig({
actions: [
{ id: 'repo-1', name: 'Repo action', command: 'echo repo', autoOpenUrl: false, source: 'repo' },
],
repoFile: { path: '.ocm/project.json', exists: true, trusted: false, hash: HASH, warnings: [] },
}),
)
const user = userEvent.setup()
renderDialog()
expect(screen.getByText(/not trusted/i)).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: /trust these commands/i }))
expect(mocks.trustMutate.mock.calls[0][0]).toEqual({ hash: HASH, directory: '/repo' })
})
it('hides the trust banner for a trusted repo file', () => {
mockConfig(
baseConfig({
repoFile: { path: '.ocm/project.json', exists: true, trusted: true, hash: HASH, warnings: [] },
}),
)
renderDialog()
expect(screen.queryByRole('button', { name: /trust these commands/i })).not.toBeInTheDocument()
})
it('renders repository config parse errors', () => {
mockConfig(
baseConfig({
repoFile: {
path: '.ocm/project.json',
exists: true,
trusted: false,
hash: null,
error: 'Invalid repository config',
warnings: [],
},
}),
)
renderDialog()
expect(screen.getByRole('alert')).toHaveTextContent('Invalid repository config')
})
it('moves a saved personal setup command to the repository', async () => {
mockConfig(
baseConfig({
worktreeSetup: [{ command: 'pnpm install', source: 'personal' }],
}),
)
const user = userEvent.setup()
renderDialog()
await user.click(screen.getByRole('button', { name: /move to repository/i }))
expect(mocks.moveMutate.mock.calls[0][0]).toEqual({
kind: 'setup',
command: 'pnpm install',
to: 'repo',
directory: '/repo',
})
})
it('disables moving a personal setup command while edits are unsaved', async () => {
mockConfig(
baseConfig({
worktreeSetup: [{ command: 'pnpm install', source: 'personal' }],
}),
)
const user = userEvent.setup()
renderDialog()
expect(screen.getByRole('button', { name: /move to repository/i })).toBeEnabled()
await user.type(screen.getByLabelText('Setup command 1'), ' --frozen-lockfile')
expect(screen.getByRole('button', { name: /move to repository/i })).toBeDisabled()
expect(mocks.moveMutate).not.toHaveBeenCalled()
})
it('reports a failed action save and keeps the draft', async () => {
mockConfig(
baseConfig({
actions: [
{ id: 'existing', name: 'Existing', command: 'echo hi', autoOpenUrl: false, source: 'personal' },
],
}),
)
mocks.updateActionsMutate.mockImplementation(
(_payload: unknown, options?: { onError?: (error: unknown) => void }) => {
options?.onError?.(new Error('Server rejected the action'))
},
)
const user = userEvent.setup()
renderDialog()
await user.click(screen.getByRole('button', { name: /add action/i }))
await user.type(screen.getByLabelText('Name'), 'Dev server')
await user.type(screen.getByLabelText('Command'), 'pnpm dev')
await user.click(screen.getByRole('button', { name: /^save$/i }))
expect(mocks.showToastError).toHaveBeenCalledWith('Server rejected the action')
expect(screen.getByLabelText('Name')).toHaveValue('Dev server')
expect(screen.getByLabelText('Command')).toHaveValue('pnpm dev')
})
it('reports a failed setup save and keeps edits', async () => {
mockConfig(
baseConfig({
worktreeSetup: [{ command: 'pnpm install', source: 'personal' }],
}),
)
mocks.updateSetupMutate.mockImplementation(
(_commands: unknown, options?: { onError?: (error: unknown) => void }) => {
options?.onError?.(new Error('Setup save rejected'))
},
)
const user = userEvent.setup()
renderDialog()
const input = screen.getByLabelText('Setup command 1')
await user.clear(input)
await user.type(input, 'pnpm ci')
await user.click(screen.getByRole('button', { name: /save setup/i }))
expect(mocks.showToastError).toHaveBeenCalledWith('Setup save rejected')
expect(screen.getByLabelText('Setup command 1')).toHaveValue('pnpm ci')
})
it('reports a failed trust attempt', async () => {
mockConfig(
baseConfig({
actions: [
{ id: 'repo-1', name: 'Repo action', command: 'echo repo', autoOpenUrl: false, source: 'repo' },
],
repoFile: { path: '.ocm/project.json', exists: true, trusted: false, hash: HASH, warnings: [] },
}),
)
mocks.trustMutate.mockImplementation(
(_request: unknown, options?: { onError?: (error: unknown) => void }) => {
options?.onError?.(new Error('Trust rejected'))
},
)
const user = userEvent.setup()
renderDialog()
await user.click(screen.getByRole('button', { name: /trust these commands/i }))
expect(mocks.showToastError).toHaveBeenCalledWith('Trust rejected')
})
it('reports a failed move', async () => {
mockConfig(
baseConfig({
actions: [
{ id: 'personal-1', name: 'Personal action', command: 'echo personal', autoOpenUrl: false, source: 'personal' },
],
}),
)
mocks.moveMutate.mockImplementation(
(_request: unknown, options?: { onError?: (error: unknown) => void }) => {
options?.onError?.(new Error('Move rejected'))
},
)
const user = userEvent.setup()
renderDialog()
await user.click(screen.getByRole('button', { name: /move to repository/i }))
expect(mocks.showToastError).toHaveBeenCalledWith('Move rejected')
})
it('preserves unsaved setup edits when unrelated config data refetches', async () => {
mockConfig(
baseConfig({
actions: [
{ id: 'existing', name: 'Existing', command: 'echo hi', autoOpenUrl: false, source: 'personal' },
],
worktreeSetup: [{ command: 'pnpm install', source: 'personal' }],
}),
)
const user = userEvent.setup()
const view = renderDialog()
await user.type(screen.getByLabelText('Setup command 1'), ' --frozen-lockfile')
mockConfig(
baseConfig({
actions: [
{ id: 'existing', name: 'Existing', command: 'echo hi', autoOpenUrl: false, source: 'personal' },
{ id: 'added', name: 'Added', command: 'pnpm dev', autoOpenUrl: false, source: 'personal' },
],
worktreeSetup: [{ command: 'pnpm install', source: 'personal' }],
repoFile: { path: '.ocm/project.json', exists: true, trusted: true, hash: HASH, warnings: [] },
}),
)
view.rerender(<RepoActionsDialog repoId={1} directory="/repo" open onOpenChange={vi.fn()} />)
expect(screen.getByLabelText('Setup command 1')).toHaveValue('pnpm install --frozen-lockfile')
})
it('reflects persisted setup commands after a setup operation', () => {
mockConfig(
baseConfig({
worktreeSetup: [{ command: 'pnpm install', source: 'personal' }],
}),
)
const view = renderDialog()
mockConfig(
baseConfig({
worktreeSetup: [{ command: 'pnpm ci', source: 'personal' }],
}),
)
view.rerender(<RepoActionsDialog repoId={1} directory="/repo" open onOpenChange={vi.fn()} />)
expect(screen.getByLabelText('Setup command 1')).toHaveValue('pnpm ci')
})
it('reinitializes setup commands from persisted data when the dialog reopens', async () => {
mockConfig(
baseConfig({
worktreeSetup: [{ command: 'pnpm install', source: 'personal' }],
}),
)
const user = userEvent.setup()
const view = renderDialog()
await user.type(screen.getByLabelText('Setup command 1'), ' --frozen-lockfile')
view.rerender(<RepoActionsDialog repoId={1} directory="/repo" open={false} onOpenChange={vi.fn()} />)
view.rerender(<RepoActionsDialog repoId={1} directory="/repo" open onOpenChange={vi.fn()} />)
expect(screen.getByLabelText('Setup command 1')).toHaveValue('pnpm install')
})
it('reinitializes setup commands when the location changes', async () => {
mockConfig(
baseConfig({
worktreeSetup: [{ command: 'pnpm install', source: 'personal' }],
}),
)
const user = userEvent.setup()
const view = renderDialog()
await user.type(screen.getByLabelText('Setup command 1'), ' --frozen-lockfile')
mockConfig(
baseConfig({
worktreeSetup: [{ command: 'pnpm ci', source: 'personal' }],
}),
)
view.rerender(<RepoActionsDialog repoId={1} directory="/repo-worktree" open onOpenChange={vi.fn()} />)
expect(screen.getByLabelText('Setup command 1')).toHaveValue('pnpm ci')
})
})
@@ -0,0 +1,581 @@
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 { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import {
useMoveProjectItem,
useProjectConfig,
useTrustRepoConfig,
useUpdateProjectActions,
useUpdateWorktreeSetup,
} from '@/api/projectConfig'
import { showToast } from '@/lib/toast'
import 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
}
interface ActionDraft {
id: string
name: string
command: string
icon: ProjectActionIcon
url: string
autoOpenUrl: boolean
}
function emptyActionDraft(): ActionDraft {
return { id: crypto.randomUUID(), name: '', command: '', icon: 'play', url: '', autoOpenUrl: false }
}
function actionToDraft(action: ProjectAction): ActionDraft {
return {
id: action.id,
name: action.name,
command: action.command,
icon: action.icon ?? 'play',
url: action.url ?? '',
autoOpenUrl: action.autoOpenUrl,
}
}
function actionToPayload(action: ProjectAction): ProjectAction {
const payload: ProjectAction = {
id: action.id,
name: action.name,
command: action.command,
autoOpenUrl: action.autoOpenUrl,
}
if (action.icon) payload.icon = action.icon
if (action.url) payload.url = action.url
return payload
}
function draftToPayload(draft: ActionDraft): ProjectAction {
const payload: ProjectAction = {
id: draft.id,
name: draft.name.trim(),
command: draft.command.trim(),
icon: draft.icon,
autoOpenUrl: draft.autoOpenUrl,
}
const url = draft.url.trim()
if (url) payload.url = url
return payload
}
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
onChange: (draft: ActionDraft) => void
onSave: (draft: ActionDraft) => void
onCancel: () => void
}
function ActionForm({ draft, isSaving, onChange, onSave, onCancel }: ActionFormProps) {
const canSave = draft.name.trim().length > 0 && draft.command.trim().length > 0
return (
<div className="space-y-3">
<div className="space-y-1">
<Label htmlFor="action-name">Name</Label>
<Input
id="action-name"
value={draft.name}
onChange={(event) => onChange({ ...draft, name: event.target.value })}
/>
</div>
<div className="space-y-1">
<Label htmlFor="action-command">Command</Label>
<Input
id="action-command"
value={draft.command}
onChange={(event) => onChange({ ...draft, command: event.target.value })}
/>
</div>
<div className="space-y-1">
<Label htmlFor="action-icon">Icon</Label>
<Select
value={draft.icon}
onValueChange={(value) => onChange({ ...draft, icon: value as ProjectActionIcon })}
>
<SelectTrigger id="action-icon">
<SelectValue />
</SelectTrigger>
<SelectContent>
{ACTION_ICON_OPTIONS.map(({ value, label }) => (
<SelectItem key={value} value={value}>
{label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-1">
<Label htmlFor="action-url">URL template</Label>
<Input
id="action-url"
placeholder="http://localhost:3000/{worktree}"
value={draft.url}
onChange={(event) => onChange({ ...draft, url: event.target.value })}
/>
</div>
<div className="flex items-center justify-between">
<Label htmlFor="action-auto-open">Auto-open URL</Label>
<Switch
id="action-auto-open"
checked={draft.autoOpenUrl}
onCheckedChange={(checked) => onChange({ ...draft, autoOpenUrl: checked })}
/>
</div>
<div className="flex justify-end gap-2">
<Button type="button" size="sm" variant="ghost" onClick={onCancel}>
Cancel
</Button>
<Button type="button" size="sm" onClick={() => onSave(draft)} disabled={!canSave || isSaving}>
Save
</Button>
</div>
</div>
)
}
interface RepoActionsDialogProps {
repoId: number
directory: string | undefined
open: boolean
onOpenChange: (open: boolean) => void
}
export function RepoActionsDialog({ repoId, directory, open, onOpenChange }: RepoActionsDialogProps) {
const configQuery = useProjectConfig(repoId, directory, open && !!directory)
const updateActions = useUpdateProjectActions(repoId, directory)
const updateSetup = useUpdateWorktreeSetup(repoId, directory)
const trustConfig = useTrustRepoConfig(repoId)
const moveItem = useMoveProjectItem(repoId)
const [draft, setDraft] = useState<ActionDraft | null>(null)
const [setupCommands, setSetupCommands] = useState<string[]>([])
const config = configQuery.data
const personalActions = useMemo(
() => (config?.actions ?? []).filter((action) => action.source === 'personal'),
[config],
)
const repoActions = useMemo(
() => (config?.actions ?? []).filter((action) => action.source === 'repo'),
[config],
)
const repoSetup = useMemo(
() => (config?.worktreeSetup ?? []).filter((item) => item.source === 'repo'),
[config],
)
const personalSetup = useMemo(
() => (config?.worktreeSetup ?? []).filter((item) => item.source === 'personal').map((item) => item.command),
[config],
)
const personalSetupBaseline = useMemo(() => JSON.stringify(personalSetup), [personalSetup])
const setupSyncKey = useRef<string | null>(null)
useEffect(() => {
if (!open || !config) {
setupSyncKey.current = null
return
}
const syncKey = `${directory ?? ''}\u0000${personalSetupBaseline}`
if (setupSyncKey.current === syncKey) return
setupSyncKey.current = syncKey
setSetupCommands(personalSetup)
}, [open, config, directory, personalSetup, personalSetupBaseline])
const setupDirty = useMemo(
() =>
setupCommands.length !== personalSetup.length ||
setupCommands.some((command, index) => command !== personalSetup[index]),
[setupCommands, personalSetup],
)
const handleSaveAction = (nextDraft: ActionDraft) => {
const payload = draftToPayload(nextDraft)
const exists = personalActions.some((action) => action.id === payload.id)
const next = exists
? personalActions.map((action) => (action.id === payload.id ? payload : actionToPayload(action)))
: [...personalActions.map(actionToPayload), payload]
updateActions.mutate(next, {
onSuccess: () => setDraft(null),
onError: (error) => showToast.error(mutationErrorMessage(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')),
})
}
const handleSaveSetup = () => {
updateSetup.mutate(setupCommands.map((command) => command.trim()), {
onError: (error) => showToast.error(mutationErrorMessage(error, 'Failed to save setup commands')),
})
}
const handleTrust = () => {
if (!config?.repoFile.hash) return
trustConfig.mutate(
{ hash: config.repoFile.hash, directory },
{ onError: (error) => showToast.error(mutationErrorMessage(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')) },
)
}
const moveSetup = (command: string, to: ProjectItemSource) => {
moveItem.mutate(
{ kind: 'setup', command, to, directory },
{ onError: (error) => showToast.error(mutationErrorMessage(error, 'Failed to move setup command')) },
)
}
const isAddingAction = draft !== null && !personalActions.some((action) => action.id === draft.id)
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent
mobileFullscreen
className="sm:fixed sm:left-1/2 sm:top-1/2 sm:-translate-x-1/2 sm:-translate-y-1/2 sm:w-[520px] sm:max-w-[520px] sm:h-auto sm:max-h-[85vh] flex flex-col gap-0 pb-safe"
>
<DialogHeader className="px-4 sm:px-6 pt-4 sm:pt-6 pb-2 sm:pb-3 shrink-0">
<DialogTitle>Project Actions</DialogTitle>
<DialogDescription>Commands and setup steps for this location.</DialogDescription>
</DialogHeader>
<div className="flex-1 overflow-y-auto px-4 sm:px-6 pb-4 sm:pb-6 space-y-6">
{configQuery.isLoading ? (
<div className="flex items-center justify-center py-8">
<Loader2 className="h-4 w-4 animate-spin text-primary" />
</div>
) : !config ? (
<p className="text-sm text-destructive">
{configQuery.error instanceof Error ? configQuery.error.message : 'No configuration available.'}
</p>
) : (
<>
<section className="space-y-3">
<div className="flex items-center justify-between">
<h3 className="text-sm font-semibold">Actions</h3>
<Button type="button" size="sm" variant="outline" onClick={() => setDraft(emptyActionDraft())}>
<Plus className="h-4 w-4 mr-1" />
Add action
</Button>
</div>
{personalActions.length === 0 && repoActions.length === 0 && (
<p className="text-sm text-muted-foreground">No actions configured.</p>
)}
{personalActions.map((action) => {
const Icon = actionIcon(action.icon)
const isEditing = draft?.id === action.id
return (
<div key={action.id} className="rounded-lg border border-border bg-card p-3 space-y-2">
{isEditing && draft ? (
<ActionForm
draft={draft}
isSaving={updateActions.isPending}
onChange={setDraft}
onSave={handleSaveAction}
onCancel={() => setDraft(null)}
/>
) : (
<>
<div className="flex items-center gap-2">
<Icon className="h-4 w-4 text-muted-foreground shrink-0" />
<span className="text-sm font-medium truncate">{action.name}</span>
</div>
<p className="font-mono text-xs text-muted-foreground truncate">{action.command}</p>
{action.url && (
<p className="text-xs text-muted-foreground truncate">{action.url}</p>
)}
<div className="flex flex-wrap gap-2">
<Button
type="button"
size="sm"
variant="outline"
onClick={() => setDraft(actionToDraft(action))}
>
<Pencil className="h-3 w-3 mr-1" />
Edit
</Button>
<Button
type="button"
size="sm"
variant="outline"
onClick={() => moveAction(action, 'repo')}
disabled={moveItem.isPending}
>
Move to repository
</Button>
<Button
type="button"
size="sm"
variant="outline"
onClick={() => handleDeleteAction(action.id)}
disabled={updateActions.isPending}
>
<Trash2 className="h-3 w-3 mr-1" />
Delete
</Button>
</div>
</>
)}
</div>
)
})}
{repoActions.map((action) => {
const Icon = actionIcon(action.icon)
return (
<div key={action.id} className="rounded-lg border border-border bg-card p-3 space-y-2">
<div className="flex items-center gap-2">
<Icon className="h-4 w-4 text-muted-foreground shrink-0" />
<span className="text-sm font-medium truncate">{action.name}</span>
<Badge variant="secondary">In repo</Badge>
</div>
<p className="font-mono text-xs text-muted-foreground truncate">{action.command}</p>
{action.url && (
<p className="text-xs text-muted-foreground truncate">{action.url}</p>
)}
<Button
type="button"
size="sm"
variant="outline"
onClick={() => moveAction(action, 'personal')}
disabled={moveItem.isPending}
>
Move to my settings
</Button>
</div>
)
})}
{isAddingAction && draft && (
<div className="rounded-lg border border-border bg-card p-3">
<ActionForm
draft={draft}
isSaving={updateActions.isPending}
onChange={setDraft}
onSave={handleSaveAction}
onCancel={() => setDraft(null)}
/>
</div>
)}
</section>
<section className="space-y-3">
<div>
<h3 className="text-sm font-semibold">Worktree setup</h3>
<p className="text-xs text-muted-foreground mt-1">
Commands run after a new worktree is created. Use{' '}
<code className="font-mono">$ROOT_PROJECT_PATH</code> to reference the main checkout.
</p>
</div>
{setupCommands.length === 0 && repoSetup.length === 0 && (
<p className="text-sm text-muted-foreground">No setup commands.</p>
)}
{setupCommands.map((command, index) => (
<div key={index} className="rounded-lg border border-border bg-card p-3 space-y-2">
<div className="flex items-center gap-2">
<Input
aria-label={`Setup command ${index + 1}`}
value={command}
onChange={(event) =>
setSetupCommands((current) =>
current.map((item, itemIndex) => (itemIndex === index ? event.target.value : item)),
)
}
/>
<Button
type="button"
size="icon"
variant="ghost"
aria-label="Move up"
disabled={index === 0}
onClick={() => setSetupCommands((current) => moveArrayItem(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) => moveArrayItem(current, index, index + 1))}
>
<ArrowDown className="h-4 w-4" />
</Button>
<Button
type="button"
size="icon"
variant="ghost"
aria-label="Remove command"
onClick={() => setSetupCommands((current) => current.filter((_, itemIndex) => itemIndex !== index))}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
<div className="flex justify-end">
<Button
type="button"
size="sm"
variant="outline"
onClick={() => moveSetup(command, 'repo')}
disabled={setupDirty || moveItem.isPending}
>
Move to repository
</Button>
</div>
</div>
))}
{repoSetup.map((item) => (
<div
key={item.command}
className="flex items-center justify-between gap-2 rounded-lg border border-border bg-card p-3"
>
<div className="flex items-center gap-2 min-w-0">
<span className="font-mono text-xs truncate">{item.command}</span>
<Badge variant="secondary">In repo</Badge>
</div>
<Button
type="button"
size="sm"
variant="outline"
onClick={() => moveSetup(item.command, 'personal')}
disabled={moveItem.isPending}
>
Move to my settings
</Button>
</div>
))}
<div className="flex justify-end gap-2">
<Button
type="button"
size="sm"
variant="outline"
onClick={() => setSetupCommands((current) => [...current, ''])}
>
<Plus className="h-4 w-4 mr-1" />
Add command
</Button>
<Button
type="button"
size="sm"
onClick={handleSaveSetup}
disabled={setupCommands.some((command) => !command.trim()) || updateSetup.isPending}
>
Save setup
</Button>
</div>
</section>
<section className="space-y-2">
{config.repoFile.error && (
<p role="alert" className="text-sm text-destructive">
{config.repoFile.error}
</p>
)}
{config.repoFile.warnings.map((warning) => (
<p key={warning} className="text-xs text-warning">
{warning}
</p>
))}
{config.repoFile.exists && !config.repoFile.trusted && config.repoFile.hash && (
<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>
<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>
</>
)}
</div>
</DialogContent>
</Dialog>
)
}
+9
View File
@@ -6,6 +6,7 @@ import { SessionList } from "@/components/session/SessionList";
import { FileBrowserSheet } from "@/components/file-browser/FileBrowserSheet";
import { Header } from "@/components/ui/header";
import { RepoMcpDialog } from "@/components/repo/RepoMcpDialog";
import { RepoActionsDialog } from "@/components/repo/RepoActionsDialog";
import { RepoSkillsDialog } from "@/components/repo/RepoSkillsDialog";
import { SourceControlPanel } from "@/components/source-control";
import { TerminalPanel } from "@/components/terminal/TerminalPanel";
@@ -35,6 +36,7 @@ export function RepoDetail() {
const [skillsDialogOpen, setSkillsDialogOpen] = useDialogParam('skills');
const [sourceControlOpen, setSourceControlOpen] = useDialogParam('sourceControl');
const [terminalOpen, setTerminalOpen] = useDialogParam('terminal');
const [actionsDialogOpen, setActionsDialogOpen] = useDialogParam('actions');
const [resetPermissionsOpen, setResetPermissionsOpen] = useDialogParam('resetPermissions');
const [createWorkspaceOpen, setCreateWorkspaceOpen] = useState(false);
const [workspaceSelectorOpen, setWorkspaceSelectorOpen] = useState(false);
@@ -279,6 +281,13 @@ export function RepoDetail() {
directory={composerDirectory}
/>
<RepoActionsDialog
repoId={repoId}
directory={composerDirectory}
open={actionsDialogOpen}
onOpenChange={setActionsDialogOpen}
/>
<RepoSkillsDialog
open={skillsDialogOpen}
onOpenChange={setSkillsDialogOpen}
+9
View File
@@ -38,6 +38,7 @@ import { showToast } from "@/lib/toast";
import { getWorkspaceFilePath } from "@/lib/markdownLinks";
import { getRepoDisplayName } from "@/lib/utils";
import { RepoMcpDialog } from "@/components/repo/RepoMcpDialog";
import { RepoActionsDialog } from "@/components/repo/RepoActionsDialog";
import { ResetPermissionsDialog } from "@/components/repo/ResetPermissionsDialog";
import { RepoSkillsDialog } from "@/components/repo/RepoSkillsDialog";
import { compactSession, forkSession, listSessionMessages } from "@/api/opencode";
@@ -119,6 +120,7 @@ export function SessionDetail() {
const [skillsDialogOpen, setSkillsDialogOpen] = useDialogParam('skills');
const [sourceControlOpen, setSourceControlOpen] = useDialogParam('sourceControl');
const [terminalOpen, setTerminalOpen] = useDialogParam('terminal');
const [actionsDialogOpen, setActionsDialogOpen] = useDialogParam('actions');
const [resetPermissionsOpen, setResetPermissionsOpen] = useDialogParam('resetPermissions');
const [selectedFilePath, setSelectedFilePath] = useState<string | undefined>();
const [showScrollButton, setShowScrollButton] = useState(false);
@@ -855,6 +857,13 @@ export function SessionDetail() {
directory={repoDirectory}
/>
<RepoActionsDialog
repoId={repoId}
directory={sessionDirectory}
open={actionsDialogOpen}
onOpenChange={setActionsDialogOpen}
/>
<SourceControlPanel
repoId={repoId}
isOpen={sourceControlOpen}
@@ -131,6 +131,7 @@ vi.mock('@/components/file-browser/FileBrowserSheet', () => ({
vi.mock('@/components/repo/RepoMcpDialog', () => ({
RepoMcpDialog: vi.fn(() => null),
}))
vi.mock('@/components/repo/RepoActionsDialog', () => ({ RepoActionsDialog: vi.fn(() => null) }))
vi.mock('@/components/repo/ResetPermissionsDialog', () => ({
ResetPermissionsDialog: vi.fn(() => null),
@@ -197,6 +197,7 @@ vi.mock('@/components/session/SideQuestionDialog', () => ({ SideQuestionDialog:
vi.mock('@/components/session/SessionList', () => ({ SessionList: vi.fn(() => null) }))
vi.mock('@/components/file-browser/FileBrowserSheet', () => ({ FileBrowserSheet: vi.fn(() => null) }))
vi.mock('@/components/repo/RepoMcpDialog', () => ({ RepoMcpDialog: vi.fn(() => null) }))
vi.mock('@/components/repo/RepoActionsDialog', () => ({ RepoActionsDialog: vi.fn(() => null) }))
vi.mock('@/components/repo/ResetPermissionsDialog', () => ({ ResetPermissionsDialog: vi.fn(() => null) }))
vi.mock('@/components/repo/RepoSkillsDialog', () => ({ RepoSkillsDialog: vi.fn(() => null) }))
vi.mock('@/components/source-control', () => ({ SourceControlPanel: vi.fn(() => null) }))
@@ -162,6 +162,7 @@ vi.mock('@/components/file-browser/FileBrowserSheet', () => ({
vi.mock('@/components/repo/RepoMcpDialog', () => ({
RepoMcpDialog: vi.fn(() => null),
}))
vi.mock('@/components/repo/RepoActionsDialog', () => ({ RepoActionsDialog: vi.fn(() => null) }))
vi.mock('@/components/repo/ResetPermissionsDialog', () => ({
ResetPermissionsDialog: vi.fn(() => null),
@@ -129,6 +129,7 @@ vi.mock('@/components/session/BackgroundWorkBar', () => ({ BackgroundWorkBar: vi
vi.mock('@/components/session/SessionList', () => ({ SessionList: vi.fn(() => null) }))
vi.mock('@/components/file-browser/FileBrowserSheet', () => ({ FileBrowserSheet: vi.fn(() => null) }))
vi.mock('@/components/repo/RepoMcpDialog', () => ({ RepoMcpDialog: vi.fn(() => null) }))
vi.mock('@/components/repo/RepoActionsDialog', () => ({ RepoActionsDialog: vi.fn(() => null) }))
vi.mock('@/components/repo/ResetPermissionsDialog', () => ({ ResetPermissionsDialog: vi.fn(() => null) }))
vi.mock('@/components/repo/RepoSkillsDialog', () => ({ RepoSkillsDialog: vi.fn(() => null) }))
vi.mock('@/components/source-control', () => ({ SourceControlPanel: vi.fn(() => null) }))
@@ -156,6 +156,7 @@ vi.mock('@/components/file-browser/FileBrowserSheet', () => ({
vi.mock('@/components/repo/RepoMcpDialog', () => ({
RepoMcpDialog: vi.fn(() => null),
}))
vi.mock('@/components/repo/RepoActionsDialog', () => ({ RepoActionsDialog: vi.fn(() => null) }))
vi.mock('@/components/repo/ResetPermissionsDialog', () => ({
ResetPermissionsDialog: vi.fn(() => null),