From d72729f379daf64d8264a532dd6dc2f494a59973 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 22 Dec 2025 15:47:31 -0600 Subject: [PATCH] Remove all the git menus --- src/components/ActionsMenu.tsx | 18 - src/components/GitDialog.test.tsx | 248 --- src/components/GitDialog.tsx | 1475 ----------------- src/components/ProjectTitleMenu.tsx | 12 - .../git/AnnounceRepositoryDialog.test.tsx | 124 -- .../git/AnnounceRepositoryDialog.tsx | 746 --------- src/components/git/BranchManager.tsx | 522 ------ src/components/git/CompareView.tsx | 352 ---- src/components/git/DiffViewer.tsx | 558 ------- src/components/git/GitManagementDialog.tsx | 168 -- src/components/git/MergeDialog.tsx | 576 ------- src/components/git/PullRequestDialog.tsx | 1301 --------------- src/components/git/PullRequestForm.tsx | 565 ------- src/components/git/index.ts | 7 - src/hooks/useGitFetch.test.tsx | 720 -------- src/hooks/useGitFetch.ts | 357 ---- src/hooks/usePullRequests.ts | 456 ----- src/lib/git-hosts/GitHubProvider.ts | 303 ---- src/lib/git-hosts/GitLabProvider.ts | 328 ---- src/lib/git-hosts/GiteaProvider.ts | 293 ---- src/lib/git-hosts/NostrGitProvider.ts | 257 --- src/lib/git-hosts/index.ts | 64 - src/lib/git-hosts/types.ts | 186 --- src/pages/ProjectView.tsx | 14 - 24 files changed, 9650 deletions(-) delete mode 100644 src/components/GitDialog.test.tsx delete mode 100644 src/components/GitDialog.tsx delete mode 100644 src/components/git/AnnounceRepositoryDialog.test.tsx delete mode 100644 src/components/git/AnnounceRepositoryDialog.tsx delete mode 100644 src/components/git/BranchManager.tsx delete mode 100644 src/components/git/CompareView.tsx delete mode 100644 src/components/git/DiffViewer.tsx delete mode 100644 src/components/git/GitManagementDialog.tsx delete mode 100644 src/components/git/MergeDialog.tsx delete mode 100644 src/components/git/PullRequestDialog.tsx delete mode 100644 src/components/git/PullRequestForm.tsx delete mode 100644 src/components/git/index.ts delete mode 100644 src/hooks/useGitFetch.test.tsx delete mode 100644 src/hooks/useGitFetch.ts delete mode 100644 src/hooks/usePullRequests.ts delete mode 100644 src/lib/git-hosts/GitHubProvider.ts delete mode 100644 src/lib/git-hosts/GitLabProvider.ts delete mode 100644 src/lib/git-hosts/GiteaProvider.ts delete mode 100644 src/lib/git-hosts/NostrGitProvider.ts delete mode 100644 src/lib/git-hosts/index.ts delete mode 100644 src/lib/git-hosts/types.ts diff --git a/src/components/ActionsMenu.tsx b/src/components/ActionsMenu.tsx index 77015443..c2a59ca1 100644 --- a/src/components/ActionsMenu.tsx +++ b/src/components/ActionsMenu.tsx @@ -8,7 +8,6 @@ import { DropdownMenuTrigger, } from '@/components/ui/dropdown-menu'; import { - GitBranch, MoreHorizontal, MessageSquarePlus, History, @@ -17,7 +16,6 @@ import { Copy, } from 'lucide-react'; import { GitHistoryDialog } from '@/components/ai/GitHistoryDialog'; -import { GitDialog } from '@/components/GitDialog'; import { DeployDialog } from '@/components/DeployDialog'; import { DuplicateProjectDialog } from '@/components/DuplicateProjectDialog'; @@ -44,7 +42,6 @@ export function ActionsMenu({ }: ActionsMenuProps) { const { t } = useTranslation(); const [gitHistoryOpen, setGitHistoryOpen] = useState(false); - const [gitDialogOpen, setGitDialogOpen] = useState(false); const [deployDialogOpen, setDeployDialogOpen] = useState(false); const [duplicateDialogOpen, setDuplicateDialogOpen] = useState(false); @@ -85,15 +82,6 @@ export function ActionsMenu({ Rollback - setGitDialogOpen(true)} - disabled={isAnyLoading} - className="gap-2" - > - - Repository - - setDeployDialogOpen(true)} disabled={isAnyLoading} @@ -126,12 +114,6 @@ export function ActionsMenu({ {/* Dialogs */} - - ({ - useGitStatus: () => mockUseGitStatus(), -})); - -vi.mock('@/hooks/useFS', () => ({ - useFS: vi.fn(() => ({ - fs: {}, - })), -})); - -vi.mock('@/hooks/useToast', () => ({ - useToast: vi.fn(() => ({ - toast: vi.fn(), - })), -})); - -const mockUseGitSettings = vi.fn(); - -vi.mock('@/hooks/useGitSettings', () => ({ - useGitSettings: () => mockUseGitSettings(), -})); - -describe('GitDialog', () => { - beforeEach(() => { - mockUseGitStatus.mockReturnValue({ - data: baseGitStatus, - refetch: mockRefetch, - }); - - mockUseGitSettings.mockReturnValue({ - settings: { - credentials: [ - { - id: crypto.randomUUID(), - name: 'GitHub', - origin: 'https://github.com', - username: 'git', - password: 'github-token', - }, - ], - }, - }); - }); - - it('renders git dialog without repository information section', () => { - render( - - {}}> - - - - ); - - expect(screen.getByText('Repository')).toBeInTheDocument(); - expect(screen.queryByText('Repository Information')).not.toBeInTheDocument(); - expect(screen.queryByText('Authentication')).not.toBeInTheDocument(); // Authentication section is removed - }); - - it('shows sync status when branch is published', () => { - // Mock git status with published branch - mockUseGitStatus.mockReturnValue({ - data: { - ...baseGitStatus, - remoteBranchExists: true, - }, - refetch: mockRefetch, - }); - - render( - - {}}> - - - - ); - - expect(screen.getByText('Sync Status')).toBeInTheDocument(); - expect(screen.getByText('Up to date')).toBeInTheDocument(); - expect(screen.getByText('Pull')).toBeInTheDocument(); - expect(screen.getByText('Push')).toBeInTheDocument(); - }); - - it('shows clean working directory when no changes', () => { - render( - - {}}> - - - - ); - - expect(screen.getByText('Working directory is clean')).toBeInTheDocument(); - expect(screen.getByText('No uncommitted changes')).toBeInTheDocument(); - }); - - it('enables push button when there are commits ahead', () => { - // Mock git status with commits ahead - mockUseGitStatus.mockReturnValue({ - data: { - ...baseGitStatus, - ahead: 2, - }, - refetch: mockRefetch, - }); - - render( - - {}}> - - - - ); - - const pushButton = screen.getByText('Push'); - expect(pushButton).toBeInTheDocument(); - expect(pushButton.closest('button')).not.toBeDisabled(); - }); - - it('disables push button when no commits ahead and branch is published', () => { - // Mock git status with published branch and no commits ahead - mockUseGitStatus.mockReturnValue({ - data: { - ...baseGitStatus, - ahead: 0, - remoteBranchExists: true, - }, - refetch: mockRefetch, - }); - - render( - - {}}> - - - - ); - - const pushButton = screen.getByText('Push'); - expect(pushButton).toBeInTheDocument(); - expect(pushButton.closest('button')).toBeDisabled(); - }); - - it('enables push and disables pull when branch is not published', () => { - // Mock git status with unpublished branch (has commits but no remote branch) - mockUseGitStatus.mockReturnValue({ - data: { - ...baseGitStatus, - ahead: 0, - remoteBranchExists: false, - totalCommits: 5, - }, - refetch: mockRefetch, - }); - - render( - - {}}> - - - - ); - - expect(screen.getByText('Sync Status')).toBeInTheDocument(); - expect(screen.getByText('Branch not published')).toBeInTheDocument(); - - const pushButton = screen.getByText('Push'); - expect(pushButton).toBeInTheDocument(); - expect(pushButton.closest('button')).not.toBeDisabled(); - - const pullButton = screen.getByText('Pull'); - expect(pullButton).toBeInTheDocument(); - expect(pullButton.closest('button')).toBeDisabled(); - }); - - it('does not show credentials warning when credentials are configured', () => { - render( - - {}}> - - - - ); - - // Should not show warning when credentials are configured - expect(screen.queryByText(/No credentials configured/)).not.toBeInTheDocument(); - expect(screen.queryByText('Authentication')).not.toBeInTheDocument(); // Authentication section is removed - }); - - it('shows credentials warning when no credentials are configured', () => { - // Mock git settings with no credentials and mock git status with an https remote - mockUseGitSettings.mockReturnValue({ - settings: { - credentials: [], - }, - }); - - mockUseGitStatus.mockReturnValue({ - data: { - ...baseGitStatus, - remotes: [{ name: 'origin', url: 'https://github.com/example/repo.git' }], - }, - refetch: mockRefetch, - }); - - render( - - {}}> - - - - ); - - // Should show warning when credentials are missing - expect(screen.getByText(/You are not logged into github.com/)).toBeInTheDocument(); - expect(screen.getByText('log in')).toBeInTheDocument(); - expect(screen.queryByText('Authentication')).not.toBeInTheDocument(); // Authentication section is removed - }); -}); \ No newline at end of file diff --git a/src/components/GitDialog.tsx b/src/components/GitDialog.tsx deleted file mode 100644 index 24e33859..00000000 --- a/src/components/GitDialog.tsx +++ /dev/null @@ -1,1475 +0,0 @@ -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, - RefreshCw, -} 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 { useGitFetch } from '@/hooks/useGitFetch'; -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'; -import { formatRelativeTime } from '@/lib/utils'; - -// Helper function to format fetch timestamp with special "fetched" prefix -function formatFetchTime(date: Date | number): string { - const timestamp = typeof date === 'number' ? date : date.getTime(); - const now = Date.now(); - const diffMs = now - timestamp; - - // Less than 20 seconds - use special "fetched just now" message - if (diffMs < 20 * 1000) { - return 'fetched just now'; - } - - // Otherwise use the standard relative time formatter - return formatRelativeTime(timestamp); -} - -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 [, setUpdateTrigger] = useState(0); - - 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 { data: gitFetchData, isFetching: isFetchingRemote, refetch: refetchRemote } = useGitFetch(projectId); - - const projectPath = `${projectsPath}/${projectId}`; - - // Update the "last fetched" timestamp display every 10 seconds - useEffect(() => { - const interval = setInterval(() => { - setUpdateTrigger(prev => prev + 1); - }, 1000); - - return () => clearInterval(interval); - }, []); - - // 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, - }); - - 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, - }); - - // Automatically check out the new branch - await git.checkout({ - dir: projectPath, - ref: newBranchName.trim(), - force: true, - }); - - // Close the dialog before showing the toast - setNewBranchName(''); - setIsCreateBranchDialogOpen(false); - - // Show success toast indicating the branch was created and checked out - toast({ - title: 'Branch created and checked out', - description: `Switched to new branch "${newBranchName.trim()}"`, - }); - - 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.'); - } - - console.log('Repository has refs:', refTags); - - // 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); - - // Wait a few seconds for GRASP servers to update - await new Promise(resolve => setTimeout(resolve, 3000)); - - // Refresh git status to pick up the new remote - await refetchGitStatus(); - - // Automatically push to the newly configured Nostr remote - // Get the current branch fresh from git instead of using stale gitStatus - console.log('Starting automatic push to Nostr...'); - - try { - const currentBranch = await git.currentBranch({ dir: projectPath }); - console.log('Current branch:', currentBranch); - - if (!currentBranch) { - throw new Error('No current branch found'); - } - - toast({ - title: 'Repository published to Nostr', - description: 'Pushing commits to ngit servers...', - }); - - console.log('Calling git.push with:', { dir: projectPath, remote: 'origin', ref: currentBranch }); - - await git.push({ - dir: projectPath, - remote: 'origin', - ref: currentBranch, - signer: user.signer, - }); - - console.log('Push completed successfully'); - - toast({ - title: 'Push successful', - description: 'Repository successfully pushed to Nostr', - }); - - // Refresh git status after push - await refetchGitStatus(); - } catch (pushError) { - console.error('Push error:', pushError); - const pushErrorMessage = pushError instanceof Error ? pushError.message : 'Unknown error occurred'; - toast({ - title: 'Automatic push failed', - description: pushErrorMessage, - variant: 'destructive', - duration: Infinity, - }); - } - } 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; - } - - // Allow push if there are commits ahead OR if the remote branch doesn't exist (publishing new branch) - if (gitStatus.ahead === 0 && gitStatus.remoteBranchExists) { - toast({ - title: "Nothing to push", - description: "No commits ahead of remote. Commit your changes first.", - variant: "destructive", - }); - return; - } - - // Ensure we have commits to push when publishing a new branch - if (!gitStatus.remoteBranchExists && gitStatus.totalCommits === 0) { - toast({ - title: "Cannot publish branch", - description: "No commits to push. 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 - }); - - // Set up upstream tracking if this is the first push for this branch - if (!gitStatus.remoteBranchExists) { - await git.setConfig({ - dir: projectPath, - path: `branch.${gitStatus.currentBranch}.remote`, - value: remote.name, - }); - await git.setConfig({ - dir: projectPath, - path: `branch.${gitStatus.currentBranch}.merge`, - value: `refs/heads/${gitStatus.currentBranch}`, - }); - } - - // Show different messages for publishing new branches vs pushing commits - if (gitStatus.remoteBranchExists) { - toast({ - title: "Push successful", - description: `${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} pushed to ${remote.name}/${gitStatus.currentBranch}`, - }); - } else { - toast({ - title: "Branch published", - description: `New branch published 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' }; - } - - // Check if remote branch doesn't exist - if (!gitStatus.remoteBranchExists && gitStatus.currentBranch) { - return { status: 'not-published', text: 'Branch not published', 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} - - - {/* Last Fetched Info - inline with sync status */} - {gitStatus.remotes.length > 0 && gitFetchData?.fetchedAt && ( - <> - - · {formatFetchTime(gitFetchData.fetchedAt)} - - - - )} -
- - {originUrl.trim() && ( -
- - - -
- )} - - {!originUrl.trim() && 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 */} - - - ); -} \ No newline at end of file diff --git a/src/components/ProjectTitleMenu.tsx b/src/components/ProjectTitleMenu.tsx index 522292a4..e576f3e8 100644 --- a/src/components/ProjectTitleMenu.tsx +++ b/src/components/ProjectTitleMenu.tsx @@ -7,7 +7,6 @@ import { DropdownMenuTrigger, } from '@/components/ui/dropdown-menu'; import { - GitBranch, MessageSquarePlus, History, Folder, @@ -21,7 +20,6 @@ interface ProjectTitleMenuProps { projectName: string; onNewChat: () => void; onGitHistory: () => void; - onGitDialog: () => void; onDeploy: () => void; onDuplicate: () => void; onProjectDetails: () => void; @@ -34,7 +32,6 @@ export function ProjectTitleMenu({ projectName, onNewChat, onGitHistory, - onGitDialog, onDeploy, onDuplicate, onProjectDetails, @@ -74,15 +71,6 @@ export function ProjectTitleMenu({ Rollback
- - - Repository - - { - it('should create tags with multiple values in single tag per NIP-34', () => { - // Test the tag structure that would be created - const webUrls = ['https://example.com/browse', 'https://mirror.example.com']; - const cloneUrls = [ - 'https://git.shakespeare.diy/npub1.../repo.git', - 'https://relay.ngit.dev/npub1.../repo.git', - ]; - const relays = ['wss://git.shakespeare.diy', 'wss://relay.ngit.dev']; - - const tags: string[][] = [['d', 'test-repo']]; - - // Simulate the tag creation logic from AnnounceRepositoryDialog - if (webUrls.length > 0) { - const trimmedUrls = webUrls.map((url) => url.trim()).filter((url) => url); - if (trimmedUrls.length > 0) { - tags.push(['web', ...trimmedUrls]); - } - } - - if (cloneUrls.length > 0) { - const trimmedUrls = cloneUrls.map((url) => url.trim()).filter((url) => url); - if (trimmedUrls.length > 0) { - tags.push(['clone', ...trimmedUrls]); - } - } - - if (relays.length > 0) { - const trimmedRelays = relays.map((relay) => relay.trim()).filter((relay) => relay); - if (trimmedRelays.length > 0) { - tags.push(['relays', ...trimmedRelays]); - } - } - - // Verify the structure matches NIP-34 spec - expect(tags).toEqual([ - ['d', 'test-repo'], - ['web', 'https://example.com/browse', 'https://mirror.example.com'], - [ - 'clone', - 'https://git.shakespeare.diy/npub1.../repo.git', - 'https://relay.ngit.dev/npub1.../repo.git', - ], - ['relays', 'wss://git.shakespeare.diy', 'wss://relay.ngit.dev'], - ]); - - // Verify we have single tags with multiple values, not multiple tags - const cloneTags = tags.filter((t) => t[0] === 'clone'); - expect(cloneTags.length).toBe(1); - expect(cloneTags[0].length).toBe(3); // ['clone', url1, url2] - - const relayTags = tags.filter((t) => t[0] === 'relays'); - expect(relayTags.length).toBe(1); - expect(relayTags[0].length).toBe(3); // ['relays', relay1, relay2] - }); - - it('should handle reading relays from single tag with multiple values', () => { - // Simulate the event structure from Nostr - const repoEvent = { - tags: [ - ['d', 'hello-shakespeare'], - [ - 'clone', - 'https://git.shakespeare.diy/npub1.../hello-shakespeare.git', - 'https://relay.ngit.dev/npub1.../hello-shakespeare.git', - ], - ['relays', 'wss://git.shakespeare.diy', 'wss://relay.ngit.dev'], - ], - }; - - // Simulate the reading logic from PullRequestDialog - const relayTag = repoEvent.tags.find((t: string[]) => t[0] === 'relays'); - let publishRelays: string[] = []; - - if (relayTag && relayTag.length > 1) { - publishRelays = relayTag.slice(1); - } - - // Verify we extracted all relay URLs correctly - expect(publishRelays).toEqual(['wss://git.shakespeare.diy', 'wss://relay.ngit.dev']); - }); - - it('should handle reading clone URLs from single tag with multiple values', () => { - const repoEvent = { - tags: [ - ['d', 'hello-shakespeare'], - [ - 'clone', - 'https://git.shakespeare.diy/npub1.../hello-shakespeare.git', - 'https://relay.ngit.dev/npub1.../hello-shakespeare.git', - ], - ], - }; - - const cloneTag = repoEvent.tags.find((t: string[]) => t[0] === 'clone'); - let cloneUrls: string[] = []; - - if (cloneTag && cloneTag.length > 1) { - cloneUrls = cloneTag.slice(1); - } - - expect(cloneUrls).toEqual([ - 'https://git.shakespeare.diy/npub1.../hello-shakespeare.git', - 'https://relay.ngit.dev/npub1.../hello-shakespeare.git', - ]); - }); - - it('should handle reading maintainers from single tag with multiple values', () => { - const repoEvent = { - tags: [ - ['d', 'hello-shakespeare'], - ['maintainers', 'pubkey1', 'pubkey2', 'pubkey3'], - ], - }; - - // Simulate the reading logic from NostrGitProvider - const maintainerTag = repoEvent.tags.find((t: string[]) => t[0] === 'maintainers'); - const maintainers = maintainerTag ? maintainerTag.slice(1) : []; - - expect(maintainers).toEqual(['pubkey1', 'pubkey2', 'pubkey3']); - }); -}); diff --git a/src/components/git/AnnounceRepositoryDialog.tsx b/src/components/git/AnnounceRepositoryDialog.tsx deleted file mode 100644 index a31641e3..00000000 --- a/src/components/git/AnnounceRepositoryDialog.tsx +++ /dev/null @@ -1,746 +0,0 @@ -import { useState, useEffect, useCallback } from 'react'; -import { Button } from '@/components/ui/button'; -import { Input } from '@/components/ui/input'; -import { Label } from '@/components/ui/label'; -import { Textarea } from '@/components/ui/textarea'; -import { TagInput } from '@/components/ui/tag-input'; -import { - Dialog, - DialogContent, - DialogDescription, - DialogHeader, - DialogTitle, - DialogFooter, -} from '@/components/ui/dialog'; -import { - Collapsible, - CollapsibleContent, - CollapsibleTrigger, -} from '@/components/ui/collapsible'; -import { Alert, AlertDescription } from '@/components/ui/alert'; -import { ScrollArea } from '@/components/ui/scroll-area'; -import { - GitBranch, - Loader2, - AlertCircle, - Plus, - X, - Settings, - ChevronDown, -} from 'lucide-react'; -import { useGit } from '@/hooks/useGit'; -import { useFSPaths } from '@/hooks/useFSPaths'; -import { useCurrentUser } from '@/hooks/useCurrentUser'; -import { useNostr } from '@/hooks/useNostr'; -import { useToast } from '@/hooks/useToast'; -import { useAppContext } from '@/hooks/useAppContext'; -import { useFS } from '@/hooks/useFS'; -import { DotAI } from '@/lib/DotAI'; -import { nip19 } from 'nostr-tools'; -import { - createRepositoryAnnouncementEvent, - createRepositoryNaddr, - validateRepositoryAnnouncementData, - validateRepositoryId, - parseRepositoryAnnouncement, -} from '@/lib/announceRepository'; - -export interface AnnounceRepositoryResult { - repoId: string; - cloneUrls: string[]; - relays: string[]; - naddr: string; -} - -interface AnnounceRepositoryDialogProps { - projectId: string; - open?: boolean; - onOpenChange?: (open: boolean) => void; - onSuccess?: (result: AnnounceRepositoryResult) => void; - /** Repository naddr to edit (if editing existing repo) */ - editNaddr?: string; -} - -export function AnnounceRepositoryDialog({ - projectId, - open, - onOpenChange, - onSuccess, - editNaddr, -}: AnnounceRepositoryDialogProps) { - const [isOpen, setIsOpen] = useState(open ?? false); - const [isPrepopulated, setIsPrepopulated] = useState(false); - const [repoId, setRepoId] = useState(''); - const [repoIdError, setRepoIdError] = useState(null); - const [name, setName] = useState(''); - const [description, setDescription] = useState(''); - const [showAdvanced, setShowAdvanced] = useState(false); - const [webUrls, setWebUrls] = useState([]); - const [cloneUrls, setCloneUrls] = useState([]); - const [relays, setRelays] = useState([]); - const [tTags, setTTags] = useState([]); - const [earliestCommit, setEarliestCommit] = useState(''); - const [isCreating, setIsCreating] = useState(false); - const [error, setError] = useState(null); - - const [newWebUrl, setNewWebUrl] = useState(''); - const [newCloneUrl, setNewCloneUrl] = useState(''); - const [newRelay, setNewRelay] = useState(''); - - const { git } = useGit(); - const { projectsPath } = useFSPaths(); - const { user } = useCurrentUser(); - const { nostr } = useNostr(); - const { toast } = useToast(); - const { config } = useAppContext(); - const { fs } = useFS(); - - const projectPath = `${projectsPath}/${projectId}`; - - useEffect(() => { - if (open !== undefined) { - setIsOpen(open); - } - }, [open]); - - // Convert projectId to kebab-case for repo ID - const toKebabCase = (str: string): string => { - return str - .toLowerCase() - .replace(/[^a-z0-9]+/g, '-') - .replace(/^-+|-+$/g, ''); - }; - - // Validate repository ID on change - const handleRepoIdChange = (value: string) => { - setRepoId(value); - try { - validateRepositoryId(value); - setRepoIdError(null); - } catch (err) { - setRepoIdError(err instanceof Error ? err.message : 'Invalid repository ID'); - } - }; - - const getEarliestCommit = useCallback(async () => { - try { - const commits = await git.log({ - dir: projectPath, - ref: 'HEAD', - }); - - if (commits.length > 0) { - // Get the earliest commit (last in the log) - const earliest = commits[commits.length - 1]; - setEarliestCommit(earliest.oid); - } - } catch (err) { - console.warn('Failed to get earliest commit:', err); - } - }, [git, projectPath]); - - const prepopulateFields = useCallback(async () => { - // Set default repo ID from project ID (kebab-case) - const defaultRepoId = toKebabCase(projectId); - setRepoId(defaultRepoId); - - // Set default name from project ID (title case) - const defaultName = projectId - .split(/[-_]/) - .map(word => word.charAt(0).toUpperCase() + word.slice(1)) - .join(' '); - setName(defaultName); - - // Prepopulate clone URLs and relays from grasp servers (matching original handlePushToNostr) - if (user?.pubkey && config.graspMetadata.relays && config.graspMetadata.relays.length > 0) { - const npub = nip19.npubEncode(user.pubkey); - - // Clone URLs: https://{hostname}/{npub}/{repo-id}.git - const cloneUrls = config.graspMetadata.relays.map(relay => { - try { - const url = new URL(relay.url); - return `https://${url.hostname}/${npub}/${defaultRepoId}.git`; - } catch { - // Fallback: extract hostname from URL string - const hostname = relay.url.replace(/^wss?:\/\//, '').replace(/\/.*$/, ''); - return `https://${hostname}/${npub}/${defaultRepoId}.git`; - } - }); - setCloneUrls(cloneUrls); - - // Relay URLs from grasp metadata - const relayUrls = config.graspMetadata.relays.map(r => r.url); - setRelays(relayUrls); - } else { - // Fallback to write relays if no grasp servers configured - const writeRelays = config.relayMetadata.relays - .filter(r => r.write) - .map(r => r.url); - setRelays(writeRelays.length > 0 ? writeRelays : ['wss://relay.nostr.band']); - } - - // Prepopulate t-tags - const defaultTTags: string[] = ['shakespeare']; - - // Try to read template.json to get template name - try { - const dotAI = new DotAI(fs, projectPath); - const template = await dotAI.readTemplate(); - if (template?.name) { - // Convert template name to lowercase and add as t-tag - const templateTag = template.name.toLowerCase(); - if (!defaultTTags.includes(templateTag)) { - defaultTTags.push(templateTag); - } - } - } catch (error) { - console.warn('Failed to read template for t-tags:', error); - } - - setTTags(defaultTTags); - - // Get earliest commit - await getEarliestCommit(); - }, [projectId, projectPath, fs, config.relayMetadata, config.graspMetadata.relays, user?.pubkey, getEarliestCommit]); - - // Load existing repository data if editing, or prepopulate fields for new repos - useEffect(() => { - // Only run when dialog opens - if (!isOpen || isPrepopulated) return; - - const loadExistingRepo = async () => { - if (!editNaddr) return; - - try { - // Decode the naddr to get repository coordinates - const decoded = nip19.decode(editNaddr); - if (decoded.type !== 'naddr') { - throw new Error('Invalid repository identifier'); - } - - const { identifier, pubkey, kind, relays: naddrRelays } = decoded.data; - - // Query for the repository announcement event - const filter = { - kinds: [kind], - authors: [pubkey], - '#d': [identifier], - }; - - const signal = AbortSignal.timeout(3000); - const readRelays = config.relayMetadata.relays - .filter(r => r.read) - .map(r => r.url); - const events = await nostr.query([filter], { - signal, - relays: naddrRelays && naddrRelays.length > 0 ? naddrRelays : readRelays - }); - - if (events.length === 0) { - throw new Error('Repository announcement not found'); - } - - // Use the most recent event - const event = events.sort((a, b) => b.created_at - a.created_at)[0]; - - // Parse the NIP-34 repository announcement - const parsed = parseRepositoryAnnouncement(event); - - setRepoId(parsed.identifier); - setName(parsed.name || ''); - setDescription(parsed.description || ''); - setWebUrls(parsed.webUrls); - setCloneUrls(parsed.httpsCloneUrls); - setRelays(parsed.relays); - setEarliestCommit(parsed.earliestCommit || ''); - - // Extract t-tags from the event - const extractedTTags = parsed.event.tags - .filter(([name]) => name === 't') - .map(([, value]) => value) - .filter((value): value is string => !!value); - setTTags(extractedTTags); - - setIsPrepopulated(true); - } catch (error) { - console.error('Failed to load repository data:', error); - toast({ - title: 'Failed to load repository', - description: error instanceof Error ? error.message : 'Unknown error', - variant: 'destructive', - }); - } - }; - - if (editNaddr) { - loadExistingRepo(); - } else { - prepopulateFields(); - setIsPrepopulated(true); - } - }, [isOpen, isPrepopulated, editNaddr, nostr, config.relayMetadata, toast, prepopulateFields]); - - const addWebUrl = () => { - if (newWebUrl.trim() && !webUrls.includes(newWebUrl.trim())) { - setWebUrls([...webUrls, newWebUrl.trim()]); - setNewWebUrl(''); - } - }; - - const removeWebUrl = (index: number) => { - setWebUrls(webUrls.filter((_, i) => i !== index)); - }; - - const addCloneUrl = () => { - const trimmedUrl = newCloneUrl.trim(); - - // Prevent nostr:// URLs in clone URLs - if (trimmedUrl.startsWith('nostr://')) { - toast({ - title: 'Invalid clone URL', - description: 'Clone URLs must be HTTPS URLs, not nostr:// URLs', - variant: 'destructive', - }); - return; - } - - if (trimmedUrl && !cloneUrls.includes(trimmedUrl)) { - setCloneUrls([...cloneUrls, trimmedUrl]); - setNewCloneUrl(''); - } - }; - - const removeCloneUrl = (index: number) => { - setCloneUrls(cloneUrls.filter((_, i) => i !== index)); - }; - - const addRelay = () => { - if (newRelay.trim() && !relays.includes(newRelay.trim())) { - setRelays([...relays, newRelay.trim()]); - setNewRelay(''); - } - }; - - const removeRelay = (index: number) => { - setRelays(relays.filter((_, i) => i !== index)); - }; - - const announceRepository = async () => { - if (!user || !user.signer) { - toast({ - title: 'Authentication required', - description: 'Please log in with Nostr to announce repositories', - variant: 'destructive', - }); - return; - } - - setIsCreating(true); - setError(null); - - try { - // Validate data - validateRepositoryAnnouncementData({ - repoId, - cloneUrls, - }); - - // Create repository announcement event using shared utility - const repoEvent = createRepositoryAnnouncementEvent({ - repoId, - name, - description, - webUrls, - cloneUrls, - relays, - tTags, - earliestCommit, - }); - - console.log('=== ANNOUNCING REPOSITORY ==='); - console.log('Repository ID:', repoId.trim()); - console.log('Owner pubkey:', user.pubkey); - console.log('Creating repository announcement event:', repoEvent); - - // Sign the event - const signedEvent = await user.signer.signEvent(repoEvent); - - console.log('Signed repository announcement:', signedEvent); - console.log('Event coordinate:', `30617:${user.pubkey}:${repoId.trim()}`); - - // Publish to Nostr relays - // Repository announcements go to: write relays + relays specified in the announcement - const writeRelays = config.relayMetadata.relays - .filter(r => r.write) - .map(r => r.url); - const publishRelays = [...new Set([...writeRelays, ...relays])]; - console.log('Publishing repository announcement to relays:', publishRelays); - - await nostr.event(signedEvent, { relays: publishRelays }); - - console.log('Published repository announcement to Nostr relays'); - console.log('To verify: Query for kind 30617 with authors=[' + user.pubkey + '] and #d=[' + repoId.trim() + ']'); - - // Create naddr for the repository using shared utility - const naddr = createRepositoryNaddr(repoId, user.pubkey, relays); - - toast({ - title: 'Published Nostr announcement', - description: 'Configuring repository...', - }); - - // Close the dialog - handleOpenChange(false); - - // Call success callback with the data needed for Git operations - onSuccess?.({ - repoId: repoId.trim(), - cloneUrls, - relays, - naddr, - }); - } catch (err) { - const errorMessage = err instanceof Error ? err.message : 'Unknown error'; - setError(errorMessage); - toast({ - title: 'Failed to announce repository', - description: errorMessage, - variant: 'destructive', - duration: Infinity, - }); - } finally { - setIsCreating(false); - } - }; - - const handleOpenChange = (newOpen: boolean) => { - setIsOpen(newOpen); - onOpenChange?.(newOpen); - - // Reset form when closing - if (!newOpen) { - setIsPrepopulated(false); - setRepoId(''); - setName(''); - setDescription(''); - setWebUrls([]); - setCloneUrls([]); - setRelays(['wss://relay.nostr.band']); - setTTags([]); - setEarliestCommit(''); - setError(null); - setNewWebUrl(''); - setNewCloneUrl(''); - setNewRelay(''); - } - }; - - return ( - - - - - - {editNaddr ? 'Edit' : ''} Nostr Repository Settings - - - {editNaddr - ? 'Update your repository announcement (NIP-34) for Nostr git clients' - : 'Configure your repository announcement (NIP-34) for Nostr git clients' - } - - - - -
- {/* Error alert */} - {error && ( - - - {error} - - )} - - {/* Repository ID */} -
- - handleRepoIdChange(e.target.value)} - disabled={isCreating} - className={repoIdError ? 'border-destructive' : ''} - /> - {repoIdError ? ( -

{repoIdError}

- ) : ( -

- Kebab-case short name (e.g., "my-project", "awesome-app") -

- )} -
- - {/* Name */} -
- - setName(e.target.value)} - disabled={isCreating} - /> -

- Display name for your repository -

-
- - {/* Description */} -
- -