'use client'; import { memo, useMemo, useState, useCallback } from 'react'; import { IconArrowBackUp, IconExternalLink, IconPlus, IconCircleFilled, IconMinus, IconCheck, IconChevronRight, IconGitCommit, IconLoader2, } from '@tabler/icons-react'; import { TabsContent } from '@kandev/ui/tabs'; import { Tooltip, TooltipContent, TooltipTrigger } from '@kandev/ui/tooltip'; import { SessionPanel, SessionPanelContent } from '@kandev/ui/pannel-session'; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from '@kandev/ui/alert-dialog'; import { LineStat } from '@/components/diff-stat'; import { cn } from '@/lib/utils'; import { useAppStore } from '@/components/state-provider'; import { useOpenSessionInEditor } from '@/hooks/use-open-session-in-editor'; import { useSessionGitStatus } from '@/hooks/domains/session/use-session-git-status'; import { useSessionCommits } from '@/hooks/domains/session/use-session-commits'; import { useGitOperations } from '@/hooks/use-git-operations'; import { getWebSocketClient } from '@/lib/ws/connection'; import type { FileInfo } from '@/lib/state/store'; import { FileBrowser } from '@/components/task/file-browser'; import { SessionTabs, type SessionTab } from '@/components/session-tabs'; import { useToast } from '@/components/toast-provider'; import type { OpenFileTab } from '@/lib/types/backend'; type TaskFilesPanelProps = { onSelectDiff: (path: string, content?: string) => void; onOpenFile: (file: OpenFileTab) => void; }; const StatusIcon = ({ status }: { status: FileInfo['status'] }) => { switch (status) { case 'added': case 'untracked': return (
); case 'modified': return (
); case 'deleted': return (
); case 'renamed': return (
); default: return (
); } }; const splitPath = (path: string) => { const lastSlash = path.lastIndexOf('/'); if (lastSlash === -1) return { folder: '', file: path }; return { folder: path.slice(0, lastSlash), file: path.slice(lastSlash + 1), }; }; const TaskFilesPanel = memo(function TaskFilesPanel({ onSelectDiff, onOpenFile }: TaskFilesPanelProps) { const [topTab, setTopTab] = useState<'diff' | 'files'>('diff'); const [showDiscardDialog, setShowDiscardDialog] = useState(false); const [fileToDiscard, setFileToDiscard] = useState(null); const activeSessionId = useAppStore((state) => state.tasks.activeSessionId); const gitStatus = useSessionGitStatus(activeSessionId); const { commits } = useSessionCommits(activeSessionId ?? null); const openEditor = useOpenSessionInEditor(activeSessionId ?? null); const gitOps = useGitOperations(activeSessionId ?? null); const { toast } = useToast(); // State for commit diffs const [expandedCommit, setExpandedCommit] = useState(null); const [commitDiffs, setCommitDiffs] = useState>>({}); const [loadingCommitSha, setLoadingCommitSha] = useState(null); // Fetch commit diff const fetchCommitDiff = useCallback(async (commitSha: string) => { if (!activeSessionId || commitDiffs[commitSha]) return; setLoadingCommitSha(commitSha); try { const ws = getWebSocketClient(); if (!ws) return; const response = await ws.request<{ success: boolean; files: Record }>( 'session.commit_diff', { session_id: activeSessionId, commit_sha: commitSha }, 10000 ); if (response?.success && response.files) { setCommitDiffs((prev) => ({ ...prev, [commitSha]: response.files })); } } catch (err) { toast({ title: 'Failed to load commit diff', description: err instanceof Error ? err.message : 'An unexpected error occurred', variant: 'error', }); } finally { setLoadingCommitSha(null); } }, [activeSessionId, commitDiffs, toast]); // Toggle commit expansion const toggleCommit = useCallback((commitSha: string) => { if (expandedCommit === commitSha) { setExpandedCommit(null); } else { setExpandedCommit(commitSha); void fetchCommitDiff(commitSha); } }, [expandedCommit, fetchCommitDiff]); // Handle discard changes const handleDiscardClick = useCallback((filePath: string) => { setFileToDiscard(filePath); setShowDiscardDialog(true); }, []); const handleDiscardConfirm = useCallback(async () => { if (!fileToDiscard) return; try { const result = await gitOps.discard([fileToDiscard]); if (result.success) { toast({ title: 'Changes discarded', description: `Successfully discarded changes to ${fileToDiscard}`, variant: 'success', }); } else { toast({ title: 'Failed to discard changes', description: result.error || 'An unknown error occurred', variant: 'error', }); } } catch (error) { toast({ title: 'Failed to discard changes', description: error instanceof Error ? error.message : 'An unknown error occurred', variant: 'error', }); } finally { setShowDiscardDialog(false); setFileToDiscard(null); } }, [fileToDiscard, gitOps, toast]); // Convert git status files to array for display const changedFiles = useMemo(() => { if (!gitStatus?.files || Object.keys(gitStatus.files).length === 0) { return []; } return (Object.values(gitStatus.files) as FileInfo[]).map((file: FileInfo) => ({ path: file.path, status: file.status, staged: file.staged, plus: file.additions, minus: file.deletions, oldPath: file.old_path, })); }, [gitStatus]); const tabs: SessionTab[] = [ { id: 'diff', label: `Diff files${changedFiles.length > 0 ? ` (${changedFiles.length})` : ''}`, }, { id: 'files', label: 'All files', }, ]; return ( setTopTab(value as 'diff' | 'files')} className="flex-1 min-h-0" >
{/* Uncommitted changes section */} {changedFiles.length > 0 && (
Uncommitted ({changedFiles.length})
    {changedFiles.map((file) => { const { folder, file: name } = splitPath(file.path); return (
  • onSelectDiff(file.path)} >
    {file.staged ? ( Click to unstage ) : ( Click to stage )}
    Discard changes Open in editor
  • ); })}
)} {/* Commits section */} {commits.length > 0 && (
Commits ({commits.length})
    {commits.map((commit) => { const isExpanded = expandedCommit === commit.commit_sha; const files = commitDiffs[commit.commit_sha]; const isLoading = loadingCommitSha === commit.commit_sha; return (
  • {isExpanded && files && (
      {Object.entries(files).map(([path, file]) => { const { folder, file: fileName } = splitPath(path); return (
    • onSelectDiff(path, file.diff)} > {folder}/ {fileName} +{file.additions ?? 0} {'/'} -{file.deletions ?? 0}
    • ); })}
    )}
  • ); })}
)} {/* Empty state */} {changedFiles.length === 0 && commits.length === 0 && (
No changes detected
)}
{activeSessionId ? ( ) : (
No task selected
)}
{/* Discard confirmation dialog */} Discard changes? This will permanently discard all changes to{' '} {fileToDiscard}. This action cannot be undone. Cancel Discard
); }); export { TaskFilesPanel };