From 204e79c7130678304823a61c19c51081f42e8b6a Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Sun, 25 Jan 2026 11:06:57 -0500 Subject: [PATCH] Add worktree support and consolidate branch management UI (#78) * Fix git credential saving and improve host matching - Fix token masking bug in GitCredentialDialog that corrupted tokens on edit - Add tokenEdited state to preserve original token when not modified - Default new credential host to https://github.com - Add normalizeHostname helper for consistent host comparison - Improve credential lookup logging to show configured vs requested hosts - Remove overly permissive fuzzy matching that could leak tokens * Make OpenCode reload non-fatal when saving git credentials Settings are now saved to database even if the OpenCode server reload fails. The reload error is returned separately so the UI can inform the user that credentials were saved but the server needs a manual restart. * Fix git fetch using credentials in silent mode Previously, silent mode (used for UI fetch operations) would skip credential lookup entirely and return empty, causing auth failures. Now credentials are always looked up via IPC regardless of silent mode. * Add worktree support and consolidate branch management UI * Remove duplicate SECURE_COOKIES property from auth config * Bump version to 0.7.8 --- backend/src/services/git/GitBranchService.ts | 12 +- frontend/src/api/repos.ts | 1 + .../file-browser/GitBranchSelector.tsx | 74 --------- .../repo/AddBranchWorkspaceDialog.tsx | 138 ---------------- .../src/components/repo/BranchSwitcher.tsx | 146 ----------------- frontend/src/components/repo/RepoCard.tsx | 44 +++-- .../components/source-control/BranchesTab.tsx | 155 +++++++++++------- .../source-control/SourceControlPanel.tsx | 63 ++----- frontend/src/pages/RepoDetail.tsx | 1 + frontend/src/pages/SessionDetail.tsx | 1 + package.json | 2 +- shared/src/config/env.ts | 1 - 12 files changed, 149 insertions(+), 489 deletions(-) delete mode 100644 frontend/src/components/file-browser/GitBranchSelector.tsx delete mode 100644 frontend/src/components/repo/AddBranchWorkspaceDialog.tsx delete mode 100644 frontend/src/components/repo/BranchSwitcher.tsx diff --git a/backend/src/services/git/GitBranchService.ts b/backend/src/services/git/GitBranchService.ts index 1ca33ebb..359eb253 100644 --- a/backend/src/services/git/GitBranchService.ts +++ b/backend/src/services/git/GitBranchService.ts @@ -12,6 +12,7 @@ interface GitBranch { upstream?: string ahead?: number behind?: number + isWorktree?: boolean } export class GitBranchService { @@ -45,19 +46,22 @@ export class GitBranchService { if (!trimmed) continue const isCurrent = trimmed.startsWith('*') - const namePart = trimmed.replace(/^\*?\s*/, '') + const isWorktree = trimmed.startsWith('+') + const namePart = trimmed.replace(/^[*+]?\s*/, '') const firstSpace = namePart.indexOf(' ') const firstBracket = namePart.indexOf('[') const cutIndex = firstSpace === -1 ? (firstBracket === -1 ? namePart.length : firstBracket) : (firstBracket === -1 ? firstSpace : Math.min(firstSpace, firstBracket)) - const branchName = namePart.slice(0, cutIndex) + const branchName = namePart.slice(0, cutIndex).trim() - if (!branchName) continue + if (!branchName || branchName === '+' || branchName === '->' || branchName.includes('->')) continue + if (/^[0-9a-f]{6,40}$/.test(branchName)) continue const branch: GitBranch = { name: branchName, type: branchName.startsWith('remotes/') ? 'remote' : 'local', - current: isCurrent && (branchName === currentBranch || branchName === `remotes/${currentBranch}`) + current: isCurrent && (branchName === currentBranch || branchName === `remotes/${currentBranch}`), + isWorktree } if (seenNames.has(branch.name)) continue diff --git a/frontend/src/api/repos.ts b/frontend/src/api/repos.ts index af7335b0..454e049b 100644 --- a/frontend/src/api/repos.ts +++ b/frontend/src/api/repos.ts @@ -149,6 +149,7 @@ interface GitBranch { upstream?: string ahead?: number behind?: number + isWorktree?: boolean } export async function listBranches(id: number): Promise<{ branches: GitBranch[], status: { ahead: number, behind: number } }> { diff --git a/frontend/src/components/file-browser/GitBranchSelector.tsx b/frontend/src/components/file-browser/GitBranchSelector.tsx deleted file mode 100644 index c6a9d50a..00000000 --- a/frontend/src/components/file-browser/GitBranchSelector.tsx +++ /dev/null @@ -1,74 +0,0 @@ -import { GitBranch, Loader2 } from 'lucide-react' -import { cn } from '@/lib/utils' -import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select' - -interface GitBranchSelectorProps { - repoId: number | undefined - branch: string | null - branches: string[] - onBranchChange: (branch: string) => void - isLoading?: boolean - error?: Error | null - ahead?: number - behind?: number -} - -export function GitBranchSelector({ branch, branches, onBranchChange, isLoading, error, ahead, behind }: GitBranchSelectorProps) { - if (isLoading) { - return ( -
- - Loading branches... -
- ) - } - - if (error) { - return ( -
- - Failed to load branches -
- ) - } - - if (!branch || branches.length === 0) { - return ( -
- - No branches available -
- ) - } - - const getBranchLabel = (branchName: string, isCurrent: boolean) => { - if (!isCurrent) return branchName - const parts = [branchName] - if (ahead && ahead > 0) parts.push(`${ahead} ahead`) - if (behind && behind > 0) parts.push(`${behind} behind`) - return parts.join(' ') - } - - return ( - - ) -} diff --git a/frontend/src/components/repo/AddBranchWorkspaceDialog.tsx b/frontend/src/components/repo/AddBranchWorkspaceDialog.tsx deleted file mode 100644 index 8e8155be..00000000 --- a/frontend/src/components/repo/AddBranchWorkspaceDialog.tsx +++ /dev/null @@ -1,138 +0,0 @@ -import { useState } from "react"; -import { useMutation, useQueryClient } from "@tanstack/react-query"; -import { createRepo, createBranch } from "@/api/repos"; -import { Button } from "@/components/ui/button"; -import { Input } from "@/components/ui/input"; -import { - Dialog, - DialogContent, - DialogHeader, - DialogTitle, -} from "@/components/ui/dialog"; -import { Loader2 } from "lucide-react"; - -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(false); - const queryClient = useQueryClient(); - - const mutation = useMutation({ - 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(false); - onOpenChange(false); - }, - }); - - const handleSubmit = (e: React.FormEvent) => { - e.preventDefault(); - if (branch.trim()) { - mutation.mutate(); - } - }; - - const handleCheckboxChange = (e: React.ChangeEvent) => { - e.stopPropagation(); - setUseWorktree(e.target.checked); - }; - - return ( - - - - - Add Branch - -

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

-
-
-
- - setBranch(e.target.value)} - disabled={mutation.isPending} - className="bg-[#1a1a1a] border-[#2a2a2a] text-white placeholder:text-zinc-500" - /> -
- -
-
- e.stopPropagation()} - /> - -
-

