From 230d4bc4435bcc97da77ffc8365d6070fb2a9ab6 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sun, 21 Sep 2025 20:07:55 -0500 Subject: [PATCH] Push to Nostr works! --- src/components/GitDialog.tsx | 241 +++++++++++++++++++++++- src/components/NostrProvider.tsx | 35 +++- src/lib/git.ts | 304 ++++++++++++++----------------- 3 files changed, 411 insertions(+), 169 deletions(-) diff --git a/src/components/GitDialog.tsx b/src/components/GitDialog.tsx index d1be2ddb..56ef8f13 100644 --- a/src/components/GitDialog.tsx +++ b/src/components/GitDialog.tsx @@ -34,13 +34,20 @@ import { RefreshCw, Settings, AlertTriangle, + Zap, } from 'lucide-react'; import { useGitStatus } from '@/hooks/useGitStatus'; import { useGitSettings } from '@/hooks/useGitSettings'; import { useGit } from '@/hooks/useGit'; import { useToast } from '@/hooks/useToast'; +import { useCurrentUser } from '@/hooks/useCurrentUser'; +import { useNostr } from '@nostrify/react'; +import { useNostrPublish } from '@/hooks/useNostrPublish'; import { cn } from '@/lib/utils'; import { findCredentialsForRepo, getOriginDisplayName } from '@/lib/gitCredentials'; +import { nip19 } from 'nostr-tools'; + +const GRASP_SERVERS = ["git.shakespeare.diy", "relay.ngit.dev", "gitnostr.com"]; interface GitDialogProps { projectId: string; @@ -52,6 +59,7 @@ interface GitDialogProps { export function GitDialog({ projectId, children, open, onOpenChange }: GitDialogProps) { const [isPushing, setIsPushing] = useState(false); const [isPulling, setIsPulling] = useState(false); + const [isPushingToNostr, setIsPushingToNostr] = useState(false); const [pushResult, setPushResult] = useState(null); const [pullResult, setPullResult] = useState(null); const navigate = useNavigate(); @@ -60,9 +68,217 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog const { settings } = useGitSettings(); const { git } = useGit(); const { toast } = useToast(); + const { user } = useCurrentUser(); + const { nostr } = useNostr(); + const { mutateAsync: publishEvent } = useNostrPublish(); const projectPath = `/projects/${projectId}`; + 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); + setPushResult(null); + + 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.`); + } + + // Create repo announcement event (NIP-34 kind 30617) + const cloneUrls = GRASP_SERVERS.map(server => + `https://${server}/${nip19.npubEncode(user.pubkey)}/${projectId}.git` + ); + const relayUrls = GRASP_SERVERS.map(server => `wss://${server}`); + + await publishEvent({ + kind: 30617, + content: "", + tags: [ + ["d", projectId], + ["clone", ...cloneUrls], + ["relays", ...relayUrls], + ], + }); + + // 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) + await publishEvent({ + kind: 30618, + content: "", + tags: [ + ["d", projectId], + ...refTags, + ...(headRef ? [["HEAD", headRef]] : []), + ], + }); + + // Set origin remote to Nostr URL + const nostrUrl = `nostr://${nip19.npubEncode(user.pubkey)}/git.shakespeare.diy/${projectId}`; + + 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, + }); + + // Set nostr.repo config + await git.setConfig({ + dir: projectPath, + path: 'nostr.repo', + value: nip19.naddrEncode({ + kind: 30617, + pubkey: user.pubkey, + identifier: projectId, + }), + }); + + toast({ + title: "Repository published to Nostr", + description: "Waiting for GRASP servers to update...", + }); + + setPushResult(`✅ Successfully published repository to Nostr`); + } catch (error) { + const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred'; + setPushResult(`❌ Push to Nostr failed: ${errorMessage}`); + toast({ + title: "Push to Nostr failed", + description: errorMessage, + variant: "destructive", + }); + } finally { + setIsPushingToNostr(false); + } + }; + const handlePush = async () => { if (!gitStatus?.isGitRepo || !gitStatus.currentBranch) { toast({ @@ -102,6 +318,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog remote: remote.name, ref: gitStatus.currentBranch, onAuth: (url) => findCredentialsForRepo(url, settings.credentials), + signer: user?.signer, // For signing if pushing to Nostr }); setPushResult(`✅ Successfully pushed ${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} to ${remote.name}/${gitStatus.currentBranch}`); @@ -427,7 +644,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
+
+ )} + {/* Operation Results */} {(pushResult || pullResult) && (
diff --git a/src/components/NostrProvider.tsx b/src/components/NostrProvider.tsx index 6d745971..7b89ae81 100644 --- a/src/components/NostrProvider.tsx +++ b/src/components/NostrProvider.tsx @@ -1,5 +1,5 @@ import React, { useEffect, useRef } from 'react'; -import { NostrEvent, NPool, NRelay1 } from '@nostrify/nostrify'; +import { NostrEvent, NostrFilter, NPool, NRelay1 } from '@nostrify/nostrify'; import { NostrContext } from '@nostrify/react'; import { useQueryClient } from '@tanstack/react-query'; import { useAppContext } from '@/hooks/useAppContext'; @@ -8,6 +8,19 @@ interface NostrProviderProps { children: React.ReactNode; } +const GIT_KINDS = [ + 30617, // NIP-34 Repository Announcement + 30618, // NIP-34 Commit Announcement + 1617, // NIP-34 Patch + 1621, // NIP-34 Issue +]; + +const GIT_RELAYS = [ + 'wss://git.shakespeare.diy/', + 'wss://relay.ngit.dev/', + 'wss://gitnostr.com/', +]; + const NostrProvider: React.FC = (props) => { const { children } = props; const { config, presetRelays } = useAppContext(); @@ -33,12 +46,28 @@ const NostrProvider: React.FC = (props) => { return new NRelay1(url); }, reqRouter(filters) { - return new Map([[relayUrl.current, filters]]); + const routes = new Map(); + routes.set(relayUrl.current, filters); + + if (filters.every((f) => f.kinds?.every((k) => GIT_KINDS.includes(k)))) { + // If all filters are git-related, route to all git relays + for (const url of GIT_RELAYS) { + routes.set(url, filters); + } + } + return routes; }, - eventRouter(_event: NostrEvent) { + eventRouter(event: NostrEvent) { // Publish to the selected relay const allRelays = new Set([relayUrl.current]); + // If it's a git-related event, also publish to the git relays + if (GIT_KINDS.includes(event.kind)) { + for (const url of GIT_RELAYS) { + allRelays.add(url); + } + } + // Also publish to the preset relays, capped to 5 for (const { url } of (presetRelays ?? [])) { allRelays.add(url); diff --git a/src/lib/git.ts b/src/lib/git.ts index 4fb75145..776eb294 100644 --- a/src/lib/git.ts +++ b/src/lib/git.ts @@ -578,7 +578,7 @@ export class Git { console.log(`Getting remote info for Nostr repository: ${nostrUrl}`); // Fetch the repository announcement and state from Nostr - const { repo, state } = await this.fetchNostrRepo(nostrURI, AbortSignal.timeout(10000)); + const { repo, state } = await this.fetchNostrRepo(nostrURI); if (!repo) { throw new Error('Repository announcement not found on Nostr network'); @@ -689,6 +689,33 @@ export class Git { } } + // If no refs found, try to get the current branch directly + if (refTags.length === 0) { + try { + const currentBranch = await this.currentBranch({ dir }); + if (currentBranch) { + const currentCommit = await this.resolveRef({ dir, 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 this.resolveRef({ dir, 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 try { const headValue = await git.resolveRef({ @@ -864,7 +891,7 @@ export class Git { // Format: nostr://npub/relay/d return { pubkey, - relay: parts[1], + relay: `wss://${parts[1]}/`, d: parts[2], }; } else if (parts.length === 2) { @@ -881,59 +908,61 @@ export class Git { } } - private async fetchNostrRepo( - nostrURI: NostrCloneURI, - signal?: AbortSignal, - ): Promise<{ repo?: NostrEvent; state?: NostrEvent }> { + private async fetchNostrRepo(nostrURI: NostrCloneURI): Promise<{ repo?: NostrEvent; state?: NostrEvent }> { // Build the filter for both NIP-34 repository announcement and state events const filter = { kinds: [30617, 30618], authors: [nostrURI.pubkey], '#d': [nostrURI.d], - limit: 2, // We want both repo and state events if they exist }; - // Use a specific relay if provided, otherwise try git-focused relays - const client = nostrURI.relay - ? this.nostr.relay(nostrURI.relay) - : this.nostr.group([ - 'wss://git.shakespeare.diy/', - 'wss://relay.ngit.dev/', - 'wss://gitnostr.com/', - 'wss://relay.nostr.band/', // Fallback to general relay - ]); + const gitRelays = new Set([ + 'wss://git.shakespeare.diy/', + 'wss://relay.ngit.dev/', + 'wss://gitnostr.com/', + 'wss://relay.nostr.band/', // General purpose relay as fallback + ]); - try { - // Query for both repository announcement and state events - const events = await client.query([filter], { - signal: signal || AbortSignal.timeout(5000) - }); + let events: NostrEvent[] = []; - const repo = events.find((e) => e.kind === 30617); - const state = events.find((e) => e.kind === 30618); - - if (!repo) { - throw new Error('Repository announcement not found on Nostr network'); + // Try the specified relay first, then fall back to known Git relays + if (nostrURI.relay) { + try { + events = await this.nostr.relay(nostrURI.relay).query([filter], { signal: AbortSignal.timeout(1000) }); + } catch (error) { + console.error(`Error querying relay ${nostrURI.relay}: ${error}`); } - - if (state) { - console.log(`Found repository state event with ${state.tags.length} tags`); - } else { - console.log('No repository state event found, proceeding with basic clone'); - } - - return { repo, state }; - } catch (error) { - if (error instanceof Error) { - throw new Error(`Failed to fetch repository from Nostr: ${error.message}`); - } - throw new Error('Failed to fetch repository from Nostr network'); } + if (!events.length) { + try { + events = await this.nostr.group([...gitRelays]).query([filter], { signal: AbortSignal.timeout(5000) }); + } catch (error) { + console.error(`Error querying group relays: ${error}`); + } + } + if (!events.length) { + throw new Error('No events found for the specified Nostr repository'); + } + + const repo = events.find((e) => e.kind === 30617); + const state = events.find((e) => e.kind === 30618); + + if (!repo) { + throw new Error('Repository announcement not found on Nostr network'); + } + + if (state) { + console.log(`Found repository state event with ${state.tags.length} tags`); + } else { + console.log('No repository state event found, proceeding with basic clone'); + } + + return { repo, state }; } private async nostrClone(nostrURI: NostrCloneURI, options: Omit[0], 'fs' | 'http' | 'corsProxy'>): Promise { // Fetch events from Nostr - const { repo, state } = await this.fetchNostrRepo(nostrURI, AbortSignal.timeout(10000)); + const { repo, state } = await this.fetchNostrRepo(nostrURI); if (!repo) { throw new Error('Repository not found'); @@ -1163,7 +1192,7 @@ export class Git { console.log(`Fetching updates from Nostr repository: ${nostrUrl}`); // Fetch the latest repository state from Nostr - const { repo, state } = await this.fetchNostrRepo(nostrURI, AbortSignal.timeout(10000)); + const { repo, state } = await this.fetchNostrRepo(nostrURI); if (!repo) { throw new Error('Repository not found on Nostr network'); @@ -1337,7 +1366,7 @@ export class Git { console.log(`Pushing to Nostr repository: ${nostrUrl}`); // Fetch the repository announcement to get relay information and clone URLs - const { repo } = await this.fetchNostrRepo(nostrURI, AbortSignal.timeout(10000)); + const { repo } = await this.fetchNostrRepo(nostrURI); if (!repo) { throw new Error('Repository announcement not found on Nostr network'); } @@ -1346,17 +1375,28 @@ export class Git { const relayUrls: string[] = []; const cloneUrls: string[] = []; - for (const [name, value] of repo.tags) { - if (name === 'relays' && value) { - relayUrls.push(value); - } else if (name === 'clone' && value) { - try { - const url = new URL(value); - if (url.protocol === 'http:' || url.protocol === 'https:') { - cloneUrls.push(url.href); + for (const [name, ...values] of repo.tags) { + if (name === 'relays' && values.length > 0) { + for (const value of values) { + try { + const url = new URL(value); + if (url.protocol === 'wss:') { + relayUrls.push(url.href); + } + } catch { + // Ignore invalid URLs + } + } + } else if (name === 'clone' && values.length > 0) { + for (const value of values) { + try { + const url = new URL(value); + if (url.protocol === 'https:') { + cloneUrls.push(url.href); + } + } catch { + // Ignore invalid URLs } - } catch { - // Ignore invalid URLs } } } @@ -1375,26 +1415,22 @@ export class Git { const repoState = await this.getCurrentRepositoryState(dir); // Create repository state event (kind 30618) - const stateEvent: Omit = { + const stateEvent = await signer.signEvent({ kind: 30618, created_at: Math.floor(Date.now() / 1000), - pubkey: '', // Will be set by signer content: '', tags: [ ['d', nostrURI.d], // Repository identifier ...repoState.refTags, ...(repoState.headRef ? [['HEAD', repoState.headRef]] : []), ], - }; - - // Sign the event - const signedStateEvent = await signer.signEvent(stateEvent); + }); // Publish the state event to Nostr relays console.log(`Publishing repository state to ${relayUrls.length} relays`); try { - await this.nostr.group(relayUrls).event(signedStateEvent); + await this.nostr.group(relayUrls).event(stateEvent); console.log('✓ Repository state published to Nostr successfully'); } catch (error) { console.warn('Failed to publish repository state to some relays:', error); @@ -1407,63 +1443,34 @@ export class Git { return; } + // Wait 5 seconds for GRASP servers to update + await new Promise(resolve => setTimeout(resolve, 5000)); + let pushSuccessful = false; let lastError: Error | null = null; for (const cloneUrl of cloneUrls) { - try { - console.log(`Pushing to Git remote: ${cloneUrl}`); + console.log(`Pushing to Git remote: ${cloneUrl}`); - // Add a temporary remote for this clone URL - const tempRemoteName = `temp-push-${Date.now()}`; - await git.addRemote({ + try { + // Push to the temporary remote + await git.push({ fs: this.fs, + http, + corsProxy: this.corsProxy, dir, - remote: tempRemoteName, url: cloneUrl, + ...gitPushOptions, }); - try { - // Push to the temporary remote - await git.push({ - fs: this.fs, - http, - corsProxy: this.corsProxy, - dir, - remote: tempRemoteName, - ...gitPushOptions, - }); + pushSuccessful = true; + console.log(`✓ Successfully pushed to ${cloneUrl}`); - pushSuccessful = true; - console.log(`✓ Successfully pushed to ${cloneUrl}`); - - // Remove the temporary remote - await git.deleteRemote({ - fs: this.fs, - dir, - remote: tempRemoteName, - }); - - // If one push succeeds, we can break (unless we want to push to all remotes) - break; - } catch (pushError) { - console.warn(`Failed to push to ${cloneUrl}:`, pushError); - lastError = pushError instanceof Error ? pushError : new Error('Unknown push error'); - - // Clean up the temporary remote - try { - await git.deleteRemote({ - fs: this.fs, - dir, - remote: tempRemoteName, - }); - } catch { - // Ignore cleanup errors - } - } - } catch (error) { - console.warn(`Failed to set up remote for ${cloneUrl}:`, error); - lastError = error instanceof Error ? error : new Error('Unknown error'); + // If one push succeeds, we can break (unless we want to push to all remotes) + break; + } catch (pushError) { + console.warn(`Failed to push to ${cloneUrl}:`, pushError); + lastError = pushError instanceof Error ? pushError : new Error('Unknown push error'); } } @@ -1497,78 +1504,47 @@ export class Git { // Try to fetch missing commits from each Git remote for (const cloneUrl of cloneUrls) { - try { - console.log(`Fetching missing commits from: ${cloneUrl}`); + console.log(`Fetching missing commits from: ${cloneUrl}`); - // Add a temporary remote - const tempRemoteName = `temp-${Date.now()}`; - await git.addRemote({ + try { + // Fetch from the clone URL + await git.fetch({ fs: this.fs, + http, + corsProxy: this.corsProxy, dir, - remote: tempRemoteName, url: cloneUrl, }); - try { - // Fetch from the temporary remote - await git.fetch({ - fs: this.fs, - http, - corsProxy: this.corsProxy, - dir, - remote: tempRemoteName, - }); - - // Update our refs to match the Nostr state - for (const [refName, commitId] of Object.entries(refs)) { - try { - // Check if we now have this commit - await git.readCommit({ - fs: this.fs, - dir, - oid: commitId, - }); - - // Update the ref - await git.writeRef({ - fs: this.fs, - dir, - ref: refName, - value: commitId, - }); - - console.log(`✓ Updated ${refName} to ${commitId} after fetching`); - } catch { - // Still don't have this commit - console.warn(`Still missing commit ${commitId} for ${refName}`); - } - } - - // Remove the temporary remote - await git.deleteRemote({ - fs: this.fs, - dir, - remote: tempRemoteName, - }); - - // Successfully fetched from this remote - return; - } catch (fetchError) { - console.warn(`Failed to fetch from ${cloneUrl}:`, fetchError); - - // Clean up the temporary remote + // Update our refs to match the Nostr state + for (const [refName, commitId] of Object.entries(refs)) { try { - await git.deleteRemote({ + // Check if we now have this commit + await git.readCommit({ fs: this.fs, dir, - remote: tempRemoteName, + oid: commitId, }); + + // Update the ref + await git.writeRef({ + fs: this.fs, + dir, + ref: refName, + value: commitId, + }); + + console.log(`✓ Updated ${refName} to ${commitId} after fetching`); } catch { - // Ignore cleanup errors + // Still don't have this commit + console.warn(`Still missing commit ${commitId} for ${refName}`); } } - } catch (error) { - console.warn(`Failed to set up temporary remote for ${cloneUrl}:`, error); + + // Successfully fetched from this remote + return; + } catch (fetchError) { + console.warn(`Failed to fetch from ${cloneUrl}:`, fetchError); } } }