From 4ad315f9643c4c4c796e74dc74698fbbfc214524 Mon Sep 17 00:00:00 2001 From: "shakespeare.diy" Date: Tue, 14 Oct 2025 20:51:53 -0500 Subject: [PATCH 01/43] feat: Auto-switch to new branch when no uncommitted changes Modified BranchManager to automatically switch to newly created branch if there are no uncommitted changes. If there are uncommitted changes, the branch is created but the user stays on the current branch with a helpful message to commit changes first. Changes: - Added useGitStatus hook to check for uncommitted changes - Updated handleCreateBranch to auto-checkout new branch when safe - Added conditional toast messages based on uncommitted changes state --- src/components/git/BranchManager.tsx | 38 ++++++++++++++++++++++++---- 1 file changed, 33 insertions(+), 5 deletions(-) diff --git a/src/components/git/BranchManager.tsx b/src/components/git/BranchManager.tsx index 42e8b42e..8050047f 100644 --- a/src/components/git/BranchManager.tsx +++ b/src/components/git/BranchManager.tsx @@ -30,6 +30,7 @@ import { ArrowUpRight, } from 'lucide-react'; import { useGit } from '@/hooks/useGit'; +import { useGitStatus } from '@/hooks/useGitStatus'; import { useToast } from '@/hooks/useToast'; import { cn } from '@/lib/utils'; @@ -60,6 +61,7 @@ export function BranchManager({ projectId, currentBranch, onBranchChange }: Bran const { git } = useGit(); const { toast } = useToast(); + const { data: gitStatus } = useGitStatus(projectId); const projectPath = `/projects/${projectId}`; const loadBranches = useCallback(async () => { @@ -179,16 +181,42 @@ export function BranchManager({ projectId, currentBranch, onBranchChange }: Bran }); // Create the new branch + const branchName = newBranchName.trim(); await git.branch({ dir: projectPath, - ref: newBranchName.trim(), + ref: branchName, object: currentRef, }); - toast({ - title: 'Branch created', - description: `Created branch "${newBranchName}"`, - }); + // Check if we can automatically switch to the new branch + const hasUncommittedChanges = gitStatus?.hasUncommittedChanges ?? false; + + if (!hasUncommittedChanges) { + // No uncommitted changes, automatically switch to the new branch + try { + await git.checkout({ + dir: projectPath, + ref: branchName, + }); + + toast({ + title: 'Branch created and switched', + description: `Created and switched to branch "${branchName}"`, + }); + } catch (checkoutError) { + // Branch created but checkout failed + toast({ + title: 'Branch created', + description: `Created branch "${branchName}" but failed to switch to it`, + }); + } + } else { + // Has uncommitted changes, don't switch automatically + toast({ + title: 'Branch created', + description: `Created branch "${branchName}". Commit your changes to switch to it.`, + }); + } setNewBranchName(''); setIsCreateDialogOpen(false); From 1bbe210f4fd614e24c12defab8dd0907beb07e0f Mon Sep 17 00:00:00 2001 From: "shakespeare.diy" Date: Tue, 14 Oct 2025 20:55:03 -0500 Subject: [PATCH 02/43] fix: Check git status directly when creating branch Updated handleCreateBranch to check git status matrix directly instead of relying on potentially stale gitStatus hook data. This ensures accurate detection of uncommitted changes at the time of branch creation. The branch will now properly auto-switch when there are no uncommitted changes, and stay on the current branch only when changes exist. --- src/components/git/BranchManager.tsx | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/src/components/git/BranchManager.tsx b/src/components/git/BranchManager.tsx index 8050047f..15fee5ef 100644 --- a/src/components/git/BranchManager.tsx +++ b/src/components/git/BranchManager.tsx @@ -188,8 +188,20 @@ export function BranchManager({ projectId, currentBranch, onBranchChange }: Bran object: currentRef, }); - // Check if we can automatically switch to the new branch - const hasUncommittedChanges = gitStatus?.hasUncommittedChanges ?? false; + // Check if we have uncommitted changes by getting status directly + const statusMatrix = await git.statusMatrix({ + dir: projectPath, + }); + + // Check if any files have changes (modified, added, deleted, or untracked) + const hasUncommittedChanges = statusMatrix.some(([, headStatus, workdirStatus, stageStatus]) => { + // No changes if all statuses match and file exists in HEAD + if (headStatus === workdirStatus && workdirStatus === stageStatus) { + return false; + } + // File has changes + return true; + }); if (!hasUncommittedChanges) { // No uncommitted changes, automatically switch to the new branch From 2ecb67e08293bfa2007ff1e54eaac4bd35609c1d Mon Sep 17 00:00:00 2001 From: "shakespeare.diy" Date: Tue, 14 Oct 2025 21:04:05 -0500 Subject: [PATCH 03/43] fix: Always switch to new branch after creation Removed the uncommitted changes check - now always attempts to checkout the new branch immediately after creation. If checkout fails, shows an error message with the reason. This ensures users are always switched to their newly created branch. --- src/components/git/BranchManager.tsx | 31 ++++++++++++++-------------- 1 file changed, 15 insertions(+), 16 deletions(-) diff --git a/src/components/git/BranchManager.tsx b/src/components/git/BranchManager.tsx index 15fee5ef..005051ec 100644 --- a/src/components/git/BranchManager.tsx +++ b/src/components/git/BranchManager.tsx @@ -203,30 +203,29 @@ export function BranchManager({ projectId, currentBranch, onBranchChange }: Bran return true; }); - if (!hasUncommittedChanges) { - // No uncommitted changes, automatically switch to the new branch - try { - await git.checkout({ - dir: projectPath, - ref: branchName, - }); + // Always try to switch to the new branch + try { + await git.checkout({ + dir: projectPath, + ref: branchName, + }); + if (hasUncommittedChanges) { + toast({ + title: 'Branch created and switched', + description: `Switched to "${branchName}" with uncommitted changes`, + }); + } else { toast({ title: 'Branch created and switched', description: `Created and switched to branch "${branchName}"`, }); - } catch (checkoutError) { - // Branch created but checkout failed - toast({ - title: 'Branch created', - description: `Created branch "${branchName}" but failed to switch to it`, - }); } - } else { - // Has uncommitted changes, don't switch automatically + } catch (checkoutError) { + // Branch created but checkout failed toast({ title: 'Branch created', - description: `Created branch "${branchName}". Commit your changes to switch to it.`, + description: `Created "${branchName}" but could not switch: ${checkoutError instanceof Error ? checkoutError.message : 'Unknown error'}`, }); } From 4226159f5d5fb14736172754deea8f0615aac8d9 Mon Sep 17 00:00:00 2001 From: "shakespeare.diy" Date: Tue, 14 Oct 2025 21:08:37 -0500 Subject: [PATCH 04/43] Revert to e4c3fc8: Make git identity configurable in settings This reverts the codebase back to the state at commit e4c3fc8. Reverted 3 commit(s): - 2ecb67e: fix: Always switch to new branch after creation - 1bbe210: fix: Check git status directly when creating branch - 4ad315f: feat: Auto-switch to new branch when no uncommitted changes --- src/components/git/BranchManager.tsx | 47 +++------------------------- 1 file changed, 4 insertions(+), 43 deletions(-) diff --git a/src/components/git/BranchManager.tsx b/src/components/git/BranchManager.tsx index 005051ec..42e8b42e 100644 --- a/src/components/git/BranchManager.tsx +++ b/src/components/git/BranchManager.tsx @@ -30,7 +30,6 @@ import { ArrowUpRight, } from 'lucide-react'; import { useGit } from '@/hooks/useGit'; -import { useGitStatus } from '@/hooks/useGitStatus'; import { useToast } from '@/hooks/useToast'; import { cn } from '@/lib/utils'; @@ -61,7 +60,6 @@ export function BranchManager({ projectId, currentBranch, onBranchChange }: Bran const { git } = useGit(); const { toast } = useToast(); - const { data: gitStatus } = useGitStatus(projectId); const projectPath = `/projects/${projectId}`; const loadBranches = useCallback(async () => { @@ -181,54 +179,17 @@ export function BranchManager({ projectId, currentBranch, onBranchChange }: Bran }); // Create the new branch - const branchName = newBranchName.trim(); await git.branch({ dir: projectPath, - ref: branchName, + ref: newBranchName.trim(), object: currentRef, }); - // Check if we have uncommitted changes by getting status directly - const statusMatrix = await git.statusMatrix({ - dir: projectPath, + toast({ + title: 'Branch created', + description: `Created branch "${newBranchName}"`, }); - // Check if any files have changes (modified, added, deleted, or untracked) - const hasUncommittedChanges = statusMatrix.some(([, headStatus, workdirStatus, stageStatus]) => { - // No changes if all statuses match and file exists in HEAD - if (headStatus === workdirStatus && workdirStatus === stageStatus) { - return false; - } - // File has changes - return true; - }); - - // Always try to switch to the new branch - try { - await git.checkout({ - dir: projectPath, - ref: branchName, - }); - - if (hasUncommittedChanges) { - toast({ - title: 'Branch created and switched', - description: `Switched to "${branchName}" with uncommitted changes`, - }); - } else { - toast({ - title: 'Branch created and switched', - description: `Created and switched to branch "${branchName}"`, - }); - } - } catch (checkoutError) { - // Branch created but checkout failed - toast({ - title: 'Branch created', - description: `Created "${branchName}" but could not switch: ${checkoutError instanceof Error ? checkoutError.message : 'Unknown error'}`, - }); - } - setNewBranchName(''); setIsCreateDialogOpen(false); await loadBranches(); From add685257bcda8d43abf8d81b6b5d17dfb686be2 Mon Sep 17 00:00:00 2001 From: "shakespeare.diy" Date: Tue, 14 Oct 2025 21:29:15 -0500 Subject: [PATCH 05/43] Add upstream PR contribution system MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Implements a complete workflow for non-technical users to contribute to open source projects: **New Features:** - ContributeButton component shows "Propose Changes" when project has upstream remote - ContributeWizard guides users through 5-step contribution process - PRStatusBadge shows existing PR status for current branch - Automatic forking when user lacks push permissions - OAuth and PAT authentication for GitHub, GitLab, Gitea/Codeberg - Pre-submission validation (type check + build) - Automatic remote configuration (upstream/origin) - PR creation and updates via Git host APIs **Git Host Abstraction:** - GitHostProvider interface for platform-agnostic operations - GitHubProvider with GitHub REST API v3 - GitLabProvider with GitLab REST API v4 - GiteaProvider for Gitea/Forgejo/Codeberg instances - Auto-detection of Git host from repository URL **Components:** - components/contribute/ContributeButton.tsx - Entry point button - components/contribute/ContributeWizard.tsx - Multi-step wizard UI - components/contribute/AuthStep.tsx - Authentication flow - components/contribute/DiffView.tsx - Changed files review - components/contribute/PRStatusBadge.tsx - PR status display **Hooks:** - hooks/useContribute.ts - Main contribution workflow orchestration **Context Updates:** - Extended GitSettings to include hostTokens for API authentication - Updated GitHubOAuth to save tokens in both formats **Integration:** - Added to ProjectView header (mobile and desktop) - Integrated with existing Git workflow - Works with existing OAuth callback system **Documentation:** - CONTRIBUTING_GUIDE.md with user guide and developer docs The system handles the entire fork → branch → commit → push → PR flow transparently, making open source contribution accessible to users without Git knowledge. --- CONTRIBUTING_GUIDE.md | 357 +++++++++++++++ src/components/GitSettingsProvider.tsx | 39 +- src/components/contribute/AuthStep.tsx | 174 ++++++++ .../contribute/ContributeButton.tsx | 65 +++ .../contribute/ContributeWizard.tsx | 406 ++++++++++++++++++ src/components/contribute/DiffView.tsx | 141 ++++++ src/components/contribute/PRStatusBadge.tsx | 157 +++++++ src/components/contribute/index.ts | 5 + src/contexts/GitSettingsContext.ts | 11 + src/hooks/useContribute.ts | 367 ++++++++++++++++ src/hooks/useGitHubOAuth.ts | 14 +- src/lib/configUtils.ts | 16 +- src/lib/git-hosts/GitHubProvider.ts | 234 ++++++++++ src/lib/git-hosts/GitLabProvider.ts | 254 +++++++++++ src/lib/git-hosts/GiteaProvider.ts | 223 ++++++++++ src/lib/git-hosts/index.ts | 45 ++ src/lib/git-hosts/types.ts | 152 +++++++ src/pages/ProjectView.tsx | 15 +- 18 files changed, 2670 insertions(+), 5 deletions(-) create mode 100644 CONTRIBUTING_GUIDE.md create mode 100644 src/components/contribute/AuthStep.tsx create mode 100644 src/components/contribute/ContributeButton.tsx create mode 100644 src/components/contribute/ContributeWizard.tsx create mode 100644 src/components/contribute/DiffView.tsx create mode 100644 src/components/contribute/PRStatusBadge.tsx create mode 100644 src/components/contribute/index.ts create mode 100644 src/hooks/useContribute.ts create mode 100644 src/lib/git-hosts/GitHubProvider.ts create mode 100644 src/lib/git-hosts/GitLabProvider.ts create mode 100644 src/lib/git-hosts/GiteaProvider.ts create mode 100644 src/lib/git-hosts/index.ts create mode 100644 src/lib/git-hosts/types.ts diff --git a/CONTRIBUTING_GUIDE.md b/CONTRIBUTING_GUIDE.md new file mode 100644 index 00000000..03bb63be --- /dev/null +++ b/CONTRIBUTING_GUIDE.md @@ -0,0 +1,357 @@ +# Contributing to Open Source Projects from Shakespeare + +Shakespeare now includes a complete contribution workflow that allows anyone to propose changes to open source projects without needing to understand Git, forks, or pull requests. + +## Overview + +The contribution system handles the entire process of submitting changes to upstream repositories: + +1. **Authentication** - Connect to GitHub, GitLab, or Gitea/Codeberg +2. **Review Changes** - See what files you've modified +3. **Branch & Commit** - Describe your changes +4. **Validation** - Automatic build and type checks +5. **Fork & Push** - Automatic forking and pushing (if needed) +6. **Pull Request** - Create or update PRs with one click + +## For Users: How to Contribute + +### Step 1: Make Your Changes + +Edit any project in Shakespeare that was cloned from a Git repository. Make your changes using the AI assistant or code editor. + +### Step 2: Click "Propose Changes" + +When you're ready to submit your changes: + +1. Look for the **"Propose Changes"** button in the project header +2. Click it to open the contribution wizard +3. The system will detect which Git host you're using (GitHub, GitLab, etc.) + +### Step 3: Connect Your Account + +**Option A: Quick Connect (GitHub only)** +- Click "Connect with GitHub" +- Authorize Shakespeare to access your GitHub account +- You'll be redirected back automatically + +**Option B: Personal Access Token** +- Click the link to create a token on the Git host +- Follow the instructions to generate a token with the right permissions +- Paste the token into Shakespeare +- Click "Connect" + +Required permissions: +- **GitHub**: `public_repo` scope +- **GitLab**: `api` or `write_repository` scope +- **Codeberg/Gitea**: `repo` permission + +### Step 4: Review Your Changes + +The wizard shows you all files that have been: +- ✅ Added (new files) +- ✏️ Modified (changed files) +- ❌ Deleted (removed files) + +Review the list and click "Continue" when ready. + +### Step 5: Describe Your Changes + +Fill in the contribution details: + +- **Branch Name**: A unique name for your changes (e.g., `fix-typo` or `add-feature`) +- **Commit Message**: Brief description of what you changed +- **PR Title**: Clear summary of your contribution +- **Description**: Detailed explanation of the changes and why they're needed +- **Allow maintainers to edit**: ✓ Recommended (lets project maintainers make small adjustments) + +Click "Run Checks" to continue. + +### Step 6: Validation + +Shakespeare automatically: +- ✅ Type checks your code +- ✅ Builds the project +- ✅ Ensures everything compiles + +If checks fail, you'll see specific errors to fix. + +### Step 7: Submit + +Click "Submit Pull Request" and Shakespeare will: + +1. **Check permissions** - See if you can push directly to the repo +2. **Create a fork** (if needed) - Automatically fork the repository to your account +3. **Create a branch** - Make a new branch with your chosen name +4. **Commit changes** - Save all your changes with your commit message +5. **Push to your fork** - Upload the changes to GitHub/GitLab/etc. +6. **Open a pull request** - Create a PR from your fork to the upstream repository + +You'll see a success message with a link to your pull request! + +### Updating an Existing PR + +If you're on a branch that already has an open PR: + +1. Make additional changes +2. The **"Update PR"** option will appear +3. Click it to push new commits to the existing PR +4. The PR is automatically updated with your latest changes + +## For Developers: Architecture + +### Git Host Abstraction + +The system uses a provider pattern to support multiple Git hosting platforms: + +```typescript +// lib/git-hosts/types.ts +interface GitHostProvider { + getRepository(owner: string, repo: string): Promise; + canUserPush(owner: string, repo: string): Promise; + createFork(owner: string, repo: string): Promise; + getFork(upstreamOwner: string, upstreamRepo: string, username: string): Promise; + createPullRequest(options: CreatePullRequestOptions): Promise; + // ... and more +} +``` + +Implemented providers: +- `GitHubProvider` - GitHub REST API v3 +- `GitLabProvider` - GitLab REST API v4 +- `GiteaProvider` - Gitea/Forgejo/Codeberg API v1 + +### Component Structure + +**ContributeButton** (`components/contribute/ContributeButton.tsx`) +- Detects if contribution is available for the current project +- Opens the ContributeWizard when clicked + +**ContributeWizard** (`components/contribute/ContributeWizard.tsx`) +- Multi-step wizard component +- Handles the entire contribution flow +- Progress bar shows current step +- Error handling and validation + +**AuthStep** (`components/contribute/AuthStep.tsx`) +- Authentication with Git hosts +- Supports OAuth (GitHub) and Personal Access Tokens +- Clear instructions for token generation + +**DiffView** (`components/contribute/DiffView.tsx`) +- Shows all changed files +- Color-coded by change type (added/modified/deleted) +- File statistics + +**PRStatusBadge** (`components/contribute/PRStatusBadge.tsx`) +- Shows existing PR status for current branch +- Displays PR state (open/merged/closed) +- Shows CI check status +- Links to the PR on the Git host + +### Hook: useContribute + +The main hook that orchestrates the contribution process: + +```typescript +const { + needsAuth, // Check if user needs to authenticate + authenticate, // Add authentication token + contribute, // Execute full contribution workflow + updatePR, // Push new commits to existing PR + isLoading, // Loading state + error, // Error message + step, // Current workflow step + pr, // Created/updated pull request +} = useContribute(); +``` + +### Token Storage + +Tokens are stored in two places for compatibility: + +1. **Git Credentials** (`settings.credentials`) - For Git push/pull operations +2. **Host Tokens** (`settings.hostTokens`) - For API operations (fork, PR creation, etc.) + +```typescript +// GitSettingsContext +interface GitSettings { + credentials: Record; // For Git auth + hostTokens: Record; // For API auth + // ... +} +``` + +### Remote Configuration + +The system automatically manages Git remotes: + +**Before Forking:** +``` +origin -> https://github.com/original/repo.git +``` + +**After Forking:** +``` +upstream -> https://github.com/original/repo.git (read-only) +origin -> https://github.com/yourname/repo.git (your fork) +``` + +This allows users to: +- Pull updates from upstream +- Push changes to their fork +- Keep their fork in sync + +### Security + +- **Tokens stored locally**: All authentication tokens are stored in browser IndexedDB, never sent to Shakespeare servers +- **Minimal scopes**: Instructions guide users to grant only necessary permissions +- **PKCE for OAuth**: GitHub OAuth uses PKCE (Proof Key for Code Exchange) for enhanced security +- **Token revocation**: Users can remove tokens anytime from Git settings + +### API Rate Limiting + +The system handles rate limiting gracefully: +- Caches Git host API responses where possible +- Shows clear error messages when rate limited +- Provides fallback to manual PR creation via compare URLs + +## Supported Git Hosts + +### GitHub +- ✅ OAuth login (PKCE) +- ✅ Personal Access Token +- ✅ Fork creation +- ✅ Pull request creation +- ✅ PR status and checks +- ✅ PR updates + +### GitLab +- ✅ Personal Access Token +- ✅ Fork creation (project forking) +- ✅ Merge request creation +- ✅ MR status and pipeline checks +- ✅ MR updates + +### Gitea/Forgejo/Codeberg +- ✅ Personal Access Token +- ✅ Fork creation +- ✅ Pull request creation +- ✅ PR status +- ✅ PR updates + +### Self-Hosted Git +For self-hosted Gitea/Forgejo instances: +- API URL is auto-detected from repository URL +- Uses same token authentication +- Full PR workflow support + +## Extending the System + +### Adding a New Git Host + +1. Create a new provider in `lib/git-hosts/`: + +```typescript +export class NewHostProvider implements GitHostProvider { + readonly name = 'NewHost'; + readonly apiBaseUrl = 'https://api.newhost.com'; + + // Implement all GitHostProvider methods + // ... +} +``` + +2. Add detection logic in `lib/git-hosts/types.ts`: + +```typescript +export function detectGitHost(url: string): HostType { + // ... existing logic + if (hostname.includes('newhost.com')) return 'newhost'; + // ... +} +``` + +3. Update factory in `lib/git-hosts/index.ts`: + +```typescript +export function createGitHostProvider(url: string, config: GitHostConfig) { + // ... existing cases + case 'newhost': + return new NewHostProvider(config, corsProxy); + // ... +} +``` + +### Customizing the Workflow + +The `ContributeWizard` component is designed to be extensible: + +- Add new validation steps in `handleBranchNext()` +- Add custom checks in the "checks" step +- Modify the UI for specific use cases +- Add custom metadata to PRs + +### Error Handling + +The system provides fallbacks at every step: + +1. **No API access** → Manual token entry +2. **Fork fails** → Direct push if user has permissions +3. **Rate limited** → Show compare URL for manual PR creation +4. **Build fails** → Show specific error, allow override with warning + +## Troubleshooting + +### "Not authenticated with github.com" + +**Solution**: Connect your GitHub account: +1. Click "Propose Changes" +2. Follow the OAuth or token flow +3. Your token is saved for future contributions + +### "Build failed. Please fix errors before submitting." + +**Solution**: Fix the TypeScript/build errors: +1. Check the error message in the wizard +2. Fix the issues in your code +3. Click "Run Checks" again + +### "Timeout waiting for fork to be created" + +**Solution**: The Git host is slow to create your fork: +1. Wait a moment and try again +2. Check if the fork exists on the Git host website +3. If it exists, the next attempt should succeed + +### "Failed to push" + +**Solution**: Check your permissions: +1. Verify your token has write access +2. Make sure the token hasn't expired +3. Try disconnecting and reconnecting your account + +### "No remote repository found" + +**Solution**: This project isn't connected to Git: +1. Clone a project from GitHub/GitLab +2. Or initialize the project with a Git remote +3. Then you can propose changes + +## Privacy & Data + +- **Local storage only**: All tokens and settings are stored in your browser's IndexedDB +- **No tracking**: Shakespeare doesn't track your contributions or activity +- **No server storage**: Your code and tokens never touch Shakespeare servers +- **Revocable**: Delete tokens anytime from Settings → Git + +## Future Enhancements + +Planned features: +- [ ] Draft PRs +- [ ] PR templates +- [ ] Custom branch naming patterns +- [ ] Conflict resolution UI +- [ ] Multi-commit PRs +- [ ] Review request suggestions +- [ ] Automated changelog generation +- [ ] Integration with CI/CD status diff --git a/src/components/GitSettingsProvider.tsx b/src/components/GitSettingsProvider.tsx index db168ebd..f6cdaa5b 100644 --- a/src/components/GitSettingsProvider.tsx +++ b/src/components/GitSettingsProvider.tsx @@ -1,5 +1,5 @@ import { ReactNode, useState, useEffect } from 'react'; -import { GitSettingsContext, type GitSettings, type GitCredential, type GitSettingsContextType } from '@/contexts/GitSettingsContext'; +import { GitSettingsContext, type GitSettings, type GitCredential, type GitHostToken, type GitSettingsContextType } from '@/contexts/GitSettingsContext'; import { useFS } from '@/hooks/useFS'; import { readGitSettings, writeGitSettings } from '@/lib/configUtils'; @@ -9,6 +9,7 @@ interface GitSettingsProviderProps { const DEFAULT_SETTINGS: GitSettings = { credentials: {}, + hostTokens: {}, }; export function GitSettingsProvider({ children }: GitSettingsProviderProps) { @@ -85,6 +86,39 @@ export function GitSettingsProvider({ children }: GitSettingsProviderProps) { })); }; + const addHostToken = (host: string, token: GitHostToken) => { + setSettings(prev => ({ + ...prev, + hostTokens: { + ...prev.hostTokens, + [host]: token, + }, + })); + }; + + const removeHostToken = (host: string) => { + setSettings(prev => { + const { [host]: removed, ...rest } = prev.hostTokens; + return { + ...prev, + hostTokens: rest, + }; + }); + }; + + const updateHostToken = (host: string, token: Partial) => { + setSettings(prev => ({ + ...prev, + hostTokens: { + ...prev.hostTokens, + [host]: { + ...prev.hostTokens[host], + ...token, + }, + }, + })); + }; + const isConfigured = Object.entries(settings.credentials).length > 0; const contextValue: GitSettingsContextType = { @@ -93,6 +127,9 @@ export function GitSettingsProvider({ children }: GitSettingsProviderProps) { addCredential, removeCredential, updateCredential, + addHostToken, + removeHostToken, + updateHostToken, isConfigured, }; diff --git a/src/components/contribute/AuthStep.tsx b/src/components/contribute/AuthStep.tsx new file mode 100644 index 00000000..bcb7e5bb --- /dev/null +++ b/src/components/contribute/AuthStep.tsx @@ -0,0 +1,174 @@ +import { useState } from 'react'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { Alert, AlertDescription } from '@/components/ui/alert'; +import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'; +import { useGitHubOAuth } from '@/hooks/useGitHubOAuth'; +import { InfoIcon, KeyRound, ExternalLink } from 'lucide-react'; + +interface AuthStepProps { + host: string; + onComplete: (host: string, token: string, username?: string) => void; +} + +export function AuthStep({ host, onComplete }: AuthStepProps) { + const { isOAuthConfigured, initiateOAuth } = useGitHubOAuth(); + const [token, setToken] = useState(''); + const [username, setUsername] = useState(''); + + const handleTokenSubmit = () => { + if (!token.trim()) return; + onComplete(host, token.trim(), username.trim() || undefined); + }; + + const getTokenInstructions = () => { + switch (host) { + case 'github.com': + return { + url: 'https://github.com/settings/tokens/new', + scopes: 'public_repo (for public repositories)', + steps: [ + 'Click "Generate new token (classic)"', + 'Set a descriptive note like "Shakespeare Contributions"', + 'Select the "public_repo" scope', + 'Click "Generate token" at the bottom', + 'Copy the token and paste it below', + ], + }; + case 'gitlab.com': + return { + url: 'https://gitlab.com/-/profile/personal_access_tokens', + scopes: 'api or write_repository', + steps: [ + 'Enter a token name like "Shakespeare"', + 'Select the "api" or "write_repository" scope', + 'Click "Create personal access token"', + 'Copy the token and paste it below', + ], + }; + case 'codeberg.org': + return { + url: 'https://codeberg.org/user/settings/applications', + scopes: 'repo', + steps: [ + 'Go to Applications > Access Tokens', + 'Click "Generate New Token"', + 'Enter a description like "Shakespeare"', + 'Select the "repo" permission', + 'Click "Generate Token"', + 'Copy the token and paste it below', + ], + }; + default: + return { + url: `https://${host}/user/settings/applications`, + scopes: 'repo or write access', + steps: [ + 'Navigate to your user settings', + 'Find the access tokens or applications section', + 'Create a new token with repository write permissions', + 'Copy the token and paste it below', + ], + }; + } + }; + + const instructions = getTokenInstructions(); + const showOAuth = host === 'github.com' && isOAuthConfigured; + + return ( +
+
+

Connect to {host}

+

+ To propose changes, you need to authenticate with {host} +

+
+ + + {showOAuth && ( + + Quick Connect + Access Token + + )} + + {showOAuth && ( + + + + + The fastest way to connect. You'll be redirected to {host} to authorize Shakespeare. + + + + + + )} + + + + + + Create a personal access token on {host} with the following scope: {instructions.scopes} + + + +
+

How to create a token:

+
    + {instructions.steps.map((step, index) => ( +
  1. {step}
  2. + ))} +
+ + Open {host} token settings + + +
+ +
+ + setUsername(e.target.value)} + /> +

+ Your username on {host} (helpful but not required) +

+
+ +
+ + setToken(e.target.value)} + /> +

+ + Your token is stored locally and never sent to Shakespeare servers +

+
+ + +
+
+
+ ); +} diff --git a/src/components/contribute/ContributeButton.tsx b/src/components/contribute/ContributeButton.tsx new file mode 100644 index 00000000..cb72dc31 --- /dev/null +++ b/src/components/contribute/ContributeButton.tsx @@ -0,0 +1,65 @@ +import { useState, useEffect } from 'react'; +import { useGit } from '@/hooks/useGit'; +import { Button } from '@/components/ui/button'; +import { ContributeWizard } from './ContributeWizard'; +import { GitPullRequest } from 'lucide-react'; +import { detectGitHost } from '@/lib/git-hosts'; + +interface ContributeButtonProps { + projectDir: string; + variant?: 'default' | 'outline' | 'ghost'; + size?: 'default' | 'sm' | 'lg' | 'icon'; + className?: string; +} + +export function ContributeButton({ projectDir, variant = 'outline', size = 'default', className }: ContributeButtonProps) { + const { git } = useGit(); + const [showWizard, setShowWizard] = useState(false); + const [canContribute, setCanContribute] = useState(false); + + useEffect(() => { + const checkContributeAvailable = async () => { + try { + // Check if there's a remote with a supported host + const upstreamUrl = await git.getRemoteURL(projectDir, 'upstream'); + const originUrl = await git.getRemoteURL(projectDir, 'origin'); + const remoteUrl = upstreamUrl || originUrl; + + if (remoteUrl) { + const hostType = detectGitHost(remoteUrl); + setCanContribute(hostType !== 'unknown'); + } else { + setCanContribute(false); + } + } catch { + setCanContribute(false); + } + }; + + checkContributeAvailable(); + }, [git, projectDir]); + + if (!canContribute) { + return null; + } + + return ( + <> + + + + + ); +} diff --git a/src/components/contribute/ContributeWizard.tsx b/src/components/contribute/ContributeWizard.tsx new file mode 100644 index 00000000..b7342f51 --- /dev/null +++ b/src/components/contribute/ContributeWizard.tsx @@ -0,0 +1,406 @@ +import { useState, useEffect } from 'react'; +import { useContribute } from '@/hooks/useContribute'; +import { useGit } from '@/hooks/useGit'; +import { useBuildProject } from '@/hooks/useBuildProject'; +import { Button } from '@/components/ui/button'; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from '@/components/ui/dialog'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { Textarea } from '@/components/ui/textarea'; +import { Alert, AlertDescription } from '@/components/ui/alert'; +import { Progress } from '@/components/ui/progress'; +import { Checkbox } from '@/components/ui/checkbox'; +import { AuthStep } from './AuthStep'; +import { DiffView } from './DiffView'; +import { AlertCircle, CheckCircle2, Loader2, GitFork, Upload, GitPullRequest } from 'lucide-react'; +import type { PullRequest } from '@/lib/git-hosts'; + +interface ContributeWizardProps { + projectDir: string; + open: boolean; + onOpenChange: (open: boolean) => void; + onComplete?: (pr: PullRequest) => void; +} + +export function ContributeWizard({ projectDir, open, onOpenChange, onComplete }: ContributeWizardProps) { + const { git } = useGit(); + const { mutateAsync: buildProject } = useBuildProject(); + const { needsAuth, authenticate, contribute, isLoading, error, step, message, pr } = useContribute(); + + const [wizardStep, setWizardStep] = useState<'auth' | 'review' | 'branch' | 'checks' | 'result'>('auth'); + const [authStatus, setAuthStatus] = useState<{ needsAuth: boolean; host?: string; url?: string } | null>(null); + const [formData, setFormData] = useState({ + branchName: '', + commitMessage: '', + prTitle: '', + prBody: '', + maintainerCanModify: true, + }); + const [validationErrors, setValidationErrors] = useState>({}); + const [buildPassed, setBuildPassed] = useState(false); + const [checkingBuild, setCheckingBuild] = useState(false); + + // Check auth status when dialog opens + useEffect(() => { + if (open) { + needsAuth(projectDir).then(status => { + setAuthStatus(status); + if (!status.needsAuth) { + setWizardStep('review'); + } else { + setWizardStep('auth'); + } + }); + } + }, [open, projectDir, needsAuth]); + + // Reset state when dialog closes + useEffect(() => { + if (!open) { + setWizardStep('auth'); + setFormData({ + branchName: '', + commitMessage: '', + prTitle: '', + prBody: '', + maintainerCanModify: true, + }); + setValidationErrors({}); + setBuildPassed(false); + } + }, [open]); + + const handleAuthComplete = (host: string, token: string, username?: string) => { + authenticate(host, token, username); + setWizardStep('review'); + }; + + const handleReviewNext = () => { + setWizardStep('branch'); + }; + + const validateBranchForm = () => { + const errors: Record = {}; + + if (!formData.branchName.trim()) { + errors.branchName = 'Branch name is required'; + } else if (!/^[a-zA-Z0-9._\/-]+$/.test(formData.branchName)) { + errors.branchName = 'Invalid branch name. Use only letters, numbers, dots, dashes, and slashes.'; + } + + if (!formData.commitMessage.trim()) { + errors.commitMessage = 'Commit message is required'; + } + + if (!formData.prTitle.trim()) { + errors.prTitle = 'Pull request title is required'; + } + + setValidationErrors(errors); + return Object.keys(errors).length === 0; + }; + + const handleBranchNext = async () => { + if (!validateBranchForm()) return; + + setWizardStep('checks'); + + // Run build check + setCheckingBuild(true); + try { + await buildProject(projectDir); + setBuildPassed(true); + } catch (error) { + setBuildPassed(false); + setValidationErrors(prev => ({ + ...prev, + build: 'Build failed. Please fix errors before submitting.', + })); + } finally { + setCheckingBuild(false); + } + }; + + const handleSubmit = async () => { + if (!buildPassed) { + setValidationErrors(prev => ({ + ...prev, + build: 'Build must pass before submitting', + })); + return; + } + + const result = await contribute({ + projectDir, + branchName: formData.branchName, + commitMessage: formData.commitMessage, + prTitle: formData.prTitle, + prBody: formData.prBody, + maintainerCanModify: formData.maintainerCanModify, + }); + + if (result) { + setWizardStep('result'); + onComplete?.(result); + } + }; + + const getProgress = () => { + switch (wizardStep) { + case 'auth': return 20; + case 'review': return 40; + case 'branch': return 60; + case 'checks': return 80; + case 'result': return 100; + default: return 0; + } + }; + + const getStepIcon = () => { + if (step === 'fork') return ; + if (step === 'push') return ; + if (step === 'pr') return ; + if (step === 'complete') return ; + return ; + }; + + return ( + + + + Propose Changes + + Submit your changes to the original project + + + + + + {error && ( + + + {error} + + )} + + {wizardStep === 'auth' && authStatus && ( + + )} + + {wizardStep === 'review' && ( +
+
+

Review Your Changes

+

+ Review the changes you're proposing to submit +

+
+ +
+ )} + + {wizardStep === 'branch' && ( +
+
+

Branch & Commit Details

+

+ Describe your changes and create a branch +

+
+ +
+ + setFormData(prev => ({ ...prev, branchName: e.target.value }))} + /> + {validationErrors.branchName && ( +

{validationErrors.branchName}

+ )} +
+ +
+ + setFormData(prev => ({ ...prev, commitMessage: e.target.value }))} + /> + {validationErrors.commitMessage && ( +

{validationErrors.commitMessage}

+ )} +
+ +
+ + setFormData(prev => ({ ...prev, prTitle: e.target.value }))} + /> + {validationErrors.prTitle && ( +

{validationErrors.prTitle}

+ )} +
+ +
+ +