import { useEffect, useMemo, useRef, useState } from 'react' import { ArrowDown, ArrowUp, Loader2, Pencil, Plus, ShieldAlert } from 'lucide-react' import { arrayMove } from '@dnd-kit/sortable' import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog' import { Button } from '@/components/ui/button' import { Badge } from '@/components/ui/badge' import { ConfirmDestructiveDialog } from '@/components/ui/confirm-destructive-dialog' import { Input } from '@/components/ui/input' import { Label } from '@/components/ui/label' import { Switch } from '@/components/ui/switch' import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select' import { SettingsList, SettingsListRow, SettingsListRowActionsMenu } from '@/components/ui/settings-list' import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs' import { useMoveProjectItem, useProjectConfig, useTrustRepoConfig, useUpdateProjectActions, useUpdateWorktreeSetup, } from '@/api/projectConfig' import { showToast } from '@/lib/toast' import { getOpenCodeApiErrorMessage } from '@/lib/opencode-errors' import { randomId } from '@/lib/utils' import type { ProjectAction, ProjectActionIcon, ProjectItemSource, } from '@opencode-manager/shared/types' import { ACTION_ICON_OPTIONS, actionIcon } from './projectActionIcons' import { TrustExecutableList } from './TrustExecutableList' import { hasExecutableContent, type RepoFileExecutable } from './trustExecutable' interface ActionDraft { id: string name: string command: string icon: ProjectActionIcon url: string autoOpenUrl: boolean } function emptyActionDraft(): ActionDraft { return { id: randomId(), name: '', command: '', icon: 'play', url: '', autoOpenUrl: false } } function actionToDraft(action: ProjectAction): ActionDraft { return { id: action.id, name: action.name, command: action.command, icon: action.icon ?? 'play', url: action.url ?? '', autoOpenUrl: action.autoOpenUrl, } } function actionToPayload(action: ProjectAction): ProjectAction { const payload: ProjectAction = { id: action.id, name: action.name, command: action.command, autoOpenUrl: action.autoOpenUrl, } if (action.icon) payload.icon = action.icon if (action.url) payload.url = action.url return payload } function draftToPayload(draft: ActionDraft): ProjectAction { const payload: ProjectAction = { id: draft.id, name: draft.name.trim(), command: draft.command.trim(), icon: draft.icon, autoOpenUrl: draft.autoOpenUrl, } const url = draft.url.trim() if (url) payload.url = url return payload } interface ActionFormProps { draft: ActionDraft isSaving: boolean onChange: (draft: ActionDraft) => void onSave: (draft: ActionDraft) => void onCancel: () => void } function ActionForm({ draft, isSaving, onChange, onSave, onCancel }: ActionFormProps) { const canSave = draft.name.trim().length > 0 && draft.command.trim().length > 0 const formRef = useRef(null) useEffect(() => { formRef.current?.scrollIntoView({ block: 'nearest' }) }, []) return (
onChange({ ...draft, name: event.target.value })} />
onChange({ ...draft, command: event.target.value })} />
onChange({ ...draft, url: event.target.value })} />
onChange({ ...draft, autoOpenUrl: checked })} />
) } interface TrustReview { hash: string directory: string | undefined executable: RepoFileExecutable } const COMPACT_ROW_CLASS = 'flex-row items-center gap-3 py-2.5' function ActionTitle({ action }: { action: ProjectAction }) { const Icon = actionIcon(action.icon) return ( <> {action.name} ) } function ActionUrl({ url }: { url: string | undefined }) { if (!url) return null return

{url}

} function TabCount({ count }: { count: number }) { return {count} } interface RepoActionsContentProps { repoId: number directory: string | undefined open: boolean } export function RepoActionsContent({ repoId, directory, open }: RepoActionsContentProps) { 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 [focusSetupIndex, setFocusSetupIndex] = useState(null) const [trustReview, setTrustReview] = useState(null) const config = configQuery.data const repoFile = config?.repoFile 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 setTrustReview(null) return } const syncKey = `${directory ?? ''}\u0000${personalSetupBaseline}` if (setupSyncKey.current === syncKey) return setupSyncKey.current = syncKey setSetupCommands(personalSetup) setFocusSetupIndex(null) }, [open, config, directory, personalSetup, personalSetupBaseline]) const setupDirty = useMemo( () => setupCommands.length !== personalSetup.length || setupCommands.some((command, index) => command !== personalSetup[index]), [setupCommands, personalSetup], ) const setupValid = setupCommands.every((command) => command.trim().length > 0) const handleSaveAction = (nextDraft: ActionDraft) => { const payload = draftToPayload(nextDraft) const exists = personalActions.some((action) => action.id === payload.id) const next = exists ? personalActions.map((action) => (action.id === payload.id ? payload : actionToPayload(action))) : [...personalActions.map(actionToPayload), payload] updateActions.mutate(next, { onSuccess: () => setDraft(null), onError: (error) => showToast.error(getOpenCodeApiErrorMessage(error, 'Failed to save action')), }) } const handleDeleteAction = (id: string) => { updateActions.mutate(personalActions.filter((action) => action.id !== id).map(actionToPayload), { onError: (error) => showToast.error(getOpenCodeApiErrorMessage(error, 'Failed to delete action')), }) } const handleSaveSetup = () => { updateSetup.mutate(setupCommands.map((command) => command.trim()), { onError: (error) => showToast.error(getOpenCodeApiErrorMessage(error, 'Failed to save setup commands')), }) } const addSetupCommand = () => { setFocusSetupIndex(setupCommands.length) setSetupCommands((current) => [...current, '']) } const needsTrust = Boolean( repoFile?.exists && !repoFile.trusted && repoFile.hash && hasExecutableContent(repoFile.executable), ) const openTrustReview = () => { if (!repoFile?.hash || !repoFile.executable) return setTrustReview({ hash: repoFile.hash, directory, executable: repoFile.executable }) } const handleTrust = () => { if (!trustReview) return trustConfig.mutate( { hash: trustReview.hash, directory: trustReview.directory }, { onSuccess: () => setTrustReview(null), onError: (error) => showToast.error(getOpenCodeApiErrorMessage(error, 'Failed to trust repository commands')), }, ) } const moveAction = (action: ProjectAction, to: ProjectItemSource) => { moveItem.mutate( { kind: 'action', id: action.id, to, directory }, { onError: (error) => showToast.error(getOpenCodeApiErrorMessage(error, 'Failed to move action')) }, ) } const moveSetup = (command: string, to: ProjectItemSource) => { moveItem.mutate( { kind: 'setup', command, to, directory }, { onError: (error) => showToast.error(getOpenCodeApiErrorMessage(error, 'Failed to move setup command')) }, ) } const isAddingAction = draft !== null && !personalActions.some((action) => action.id === draft.id) const hasRepoFileStatus = Boolean(repoFile?.error) || (repoFile?.warnings.length ?? 0) > 0 || needsTrust const renderActionForm = (current: ActionDraft) => ( setDraft(null)} /> ) return (
{configQuery.isLoading ? (
) : !config ? (

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

) : ( <> {hasRepoFileStatus && (
{config.repoFile.error && (

{config.repoFile.error}

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

{warning}

))} {needsTrust && (

Repository commands are not trusted

They won't run until you review and trust them.

)}
)}
Actions Worktree setup

Start these from the actions menu in the header.

{personalActions.map((action) => draft?.id === action.id ? ( renderActionForm(draft) ) : ( } description={{action.command}} belowDescription={} onClick={() => setDraft(actionToDraft(action))} trailing={ } actions={[ { label: 'Move to repository', onClick: () => moveAction(action, 'repo'), disabled: moveItem.isPending, }, { label: 'Delete', destructive: true, separatorBefore: true, onClick: () => handleDeleteAction(action.id), disabled: updateActions.isPending, }, ]} actionsLabel={`Actions for ${action.name}`} /> ), )} {isAddingAction && draft && renderActionForm(draft)} {repoActions.map((action) => ( } badges={In repo} description={{action.command}} belowDescription={} actions={[ { label: 'Move to my settings', onClick: () => moveAction(action, 'personal'), disabled: moveItem.isPending, }, ]} actionsLabel={`Actions for ${action.name}`} /> ))}