- {useWorktree - ? "Creates a separate workspace directory - allows working on multiple branches simultaneously" - : "Creates a local branch in the current repository"} -

-
- - - {mutation.isError && ( -

{mutation.error.message}

- )} -
-
-
- ); -} diff --git a/frontend/src/components/repo/BranchSwitcher.tsx b/frontend/src/components/repo/BranchSwitcher.tsx deleted file mode 100644 index 8a1c2828..00000000 --- a/frontend/src/components/repo/BranchSwitcher.tsx +++ /dev/null @@ -1,146 +0,0 @@ -import { useState, useCallback } from "react"; -import { Button } from "@/components/ui/button"; -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuItem, - DropdownMenuSeparator, - DropdownMenuTrigger, -} from "@/components/ui/dropdown-menu"; -import { GitBranch, Check, Plus, Loader2 } from "lucide-react"; -import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"; -import { listBranches, switchBranch, GitAuthError } from "@/api/repos"; -import { AddBranchWorkspaceDialog } from "@/components/repo/AddBranchWorkspaceDialog"; -import { showToast } from "@/lib/toast"; - -interface BranchSwitcherProps { - repoId: number; - currentBranch: string; - isWorktree?: boolean; - repoUrl?: string | null; - className?: string; - iconOnly?: boolean; -} - -export function BranchSwitcher({ repoId, currentBranch, isWorktree, repoUrl, className, iconOnly }: BranchSwitcherProps) { - const [addBranchOpen, setAddBranchOpen] = useState(false); - const queryClient = useQueryClient(); - - const { data: branches, isLoading: branchesLoading, refetch: refetchBranches } = useQuery({ - queryKey: ["branches", repoId], - queryFn: () => listBranches(repoId), - enabled: false, - staleTime: Infinity, - }); - - const activeBranch = branches?.branches?.find(b => b.current)?.name ?? currentBranch; - - const handleDropdownOpenChange = useCallback((open: boolean) => { - if (open && repoId) { - refetchBranches(); - } - }, [repoId, refetchBranches]); - - const switchBranchMutation = useMutation({ - mutationFn: (branch: string) => switchBranch(repoId, branch), - onSuccess: async (updatedRepo) => { - queryClient.setQueryData(["repo", repoId], updatedRepo); - queryClient.invalidateQueries({ queryKey: ["repos"] }); - await refetchBranches(); - showToast.success(`Switched to branch: ${updatedRepo.currentBranch}`); - }, - 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'); - } - }, - }); - - const showLoading = switchBranchMutation.isPending || (branchesLoading && !branches); - - return ( - <> - - - - - - {isWorktree ? ( - -
- - Worktree: {activeBranch} -
-
- ) : ( - <> - {repoUrl && ( - <> - setAddBranchOpen(true)} - className="text-muted-foreground hover:text-foreground hover:bg-accent cursor-pointer" - > -
- - Add Branch -
-
- - - )} -
- {branchesLoading && !branches ? ( - - Loading branches... - - ) : branches?.branches && branches.branches.length > 0 ? ( - branches.branches.filter(b => b.type === 'local').map((branch) => ( - switchBranchMutation.mutate(branch.name)} - disabled={switchBranchMutation.isPending} - className="text-muted-foreground hover:text-foreground hover:bg-accent cursor-pointer" - > -
- - {branch.name} - {branch.name === activeBranch && } -
-
- )) - ) : ( - - No branches available - - )} -
- - )} -
-
- - {repoUrl && ( - - )} - - ); -} diff --git a/frontend/src/components/repo/RepoCard.tsx b/frontend/src/components/repo/RepoCard.tsx index 078dc6cf..5b4e14cf 100644 --- a/frontend/src/components/repo/RepoCard.tsx +++ b/frontend/src/components/repo/RepoCard.tsx @@ -1,14 +1,13 @@ import { useState } from "react"; import { Button } from "@/components/ui/button"; -import { Badge } from "@/components/ui/badge"; + import { Checkbox } from "@/components/ui/checkbox"; import { Loader2, Trash2, Download, GitBranch, FolderOpen, AlertCircle } from "lucide-react"; import { useNavigate } from "react-router-dom"; import { downloadRepo } from "@/api/repos"; import { showToast } from "@/lib/toast"; import type { GitStatusResponse } from "@/types/git"; - -import { BranchSwitcher } from "./BranchSwitcher"; +import { SourceControlPanel } from "@/components/source-control/SourceControlPanel"; interface RepoCardProps { repo: { @@ -38,6 +37,7 @@ export function RepoCard({ }: RepoCardProps) { const navigate = useNavigate(); const [isDownloading, setIsDownloading] = useState(false); + const [showSourceControl, setShowSourceControl] = useState(false); const repoName = repo.repoUrl ? repo.repoUrl.split("/").slice(-1)[0].replace(".git", "") @@ -53,7 +53,7 @@ export function RepoCard({ const unstagedCount = gitStatus?.files.filter((f) => !f.staged).length || 0; const handleCardClick = () => { - if (isReady) { + if (isReady && !showSourceControl) { navigate(`/repos/${repo.id}`); } }; @@ -96,11 +96,7 @@ export function RepoCard({ {isReady && (
)} - {repo.isWorktree && ( - - worktree - - )} +
@@ -113,7 +109,7 @@ export function RepoCard({ ) : ( <> - + {branchToDisplay || "main"} @@ -145,14 +141,16 @@ export function RepoCard({
e.stopPropagation()}> - +
+ + setShowSourceControl(false)} + currentBranch={branchToDisplay || ""} + repoUrl={repo.repoUrl} + isRepoWorktree={repo.isWorktree} + repoName={repoName} + /> ); } diff --git a/frontend/src/components/source-control/BranchesTab.tsx b/frontend/src/components/source-control/BranchesTab.tsx index 89a0344d..ec6af606 100644 --- a/frontend/src/components/source-control/BranchesTab.tsx +++ b/frontend/src/components/source-control/BranchesTab.tsx @@ -1,9 +1,10 @@ import { useState } from 'react' import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' -import { listBranches, switchBranch, GitAuthError } from '@/api/repos' +import { listBranches, switchBranch, createRepo, GitAuthError } from '@/api/repos' import { useGitStatus } from '@/api/git' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' +import { Checkbox } from '@/components/ui/checkbox' import { Loader2, GitBranch, Check, Plus, AlertCircle, ArrowUp, ArrowDown, Globe } from 'lucide-react' import { cn } from '@/lib/utils' import { showToast } from '@/lib/toast' @@ -13,12 +14,15 @@ import { GIT_UI_COLORS } from '@/lib/git-status-styles' interface BranchesTabProps { repoId: number currentBranch: string + repoUrl?: string | null + isRepoWorktree?: boolean } -export function BranchesTab({ repoId, currentBranch }: BranchesTabProps) { +export function BranchesTab({ repoId, currentBranch, repoUrl, isRepoWorktree }: BranchesTabProps) { const queryClient = useQueryClient() const [newBranchName, setNewBranchName] = useState('') const [isCreating, setIsCreating] = useState(false) + const [useWorktree, setUseWorktree] = useState(false) const git = useGit(repoId) const { data: status } = useGitStatus(repoId) @@ -47,14 +51,33 @@ export function BranchesTab({ repoId, currentBranch }: BranchesTabProps) { }, }) + const worktreeMutation = useMutation({ + mutationFn: (branch: string) => createRepo(repoUrl || undefined, undefined, branch, undefined, true), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: ['repos'] }) + setNewBranchName('') + setIsCreating(false) + setUseWorktree(false) + showToast.success('Branch workspace created') + }, + onError: (error) => { + showToast.error(error instanceof Error ? error.message : 'Failed to create branch workspace') + }, + }) + const handleCreateBranch = async () => { if (!newBranchName.trim()) return try { - await git.createBranch.mutateAsync(newBranchName.trim()) - setNewBranchName('') - setIsCreating(false) - refetch() + if (useWorktree && repoUrl) { + await worktreeMutation.mutateAsync(newBranchName.trim()) + } else { + await git.createBranch.mutateAsync(newBranchName.trim()) + setNewBranchName('') + setIsCreating(false) + setUseWorktree(false) + refetch() + } } catch { // Error handled by mutation } @@ -103,44 +126,57 @@ export function BranchesTab({ repoId, currentBranch }: BranchesTabProps) { {isCreating ? ( -
- setNewBranchName(e.target.value)} - className="h-8 text-sm" - autoFocus - onKeyDown={(e) => { - if (e.key === 'Enter') handleCreateBranch() - if (e.key === 'Escape') { +
+
+ setNewBranchName(e.target.value)} + className="h-8 text-sm" + autoFocus + onKeyDown={(e) => { + if (e.key === 'Enter') handleCreateBranch() + if (e.key === 'Escape') { + setIsCreating(false) + setNewBranchName('') + setUseWorktree(false) + } + }} + /> + + - + setUseWorktree(false) + }} + > + Cancel + +
+ {repoUrl && ( + + )}
) : ( ) })} diff --git a/frontend/src/components/source-control/SourceControlPanel.tsx b/frontend/src/components/source-control/SourceControlPanel.tsx index 0ecb264c..4994610c 100644 --- a/frontend/src/components/source-control/SourceControlPanel.tsx +++ b/frontend/src/components/source-control/SourceControlPanel.tsx @@ -1,7 +1,6 @@ import { useState } from 'react' -import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' import { useGitStatus, getApiErrorMessage } from '@/api/git' -import { listBranches, switchBranch } from '@/api/repos' + import { useGit } from '@/hooks/useGit' import { ChangesTab } from './ChangesTab' import { CommitsTab } from './CommitsTab' @@ -9,7 +8,6 @@ import { BranchesTab } from './BranchesTab' import { FileDiffView } from '@/components/file-browser/FileDiffView' import { Button } from '@/components/ui/button' import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog' -import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu' import { GIT_UI_COLORS } from '@/lib/git-status-styles' import { Loader2, @@ -22,8 +20,6 @@ import { RefreshCw, ArrowDownFromLine, X, - ChevronDown, - Check, } from 'lucide-react' import { cn } from '@/lib/utils' import { useMobile } from '@/hooks/useMobile' @@ -34,6 +30,9 @@ interface SourceControlPanelProps { isOpen: boolean onClose: () => void currentBranch: string + repoUrl?: string | null + isRepoWorktree?: boolean + repoName?: string } type Tab = 'changes' | 'commits' | 'branches' @@ -43,32 +42,15 @@ export function SourceControlPanel({ isOpen, onClose, currentBranch, + repoUrl, + isRepoWorktree, + repoName, }: SourceControlPanelProps) { const [activeTab, setActiveTab] = useState('changes') const [selectedFile, setSelectedFile] = useState<{path: string, staged: boolean} | undefined>() const { data: status } = useGitStatus(repoId) - const { data: branches } = useQuery({ - queryKey: ['branches', repoId], - queryFn: () => listBranches(repoId), - staleTime: 30000, - }) const git = useGit(repoId) - const queryClient = useQueryClient() const isMobile = useMobile() - - const switchBranchMutation = useMutation({ - mutationFn: (branch: string) => switchBranch(repoId, branch), - onSuccess: (updatedRepo) => { - queryClient.setQueryData(['repo', repoId], updatedRepo) - queryClient.invalidateQueries({ queryKey: ['repos'] }) - queryClient.invalidateQueries({ queryKey: ['gitStatus', repoId] }) - queryClient.invalidateQueries({ queryKey: ['branches', repoId] }) - }, - onError: (error) => { - showToast.error(getApiErrorMessage(error)) - }, - }) - const handleGitAction = async (action: () => Promise) => { try { await action() @@ -91,29 +73,10 @@ export function SourceControlPanel({
- - - - - - {branches?.branches?.filter(b => b.type === 'local')?.map((branch) => ( - branch.name !== currentBranch && switchBranchMutation.mutate(branch.name)} - disabled={branch.name === currentBranch || switchBranchMutation.isPending} - className="flex items-center gap-2" - > - - {branch.name} - {branch.name === currentBranch && } - - ))} - - +
+ + {currentBranch} +
{status && (status.ahead > 0 || status.behind > 0) && (
{status.ahead > 0 && ( @@ -218,7 +181,7 @@ export function SourceControlPanel({ )} {activeTab === 'branches' && ( - + )}
@@ -260,7 +223,7 @@ export function SourceControlPanel({ )}> - Source Control + {isMobile && repoName ? repoName : 'Source Control'} {isMobile && (
); diff --git a/package.json b/package.json index c23f8d26..fe315685 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "opencode-manager", - "version": "0.7.7", + "version": "0.7.8", "private": false, "type": "module", "packageManager": "pnpm@10.28.1", diff --git a/shared/src/config/env.ts b/shared/src/config/env.ts index 893d4cb9..859f8d34 100644 --- a/shared/src/config/env.ts +++ b/shared/src/config/env.ts @@ -94,7 +94,6 @@ export const ENV = { ADMIN_EMAIL: process.env.ADMIN_EMAIL, ADMIN_PASSWORD: process.env.ADMIN_PASSWORD, ADMIN_PASSWORD_RESET: getEnvBoolean('ADMIN_PASSWORD_RESET', false), - SECURE_COOKIES: getEnvBoolean('AUTH_SECURE_COOKIES', process.env.NODE_ENV === 'production'), GITHUB_CLIENT_ID: process.env.GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET: process.env.GITHUB_CLIENT_SECRET, GOOGLE_CLIENT_ID: process.env.GOOGLE_CLIENT_ID,