diff --git a/src/components/GitDialog.tsx b/src/components/GitDialog.tsx index 9e120a39..92189d06 100644 --- a/src/components/GitDialog.tsx +++ b/src/components/GitDialog.tsx @@ -55,15 +55,14 @@ import { useFSPaths } from '@/hooks/useFSPaths'; import { useToast } from '@/hooks/useToast'; import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useNostr } from '@nostrify/react'; -import { useNostrPublish } from '@/hooks/useNostrPublish'; import { usePullRequests } from '@/hooks/usePullRequests'; -import { useAppContext } from '@/hooks/useAppContext'; 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; @@ -76,6 +75,8 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog 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(); @@ -96,19 +97,36 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog const { toast } = useToast(); const { user } = useCurrentUser(); const { nostr } = useNostr(); - const { mutateAsync: publishEvent } = useNostrPublish(); const { data: pullRequests, isLoading: isLoadingPRs } = usePullRequests(originUrl); - const { config } = useAppContext(); const projectPath = `${projectsPath}/${projectId}`; - // Initialize origin URL from git status + // Initialize origin URL from git status and load nostr.repo config useEffect(() => { - if (gitStatus?.remotes) { - const originRemote = gitStatus.remotes.find(remote => remote.name === 'origin'); - setOriginUrl(originRemote?.url || ''); - } - }, [gitStatus?.remotes]); + 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); @@ -306,22 +324,27 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog throw new Error(`Repository announcement already exists for project "${projectId}". Cannot create duplicate.`); } - // Create repo announcement event (NIP-34 kind 30617) - const cloneUrls = config.ngitServers.map(server => - `https://${server}/${nip19.npubEncode(user.pubkey)}/${projectId}.git` - ); - const relayUrls = config.ngitServers.map(server => `wss://${server}`); - - await publishEvent({ - kind: 30617, - content: "", - tags: [ - ["d", projectId], - ["clone", ...cloneUrls], - ["relays", ...relayUrls], - ], + // 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[][] = []; @@ -417,19 +440,31 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog } // Create repo state event (NIP-34 kind 30618) - await publishEvent({ + const stateEvent = { kind: 30618, - content: "", + content: '', tags: [ - ["d", projectId], + ['d', result.repoId], ...refTags, - ...(headRef ? [["HEAD", headRef]] : []), + ...(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)}/${projectId}`; + const nostrUrl = `nostr://${nip19.npubEncode(user.pubkey)}/${result.repoId}`; try { // Remove existing origin if it exists @@ -447,22 +482,24 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog url: nostrUrl, }); + console.log('Set Git origin to:', nostrUrl); + // Set nostr.repo config await git.setConfig({ dir: projectPath, path: 'nostr.repo', - value: nip19.naddrEncode({ - kind: 30617, - pubkey: user.pubkey, - identifier: projectId, - }), + 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...", + 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({ @@ -684,6 +721,24 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog 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'); @@ -1038,6 +1093,19 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog {isPushingToNostr ? 'Publishing to Nostr...' : 'Push to Nostr'} )} + + {/* Edit Nostr Repository Settings */} + {gitStatus.remotes.length > 0 && isOwnNostrRepo() && editNaddr && ( + + )} {/* Merge Branch Action */} @@ -1297,6 +1365,15 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog + + {/* Announce Repository Dialog */} + ); } \ No newline at end of file diff --git a/src/components/git/AnnounceRepositoryDialog.tsx b/src/components/git/AnnounceRepositoryDialog.tsx index 627ba7e7..706eb28c 100644 --- a/src/components/git/AnnounceRepositoryDialog.tsx +++ b/src/components/git/AnnounceRepositoryDialog.tsx @@ -9,51 +9,74 @@ import { DialogDescription, DialogHeader, DialogTitle, - DialogTrigger, 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, - CheckCircle, Plus, X, - Megaphone, + 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 { nip19 } from 'nostr-tools'; +import { + createRepositoryAnnouncementEvent, + createRepositoryNaddr, + validateRepositoryAnnouncementData, + validateRepositoryId, +} from '@/lib/announceRepository'; + +export interface AnnounceRepositoryResult { + repoId: string; + cloneUrls: string[]; + relays: string[]; + naddr: string; +} interface AnnounceRepositoryDialogProps { projectId: string; - remoteUrl?: 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, - remoteUrl, 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(['wss://relay.nostr.band']); + const [relays, setRelays] = useState([]); const [earliestCommit, setEarliestCommit] = useState(''); const [isCreating, setIsCreating] = useState(false); const [error, setError] = useState(null); - const [createdNaddr, setCreatedNaddr] = useState(null); const [newWebUrl, setNewWebUrl] = useState(''); const [newCloneUrl, setNewCloneUrl] = useState(''); @@ -64,6 +87,7 @@ export function AnnounceRepositoryDialog({ const { user } = useCurrentUser(); const { nostr } = useNostr(); const { toast } = useToast(); + const { config } = useAppContext(); const projectPath = `${projectsPath}/${projectId}`; @@ -73,22 +97,24 @@ export function AnnounceRepositoryDialog({ } }, [open]); - const parseRemoteUrl = useCallback((url: string) => { - // Extract repo ID from Nostr URL - if (url.startsWith('nostr://')) { - const match = url.match(/^nostr:\/\/[^/]+\/(.+)$/); - if (match) { - const id = match[1]; - setRepoId(id); - setName(id.split('/').pop() || id); - } - } + // Convert projectId to kebab-case for repo ID + const toKebabCase = (str: string): string => { + return str + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, ''); + }; - // Add the remote URL as a clone URL - if (url && !cloneUrls.includes(url)) { - setCloneUrls([url]); + // 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'); } - }, [cloneUrls]); + }; const getEarliestCommit = useCallback(async () => { try { @@ -107,14 +133,110 @@ export function AnnounceRepositoryDialog({ } }, [git, projectPath]); - useEffect(() => { - if (isOpen && remoteUrl) { - // Parse remote URL to pre-fill data - parseRemoteUrl(remoteUrl); - // Get earliest commit - getEarliestCommit(); + 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); + + // Only prepopulate if the arrays are empty (user hasn't made changes yet) + if (cloneUrls.length === 0 && relays.length === 0) { + // Prepopulate clone URLs and relays from ngitServers (matching original handlePushToNostr) + if (user?.pubkey && config.ngitServers && config.ngitServers.length > 0) { + // Clone URLs: https://{server}/{npub}/{repo-id}.git + const npub = nip19.npubEncode(user.pubkey); + const cloneUrls = config.ngitServers.map(server => + `https://${server}/${npub}/${defaultRepoId}.git` + ); + setCloneUrls(cloneUrls); + + // Relay URLs: wss://{server} + const relayUrls = config.ngitServers.map(server => `wss://${server}`); + setRelays(relayUrls); + } else { + // Fallback to default relay if no ngitServers configured + setRelays([config.relayUrl || 'wss://relay.nostr.band']); + } } - }, [isOpen, remoteUrl, parseRemoteUrl, getEarliestCommit]); + + // Get earliest commit + await getEarliestCommit(); + }, [projectId, config.relayUrl, config.ngitServers, user?.pubkey, getEarliestCommit, cloneUrls.length, relays.length]); + + // Load existing repository data if editing + useEffect(() => { + const loadExistingRepo = async () => { + if (!editNaddr || !isOpen) 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 events = await nostr.query([filter], { + signal, + relays: naddrRelays && naddrRelays.length > 0 ? naddrRelays : [config.relayUrl] + }); + + 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 tags to populate form fields + const nameTag = event.tags.find(([name]) => name === 'name'); + const descriptionTag = event.tags.find(([name]) => name === 'description'); + const webTag = event.tags.find(([name]) => name === 'web'); + const cloneTag = event.tags.find(([name]) => name === 'clone'); + const relaysTag = event.tags.find(([name]) => name === 'relays'); + const eucTag = event.tags.find(([name, , marker]) => name === 'r' && marker === 'euc'); + + setRepoId(identifier); + setName(nameTag?.[1] || ''); + setDescription(descriptionTag?.[1] || ''); + setWebUrls(webTag ? webTag.slice(1) : []); + setCloneUrls(cloneTag ? cloneTag.slice(1) : []); + setRelays(relaysTag ? relaysTag.slice(1) : []); + setEarliestCommit(eucTag?.[1] || ''); + + 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 (isOpen && editNaddr) { + loadExistingRepo(); + } else if (isOpen && !isPrepopulated) { + prepopulateFields(); + setIsPrepopulated(true); + } + }, [isOpen, isPrepopulated, prepopulateFields, editNaddr, nostr, config.relayUrl, toast]); const addWebUrl = () => { if (newWebUrl.trim() && !webUrls.includes(newWebUrl.trim())) { @@ -128,8 +250,20 @@ export function AnnounceRepositoryDialog({ }; const addCloneUrl = () => { - if (newCloneUrl.trim() && !cloneUrls.includes(newCloneUrl.trim())) { - setCloneUrls([...cloneUrls, newCloneUrl.trim()]); + 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(''); } }; @@ -159,77 +293,26 @@ export function AnnounceRepositoryDialog({ return; } - if (!repoId.trim()) { - toast({ - title: 'Repository ID required', - description: 'Please enter a repository identifier', - variant: 'destructive', - }); - return; - } - - if (cloneUrls.length === 0) { - toast({ - title: 'Clone URL required', - description: 'Please add at least one clone URL', - variant: 'destructive', - }); - return; - } - setIsCreating(true); setError(null); try { - // Build tags array per NIP-34 - const tags: string[][] = [ - ['d', repoId.trim()], // Required: repository identifier - ]; + // Validate data + validateRepositoryAnnouncementData({ + repoId, + cloneUrls, + }); - if (name.trim()) { - tags.push(['name', name.trim()]); - } - - if (description.trim()) { - tags.push(['description', description.trim()]); - } - - // Add web URLs (all in a single tag per NIP-34) - if (webUrls.length > 0) { - const trimmedUrls = webUrls.map(url => url.trim()).filter(url => url); - if (trimmedUrls.length > 0) { - tags.push(['web', ...trimmedUrls]); - } - } - - // Add clone URLs (required, all in a single tag per NIP-34) - if (cloneUrls.length > 0) { - const trimmedUrls = cloneUrls.map(url => url.trim()).filter(url => url); - if (trimmedUrls.length > 0) { - tags.push(['clone', ...trimmedUrls]); - } - } - - // Add relays for patch submissions (all in a single tag per NIP-34) - if (relays.length > 0) { - const trimmedRelays = relays.map(relay => relay.trim()).filter(relay => relay); - if (trimmedRelays.length > 0) { - tags.push(['relays', ...trimmedRelays]); - } - } - - // Add earliest unique commit (euc) for repository identification - if (earliestCommit.trim()) { - tags.push(['r', earliestCommit.trim(), 'euc']); - } - - // Create repository announcement event (kind 30617) - const repoEvent = { - kind: 30617, - content: '', - tags, - created_at: Math.floor(Date.now() / 1000), - }; + // Create repository announcement event using shared utility + const repoEvent = createRepositoryAnnouncementEvent({ + repoId, + name, + description, + webUrls, + cloneUrls, + relays, + earliestCommit, + }); console.log('=== ANNOUNCING REPOSITORY ==='); console.log('Repository ID:', repoId.trim()); @@ -243,24 +326,32 @@ export function AnnounceRepositoryDialog({ console.log('Event coordinate:', `30617:${user.pubkey}:${repoId.trim()}`); // Publish to Nostr relays - await nostr.event(signedEvent); + // Repository announcements go to: global relayUrl + relays specified in the announcement + const publishRelays = [config.relayUrl, ...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 - const naddr = nip19.naddrEncode({ - identifier: repoId.trim(), - pubkey: user.pubkey, - kind: 30617, - relays: relays.length > 0 ? relays : undefined, - }); - - setCreatedNaddr(naddr); + // Create naddr for the repository using shared utility + const naddr = createRepositoryNaddr(repoId, user.pubkey, relays); toast({ - title: 'Repository announced!', - description: 'Your repository has been announced on Nostr', + 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'; @@ -269,6 +360,7 @@ export function AnnounceRepositoryDialog({ title: 'Failed to announce repository', description: errorMessage, variant: 'destructive', + duration: Infinity, }); } finally { setIsCreating(false); @@ -281,6 +373,7 @@ export function AnnounceRepositoryDialog({ // Reset form when closing if (!newOpen) { + setIsPrepopulated(false); setRepoId(''); setName(''); setDescription(''); @@ -288,7 +381,6 @@ export function AnnounceRepositoryDialog({ setCloneUrls([]); setRelays(['wss://relay.nostr.band']); setEarliestCommit(''); - setCreatedNaddr(null); setError(null); setNewWebUrl(''); setNewCloneUrl(''); @@ -296,284 +388,294 @@ export function AnnounceRepositoryDialog({ } }; - const copyNaddr = () => { - if (createdNaddr) { - navigator.clipboard.writeText(createdNaddr); - toast({ - title: 'Copied to clipboard', - description: 'Repository address copied', - }); - } - }; - return ( - - - - - Announce Repository on Nostr + + {editNaddr ? 'Edit' : ''} Nostr Repository Settings - Publish a repository announcement (NIP-34) to make it discoverable on Nostr git - clients + {editNaddr + ? 'Update your repository announcement (NIP-34) for Nostr git clients' + : 'Configure your repository announcement (NIP-34) for Nostr git clients' + } - {createdNaddr ? ( - // Success state -
- -
-

Repository Announced!

-

- Your repository is now discoverable on Nostr git clients -

-
-
- -
- - -
-

- Share this address with others to let them find your repository -

-
-
- ) : ( - // Form - -
- {/* Error alert */} - {error && ( - - - {error} - - )} + +
+ {/* Error alert */} + {error && ( + + + {error} + + )} - {/* Repository ID */} -
- - setRepoId(e.target.value)} - disabled={isCreating} - /> -

- Unique identifier for this repository (like GitHub's owner/repo) -

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