import { useState, useEffect, useCallback } from 'react'; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'; import { Button } from '@/components/ui/button'; import { ScrollArea } from '@/components/ui/scroll-area'; import { Badge } from '@/components/ui/badge'; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog'; import { History, GitCommit, RotateCcw, AlertTriangle, ChevronDown, ChevronUp } from 'lucide-react'; import { useGit } from '@/hooks/useGit'; import { useFS } from '@/hooks/useFS'; import { useToast } from '@/hooks/useToast'; interface GitCommit { oid: string; commit: { message: string; author: { name: string; email: string; timestamp: number; }; committer: { name: string; email: string; timestamp: number; }; }; } interface GitHistoryDialogProps { projectId: string; open?: boolean; onOpenChange?: (open: boolean) => void; } export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange }: GitHistoryDialogProps) { const [commits, setCommits] = useState([]); const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(null); const [internalOpen, setInternalOpen] = useState(false); // Use controlled or internal state const isOpen = controlledOpen !== undefined ? controlledOpen : internalOpen; const setIsOpen = onOpenChange || setInternalOpen; const [isRollingBack, setIsRollingBack] = useState(null); const [expandedCommits, setExpandedCommits] = useState>(new Set()); const { fs } = useFS(); const { git } = useGit(); const { toast } = useToast(); const loadGitHistory = useCallback(async () => { setIsLoading(true); setError(null); try { const projectPath = `/projects/${projectId}`; // Check if git repository exists try { await git.findRoot({ filepath: projectPath }); } catch { setError('No git repository found in this project'); return; } // Get git log const gitLog = await git.log({ dir: projectPath, depth: 50, // Limit to last 50 commits }); setCommits(gitLog); } catch (err) { console.error('Failed to load git history:', err); setError(err instanceof Error ? err.message : 'Failed to load git history'); } finally { setIsLoading(false); } }, [git, projectId]); const rollbackToCommit = useCallback(async (targetCommit: GitCommit) => { if (!fs) return; setIsRollingBack(targetCommit.oid); try { const projectPath = `/projects/${projectId}`; // Get the current HEAD commit const currentCommit = await git.resolveRef({ dir: projectPath, ref: 'HEAD', }); // If we're already at this commit, no need to rollback if (currentCommit === targetCommit.oid) { toast({ title: "Already at this commit", description: "The codebase is already at this commit.", }); return; } // Get all commits between the target commit and HEAD const allCommits = await git.log({ dir: projectPath, depth: 1000, }); // Find the index of target commit and current HEAD const targetIndex = allCommits.findIndex(c => c.oid === targetCommit.oid); const currentIndex = allCommits.findIndex(c => c.oid === currentCommit); if (targetIndex === -1) { throw new Error('Target commit not found in history'); } if (currentIndex === -1) { throw new Error('Current commit not found in history'); } // Get commits to revert (from current back to target, exclusive) const commitsToRevert = allCommits.slice(currentIndex, targetIndex); if (commitsToRevert.length === 0) { toast({ title: "No commits to revert", description: "The target commit is ahead of the current commit.", }); return; } // Simple approach: checkout the target commit's tree and create a new commit // This effectively "reverts" to that state without complex merge logic // Get all files from the target commit const targetFiles = await git.listFiles({ dir: projectPath, ref: targetCommit.oid, }); // Get current files to know what to remove const currentFiles = await git.listFiles({ dir: projectPath, ref: 'HEAD', }); // Remove files that don't exist in target commit for (const filepath of currentFiles) { if (!targetFiles.includes(filepath)) { try { await fs.unlink(`${projectPath}/${filepath}`); await git.remove({ dir: projectPath, filepath, }); } catch (err) { // File might not exist, continue console.warn(`Could not remove ${filepath}:`, err); } } } // Restore all files from target commit for (const filepath of targetFiles) { try { const { blob } = await git.readBlob({ dir: projectPath, oid: targetCommit.oid, filepath, }); // Ensure directory exists const dirPath = filepath.split('/').slice(0, -1).join('/'); if (dirPath) { await fs.mkdir(`${projectPath}/${dirPath}`, { recursive: true }); } // Write the file await fs.writeFile(`${projectPath}/${filepath}`, blob); // Stage the file await git.add({ dir: projectPath, filepath, }); } catch (err) { console.error(`Failed to restore ${filepath}:`, err); } } // Create a revert commit const targetFirstLine = getCommitMessageLines(targetCommit.commit.message).firstLine; const revertMessage = `Revert to ${targetCommit.oid.substring(0, 7)}: ${targetFirstLine} This reverts the codebase back to the state at commit ${targetCommit.oid.substring(0, 7)}. Reverted ${commitsToRevert.length} commit(s): ${commitsToRevert.map(c => { const commitFirstLine = getCommitMessageLines(c.commit.message).firstLine; return `- ${c.oid.substring(0, 7)}: ${commitFirstLine}`; }).join('\n')}`; await git.commit({ dir: projectPath, message: revertMessage, author: { name: 'shakespeare.diy', email: 'assistant@shakespeare.diy', }, }); toast({ title: "Rollback successful", description: `Reverted ${commitsToRevert.length} commit(s) back to ${targetCommit.oid.substring(0, 7)}`, }); // Reload the git history to show the new commit await loadGitHistory(); } catch (err) { console.error('Failed to rollback:', err); toast({ title: "Rollback failed", description: err instanceof Error ? err.message : 'Failed to rollback to this commit', variant: "destructive", }); } finally { setIsRollingBack(null); } }, [git, fs, projectId, toast, loadGitHistory]); useEffect(() => { if (isOpen) { loadGitHistory(); } }, [isOpen, loadGitHistory]); const formatRelativeTime = (timestamp: number) => { const now = Date.now(); const commitTime = timestamp * 1000; const diffMs = now - commitTime; const diffMinutes = Math.floor(diffMs / (1000 * 60)); const diffHours = Math.floor(diffMs / (1000 * 60 * 60)); const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24)); if (diffMinutes < 60) { return `${diffMinutes} minutes ago`; } else if (diffHours < 24) { return `${diffHours} hours ago`; } else { return `${diffDays} days ago`; } }; const getCommitMessageLines = (message: string) => { const lines = message.split('\n').filter(line => line.trim() !== ''); return { firstLine: lines[0] || '', hasMoreLines: lines.length > 1, fullMessage: message, }; }; const toggleCommitExpansion = (commitOid: string) => { setExpandedCommits(prev => { const newSet = new Set(prev); if (newSet.has(commitOid)) { newSet.delete(commitOid); } else { newSet.add(commitOid); } return newSet; }); }; return ( {/* Only show trigger if not controlled externally */} {controlledOpen === undefined && ( )} Git History View the commit history for this project
{isLoading ? (
Loading git history...
) : error ? (

Error loading git history

{error}

) : !commits || commits.length === 0 ? (

No commits found

This project doesn't have any git commits yet

) : (
{commits.map((commit, index) => { const { firstLine, hasMoreLines, fullMessage } = getCommitMessageLines(commit.commit.message); const isExpanded = expandedCommits.has(commit.oid); return (

{firstLine}

{hasMoreLines && ( )}
{isExpanded && hasMoreLines && (
{fullMessage.split('\n').slice(1).join('\n').trim()}
)}
{commit.commit.author.name} committed {formatRelativeTime(commit.commit.author.timestamp)}
{index > 0 && ( // Don't show rollback for the most recent commit Confirm Rollback

This will create a new commit that reverts the codebase back to:

{firstLine}
{commit.oid.substring(0, 7)} • {formatRelativeTime(commit.commit.author.timestamp)}

This action will revert {index} commit(s) and cannot be undone easily. A new commit will be created with the reverted changes.

Cancel rollbackToCommit(commit)} className="bg-destructive text-destructive-foreground hover:bg-destructive/90" disabled={isRollingBack !== null} > {isRollingBack === commit.oid ? ( <>
Rolling back... ) : ( <> Rollback )} )} {commit.oid.substring(0, 7)}
); })}
)}
); }