diff --git a/src/components/GitDialog.tsx b/src/components/GitDialog.tsx index 4e5aea1f..ad580a52 100644 --- a/src/components/GitDialog.tsx +++ b/src/components/GitDialog.tsx @@ -982,34 +982,87 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog {!isLoadingPRs && pullRequests && pullRequests.length > 0 && (
- {originUrl.startsWith('nostr://') ? 'Your Patches' : 'Your Open PRs'} + {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.title} +

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

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

- {!originUrl.startsWith('nostr://') && ( - - )} +
+ {!pr.isOwner && pr.state === 'open' && ( + <> + + + + )} + {!originUrl.startsWith('nostr://') && ( + + )} +
diff --git a/src/components/git/MergeDialog.tsx b/src/components/git/MergeDialog.tsx index 01669581..23cbe8cc 100644 --- a/src/components/git/MergeDialog.tsx +++ b/src/components/git/MergeDialog.tsx @@ -35,6 +35,8 @@ import { useSearchParams } from 'react-router-dom'; interface MergeDialogProps { projectId: string; currentBranch: string | null; + sourceBranch?: string; + targetBranch?: string; open?: boolean; onOpenChange?: (open: boolean) => void; onMergeComplete?: () => void; @@ -58,13 +60,15 @@ interface MergePreview { export function MergeDialog({ projectId, currentBranch, + sourceBranch: initialSourceBranch, + targetBranch: initialTargetBranch, open, onOpenChange, onMergeComplete, }: MergeDialogProps) { const [isOpen, setIsOpen] = useState(open ?? false); const [branches, setBranches] = useState([]); - const [sourceBranch, setSourceBranch] = useState(''); + const [sourceBranch, setSourceBranch] = useState(initialSourceBranch || ''); const [isLoadingBranches, setIsLoadingBranches] = useState(false); const [isLoadingPreview, setIsLoadingPreview] = useState(false); const [isMerging, setIsMerging] = useState(false); diff --git a/src/hooks/usePullRequests.ts b/src/hooks/usePullRequests.ts index a70e431e..0d0af650 100644 --- a/src/hooks/usePullRequests.ts +++ b/src/hooks/usePullRequests.ts @@ -6,16 +6,18 @@ import { findCredentialsForRepo } from '@/lib/gitCredentials'; import { nip19 } from 'nostr-tools'; import type { NostrEvent } from '@nostrify/nostrify'; -interface PullRequest { +export interface PullRequest { id: number | string; number: number | string; title: string; state: 'open' | 'closed' | 'merged'; author: string; + authorPubkey?: string; // For Nostr patches url: string; createdAt: string; sourceBranch: string; targetBranch: string; + isOwner?: boolean; // Whether current user is the PR creator } interface RemoteInfo { @@ -112,28 +114,7 @@ function parseRemoteUrl(url: string): RemoteInfo | null { } } -async function fetchGitHubPRs(info: RemoteInfo, token?: string): Promise { - // First get the current user if we have a token - let currentUsername: string | null = null; - - if (token) { - try { - const userResponse = await fetch(`${info.apiUrl}/user`, { - headers: { - 'Authorization': `token ${token}`, - 'Accept': 'application/vnd.github.v3+json', - }, - }); - - if (userResponse.ok) { - const userData = await userResponse.json(); - currentUsername = userData.login; - } - } catch (error) { - console.warn('Failed to fetch current GitHub user:', error); - } - } - +async function fetchGitHubPRs(info: RemoteInfo, token?: string, currentUsername?: string, isRepoOwner?: boolean): Promise { const url = `${info.apiUrl}/repos/${info.owner}/${info.repo}/pulls?state=open`; const headers: Record = { 'Accept': 'application/vnd.github.v3+json', @@ -161,38 +142,20 @@ async function fetchGitHubPRs(info: RemoteInfo, token?: string): Promise pr.author === currentUsername); } - // If no token/username, return empty array (can't determine which PRs are theirs) return []; } -async function fetchGitLabMRs(info: RemoteInfo, token?: string): Promise { - // First get the current user if we have a token - let currentUsername: string | null = null; - - if (token) { - try { - const userResponse = await fetch(`${info.apiUrl}/user`, { - headers: { - 'PRIVATE-TOKEN': token, - }, - }); - - if (userResponse.ok) { - const userData = await userResponse.json(); - currentUsername = userData.username; - } - } catch (error) { - console.warn('Failed to fetch current GitLab user:', error); - } - } - +async function fetchGitLabMRs(info: RemoteInfo, token?: string, currentUsername?: string, isRepoOwner?: boolean): Promise { // Get project ID first const projectUrl = `${info.apiUrl}/projects/${encodeURIComponent(`${info.owner}/${info.repo}`)}`; const projectHeaders: Record = {}; @@ -235,14 +198,16 @@ async function fetchGitLabMRs(info: RemoteInfo, token?: string): Promise mr.author === currentUsername); } - // If no token/username, return empty array (can't determine which MRs are theirs) return []; } @@ -250,52 +215,80 @@ async function fetchNostrPatches( info: RemoteInfo, currentUserPubkey: string | undefined, nostr: any, - signal: AbortSignal + signal: AbortSignal, + isRepoOwner?: boolean ): Promise { console.log('=== FETCHING NOSTR PATCHES ==='); console.log('Repository:', `${info.owner}/${info.repo}`); console.log('Current user pubkey:', currentUserPubkey); + console.log('Is repo owner:', isRepoOwner); - if (!currentUserPubkey) { + if (!currentUserPubkey && !isRepoOwner) { 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:', { + // Build query filter based on whether user is repo owner or contributor + const filter: any = { kinds: [1617], - authors: [currentUserPubkey], '#a': [`30617:${info.owner}:${info.repo}`], - }); + limit: 50, + }; - const patches = await nostr.query([ - { - kinds: [1617], - authors: [currentUserPubkey], - '#a': [`30617:${info.owner}:${info.repo}`], - limit: 50, - } - ], { signal }); + // If not repo owner, only fetch user's own patches + if (!isRepoOwner && currentUserPubkey) { + filter.authors = [currentUserPubkey]; + } - console.log(`Found ${patches.length} patches for current user`); + console.log('Querying patches with filter:', filter); + + const patches = await nostr.query([filter], { signal }); + + console.log(`Found ${patches.length} patches`); if (patches.length > 0) { console.log('Sample patch:', patches[0]); } + // Query for status events (kind 1630-1633) to determine patch state + const patchIds = patches.map((p: NostrEvent) => p.id); + let statusEvents: NostrEvent[] = []; + + if (patchIds.length > 0) { + statusEvents = await nostr.query([ + { + kinds: [1630, 1631, 1632, 1633], // Open, Applied/Merged, Closed, Draft + '#e': patchIds, + } + ], { signal }); + console.log(`Found ${statusEvents.length} status events`); + } + + // Build a map of patch ID to latest status + const patchStatus = new Map(); + statusEvents.forEach((statusEvent: NostrEvent) => { + const patchId = statusEvent.tags.find(t => t[0] === 'e' && t[3] === 'root')?.[1]; + if (patchId) { + // Status event kinds: 1630=Open, 1631=Applied/Merged, 1632=Closed, 1633=Draft + const status = statusEvent.kind === 1631 ? 'merged' : statusEvent.kind === 1632 ? 'closed' : 'open'; + + // Only update if we don't have a status or this event is newer + const existing = patchStatus.get(patchId); + if (!existing || statusEvent.created_at > (statusEvents.find(e => e.tags.find(t => t[1] === patchId))?.created_at || 0)) { + patchStatus.set(patchId, status); + } + } + }); + // 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'; + // Get status from status events, default to 'open' + const state = patchStatus.get(patch.id) || 'open'; // Extract source/target branches from content if available - // Patch content format: "From: \nTo: ..." const contentLines = patch.content.split('\n'); let sourceBranch = 'unknown'; let targetBranch = 'main'; @@ -311,14 +304,16 @@ async function fetchNostrPatches( return { id: patch.id, - number: patch.id.slice(0, 8), // Use first 8 chars of event ID as number + number: patch.id.slice(0, 8), title: subject, state: state as 'open' | 'closed' | 'merged', author: nip19.npubEncode(patch.pubkey), - url: `nostr:${patch.id}`, // Event reference + authorPubkey: patch.pubkey, + url: `nostr:${patch.id}`, createdAt: new Date(patch.created_at * 1000).toISOString(), sourceBranch, targetBranch, + isOwner: patch.pubkey === currentUserPubkey, }; }); @@ -348,19 +343,72 @@ export function usePullRequests(remoteUrl?: string) { throw new Error('Invalid remote URL format'); } - // Fetch PRs based on platform + // Determine if current user is the repo owner + let isRepoOwner = false; + let currentUsername: string | undefined; + if (remoteInfo.platform === 'nostr') { - return await fetchNostrPatches(remoteInfo, user?.pubkey, nostr, signal); + // For Nostr, check if user's pubkey matches repo owner + isRepoOwner = user?.pubkey === remoteInfo.owner; } else if (remoteInfo.platform === 'github') { - // Get credentials if available + // For GitHub, fetch current username const credentials = findCredentialsForRepo(remoteUrl, settings.credentials); const token = credentials?.password; - return await fetchGitHubPRs(remoteInfo, token); + + if (token) { + try { + const userResponse = await fetch(`${remoteInfo.apiUrl}/user`, { + headers: { + 'Authorization': `token ${token}`, + 'Accept': 'application/vnd.github.v3+json', + }, + }); + if (userResponse.ok) { + const userData = await userResponse.json(); + currentUsername = userData.login; + isRepoOwner = currentUsername === remoteInfo.owner; + } + } catch (error) { + console.warn('Failed to fetch current GitHub user:', error); + } + } } else { // GitLab const credentials = findCredentialsForRepo(remoteUrl, settings.credentials); const token = credentials?.password; - return await fetchGitLabMRs(remoteInfo, token); + + if (token) { + try { + const userResponse = await fetch(`${remoteInfo.apiUrl}/user`, { + headers: { + 'PRIVATE-TOKEN': token, + }, + }); + if (userResponse.ok) { + const userData = await userResponse.json(); + currentUsername = userData.username; + isRepoOwner = currentUsername === remoteInfo.owner; + } + } catch (error) { + console.warn('Failed to fetch current GitLab user:', error); + } + } + } + + console.log('Fetching PRs - isRepoOwner:', isRepoOwner, 'currentUser:', currentUsername || user?.pubkey); + + // Fetch PRs based on platform + if (remoteInfo.platform === 'nostr') { + return await fetchNostrPatches(remoteInfo, user?.pubkey, nostr, signal, isRepoOwner); + } else if (remoteInfo.platform === 'github') { + const credentials = findCredentialsForRepo(remoteUrl, settings.credentials); + const token = credentials?.password; + return await fetchGitHubPRs(remoteInfo, token, currentUsername, isRepoOwner); + } else { + // GitLab + const credentials = findCredentialsForRepo(remoteUrl, settings.credentials); + const token = credentials?.password; + return await fetchGitLabMRs(remoteInfo, token, currentUsername, isRepoOwner); } }, enabled: !!remoteUrl,