Add Nostr patch display and enhanced debugging for git operations

Extended usePullRequests hook to fetch and display Nostr patches (kind 1617):
- Parse nostr:// URLs with npub/hex pubkey support
- Query patches created by current user using #a tag filter
- Convert patch events to PullRequest format for unified display
- Extract source/target branches from patch content

Updated GitDialog to show Nostr patches:
- Display "Your Patches" section for Nostr repos (like GitHub/GitLab PRs)
- Show patch title, number (first 8 chars of event ID), and branches
- Remove external link button for Nostr (event references aren't clickable URLs)

Enhanced debugging for troubleshooting patch discovery issues:
- Log repository announcement query filter and results
- Log event coordinates and relay information
- Provide verification instructions after publishing announcements
- Warn when repository announcement not found with helpful context

This helps diagnose why patches aren't showing in NostrHub - likely due to:
1. Repository announcement not published to same relay
2. Different relays between Shakespeare and NostrHub
3. Relay propagation delays
This commit is contained in:
shakespeare.diy committed 2025-10-15 00:27:37 -05:00
1 parent 166c2eb72c
commit 37fb176ea1
4 files changed
+167 -22

No files matched your search

+15 -11
View File
@@ -980,9 +980,11 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
Loading pull requests...
</div>
)}
{!originUrl.startsWith('nostr://') && !isLoadingPRs && pullRequests && pullRequests.length > 0 && (
{!isLoadingPRs && pullRequests && pullRequests.length > 0 && (
<div className="space-y-2 mb-3">
<div className="text-xs font-medium text-muted-foreground mb-2">Your Open PRs</div>
<div className="text-xs font-medium text-muted-foreground mb-2">
{originUrl.startsWith('nostr://') ? 'Your Patches' : 'Your Open PRs'}
</div>
{pullRequests.map((pr) => (
<div
key={pr.id}
@@ -996,17 +998,19 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
{pr.title}
</h4>
<p className="text-xs text-muted-foreground mt-1">
#{pr.number} by {pr.author} • {pr.sourceBranch} → {pr.targetBranch}
#{pr.number} • {pr.sourceBranch} → {pr.targetBranch}
</p>
</div>
<Button
variant="ghost"
size="sm"
className="h-8 shrink-0"
onClick={() => window.open(pr.url, '_blank')}
>
<ExternalLink className="h-3 w-3" />
</Button>
{!originUrl.startsWith('nostr://') && (
<Button
variant="ghost"
size="sm"
className="h-8 shrink-0"
onClick={() => window.open(pr.url, '_blank')}
>
<ExternalLink className="h-3 w-3" />
</Button>
)}
</div>
</div>
</div>
@@ -221,17 +221,22 @@ export function AnnounceRepositoryDialog({
created_at: Math.floor(Date.now() / 1000),
};
console.log('Creating repository announcement:', repoEvent);
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
await nostr.event(signedEvent);
console.log('Published repository announcement to Nostr');
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({
+16
View File
@@ -683,6 +683,13 @@ export function PullRequestDialog({
}
// Query for the repository announcement to get earliest unique commit (euc)
console.log('Querying for repository announcement with filter:', {
kinds: [30617],
authors: [info.owner],
'#d': [info.repo],
limit: 1,
});
const repoEvents = await nostr.query([
{
kinds: [30617],
@@ -692,17 +699,22 @@ export function PullRequestDialog({
}
]);
console.log(`Repository announcement query returned ${repoEvents.length} events`);
let earliestUniqueCommit: string | null = null;
let publishRelays = ['wss://relay.nostr.band']; // Default relay
if (repoEvents.length > 0) {
const repoEvent = repoEvents[0];
console.log('Found repository announcement event:', repoEvent);
// Get earliest unique commit from repository announcement
const eucTag = repoEvent.tags.find((t: string[]) => t[0] === 'r' && t[2] === 'euc');
if (eucTag) {
earliestUniqueCommit = eucTag[1];
console.log('Found earliest unique commit:', earliestUniqueCommit);
} else {
console.warn('No euc tag found in repository announcement');
}
// Get relay hints from repository announcement
@@ -710,9 +722,13 @@ export function PullRequestDialog({
if (relayTags.length > 0) {
publishRelays = relayTags.map((t: string[]) => t[1]);
console.log('Publishing to repository relays:', publishRelays);
} else {
console.log('No relay hints in repository announcement, using default relay');
}
} else {
console.warn('Repository announcement not found - patch may not be discoverable');
console.warn('Make sure to use "Announce Repository" button first to create kind 30617 event');
console.warn('The announcement must be on the same relay you are currently connected to');
}
// Generate git format-patch style content
+129 -9
View File
@@ -1,10 +1,14 @@
import { useQuery } from '@tanstack/react-query';
import { useGitSettings } from '@/hooks/useGitSettings';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNostr } from '@nostrify/react';
import { findCredentialsForRepo } from '@/lib/gitCredentials';
import { nip19 } from 'nostr-tools';
import type { NostrEvent } from '@nostrify/nostrify';
interface PullRequest {
id: number;
number: number;
id: number | string;
number: number | string;
title: string;
state: 'open' | 'closed' | 'merged';
author: string;
@@ -17,12 +21,37 @@ interface PullRequest {
interface RemoteInfo {
owner: string;
repo: string;
platform: 'github' | 'gitlab';
platform: 'github' | 'gitlab' | 'nostr';
apiUrl: string;
}
function parseRemoteUrl(url: string): RemoteInfo | null {
try {
// Nostr git: nostr://<pubkey>/<repo-id>
if (url.startsWith('nostr://')) {
const match = url.match(/^nostr:\/\/([^/]+)\/(.+)$/);
if (match) {
let pubkeyOrNpub = match[1];
const repo = match[2];
// Convert npub to hex if needed
let owner = pubkeyOrNpub;
if (pubkeyOrNpub.startsWith('npub1')) {
try {
const decoded = nip19.decode(pubkeyOrNpub);
if (decoded.type === 'npub') {
owner = decoded.data; // hex pubkey
}
} catch (err) {
console.error('Failed to decode npub:', err);
return null;
}
}
return { owner, repo, platform: 'nostr', apiUrl: '' };
}
}
// Normalize URL - remove .git suffix if present
const normalizedUrl = url.replace(/\.git$/, '');
let match;
@@ -217,11 +246,98 @@ async function fetchGitLabMRs(info: RemoteInfo, token?: string): Promise<PullReq
return [];
}
async function fetchNostrPatches(
info: RemoteInfo,
currentUserPubkey: string | undefined,
nostr: any,
signal: AbortSignal
): Promise<PullRequest[]> {
console.log('=== FETCHING NOSTR PATCHES ===');
console.log('Repository:', `${info.owner}/${info.repo}`);
console.log('Current user pubkey:', currentUserPubkey);
if (!currentUserPubkey) {
console.log('No current user, returning empty array');
return [];
}
try {
// Query for patches (kind 1617) for this repository created by current user
console.log('Querying patches with filter:', {
kinds: [1617],
authors: [currentUserPubkey],
'#a': [`30617:${info.owner}:${info.repo}`],
});
const patches = await nostr.query([
{
kinds: [1617],
authors: [currentUserPubkey],
'#a': [`30617:${info.owner}:${info.repo}`],
limit: 50,
}
], { signal });
console.log(`Found ${patches.length} patches for current user`);
if (patches.length > 0) {
console.log('Sample patch:', patches[0]);
}
// Convert Nostr patches to PullRequest format
const pullRequests: PullRequest[] = patches.map((patch: NostrEvent) => {
const subject = patch.tags.find(t => t[0] === 'subject')?.[1] || 'Untitled patch';
// Check if it's a root patch (unmerged/open)
const isRoot = patch.tags.some(t => t[0] === 't' && t[1] === 'root');
// For now, assume all patches are open (we'd need to query status events to know if merged/closed)
const state = 'open';
// Extract source/target branches from content if available
// Patch content format: "From: <branch>\nTo: <branch>..."
const contentLines = patch.content.split('\n');
let sourceBranch = 'unknown';
let targetBranch = 'main';
for (const line of contentLines) {
if (line.startsWith('From:')) {
sourceBranch = line.replace('From:', '').trim();
}
if (line.startsWith('To:')) {
targetBranch = line.replace('To:', '').trim();
}
}
return {
id: patch.id,
number: patch.id.slice(0, 8), // Use first 8 chars of event ID as number
title: subject,
state: state as 'open' | 'closed' | 'merged',
author: nip19.npubEncode(patch.pubkey),
url: `nostr:${patch.id}`, // Event reference
createdAt: new Date(patch.created_at * 1000).toISOString(),
sourceBranch,
targetBranch,
};
});
console.log('Converted patches to PRs:', pullRequests);
return pullRequests;
} catch (error) {
console.error('Failed to fetch Nostr patches:', error);
throw error;
}
}
export function usePullRequests(remoteUrl?: string) {
const { settings } = useGitSettings();
const { user } = useCurrentUser();
const { nostr } = useNostr();
return useQuery({
queryKey: ['pull-requests', remoteUrl],
queryKey: ['pull-requests', remoteUrl, user?.pubkey],
queryFn: async ({ signal }) => {
if (!remoteUrl) {
return [];
@@ -232,14 +348,18 @@ export function usePullRequests(remoteUrl?: string) {
throw new Error('Invalid remote URL format');
}
// Get credentials if available
const credentials = findCredentialsForRepo(remoteUrl, settings.credentials);
const token = credentials?.password;
// Fetch PRs based on platform
if (remoteInfo.platform === 'github') {
if (remoteInfo.platform === 'nostr') {
return await fetchNostrPatches(remoteInfo, user?.pubkey, nostr, signal);
} else if (remoteInfo.platform === 'github') {
// Get credentials if available
const credentials = findCredentialsForRepo(remoteUrl, settings.credentials);
const token = credentials?.password;
return await fetchGitHubPRs(remoteInfo, token);
} else {
// GitLab
const credentials = findCredentialsForRepo(remoteUrl, settings.credentials);
const token = credentials?.password;
return await fetchGitLabMRs(remoteInfo, token);
}
},