diff --git a/src/components/ai/GitHistoryDialog.test.tsx b/src/components/ai/GitHistoryDialog.test.tsx index 5b6c2a5f..c035fb75 100644 --- a/src/components/ai/GitHistoryDialog.test.tsx +++ b/src/components/ai/GitHistoryDialog.test.tsx @@ -7,6 +7,13 @@ import { GitHistoryDialog } from './GitHistoryDialog'; vi.mock('isomorphic-git', () => ({ default: { log: vi.fn(), + resolveRef: vi.fn(), + readCommit: vi.fn(), + listFiles: vi.fn(), + readBlob: vi.fn(), + add: vi.fn(), + remove: vi.fn(), + commit: vi.fn(), }, })); @@ -15,10 +22,20 @@ vi.mock('@/hooks/useFS', () => ({ useFS: () => ({ fs: { stat: vi.fn(), + unlink: vi.fn(), + mkdir: vi.fn(), + writeFile: vi.fn(), }, }), })); +// Mock the useToast hook +vi.mock('@/hooks/useToast', () => ({ + useToast: () => ({ + toast: vi.fn(), + }), +})); + describe('GitHistoryDialog', () => { beforeEach(() => { vi.clearAllMocks(); @@ -63,4 +80,52 @@ describe('GitHistoryDialog', () => { expect(screen.getByText('Loading git history...')).toBeInTheDocument(); }); }); + + it('renders rollback buttons for commits (except the first one)', async () => { + const mockCommits = [ + { + oid: 'commit1', + commit: { + message: 'Latest commit', + author: { name: 'User', email: 'user@example.com', timestamp: Math.floor(Date.now() / 1000), timezoneOffset: 0 }, + committer: { name: 'User', email: 'user@example.com', timestamp: Math.floor(Date.now() / 1000), timezoneOffset: 0 }, + parent: [], + tree: 'tree1', + }, + payload: '', + }, + { + oid: 'commit2', + commit: { + message: 'Previous commit', + author: { name: 'User', email: 'user@example.com', timestamp: Math.floor(Date.now() / 1000) - 3600, timezoneOffset: 0 }, + committer: { name: 'User', email: 'user@example.com', timestamp: Math.floor(Date.now() / 1000) - 3600, timezoneOffset: 0 }, + parent: [], + tree: 'tree2', + }, + payload: '', + }, + ]; + + const git = await import('isomorphic-git'); + vi.mocked(git.default.log).mockResolvedValue(mockCommits); + + render( + + + + ); + + const historyButton = screen.getByRole('button', { name: /history/i }); + fireEvent.click(historyButton); + + await waitFor(() => { + expect(screen.getByText('Latest commit')).toBeInTheDocument(); + expect(screen.getByText('Previous commit')).toBeInTheDocument(); + }); + + // Should have one rollback button (not for the latest commit) + const rollbackButtons = screen.getAllByText('Rollback'); + expect(rollbackButtons).toHaveLength(1); + }); }); \ No newline at end of file diff --git a/src/components/ai/GitHistoryDialog.tsx b/src/components/ai/GitHistoryDialog.tsx index a44e2205..e474b864 100644 --- a/src/components/ai/GitHistoryDialog.tsx +++ b/src/components/ai/GitHistoryDialog.tsx @@ -3,8 +3,10 @@ import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, Di import { Button } from '@/components/ui/button'; import { ScrollArea } from '@/components/ui/scroll-area'; import { Badge } from '@/components/ui/badge'; -import { History, GitCommit, User, Calendar, Hash } from 'lucide-react'; +import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog'; +import { History, GitCommit, User, Calendar, Hash, RotateCcw, AlertTriangle } from 'lucide-react'; import { useFS } from '@/hooks/useFS'; +import { useToast } from '@/hooks/useToast'; import git from 'isomorphic-git'; interface GitCommit { @@ -33,7 +35,9 @@ export function GitHistoryDialog({ projectId }: GitHistoryDialogProps) { const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(null); const [isOpen, setIsOpen] = useState(false); + const [isRollingBack, setIsRollingBack] = useState(null); const { fs } = useFS(); + const { toast } = useToast(); const loadGitHistory = useCallback(async () => { if (!fs) return; @@ -68,6 +72,162 @@ export function GitHistoryDialog({ projectId }: GitHistoryDialogProps) { } }, [fs, 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({ + fs, + 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({ + fs, + 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({ + fs, + dir: projectPath, + ref: targetCommit.oid, + }); + + // Get current files to know what to remove + const currentFiles = await git.listFiles({ + fs, + 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({ + fs, + 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({ + fs, + 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({ + fs, + dir: projectPath, + filepath, + }); + } catch (err) { + console.error(`Failed to restore ${filepath}:`, err); + } + } + + // Create a revert commit + const revertMessage = `Revert to ${targetCommit.oid.substring(0, 7)}: ${targetCommit.commit.message} + +This reverts the codebase back to the state at commit ${targetCommit.oid.substring(0, 7)}. + +Reverted ${commitsToRevert.length} commit(s): +${commitsToRevert.map(c => `- ${c.oid.substring(0, 7)}: ${c.commit.message}`).join('\n')}`; + + await git.commit({ + fs, + dir: projectPath, + message: revertMessage, + author: { + name: 'Shakespeare AI', + email: 'ai@shakespeare.dev', + }, + }); + + 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); + } + }, [fs, projectId, toast, loadGitHistory]); + useEffect(() => { if (isOpen) { loadGitHistory(); @@ -162,10 +322,70 @@ export function GitHistoryDialog({ projectId }: GitHistoryDialogProps) { {commit.commit.message} - - - {commit.oid.substring(0, 7)} - + + + + {commit.oid.substring(0, 7)} + + {index > 0 && ( // Don't show rollback for the most recent commit + + + + + Rollback + + + + + + + Confirm Rollback + + + + This will create a new commit that reverts the codebase back to: + + + {commit.commit.message} + + {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 + > + )} + + + + + )} +
+ This will create a new commit that reverts the codebase back to: +
+ This action will revert {index} commit(s) and cannot be undone easily. + A new commit will be created with the reverted changes. +