import { useState, useEffect, useCallback } from 'react'; import { useNavigate, useSearchParams } from 'react-router-dom'; import { Button } from '@/components/ui/button'; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger, } from '@/components/ui/dialog'; import { Card, CardContent, CardDescription, CardHeader, CardTitle, } from '@/components/ui/card'; import { Badge } from '@/components/ui/badge'; import { ScrollArea } from '@/components/ui/scroll-area'; import { Alert, AlertDescription } from '@/components/ui/alert'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from '@/components/ui/select'; import { GitBranch, Upload, Download, Loader2, CheckCircle, AlertCircle, Clock, FileIcon, Plus, Minus, Edit, AlertTriangle, Zap, Save, Settings2, GitPullRequest, ExternalLink, Copy, } from 'lucide-react'; import { useGitStatus } from '@/hooks/useGitStatus'; import { useGitSettings } from '@/hooks/useGitSettings'; import { useGit } from '@/hooks/useGit'; import { useFSPaths } from '@/hooks/useFSPaths'; import { useToast } from '@/hooks/useToast'; import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useNostr } from '@nostrify/react'; import { usePullRequests } from '@/hooks/usePullRequests'; import { cn } from '@/lib/utils'; import { findCredentialsForRepo } from '@/lib/gitCredentials'; import { nip19 } from 'nostr-tools'; import { GitManagementDialog } from '@/components/git/GitManagementDialog'; import { MergeDialog } from '@/components/git/MergeDialog'; import { PullRequestDialog } from '@/components/git/PullRequestDialog'; import { AnnounceRepositoryDialog, type AnnounceRepositoryResult } from '@/components/git/AnnounceRepositoryDialog'; interface GitDialogProps { projectId: string; children?: React.ReactNode; open?: boolean; onOpenChange?: (open: boolean) => void; } export function GitDialog({ projectId, children, open, onOpenChange }: GitDialogProps) { const [isPushing, setIsPushing] = useState(false); const [isPulling, setIsPulling] = useState(false); const [isPushingToNostr, setIsPushingToNostr] = useState(false); const [isAnnounceDialogOpen, setIsAnnounceDialogOpen] = useState(false); const [editNaddr, setEditNaddr] = useState(undefined); const [originUrl, setOriginUrl] = useState(''); const [isSavingOrigin, setIsSavingOrigin] = useState(false); const [searchParams, setSearchParams] = useSearchParams(); const navigate = useNavigate(); // Branch management state const [branches, setBranches] = useState([]); const [isLoadingBranches, setIsLoadingBranches] = useState(false); const [isSwitchingBranch, setIsSwitchingBranch] = useState(false); const [isCreatingBranch, setIsCreatingBranch] = useState(false); const [newBranchName, setNewBranchName] = useState(''); const [isCreateBranchDialogOpen, setIsCreateBranchDialogOpen] = useState(false); const { data: gitStatus, refetch: refetchGitStatus } = useGitStatus(projectId); const { settings } = useGitSettings(); const { git } = useGit(); const { projectsPath } = useFSPaths(); const { toast } = useToast(); const { user } = useCurrentUser(); const { nostr } = useNostr(); const { data: pullRequests, isLoading: isLoadingPRs } = usePullRequests(originUrl); const projectPath = `${projectsPath}/${projectId}`; // Initialize origin URL from git status and load nostr.repo config useEffect(() => { const loadGitConfig = async () => { if (gitStatus?.remotes) { const originRemote = gitStatus.remotes.find(remote => remote.name === 'origin'); setOriginUrl(originRemote?.url || ''); // Load nostr.repo config if origin is a nostr:// URL if (originRemote?.url.startsWith('nostr://')) { try { const naddr = await git.getConfig({ dir: projectPath, path: 'nostr.repo', }); setEditNaddr(naddr || undefined); } catch { setEditNaddr(undefined); } } else { setEditNaddr(undefined); } } }; loadGitConfig(); }, [gitStatus?.remotes, git, projectPath]); const loadBranches = useCallback(async () => { setIsLoadingBranches(true); try { const localBranches = await git.listBranches({ dir: projectPath }); setBranches(localBranches); } catch (error) { console.error('Failed to load branches:', error); } finally { setIsLoadingBranches(false); } }, [git, projectPath]); // Load branches when dialog opens useEffect(() => { if (open && gitStatus?.isGitRepo) { loadBranches(); } }, [open, gitStatus?.isGitRepo, loadBranches]); const handleSwitchBranch = async (branchName: string) => { setIsSwitchingBranch(true); try { await git.checkout({ dir: projectPath, ref: branchName, force: true, }); toast({ title: 'Branch switched', description: `Switched to branch "${branchName}"`, }); await refetchGitStatus(); // Trigger rebuild const newSearchParams = new URLSearchParams(searchParams); newSearchParams.set('build', ''); setSearchParams(newSearchParams); } catch (error) { toast({ title: 'Failed to switch branch', description: error instanceof Error ? error.message : 'Unknown error', variant: 'destructive', }); } finally { setIsSwitchingBranch(false); } }; const handleCreateBranch = async () => { if (!newBranchName.trim()) { toast({ title: 'Invalid branch name', description: 'Please enter a branch name', variant: 'destructive', }); return; } // Validate branch name const invalidChars = /[~^: \\?*[\]]/; if (invalidChars.test(newBranchName)) { toast({ title: 'Invalid branch name', description: 'Branch name contains invalid characters', variant: 'destructive', }); return; } setIsCreatingBranch(true); try { // Get current HEAD to base the new branch on const currentRef = await git.resolveRef({ dir: projectPath, ref: 'HEAD', }); // Create the new branch await git.branch({ dir: projectPath, ref: newBranchName.trim(), object: currentRef, }); toast({ title: 'Branch created', description: `Created branch "${newBranchName}"`, }); setNewBranchName(''); setIsCreateBranchDialogOpen(false); await loadBranches(); await refetchGitStatus(); } catch (error) { toast({ title: 'Failed to create branch', description: error instanceof Error ? error.message : 'Unknown error', variant: 'destructive', }); } finally { setIsCreatingBranch(false); } }; const handleSaveOrigin = async () => { if (!gitStatus?.isGitRepo) { toast({ title: "Cannot configure origin", description: "Not a git repository", variant: "destructive", }); return; } setIsSavingOrigin(true); try { // Remove existing origin if it exists try { await git.deleteRemote({ dir: projectPath, remote: 'origin', }); } catch { // Ignore if origin doesn't exist } // Add new origin if URL is provided if (originUrl.trim()) { await git.addRemote({ dir: projectPath, remote: 'origin', url: originUrl.trim(), }); toast({ title: "Origin configured", description: `Origin remote set to ${originUrl.trim()}`, }); } else { toast({ title: "Origin removed", description: "Origin remote has been removed", }); } // Refresh git status after changing origin await refetchGitStatus(); } catch (error) { const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred'; toast({ title: "Failed to configure origin", description: errorMessage, variant: "destructive", }); } finally { setIsSavingOrigin(false); } }; const handlePushToNostr = async () => { if (!user) { toast({ title: "Cannot push to Nostr", description: "You must be logged in to push to Nostr", variant: "destructive", }); return; } if (!gitStatus?.isGitRepo || !gitStatus.currentBranch) { toast({ title: "Cannot push to Nostr", description: "Not a git repository or no current branch", variant: "destructive", }); return; } setIsPushingToNostr(true); try { // Check if repo announcement already exists const existingRepoEvents = await nostr.query([{ kinds: [30617], authors: [user.pubkey], '#d': [projectId], limit: 1, }], { signal: AbortSignal.timeout(5000) }); if (existingRepoEvents.length > 0) { throw new Error(`Repository announcement already exists for project "${projectId}". Cannot create duplicate.`); } // Open the announcement dialog setIsAnnounceDialogOpen(true); onOpenChange?.(false); } catch (error) { const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred'; toast({ title: "Cannot push to Nostr", description: errorMessage, variant: "destructive", }); } finally { setIsPushingToNostr(false); } }; const handleAnnounceSuccess = async (result: AnnounceRepositoryResult) => { if (!user) return; setIsPushingToNostr(true); try { // Get current repository state const refTags: string[][] = []; // First check if we have any commits at all try { const log = await git.log({ dir: projectPath, depth: 1 }); if (log.length === 0) { throw new Error('Repository has no commits. Please make at least one commit before publishing to Nostr.'); } console.log(`Repository has ${log.length} commit(s), latest: ${log[0].oid}`); } catch (error) { if (error instanceof Error && error.message.includes('no commits')) { throw error; // Re-throw our custom error } throw new Error('Repository has no commits. Please make at least one commit before publishing to Nostr.'); } try { // Get all refs using listRefs const refs = await git.listRefs({ dir: projectPath }); console.log('Found refs:', refs); for (const ref of refs) { try { const commitId = await git.resolveRef({ dir: projectPath, ref, }); if (ref.startsWith('refs/heads/') || ref.startsWith('refs/tags/')) { refTags.push([ref, commitId]); } } catch (error) { console.warn(`Failed to resolve ref ${ref}:`, error); } } } catch (error) { console.warn('Failed to list refs, trying alternative approach:', error); } // If no refs found, try to get the current branch directly if (refTags.length === 0) { try { const currentBranch = await git.currentBranch({ dir: projectPath }); if (currentBranch) { const currentCommit = await git.resolveRef({ dir: projectPath, ref: 'HEAD', }); refTags.push([`refs/heads/${currentBranch}`, currentCommit]); console.log(`Added current branch: refs/heads/${currentBranch} -> ${currentCommit}`); } else { // Try to get HEAD directly even if no current branch try { const headCommit = await git.resolveRef({ dir: projectPath, ref: 'HEAD', }); refTags.push(['refs/heads/main', headCommit]); // Assume main branch console.log(`Added assumed main branch: refs/heads/main -> ${headCommit}`); } catch (headError) { console.warn('Failed to resolve HEAD directly:', headError); } } } catch (error) { console.warn('Failed to get current branch:', error); } } if (refTags.length === 0) { throw new Error('Could not determine repository state. The repository might not have any commits or branches.'); } // Get HEAD reference let headRef: string | undefined; try { const currentBranch = await git.currentBranch({ dir: projectPath }); if (currentBranch) { headRef = `ref: refs/heads/${currentBranch}`; console.log(`HEAD points to: ${headRef}`); } else { // HEAD is detached, use the commit ID directly const headValue = await git.resolveRef({ dir: projectPath, ref: 'HEAD', }); if (headValue) { headRef = headValue; console.log(`HEAD is detached at: ${headRef}`); } } } catch (error) { console.warn('Failed to resolve HEAD:', error); } // Create repo state event (NIP-34 kind 30618) const stateEvent = { kind: 30618, content: '', tags: [ ['d', result.repoId], ...refTags, ...(headRef ? [['HEAD', headRef]] : []), ], created_at: Math.floor(Date.now() / 1000), }; console.log('Creating repository state event:', stateEvent); // Sign and publish the state event const signedStateEvent = await user.signer.signEvent(stateEvent); // State events only go to the relays specified in the repo announcement console.log('Publishing repository state to relays:', result.relays); await nostr.event(signedStateEvent, { relays: result.relays }); console.log('Published repository state to Nostr relays'); // Set origin remote to Nostr URL // Format: nostr:/// const nostrUrl = `nostr://${nip19.npubEncode(user.pubkey)}/${result.repoId}`; try { // Remove existing origin if it exists await git.deleteRemote({ dir: projectPath, remote: 'origin', }); } catch { // Ignore if origin doesn't exist } await git.addRemote({ dir: projectPath, remote: 'origin', url: nostrUrl, }); console.log('Set Git origin to:', nostrUrl); // Set nostr.repo config await git.setConfig({ dir: projectPath, path: 'nostr.repo', value: result.naddr, }); console.log('Set nostr.repo config to:', result.naddr); toast({ title: 'Repository published to Nostr', description: 'Waiting for GRASP servers to update...', }); // Refresh git status to pick up the new remote await refetchGitStatus(); } catch (error) { const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred'; toast({ title: "Push to Nostr failed", description: errorMessage, variant: "destructive", duration: Infinity, }); } finally { setIsPushingToNostr(false); } }; const handlePush = async () => { if (!gitStatus?.isGitRepo || !gitStatus.currentBranch) { toast({ title: "Cannot push", description: "Not a git repository or no current branch", variant: "destructive", }); return; } if (gitStatus.remotes.length === 0) { toast({ title: "Cannot push", description: "No remote repositories configured", variant: "destructive", }); return; } if (gitStatus.ahead === 0) { toast({ title: "Nothing to push", description: "No commits ahead of remote. Commit your changes first.", variant: "destructive", }); return; } setIsPushing(true); try { const remote = gitStatus.remotes[0]; // Use first remote (usually 'origin') await git.push({ dir: projectPath, remote: remote.name, ref: gitStatus.currentBranch, onAuth: (url) => findCredentialsForRepo(url, settings.credentials), signer: user?.signer, // For signing if pushing to Nostr }); toast({ title: "Push successful", description: `${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} pushed to ${remote.name}/${gitStatus.currentBranch}`, }); // Refresh git status after push await refetchGitStatus(); } catch (error) { const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred'; toast({ title: "Push failed", description: errorMessage, variant: "destructive", duration: Infinity, }); } finally { setIsPushing(false); } }; const handlePull = async () => { if (!gitStatus?.isGitRepo || !gitStatus.currentBranch) { toast({ title: "Cannot pull", description: "Not a git repository or no current branch", variant: "destructive", }); return; } if (gitStatus.remotes.length === 0) { toast({ title: "Cannot pull", description: "No remote repositories configured", variant: "destructive", }); return; } setIsPulling(true); try { const remote = gitStatus.remotes[0]; // Use first remote (usually 'origin') // Get the current HEAD commit before pulling const beforeCommit = await git.resolveRef({ dir: projectPath, ref: 'HEAD', }); await git.pull({ dir: projectPath, ref: gitStatus.currentBranch, singleBranch: true, author: { name: 'shakespeare.diy', email: 'assistant@shakespeare.diy', }, onAuth: (url) => findCredentialsForRepo(url, settings.credentials), }); // Get the current HEAD commit after pulling const afterCommit = await git.resolveRef({ dir: projectPath, ref: 'HEAD', }); // Check if the repository actually changed const repoChanged = beforeCommit !== afterCommit; toast({ title: "Pull successful", description: repoChanged ? `Latest changes pulled from ${remote.name}/${gitStatus.currentBranch}` : `Already up to date with ${remote.name}/${gitStatus.currentBranch}`, }); // Refresh git status after pull await refetchGitStatus(); // Only trigger build if the repository actually changed if (repoChanged) { const newSearchParams = new URLSearchParams(searchParams); newSearchParams.set('build', ''); setSearchParams(newSearchParams); } } catch (error) { const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred'; toast({ title: "Pull failed", description: errorMessage, variant: "destructive", duration: Infinity, }); } finally { setIsPulling(false); } }; const getFileStatusIcon = (status: string) => { switch (status) { case 'added': return ; case 'deleted': return ; case 'modified': return ; case 'staged': return ; case 'untracked': return ; default: return ; } }; const getFileStatusColor = (status: string) => { switch (status) { case 'added': return 'bg-green-100 text-green-800 border-green-200'; case 'deleted': return 'bg-red-100 text-red-800 border-red-200'; case 'modified': return 'bg-blue-100 text-blue-800 border-blue-200'; case 'staged': return 'bg-green-100 text-green-800 border-green-200'; case 'untracked': return 'bg-gray-100 text-gray-800 border-gray-200'; default: return 'bg-gray-100 text-gray-800 border-gray-200'; } }; const getSyncStatus = () => { if (!gitStatus?.isGitRepo) { return { status: 'not-repo', text: 'Not a Git repository', icon: AlertCircle, color: 'text-gray-500' }; } if (gitStatus.remotes.length === 0) { return { status: 'no-remote', text: 'No remote configured', icon: AlertCircle, color: 'text-yellow-600' }; } if (gitStatus.ahead > 0 && gitStatus.behind > 0) { return { status: 'diverged', text: `${gitStatus.ahead} ahead, ${gitStatus.behind} behind`, icon: AlertCircle, color: 'text-red-600' }; } if (gitStatus.ahead > 0) { return { status: 'ahead', text: `${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} ahead`, icon: Upload, color: 'text-blue-600' }; } // Show uncommitted changes but with different styling since they can't be pushed directly if (gitStatus.hasUncommittedChanges) { return { status: 'uncommitted', text: `${gitStatus.changedFiles.length} uncommitted change${gitStatus.changedFiles.length !== 1 ? 's' : ''}`, icon: Clock, color: 'text-yellow-600' }; } if (gitStatus.behind > 0) { return { status: 'behind', text: `${gitStatus.behind} commit${gitStatus.behind !== 1 ? 's' : ''} behind`, icon: Download, color: 'text-orange-600' }; } return { status: 'synced', text: 'Up to date', icon: CheckCircle, color: 'text-green-600' }; }; const syncStatus = getSyncStatus(); // Check if the nostr:// remote belongs to the current user const isOwnNostrRepo = () => { if (!originUrl.startsWith('nostr://') || !user?.pubkey) return false; try { // Parse nostr:/// const urlParts = originUrl.replace('nostr://', '').split('/'); if (urlParts.length < 1) return false; const npub = urlParts[0]; const decoded = nip19.decode(npub); return decoded.type === 'npub' && decoded.data === user.pubkey; } catch { return false; } }; const [isGitManagementOpen, setIsGitManagementOpen] = useState(false); const [gitManagementDefaultTab, setGitManagementDefaultTab] = useState('branches'); const handleCopyShakespeareURL = async () => { if (!originUrl.trim()) { toast({ title: "No repository URL", description: "Please enter a Git URL first", variant: "destructive", }); return; } // Create the Shakespeare clone URL by encoding the origin URL const shakespeareURL = `${location.origin}/clone?url=${encodeURIComponent(originUrl.trim())}`; // Try modern clipboard API first try { await navigator.clipboard.writeText(shakespeareURL); toast({ title: "Copied to clipboard", description: "Edit with Shakespeare URL copied", }); return; } catch { // Fallback to older method try { const textArea = document.createElement('textarea'); textArea.value = shakespeareURL; textArea.style.position = 'fixed'; textArea.style.left = '-999999px'; textArea.style.top = '-999999px'; document.body.appendChild(textArea); textArea.focus(); textArea.select(); const successful = document.execCommand('copy'); document.body.removeChild(textArea); if (successful) { toast({ title: "Copied to clipboard", description: "Edit with Shakespeare URL copied", }); } else { throw new Error('execCommand failed'); } } catch { toast({ title: "Failed to copy", description: "Could not copy to clipboard. Please copy manually.", variant: "destructive", }); } } }; return ( <> {children && {children}} e.preventDefault()}>
Repository {gitStatus?.isGitRepo && ( )}
{/* Section 1: Git URL, Current Branch, Sync Status, Merge Branch */} {gitStatus?.isGitRepo && ( Repository Info {/* Git URL */}
setOriginUrl(e.target.value)} disabled={isSavingOrigin} className="flex-1" />
{/* Edit with Shakespeare URL */} {originUrl.trim() ? (
) : (
Push your repository to get a shareable Shakespeare link
)} {/* Credentials Warning */} {gitStatus.remotes.length > 0 && ( (() => { const remoteWithoutCredentials = gitStatus.remotes.find((remote) => !findCredentialsForRepo(remote.url, settings.credentials)); if (!remoteWithoutCredentials) return null; let protocol = ''; let hostname = 'the remote host'; try { const url = new URL(remoteWithoutCredentials.url); protocol = url.protocol; hostname = url.hostname; } catch { return ( Invalid URL format. Enter an https URL. ); } if (protocol !== 'https:' && protocol !== 'nostr:') { return ( The {protocol.replace(':', '')} URL type is not supported. Enter an https URL. ); } if (protocol === 'nostr:' && !user) { return ( You are not logged into Nostr. Push & pull might not work unless you{' '} . ); } if (protocol === 'https:') { return ( You are not logged into {hostname}. Push & pull might not work unless you{' '} . ); } return null; })() )}
{/* Current Branch */} {gitStatus.currentBranch && (
)} {/* Sync Status */}
{syncStatus.text}
{gitStatus.remotes.length > 0 && (
)} {gitStatus.remotes.length === 0 && user && ( )} {/* Edit Nostr Repository Settings */} {gitStatus.remotes.length > 0 && isOwnNostrRepo() && editNaddr && ( )}
{/* Merge Branch Action */} {gitStatus.currentBranch && (
refetchGitStatus()} />
)}
)} {/* Section 2: Your Open PRs and Create PR Button */} {gitStatus?.isGitRepo && gitStatus.remotes.length > 0 && originUrl && ( {originUrl.startsWith('nostr://') ? 'Patches' : 'Pull Requests'} {originUrl.startsWith('nostr://') ? 'Submit patches to the repository' : 'Manage pull requests for this repository' } {/* Open Pull Requests List */} {!originUrl.startsWith('nostr://') && isLoadingPRs && (
Loading pull requests...
)} {!isLoadingPRs && pullRequests && pullRequests.length > 0 && (
{pullRequests.some(pr => !pr.isOwner) ? (originUrl.startsWith('nostr://') ? 'Incoming Patches' : 'Incoming PRs') : (originUrl.startsWith('nostr://') ? 'Your Patches' : 'Your Open PRs') }
{pullRequests.map((pr) => (

{pr.title}

{pr.state === 'merged' && ( Merged )}

#{pr.number} by {pr.isOwner ? 'you' : pr.author} • {pr.sourceBranch} → {pr.targetBranch}

{/* Actions row */} {(!pr.isOwner && pr.state === 'open') || !originUrl.startsWith('nostr://') ? (
{!pr.isOwner && pr.state === 'open' && ( <> {!originUrl.startsWith('nostr://') && ( )} )} {!originUrl.startsWith('nostr://') && ( )}
) : null}
))}
)} {/* Create PR/Patch Button */}
)} {/* Section 3: Working Directory */} {gitStatus?.isGitRepo && ( Working Directory {gitStatus.changedFiles.length > 0 && ( {gitStatus.changedFiles.length} file{gitStatus.changedFiles.length !== 1 ? 's' : ''} with changes )} {gitStatus.changedFiles.length > 0 ? (
{gitStatus.changedFiles.map((file, index) => (
{getFileStatusIcon(file.status)} {file.filepath} {file.status}
))}
) : (

Working directory is clean

No uncommitted changes

)}
)}
{/* Advanced Git Management Dialog */} {/* Create Branch Dialog */} Create New Branch Create a new branch from {gitStatus?.currentBranch || 'current HEAD'}
setNewBranchName(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter' && !isCreatingBranch) { handleCreateBranch(); } }} autoFocus />
{gitStatus?.currentBranch && (
Creating from: {gitStatus.currentBranch}
)}
{/* Announce Repository Dialog */} ); }