Run in order after a new worktree is created.{' '} $ROOT_PROJECT_PATH points to the main checkout.

{setupCommands.map((command, index) => (
setSetupCommands((current) => current.map((item, itemIndex) => (itemIndex === index ? event.target.value : item)), ) } /> moveSetup(command, 'repo'), disabled: setupDirty || moveItem.isPending, }, { label: 'Remove', destructive: true, separatorBefore: true, onClick: () => setSetupCommands((current) => current.filter((_, itemIndex) => itemIndex !== index)), }, ]} />
))} {repoSetup.map((item) => ( {item.command}} titleClassName="font-mono text-xs font-normal" badges={In repo} actions={[ { label: 'Move to my settings', onClick: () => moveSetup(item.command, 'personal'), disabled: moveItem.isPending, }, ]} actionsLabel={`Actions for ${item.command}`} /> ))}

{setupDirty ? 'Unsaved changes' : ''}

)} { if (!next) setTrustReview(null) }} onConfirm={handleTrust} onCancel={() => setTrustReview(null)} title="Trust repository commands" description="This repository defines commands that run on your machine." warning={trustReview ? : undefined} confirmLabel="Trust these commands" pendingLabel="Trusting…" isPending={trustConfig.isPending} />
) } interface RepoActionsDialogProps { repoId: number directory: string | undefined open: boolean onOpenChange: (open: boolean) => void } export function RepoActionsDialog({ repoId, directory, open, onOpenChange }: RepoActionsDialogProps) { return ( Project Actions Commands and setup steps for this location. ) }