'use client'; import { memo, useState, useCallback } from 'react'; import Link from 'next/link'; import { IconArrowLeft, IconCopy, IconDots, IconFolderOpen, IconGitBranch, IconGitMerge, IconGitPullRequest, IconChevronDown, IconCheck, IconLoader2, IconCloudDownload, IconCloudUpload, IconGitCherryPick, IconGitCommit, } from '@tabler/icons-react'; import { Button } from '@kandev/ui/button'; import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogClose, } from '@kandev/ui/dialog'; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, DropdownMenuSeparator, } from '@kandev/ui/dropdown-menu'; import { Textarea } from '@kandev/ui/textarea'; import { Tooltip, TooltipContent, TooltipTrigger } from '@kandev/ui/tooltip'; import { Popover, PopoverContent, PopoverTrigger } from '@kandev/ui/popover'; import { Checkbox } from '@kandev/ui/checkbox'; import { Label } from '@kandev/ui/label'; import { CommitStatBadge, LineStat } from '@/components/diff-stat'; import { useSessionGitStatus } from '@/hooks/use-session-git-status'; import { useGitOperations } from '@/hooks/use-git-operations'; import { formatUserHomePath } from '@/lib/utils'; import { EditorsMenu } from '@/components/task/editors-menu'; import { useToast } from '@/components/toast-provider'; type TaskTopBarProps = { taskId?: string | null; activeSessionId?: string | null; taskTitle?: string; taskDescription?: string; baseBranch?: string; onStartAgent?: (agentProfileId: string) => void; onStopAgent?: () => void; isAgentRunning?: boolean; isAgentLoading?: boolean; worktreePath?: string | null; worktreeBranch?: string | null; repositoryPath?: string | null; repositoryName?: string | null; }; const TaskTopBar = memo(function TaskTopBar({ activeSessionId, taskTitle, baseBranch, worktreePath, worktreeBranch, repositoryPath, repositoryName, }: TaskTopBarProps) { const [copiedBranch, setCopiedBranch] = useState(false); const [popoverOpen, setPopoverOpen] = useState(false); const [copiedRepo, setCopiedRepo] = useState(false); const [copiedWorktree, setCopiedWorktree] = useState(false); const [commitDialogOpen, setCommitDialogOpen] = useState(false); const [commitMessage, setCommitMessage] = useState(''); const [stageAll, setStageAll] = useState(true); const [prDialogOpen, setPrDialogOpen] = useState(false); const [prTitle, setPrTitle] = useState(''); const [prBody, setPrBody] = useState(''); const { toast } = useToast(); const gitStatus = useSessionGitStatus(activeSessionId ?? null); const { pull, push, rebase, merge, commit, createPR, isLoading: isGitLoading } = useGitOperations(activeSessionId ?? null); // Use worktree branch if available, otherwise fall back to base branch const displayBranch = worktreeBranch || baseBranch; // Calculate total additions and deletions from all files. let totalAdditions = 0; let totalDeletions = 0; if (gitStatus?.files && Object.keys(gitStatus.files).length > 0) { for (const file of Object.values(gitStatus.files)) { totalAdditions += file.additions || 0; totalDeletions += file.deletions || 0; } } const handleGitOperation = useCallback(async ( operation: () => Promise<{ success: boolean; output: string; error?: string; conflict_files?: string[] }>, operationName: string ) => { try { const result = await operation(); if (result.success) { toast({ title: `${operationName} successful`, description: result.output.slice(0, 200) || `${operationName} completed successfully`, variant: 'success', }); } else { toast({ title: `${operationName} failed`, description: result.error || 'An error occurred', variant: 'error', }); if (result.conflict_files && result.conflict_files.length > 0) { console.log('Conflict files:', result.conflict_files); } } } catch (error) { toast({ title: `${operationName} failed`, description: error instanceof Error ? error.message : 'An unexpected error occurred', variant: 'error', }); } }, [toast]); const handlePull = useCallback(() => { handleGitOperation(() => pull(), 'Pull'); }, [handleGitOperation, pull]); const handlePush = useCallback(() => { handleGitOperation(() => push(), 'Push'); }, [handleGitOperation, push]); const handleRebase = useCallback(() => { // Rebase onto the base branch (e.g., origin/main) const targetBranch = baseBranch || 'origin/main'; handleGitOperation(() => rebase(targetBranch), 'Rebase'); }, [handleGitOperation, rebase, baseBranch]); const handleMerge = useCallback(() => { // Merge from the base branch (e.g., origin/main) const targetBranch = baseBranch || 'origin/main'; handleGitOperation(() => merge(targetBranch), 'Merge'); }, [handleGitOperation, merge, baseBranch]); const handleOpenCommitDialog = useCallback(() => { setCommitMessage(''); setStageAll(true); setCommitDialogOpen(true); }, []); const handleCommit = useCallback(async () => { if (!commitMessage.trim()) return; setCommitDialogOpen(false); await handleGitOperation(() => commit(commitMessage.trim(), stageAll), 'Commit'); setCommitMessage(''); }, [commitMessage, stageAll, handleGitOperation, commit]); const handleOpenPRDialog = useCallback(() => { setPrTitle(taskTitle || ''); setPrBody(''); setPrDialogOpen(true); }, [taskTitle]); const handleCreatePR = useCallback(async () => { if (!prTitle.trim()) return; setPrDialogOpen(false); try { const result = await createPR(prTitle.trim(), prBody.trim(), baseBranch); if (result.success) { toast({ title: 'Pull Request created', description: result.pr_url || 'PR created successfully', variant: 'success', }); // Open the PR URL in a new tab if (result.pr_url) { window.open(result.pr_url, '_blank'); } } else { toast({ title: 'Create PR failed', description: result.error || 'An error occurred', variant: 'error', }); } } catch (e) { toast({ title: 'Create PR failed', description: e instanceof Error ? e.message : 'An error occurred', variant: 'error', }); } setPrTitle(''); setPrBody(''); }, [prTitle, prBody, baseBranch, createPR, toast]); const handleBranchClick = (e: React.MouseEvent) => { e.stopPropagation(); if (displayBranch) { navigator.clipboard?.writeText(displayBranch); setCopiedBranch(true); setTimeout(() => setCopiedBranch(false), 500); } }; const handleCopyRepo = (e: React.MouseEvent) => { e.stopPropagation(); if (repositoryPath) { navigator.clipboard?.writeText(formatUserHomePath(repositoryPath)); setCopiedRepo(true); setTimeout(() => setCopiedRepo(false), 500); } }; const handleCopyWorktree = (e: React.MouseEvent) => { e.stopPropagation(); if (worktreePath) { navigator.clipboard?.writeText(formatUserHomePath(worktreePath)); setCopiedWorktree(true); setTimeout(() => setCopiedWorktree(false), 500); } }; return (
{repositoryName && ( <> {repositoryName} › )} {taskTitle ?? 'Task details'} {displayBranch && (
{displayBranch}
Current branch
{repositoryPath && (
Repository
{formatUserHomePath(repositoryPath)}
)} {worktreePath && (
Worktree
{formatUserHomePath(worktreePath)}
)}
)} {/* Git Status: Ahead/Behind */} {((gitStatus?.ahead ?? 0) > 0 || (gitStatus?.behind ?? 0) > 0) && (
{(gitStatus?.ahead ?? 0) > 0 && ( {gitStatus?.ahead ?? 0} commit{(gitStatus?.ahead ?? 0) !== 1 ? 's' : ''} ahead of {gitStatus?.remote_branch || 'remote'} )} {(gitStatus?.behind ?? 0) > 0 && ( {gitStatus?.behind ?? 0} commit{(gitStatus?.behind ?? 0) !== 1 ? 's' : ''} behind {gitStatus?.remote_branch || 'remote'} )}
)} {/* Git Status: Lines Changed */} {(totalAdditions > 0 || totalDeletions > 0) && ( Lines changed )}
{/* Commit Split Button */}
{gitStatus?.files && Object.keys(gitStatus.files).length > 0 ? `Commit ${Object.keys(gitStatus.files).length} changed file${Object.keys(gitStatus.files).length !== 1 ? 's' : ''}` : 'No changes to commit'} Create PR Pull {(gitStatus?.behind ?? 0) > 0 && ( ↓{gitStatus?.behind} )} Push {(gitStatus?.ahead ?? 0) > 0 && ( ↑{gitStatus?.ahead} )} Rebase onto {baseBranch || 'origin/main'} Merge from {baseBranch || 'origin/main'}
{/* More Options (3-dot) Dropdown */} { if (worktreePath) { navigator.clipboard?.writeText(worktreePath); } }} disabled={!worktreePath} > Copy workspace path { // TODO: Implement open workspace folder console.log('Open workspace folder:', worktreePath); }} disabled={!worktreePath} > Open workspace folder
{/* Commit Dialog */} Commit Changes
{gitStatus?.files && Object.keys(gitStatus.files).length > 0 ? ( {Object.keys(gitStatus.files).length} file{Object.keys(gitStatus.files).length !== 1 ? 's' : ''} changed {(totalAdditions > 0 || totalDeletions > 0) && ( (+{totalAdditions} {' / '} -{totalDeletions}) )} ) : ( No changes to commit )}