Add PR review and merge capabilities for repository owners

Implemented comprehensive PR management for repo owners across GitHub, GitLab, and Nostr:

**For Repository Owners (viewing their own repos):**
- See ALL incoming PRs/patches from contributors, not just their own
- "Review" button to checkout PR branch and preview changes live
- Merge button to merge PRs directly from UI
- Works for GitHub, GitLab, and Nostr repositories

**For Contributors (viewing others' repos):**
- See only their own PRs/patches
- "Merged" badge displayed when PR has been merged
- State tracking via NIP-34 status events (kind 1630-1633) for Nostr

**PR List Enhancements:**
- Show author (display "you" for own PRs, username for others)
- Color coding: green for open, purple for merged
- Conditional actions based on ownership and state
- Different section titles: "Incoming PRs/Patches" vs "Your PRs/Patches"

**Technical Implementation:**
- Extended usePullRequests to detect repo ownership via pubkey/username
- Query all PRs when user is owner, filter to user's PRs otherwise
- For Nostr: query status events to determine merged/closed state
- Updated MergeDialog to accept pre-filled source/target branches
- Added isOwner and authorPubkey fields to PullRequest interface

This enables full PR workflow in Shakespeare: review, preview, and merge contributions.
This commit is contained in:
shakespeare.diy committed 2025-10-15 00:56:08 -05:00
1 parent b88e2ab4f8
commit 0318a8c836
3 files changed
+200 -95

No files matched your search

+69 -16
View File
@@ -982,34 +982,87 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
{!isLoadingPRs && pullRequests && pullRequests.length > 0 && (
<div className="space-y-2 mb-3">
<div className="text-xs font-medium text-muted-foreground mb-2">
{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')
}
</div>
{pullRequests.map((pr) => (
<div
key={pr.id}
className="flex items-start gap-3 p-3 rounded-md border bg-muted/20 hover:bg-muted/40 transition-colors"
>
<GitPullRequest className="h-4 w-4 text-green-600 mt-0.5 shrink-0" />
<GitPullRequest className={cn(
"h-4 w-4 mt-0.5 shrink-0",
pr.state === 'merged' ? 'text-purple-600' : 'text-green-600'
)} />
<div className="flex-1 min-w-0">
<div className="flex items-start justify-between gap-2">
<div className="flex-1 min-w-0">
<h4 className="text-sm font-medium truncate">
{pr.title}
</h4>
<div className="flex items-center gap-2">
<h4 className="text-sm font-medium truncate">
{pr.title}
</h4>
{pr.state === 'merged' && (
<Badge variant="secondary" className="text-xs">
Merged
</Badge>
)}
</div>
<p className="text-xs text-muted-foreground mt-1">
#{pr.number} • {pr.sourceBranch} → {pr.targetBranch}
#{pr.number} by {pr.isOwner ? 'you' : pr.author} • {pr.sourceBranch} → {pr.targetBranch}
</p>
</div>
{!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 className="flex items-center gap-1">
{!pr.isOwner && pr.state === 'open' && (
<>
<Button
variant="ghost"
size="sm"
className="h-8"
onClick={async () => {
try {
await git.checkout({
dir: projectPath,
ref: pr.sourceBranch,
});
await refetchGitStatus();
toast({
title: 'Branch checked out',
description: `Switched to ${pr.sourceBranch}`,
});
} catch (err) {
toast({
title: 'Checkout failed',
description: err instanceof Error ? err.message : 'Unknown error',
variant: 'destructive',
});
}
}}
>
<GitBranch className="h-3 w-3 mr-1" />
Review
</Button>
<MergeDialog
projectId={projectId}
currentBranch={gitStatus.currentBranch}
sourceBranch={pr.sourceBranch}
targetBranch={pr.targetBranch}
onMergeComplete={refetchGitStatus}
/>
</>
)}
{!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>
</div>
+5 -1
View File
@@ -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<string[]>([]);
const [sourceBranch, setSourceBranch] = useState<string>('');
const [sourceBranch, setSourceBranch] = useState<string>(initialSourceBranch || '');
const [isLoadingBranches, setIsLoadingBranches] = useState(false);
const [isLoadingPreview, setIsLoadingPreview] = useState(false);
const [isMerging, setIsMerging] = useState(false);
+126 -78
View File
@@ -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<PullRequest[]> {
// 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<PullRequest[]> {
const url = `${info.apiUrl}/repos/${info.owner}/${info.repo}/pulls?state=open`;
const headers: Record<string, string> = {
'Accept': 'application/vnd.github.v3+json',
@@ -161,38 +142,20 @@ async function fetchGitHubPRs(info: RemoteInfo, token?: string): Promise<PullReq
createdAt: pr.created_at,
sourceBranch: pr.head.ref,
targetBranch: pr.base.ref,
isOwner: pr.user.login === currentUsername,
}));
// Filter to only show PRs created by the current user
if (currentUsername) {
// If repo owner, return all PRs. Otherwise, return only user's PRs
if (isRepoOwner) {
return allPRs;
} else if (currentUsername) {
return allPRs.filter((pr: PullRequest) => 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<PullRequest[]> {
// 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<PullRequest[]> {
// Get project ID first
const projectUrl = `${info.apiUrl}/projects/${encodeURIComponent(`${info.owner}/${info.repo}`)}`;
const projectHeaders: Record<string, string> = {};
@@ -235,14 +198,16 @@ async function fetchGitLabMRs(info: RemoteInfo, token?: string): Promise<PullReq
createdAt: mr.created_at,
sourceBranch: mr.source_branch,
targetBranch: mr.target_branch,
isOwner: mr.author.username === currentUsername,
}));
// Filter to only show MRs created by the current user
if (currentUsername) {
// If repo owner, return all MRs. Otherwise, return only user's MRs
if (isRepoOwner) {
return allMRs;
} else if (currentUsername) {
return allMRs.filter((mr: PullRequest) => 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<PullRequest[]> {
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<string, string>();
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: <branch>\nTo: <branch>..."
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,