From 99ed632355e4bc033f902ad363269c7eb597b607 Mon Sep 17 00:00:00 2001 From: Chris Scott Date: Sun, 14 Dec 2025 19:11:27 -0500 Subject: [PATCH] Add branch creation endpoint and improve git auth fallback handling --- backend/src/routes/repos.ts | 35 +++++ backend/src/services/repo.ts | 144 ++++++++++++++---- frontend/src/api/repos.ts | 32 +++- .../repo/AddBranchWorkspaceDialog.tsx | 30 ++-- .../src/components/repo/BranchSwitcher.tsx | 20 ++- 5 files changed, 212 insertions(+), 49 deletions(-) diff --git a/backend/src/routes/repos.ts b/backend/src/routes/repos.ts index 8250d058..c74bc651 100644 --- a/backend/src/routes/repos.ts +++ b/backend/src/routes/repos.ts @@ -2,6 +2,7 @@ import { Hono } from 'hono' import type { Database } from 'bun:sqlite' import * as db from '../db/queries' import * as repoService from '../services/repo' +import { GitAuthenticationError } from '../services/repo' import * as gitOperations from '../services/git-operations' import * as archiveService from '../services/archive' import { SettingsService } from '../services/settings' @@ -191,6 +192,40 @@ export function createRepoRoutes(database: Database) { return c.json({ ...updatedRepo, currentBranch }) } catch (error: any) { logger.error('Failed to switch branch:', error) + if (error instanceof GitAuthenticationError) { + return c.json({ error: error.message, code: 'AUTH_FAILED' }, 401) + } + return c.json({ error: error.message }, 500) + } + }) + + app.post('/:id/branch/create', async (c) => { + try { + const id = parseInt(c.req.param('id')) + const repo = db.getRepoById(database, id) + + if (!repo) { + return c.json({ error: 'Repo not found' }, 404) + } + + const body = await c.req.json() + const { branch } = body + + if (!branch) { + return c.json({ error: 'branch is required' }, 400) + } + + await repoService.createBranch(database, id, branch) + + const updatedRepo = db.getRepoById(database, id) + const currentBranch = await repoService.getCurrentBranch(updatedRepo!) + + return c.json({ ...updatedRepo, currentBranch }) + } catch (error: any) { + logger.error('Failed to create branch:', error) + if (error instanceof GitAuthenticationError) { + return c.json({ error: error.message, code: 'AUTH_FAILED' }, 401) + } return c.json({ error: error.message }, 500) } }) diff --git a/backend/src/services/repo.ts b/backend/src/services/repo.ts index de446a01..f1a8885d 100644 --- a/backend/src/services/repo.ts +++ b/backend/src/services/repo.ts @@ -5,10 +5,59 @@ import type { Database } from 'bun:sqlite' import type { Repo, CreateRepoInput } from '../types/repo' import { logger } from '../utils/logger' import { SettingsService } from './settings' -import { createGitEnvForRepoUrl, createNoPromptGitEnv } from '../utils/git-auth' +import { createGitEnvForRepoUrl, createNoPromptGitEnv, createGitHubGitEnv } from '../utils/git-auth' import { getReposPath } from '@opencode-manager/shared' import path from 'path' +export class GitAuthenticationError extends Error { + constructor(message: string) { + super(message) + this.name = 'GitAuthenticationError' + } +} + +function isAuthenticationError(error: any): boolean { + const message = error?.message?.toLowerCase() || '' + return message.includes('authentication failed') || + message.includes('invalid username or token') || + message.includes('could not read username') +} + +interface GitCommandOptions { + cwd?: string + env?: Record + silent?: boolean +} + +async function executeGitWithFallback( + cmd: string[], + options: GitCommandOptions = {} +): Promise { + const { cwd, env = createNoPromptGitEnv(), silent } = options + + try { + return await executeCommand(cmd, { cwd, env, silent }) + } catch (error: any) { + if (!isAuthenticationError(error)) { + throw error + } + + logger.warn(`Git command failed with auth, trying gh auth fallback`) + try { + const ghToken = (await executeCommand(['gh', 'auth', 'token'])).trim() + const ghEnv = createGitHubGitEnv(ghToken) + return await executeCommand(cmd, { cwd, env: ghEnv, silent }) + } catch (ghError: any) { + if (!isAuthenticationError(ghError)) { + throw ghError + } + + logger.warn(`Git command failed with gh auth, trying without auth (public repo)`) + return await executeCommand(cmd, { cwd, env: createNoPromptGitEnv(), silent }) + } + } +} + async function hasCommits(repoPath: string): Promise { try { await executeCommand(['git', '-C', repoPath, 'rev-parse', 'HEAD'], { silent: true }) @@ -216,8 +265,7 @@ export async function cloneRepo( } try { - const cloneCmd = ['git', 'clone', '-b', branch, repoUrl, worktreeDirName] - await executeCommand(cloneCmd, { cwd: getReposPath(), env }) + await executeGitWithFallback(['git', 'clone', '-b', branch, repoUrl, worktreeDirName], { cwd: getReposPath(), env }) } catch (error: any) { if (error.message.includes('destination path') && error.message.includes('already exists')) { logger.error(`Clone failed: directory still exists after cleanup attempt`) @@ -225,8 +273,7 @@ export async function cloneRepo( } logger.info(`Branch '${branch}' not found during clone, cloning default branch and creating branch locally`) - const cloneCmd = ['git', 'clone', repoUrl, worktreeDirName] - await executeCommand(cloneCmd, { cwd: getReposPath(), env }) + await executeGitWithFallback(['git', 'clone', repoUrl, worktreeDirName], { cwd: getReposPath(), env }) let localBranchExists = 'missing' try { await executeCommand(['git', '-C', path.resolve(getReposPath(), worktreeDirName), 'rev-parse', '--verify', `refs/heads/${branch}`]) @@ -311,7 +358,7 @@ export async function cloneRepo( ? ['git', 'clone', '-b', branch, repoUrl, worktreeDirName] : ['git', 'clone', repoUrl, worktreeDirName] - await executeCommand(cloneCmd, { cwd: getReposPath(), env }) + await executeGitWithFallback(cloneCmd, { cwd: getReposPath(), env }) } catch (error: any) { if (error.message.includes('destination path') && error.message.includes('already exists')) { logger.error(`Clone failed: directory still exists after cleanup attempt`) @@ -320,8 +367,7 @@ export async function cloneRepo( if (branch && (error.message.includes('Remote branch') || error.message.includes('not found'))) { logger.info(`Branch '${branch}' not found, cloning default branch and creating branch locally`) -const cloneCmd = ['git', 'clone', repoUrl, worktreeDirName] - await executeCommand(cloneCmd, { cwd: getReposPath(), env }) + await executeGitWithFallback(['git', 'clone', repoUrl, worktreeDirName], { cwd: getReposPath(), env }) let localBranchExists = 'missing' try { await executeCommand(['git', '-C', path.resolve(getReposPath(), worktreeDirName), 'rev-parse', '--verify', `refs/heads/${branch}`]) @@ -357,38 +403,42 @@ export async function getCurrentBranch(repo: Repo): Promise { return branch || repo.branch || repo.defaultBranch || null } -export async function listBranches(database: Database, repo: Repo): Promise<{ local: string[], remote: string[], current: string | null }> { +export async function listBranches(database: Database, repo: Repo): Promise<{ local: string[], all: string[], current: string | null }> { try { const repoPath = path.resolve(getReposPath(), repo.localPath) const env = getGitEnv(database, repo.repoUrl) if (!repo.isLocal) { - await executeCommand(['git', '-C', repoPath, 'fetch', '--all'], { env }) + try { + await executeGitWithFallback(['git', '-C', repoPath, 'fetch', '--all'], { env }) + } catch (error) { + logger.warn(`Failed to fetch remote for repo ${repo.id}, using cached branch info:`, error) + } } const localBranchesOutput = await executeCommand(['git', '-C', repoPath, 'branch', '--format=%(refname:short)']) const localBranches = localBranchesOutput.trim().split('\n').filter(b => b.trim()) let remoteBranches: string[] = [] - if (!repo.isLocal) { - try { - const remoteBranchesOutput = await executeCommand(['git', '-C', repoPath, 'branch', '-r', '--format=%(refname:short)']) - remoteBranches = remoteBranchesOutput.trim().split('\n') - .filter(b => b.trim() && !b.includes('HEAD')) - .map(b => b.replace('origin/', '')) - } catch (error) { - logger.warn(`Failed to get remote branches for repo ${repo.id}:`, error) - remoteBranches = [] - } + try { + const remoteBranchesOutput = await executeCommand(['git', '-C', repoPath, 'branch', '-r', '--format=%(refname:short)']) + remoteBranches = remoteBranchesOutput.trim().split('\n') + .filter(b => b.trim() && !b.includes('HEAD') && b.includes('/')) + } catch (error) { + logger.warn(`Failed to get remote branches for repo ${repo.id}:`, error) } const current = await getCurrentBranch(repo) - const allBranches = new Set([...localBranches, ...remoteBranches]) + const remoteOnlyBranches = remoteBranches + .map(b => b.replace(/^[^/]+\//, '')) + .filter(b => !localBranches.includes(b)) + + const allBranches = [...localBranches, ...remoteOnlyBranches] return { local: localBranches, - remote: Array.from(allBranches), + all: allBranches, current } } catch (error: any) { @@ -407,13 +457,18 @@ export async function switchBranch(database: Database, repoId: number, branch: s const repoPath = path.resolve(getReposPath(), repo.localPath) const env = getGitEnv(database, repo.repoUrl) - logger.info(`Switching to branch: ${branch} in ${repo.localPath}`) + const sanitizedBranch = branch + .replace(/^refs\/heads\//, '') + .replace(/^refs\/remotes\//, '') + .replace(/^origin\//, '') - await executeCommand(['git', '-C', repoPath, 'fetch', '--all'], { env }) + logger.info(`Switching to branch: ${sanitizedBranch} in ${repo.localPath}`) + + await executeGitWithFallback(['git', '-C', repoPath, 'fetch', '--all'], { env }) let localBranchExists = false try { - await executeCommand(['git', '-C', repoPath, 'rev-parse', '--verify', `refs/heads/${branch}`]) + await executeCommand(['git', '-C', repoPath, 'rev-parse', '--verify', `refs/heads/${sanitizedBranch}`]) localBranchExists = true } catch { localBranchExists = false @@ -421,30 +476,53 @@ export async function switchBranch(database: Database, repoId: number, branch: s let remoteBranchExists = false try { - await executeCommand(['git', '-C', repoPath, 'rev-parse', '--verify', `refs/remotes/origin/${branch}`]) + await executeCommand(['git', '-C', repoPath, 'rev-parse', '--verify', `refs/remotes/origin/${sanitizedBranch}`]) remoteBranchExists = true } catch { remoteBranchExists = false } if (localBranchExists) { - logger.info(`Checking out existing local branch: ${branch}`) - await executeCommand(['git', '-C', repoPath, 'checkout', branch]) + logger.info(`Checking out existing local branch: ${sanitizedBranch}`) + await executeCommand(['git', '-C', repoPath, 'checkout', sanitizedBranch]) } else if (remoteBranchExists) { - logger.info(`Checking out remote branch: ${branch}`) - await executeCommand(['git', '-C', repoPath, 'checkout', '-b', branch, `origin/${branch}`]) + logger.info(`Checking out remote branch: ${sanitizedBranch}`) + await executeCommand(['git', '-C', repoPath, 'checkout', '-b', sanitizedBranch, `origin/${sanitizedBranch}`]) } else { - logger.info(`Creating new branch: ${branch}`) - await executeCommand(['git', '-C', repoPath, 'checkout', '-b', branch]) + logger.info(`Creating new branch: ${sanitizedBranch}`) + await executeCommand(['git', '-C', repoPath, 'checkout', '-b', sanitizedBranch]) } - logger.info(`Successfully switched to branch: ${branch}`) + logger.info(`Successfully switched to branch: ${sanitizedBranch}`) } catch (error: any) { logger.error(`Failed to switch branch for repo ${repoId}:`, error) throw error } } +export async function createBranch(database: Database, repoId: number, branch: string): Promise { + const repo = db.getRepoById(database, repoId) + if (!repo) { + throw new Error(`Repo not found: ${repoId}`) + } + + try { + const repoPath = path.resolve(getReposPath(), repo.localPath) + + const sanitizedBranch = branch + .replace(/^refs\/heads\//, '') + .replace(/^refs\/remotes\//, '') + .replace(/^origin\//, '') + + logger.info(`Creating new branch: ${sanitizedBranch} in ${repo.localPath}`) + await executeCommand(['git', '-C', repoPath, 'checkout', '-b', sanitizedBranch]) + logger.info(`Successfully created and switched to branch: ${sanitizedBranch}`) + } catch (error: any) { + logger.error(`Failed to create branch for repo ${repoId}:`, error) + throw error + } +} + export async function pullRepo(database: Database, repoId: number): Promise { const repo = db.getRepoById(database, repoId) if (!repo) { diff --git a/frontend/src/api/repos.ts b/frontend/src/api/repos.ts index 0bde92a6..bbf7c923 100644 --- a/frontend/src/api/repos.ts +++ b/frontend/src/api/repos.ts @@ -115,6 +115,15 @@ export async function switchRepoConfig(id: number, configName: string): Promise< return response.json() } +export class GitAuthError extends Error { + code: string + constructor(message: string, code: string) { + super(message) + this.name = 'GitAuthError' + this.code = code + } +} + export async function switchBranch(id: number, branch: string): Promise { const response = await fetch(`${API_BASE_URL}/api/repos/${id}/branch/switch`, { method: 'POST', @@ -124,13 +133,16 @@ export async function switchBranch(id: number, branch: string): Promise { if (!response.ok) { const error = await response.json() + if (error.code === 'AUTH_FAILED') { + throw new GitAuthError(error.error || 'Git authentication failed', error.code) + } throw new Error(error.error || 'Failed to switch branch') } return response.json() } -export async function listBranches(id: number): Promise<{ local: string[], remote: string[], current: string | null }> { +export async function listBranches(id: number): Promise<{ local: string[], all: string[], current: string | null }> { const response = await fetch(`${API_BASE_URL}/api/repos/${id}/branches`) if (!response.ok) { @@ -140,6 +152,24 @@ export async function listBranches(id: number): Promise<{ local: string[], remot return response.json() } +export async function createBranch(id: number, branch: string): Promise { + const response = await fetch(`${API_BASE_URL}/api/repos/${id}/branch/create`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ branch }), + }) + + if (!response.ok) { + const error = await response.json() + if (error.code === 'AUTH_FAILED') { + throw new GitAuthError(error.error || 'Git authentication failed', error.code) + } + throw new Error(error.error || 'Failed to create branch') + } + + return response.json() +} + export async function downloadRepo(id: number, repoName: string): Promise { const response = await fetch(`${API_BASE_URL}/api/repos/${id}/download`) diff --git a/frontend/src/components/repo/AddBranchWorkspaceDialog.tsx b/frontend/src/components/repo/AddBranchWorkspaceDialog.tsx index 44acd5bd..8e8155be 100644 --- a/frontend/src/components/repo/AddBranchWorkspaceDialog.tsx +++ b/frontend/src/components/repo/AddBranchWorkspaceDialog.tsx @@ -1,6 +1,6 @@ import { useState } from "react"; import { useMutation, useQueryClient } from "@tanstack/react-query"; -import { createRepo } from "@/api/repos"; +import { createRepo, createBranch } from "@/api/repos"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { @@ -15,24 +15,32 @@ interface AddBranchWorkspaceDialogProps { open: boolean; onOpenChange: (open: boolean) => void; repoUrl: string; + repoId: number; } export function AddBranchWorkspaceDialog({ open, onOpenChange, repoUrl, + repoId, }: AddBranchWorkspaceDialogProps) { const [branch, setBranch] = useState(""); - const [useWorktree, setUseWorktree] = useState(true); + const [useWorktree, setUseWorktree] = useState(false); const queryClient = useQueryClient(); const mutation = useMutation({ - mutationFn: () => - createRepo(repoUrl, undefined, branch || undefined, undefined, useWorktree), + mutationFn: () => { + if (useWorktree) { + return createRepo(repoUrl, undefined, branch || undefined, undefined, true) + } + return createBranch(repoId, branch) + }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ["repos"] }); + queryClient.invalidateQueries({ queryKey: ["branches", repoId] }); + queryClient.invalidateQueries({ queryKey: ["repo", repoId] }); setBranch(""); - setUseWorktree(true); + setUseWorktree(false); onOpenChange(false); }, }); @@ -54,10 +62,10 @@ export function AddBranchWorkspaceDialog({ - Add Branch Workspace + Add Branch

- Create a new workspace for{" "} + Create a new branch for{" "} {repoUrl.split("/").pop()?.replace(".git", "")}

@@ -99,8 +107,8 @@ export function AddBranchWorkspaceDialog({

{useWorktree - ? "Creates a git worktree - shares git history with base repo (recommended, faster)" - : "Creates a full clone - independent copy of the repository (slower, more disk space)"} + ? "Creates a separate workspace directory - allows working on multiple branches simultaneously" + : "Creates a local branch in the current repository"}

@@ -112,12 +120,12 @@ export function AddBranchWorkspaceDialog({ {mutation.isPending ? ( <> - {useWorktree ? "Creating worktree..." : "Cloning..."} + {useWorktree ? "Creating worktree..." : "Creating branch..."} ) : useWorktree ? ( "Create Worktree" ) : ( - "Clone Branch" + "Create Branch" )} {mutation.isError && ( diff --git a/frontend/src/components/repo/BranchSwitcher.tsx b/frontend/src/components/repo/BranchSwitcher.tsx index 34cd27ec..d5d52ca7 100644 --- a/frontend/src/components/repo/BranchSwitcher.tsx +++ b/frontend/src/components/repo/BranchSwitcher.tsx @@ -9,10 +9,11 @@ import { } from "@/components/ui/dropdown-menu"; import { GitBranch, Check, Plus, GitCommit, Loader2 } from "lucide-react"; import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"; -import { listBranches, switchBranch } from "@/api/repos"; +import { listBranches, switchBranch, GitAuthError } from "@/api/repos"; import { useGitStatus } from "@/api/git"; import { AddBranchWorkspaceDialog } from "@/components/repo/AddBranchWorkspaceDialog"; import { GitChangesSheet } from "@/components/file-browser/GitChangesSheet"; +import { showToast } from "@/lib/toast"; interface BranchSwitcherProps { repoId: number; @@ -50,12 +51,22 @@ export function BranchSwitcher({ repoId, currentBranch, isWorktree, repoUrl, rep queryClient.invalidateQueries({ queryKey: ["branches", repoId] }); queryClient.invalidateQueries({ queryKey: ["repos"] }); }, + onError: (error) => { + if (error instanceof GitAuthError) { + showToast.error('Authentication failed. Please update your Git token in Settings or run "gh auth login".'); + } else { + showToast.error(error.message || 'Failed to switch branch'); + } + }, }); if (isWorktree) { return null; } + const isCurrentBranchInList = branches?.all?.includes(currentBranch) ?? false; + const showLoading = switchBranchMutation.isPending || (branchesLoading && !isCurrentBranchInList); + return ( <> @@ -66,7 +77,7 @@ export function BranchSwitcher({ repoId, currentBranch, isWorktree, repoUrl, rep disabled={switchBranchMutation.isPending} className={`h-6 px-1 sm:px-2 text-[10px] sm:text-xs text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 hover:bg-accent gap-1 border border-blue-500/20 ${iconOnly ? 'w-6' : ''} ${className || ""}`} > - {switchBranchMutation.isPending ? ( + {showLoading ? ( ) : ( @@ -79,8 +90,8 @@ export function BranchSwitcher({ repoId, currentBranch, isWorktree, repoUrl, rep Loading branches... - ) : branches?.local && branches.local.length > 0 ? ( - branches.local.map((branch: string) => ( + ) : branches?.all && branches.all.length > 0 ? ( + branches.all.map((branch: string) => ( switchBranchMutation.mutate(branch)} @@ -136,6 +147,7 @@ export function BranchSwitcher({ repoId, currentBranch, isWorktree, repoUrl, rep open={addBranchOpen} onOpenChange={setAddBranchOpen} repoUrl={repoUrl} + repoId={repoId} /> )}