From 81a9f0c8ef70ed47393a761ac9cbcb07f7512ee2 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Sat, 3 Oct 2026 02:32:44 -0400 Subject: [PATCH] section 9: Phase 9: Project actions settings dialog --- frontend/src/api/projectConfig.ts | 136 ++++ .../navigation/moreDrawerItems.test.ts | 16 +- .../components/navigation/moreDrawerItems.ts | 4 +- .../repo/RepoActionsDialog.test.tsx | 353 +++++++++++ .../src/components/repo/RepoActionsDialog.tsx | 581 ++++++++++++++++++ frontend/src/pages/RepoDetail.tsx | 9 + frontend/src/pages/SessionDetail.tsx | 9 + .../SessionDetail.assistant-loading.test.tsx | 1 + .../__tests__/SessionDetail.commands.test.tsx | 1 + .../SessionDetail.form-prompt.test.tsx | 1 + .../__tests__/SessionDetail.polling.test.tsx | 1 + .../SessionDetail.scroll-floating.test.tsx | 1 + 12 files changed, 1106 insertions(+), 7 deletions(-) create mode 100644 frontend/src/api/projectConfig.ts create mode 100644 frontend/src/components/repo/RepoActionsDialog.test.tsx create mode 100644 frontend/src/components/repo/RepoActionsDialog.tsx diff --git a/frontend/src/api/projectConfig.ts b/frontend/src/api/projectConfig.ts new file mode 100644 index 00000000..e5a0e574 --- /dev/null +++ b/frontend/src/api/projectConfig.ts @@ -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 { + return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/project-config${directoryQuery(directory)}`) +} + +export function updateProjectActions( + repoId: number, + actions: ProjectAction[], + directory?: string, +): Promise { + 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 { + 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 { + 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 { + 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 { + 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] }) + }, + }) +} diff --git a/frontend/src/components/navigation/moreDrawerItems.test.ts b/frontend/src/components/navigation/moreDrawerItems.test.ts index 30bcd2dc..7dc39e72 100644 --- a/frontend/src/components/navigation/moreDrawerItems.test.ts +++ b/frontend/src/components/navigation/moreDrawerItems.test.ts @@ -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', () => { diff --git a/frontend/src/components/navigation/moreDrawerItems.ts b/frontend/src/components/navigation/moreDrawerItems.ts index b327463e..168df87e 100644 --- a/frontend/src/components/navigation/moreDrawerItems.ts +++ b/frontend/src/components/navigation/moreDrawerItems.ts @@ -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, ] diff --git a/frontend/src/components/repo/RepoActionsDialog.test.tsx b/frontend/src/components/repo/RepoActionsDialog.test.tsx new file mode 100644 index 00000000..450e2588 --- /dev/null +++ b/frontend/src/components/repo/RepoActionsDialog.test.tsx @@ -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 { + 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( + , + ) +} + +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() + + 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() + + 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() + view.rerender() + + 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() + + expect(screen.getByLabelText('Setup command 1')).toHaveValue('pnpm ci') + }) +}) diff --git a/frontend/src/components/repo/RepoActionsDialog.tsx b/frontend/src/components/repo/RepoActionsDialog.tsx new file mode 100644 index 00000000..53ddd4f2 --- /dev/null +++ b/frontend/src/components/repo/RepoActionsDialog.tsx @@ -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(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 ( +
+
+ + onChange({ ...draft, name: event.target.value })} + /> +
+
+ + onChange({ ...draft, command: event.target.value })} + /> +
+
+ + +
+
+ + onChange({ ...draft, url: event.target.value })} + /> +
+
+ + onChange({ ...draft, autoOpenUrl: checked })} + /> +
+
+ + +
+
+ ) +} + +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(null) + const [setupCommands, setSetupCommands] = useState([]) + + 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(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 ( + + + + Project Actions + Commands and setup steps for this location. + + +
+ {configQuery.isLoading ? ( +
+ +
+ ) : !config ? ( +

+ {configQuery.error instanceof Error ? configQuery.error.message : 'No configuration available.'} +

+ ) : ( + <> +
+
+

Actions

+ +
+ + {personalActions.length === 0 && repoActions.length === 0 && ( +

No actions configured.

+ )} + + {personalActions.map((action) => { + const Icon = actionIcon(action.icon) + const isEditing = draft?.id === action.id + return ( +
+ {isEditing && draft ? ( + setDraft(null)} + /> + ) : ( + <> +
+ + {action.name} +
+

{action.command}

+ {action.url && ( +

{action.url}

+ )} +
+ + + +
+ + )} +
+ ) + })} + + {repoActions.map((action) => { + const Icon = actionIcon(action.icon) + return ( +
+
+ + {action.name} + In repo +
+

{action.command}

+ {action.url && ( +

{action.url}

+ )} + +
+ ) + })} + + {isAddingAction && draft && ( +
+ setDraft(null)} + /> +
+ )} +
+ +
+
+

Worktree setup

+

+ Commands run after a new worktree is created. Use{' '} + $ROOT_PROJECT_PATH to reference the main checkout. +

+
+ + {setupCommands.length === 0 && repoSetup.length === 0 && ( +

No setup commands.

+ )} + + {setupCommands.map((command, index) => ( +
+
+ + setSetupCommands((current) => + current.map((item, itemIndex) => (itemIndex === index ? event.target.value : item)), + ) + } + /> + + + +
+
+ +
+
+ ))} + + {repoSetup.map((item) => ( +
+
+ {item.command} + In repo +
+ +
+ ))} + +
+ + +
+
+ +
+ {config.repoFile.error && ( +

+ {config.repoFile.error} +

+ )} + {config.repoFile.warnings.map((warning) => ( +

+ {warning} +

+ ))} + {config.repoFile.exists && !config.repoFile.trusted && config.repoFile.hash && ( +
+
+ + Repository commands are not trusted +
+

+ This repository defines commands that run on your machine. Review and trust them to enable. +

+
    + {repoActions.map((action) => ( +
  • + {action.command} + {action.url ? ` — ${action.url}` : ''} +
  • + ))} + {repoSetup.map((item) => ( +
  • + {item.command} +
  • + ))} +
+ +
+ )} +
+ + )} +
+
+
+ ) +} diff --git a/frontend/src/pages/RepoDetail.tsx b/frontend/src/pages/RepoDetail.tsx index b517f5bb..04613f71 100644 --- a/frontend/src/pages/RepoDetail.tsx +++ b/frontend/src/pages/RepoDetail.tsx @@ -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} /> + + (); const [showScrollButton, setShowScrollButton] = useState(false); @@ -855,6 +857,13 @@ export function SessionDetail() { directory={repoDirectory} /> + + ({ 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), diff --git a/frontend/src/pages/__tests__/SessionDetail.commands.test.tsx b/frontend/src/pages/__tests__/SessionDetail.commands.test.tsx index fba20fc5..efe536a8 100644 --- a/frontend/src/pages/__tests__/SessionDetail.commands.test.tsx +++ b/frontend/src/pages/__tests__/SessionDetail.commands.test.tsx @@ -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) })) diff --git a/frontend/src/pages/__tests__/SessionDetail.form-prompt.test.tsx b/frontend/src/pages/__tests__/SessionDetail.form-prompt.test.tsx index 762afecd..e021fc5e 100644 --- a/frontend/src/pages/__tests__/SessionDetail.form-prompt.test.tsx +++ b/frontend/src/pages/__tests__/SessionDetail.form-prompt.test.tsx @@ -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), diff --git a/frontend/src/pages/__tests__/SessionDetail.polling.test.tsx b/frontend/src/pages/__tests__/SessionDetail.polling.test.tsx index c899bbf2..ba582c7c 100644 --- a/frontend/src/pages/__tests__/SessionDetail.polling.test.tsx +++ b/frontend/src/pages/__tests__/SessionDetail.polling.test.tsx @@ -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) })) diff --git a/frontend/src/pages/__tests__/SessionDetail.scroll-floating.test.tsx b/frontend/src/pages/__tests__/SessionDetail.scroll-floating.test.tsx index 0772e469..e3ba5478 100644 --- a/frontend/src/pages/__tests__/SessionDetail.scroll-floating.test.tsx +++ b/frontend/src/pages/__tests__/SessionDetail.scroll-floating.test.tsx @@ -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),