feat(git): extend source control with worktrees, stashes, conflicts and identities

- Create a worktree from a new or existing branch
- Integrate a worktree branch into a target branch by merge commit or cherry-pick, with continue/abort on conflicts
- Delete a worktree with keep, delete-local, or delete-local-and-remote branch options, using safe branch deletion for unmerged branches
- Add a stash tab (list, push, apply, pop, drop) shared across a repository and its worktrees
- Rename and delete branches, optionally deleting the remote branch and updating scheduled base branches
- Detect in-progress merge, rebase, cherry-pick and revert operations and hand conflicts to an agent session
- Generate commit messages from staged changes with the default model
- Add a default git identity and saved per-repository identities written to git config
- Unify git error mapping behind a typed error and one route helper; consolidate git mutations and cache invalidation
- Update repository docs
This commit is contained in:
Chris Scott committed 2026-10-03 21:59:00 -04:00
1 parent 52b6147ed3
commit 53238a6324
89 files changed
+7704 -793

No files matched your search

@@ -0,0 +1,75 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { BranchesTab } from './BranchesTab'
const mutateAsync = vi.fn()
vi.mock('@/api/repos', () => {
class GitAuthError extends Error {}
return {
GitAuthError,
listBranches: vi.fn(),
getRepo: vi.fn(),
switchBranch: vi.fn(),
}
})
vi.mock('@/api/git', () => ({
fetchGitStatus: vi.fn(),
useGitStatus: () => ({ data: undefined, dataUpdatedAt: 0 }),
}))
vi.mock('@/hooks/useGit', () => ({
useGit: () => ({
createBranch: { isPending: false, mutateAsync },
switchBranch: { isPending: false, mutateAsync },
renameBranch: { isPending: false, mutateAsync },
deleteBranch: { isPending: false, mutateAsync },
integrateBranch: { isPending: false, mutate: vi.fn() },
}),
}))
vi.mock('@/lib/toast', () => ({
showToast: { success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn() },
}))
vi.mock('@/components/repo/CreateWorktreeDialog', () => ({
CreateWorktreeDialog: () => null,
}))
import { listBranches, getRepo } from '@/api/repos'
const createWrapper = () => {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
})
return ({ children }: { children: React.ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
}
beforeEach(() => {
vi.clearAllMocks()
vi.mocked(listBranches).mockResolvedValue({
branches: [
{ name: 'main', type: 'local', current: true },
{ name: 'feature', type: 'local', current: false },
],
status: { ahead: 0, behind: 0 },
})
vi.mocked(getRepo).mockResolvedValue({ repoUrl: 'git@example.com:org/repo.git', isWorktree: false } as never)
})
describe('BranchesTab', () => {
it('gives the inline rename textbox a descriptive accessible name', async () => {
const user = userEvent.setup()
render(<BranchesTab repoId={1} currentBranch="main" />, { wrapper: createWrapper() })
await user.click(await screen.findByRole('button', { name: 'Actions for feature' }))
await user.click(await screen.findByRole('menuitem', { name: 'Rename' }))
expect(screen.getByRole('textbox', { name: 'New name for branch feature' })).toBeInTheDocument()
})
})
@@ -4,12 +4,16 @@ import { listBranches, switchBranch, GitAuthError, getRepo } from '@/api/repos'
import { fetchGitStatus } from '@/api/git'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Loader2, GitBranch, GitBranchPlus, Check, Plus, AlertCircle, Globe } from 'lucide-react'
import { Checkbox } from '@/components/ui/checkbox'
import { ConfirmDestructiveDialog } from '@/components/ui/confirm-destructive-dialog'
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
import { Loader2, GitBranch, GitBranchPlus, GitMerge, Check, Plus, AlertCircle, Globe, MoreHorizontal, Pencil, Trash2 } from 'lucide-react'
import { cn } from '@/lib/utils'
import { showToast } from '@/lib/toast'
import { useGit } from '@/hooks/useGit'
import { GIT_UI_COLORS } from '@/lib/git-status-styles'
import { CreateWorktreeDialog } from '@/components/repo/CreateWorktreeDialog'
import { IntegrateBranchDialog } from '@/components/source-control/IntegrateBranchDialog'
import { invalidateRepoGitCaches, setRepoGitStatusCaches } from '@/lib/queryInvalidation'
interface BranchesTabProps {
@@ -17,12 +21,23 @@ interface BranchesTabProps {
currentBranch: string
}
interface BranchTarget {
name: string
upstream?: string
}
export function BranchesTab({ repoId, currentBranch }: BranchesTabProps) {
const queryClient = useQueryClient()
const [newBranchName, setNewBranchName] = useState('')
const [searchQuery, setSearchQuery] = useState('')
const [isCreating, setIsCreating] = useState(false)
const [worktreeDialogOpen, setWorktreeDialogOpen] = useState(false)
const [integrateDialogOpen, setIntegrateDialogOpen] = useState(false)
const [renamingBranch, setRenamingBranch] = useState<string | null>(null)
const [renameValue, setRenameValue] = useState('')
const [branchToDelete, setBranchToDelete] = useState<BranchTarget | null>(null)
const [forceDelete, setForceDelete] = useState(false)
const [deleteRemote, setDeleteRemote] = useState(false)
const git = useGit(repoId)
const { data: branches, isLoading, error, refetch } = useQuery({
@@ -82,6 +97,58 @@ export function BranchesTab({ repoId, currentBranch }: BranchesTabProps) {
}
}
const startRename = (branch: BranchTarget) => {
setRenamingBranch(branch.name)
setRenameValue(branch.name)
}
const cancelRename = () => {
setRenamingBranch(null)
setRenameValue('')
}
const handleRename = async () => {
const nextName = renameValue.trim()
if (!renamingBranch || !nextName || nextName === renamingBranch) {
cancelRename()
return
}
try {
await git.renameBranch.mutateAsync({ from: renamingBranch, to: nextName })
cancelRename()
} catch {
// Error handled by mutation
}
}
const startDelete = (branch: BranchTarget) => {
setBranchToDelete({ name: branch.name, upstream: branch.upstream })
setForceDelete(false)
setDeleteRemote(false)
}
const closeDelete = () => {
setBranchToDelete(null)
setForceDelete(false)
setDeleteRemote(false)
}
const handleDelete = async () => {
if (!branchToDelete) return
try {
await git.deleteBranch.mutateAsync({
name: branchToDelete.name,
force: forceDelete,
deleteRemote: branchToDelete.upstream ? deleteRemote : false,
})
closeDelete()
} catch {
// Error handled by mutation
}
}
if (isLoading) {
return (
<div className="flex items-center justify-center py-12">
@@ -178,6 +245,18 @@ export function BranchesTab({ repoId, currentBranch }: BranchesTabProps) {
<span className="hidden sm:inline ml-1">Worktree</span>
</Button>
)}
{isRepoWorktree && (
<Button
size="sm"
variant="outline"
className="h-10 md:h-8 flex-shrink-0"
onClick={() => setIntegrateDialogOpen(true)}
title="Integrate this worktree branch into another branch"
>
<GitMerge className="w-4 h-4" />
<span className="hidden sm:inline ml-1">Integrate</span>
</Button>
)}
</div>
)}
</div>
@@ -202,32 +281,91 @@ export function BranchesTab({ repoId, currentBranch }: BranchesTabProps) {
switchBranchMutation.mutate(checkoutName)
}
if (renamingBranch === branch.name) {
return (
<div key={branch.name} className="flex items-center gap-2 px-3 py-2">
<Input
value={renameValue}
onChange={(e) => setRenameValue(e.target.value)}
className="h-10 md:h-8 md:text-sm flex-1 min-w-0"
aria-label={`New name for branch ${renamingBranch}`}
autoFocus
onKeyDown={(e) => {
if (e.key === 'Enter') handleRename()
if (e.key === 'Escape') cancelRename()
}}
/>
<Button
size="sm"
className="h-10 md:h-8"
onClick={handleRename}
disabled={!renameValue.trim() || git.renameBranch.isPending}
>
{git.renameBranch.isPending ? <Loader2 className="w-4 h-4 animate-spin" /> : 'Rename'}
</Button>
<Button size="sm" variant="ghost" className="h-10 md:h-8" onClick={cancelRename}>
Cancel
</Button>
</div>
)
}
return (
<button
<div
key={branch.name}
className={cn(
'flex items-center gap-2 px-3 py-2 w-full text-left transition-colors',
'flex items-center gap-1 px-3 py-2 w-full transition-colors',
isCurrent && 'bg-highlight/10',
isCheckedOutElsewhere ? 'opacity-60 cursor-not-allowed' : 'hover:bg-accent/50'
isCheckedOutElsewhere ? 'opacity-60' : 'hover:bg-accent/50'
)}
onClick={handleClick}
disabled={isCurrent || isCheckedOutElsewhere || switchBranchMutation.isPending}
title={isCheckedOutElsewhere ? 'Branch is checked out in another worktree' : undefined}
>
{isRemote ? (
<Globe className="w-4 h-4 text-info" />
) : (
<GitBranch className={cn('w-4 h-4', isCurrent ? GIT_UI_COLORS.current : 'text-muted-foreground')} />
<button
className="flex items-center gap-2 flex-1 min-w-0 text-left"
onClick={handleClick}
disabled={isCurrent || isCheckedOutElsewhere || switchBranchMutation.isPending}
title={isCheckedOutElsewhere ? 'Branch is checked out in another worktree' : undefined}
>
{isRemote ? (
<Globe className="w-4 h-4 text-info" />
) : (
<GitBranch className={cn('w-4 h-4', isCurrent ? GIT_UI_COLORS.current : 'text-muted-foreground')} />
)}
<span className="flex-1 text-sm truncate">{branch.name}</span>
{(isCheckedOutElsewhere || (isCurrent && isRepoWorktree)) && (
<span className="text-[10px] px-1.5 py-0.5 rounded bg-primary/20 text-primary">worktree</span>
)}
{branch.type === 'local' && !branch.upstream && !branch.isWorktree && !(isCurrent && isRepoWorktree) && (
<span className="text-[10px] px-1.5 py-0.5 rounded bg-muted text-muted-foreground">local</span>
)}
{isCurrent && <Check className={`w-4 h-4 ${GIT_UI_COLORS.current}`} />}
</button>
{!isRemote && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
type="button"
className="p-1 rounded text-muted-foreground hover:bg-accent"
aria-label={`Actions for ${branch.name}`}
>
<MoreHorizontal className="w-4 h-4" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onSelect={() => startRename(branch)} disabled={isCheckedOutElsewhere}>
<Pencil className="w-4 h-4 mr-2" />
Rename
</DropdownMenuItem>
<DropdownMenuItem
onSelect={() => startDelete(branch)}
disabled={isCurrent || !!branch.isWorktree}
>
<Trash2 className="w-4 h-4 mr-2" />
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)}
<span className="flex-1 text-sm truncate">{branch.name}</span>
{(isCheckedOutElsewhere || (isCurrent && isRepoWorktree)) && (
<span className="text-[10px] px-1.5 py-0.5 rounded bg-primary/20 text-primary">worktree</span>
)}
{branch.type === 'local' && !branch.upstream && !branch.isWorktree && !(isCurrent && isRepoWorktree) && (
<span className="text-[10px] px-1.5 py-0.5 rounded bg-muted text-muted-foreground">local</span>
)}
{isCurrent && <Check className={`w-4 h-4 ${GIT_UI_COLORS.current}`} />}
</button>
</div>
)
})}
</div>
@@ -250,6 +388,46 @@ export function BranchesTab({ repoId, currentBranch }: BranchesTabProps) {
repoUrl={repoUrl}
defaultBaseBranch={activeBranch}
/>
<IntegrateBranchDialog
open={integrateDialogOpen}
onOpenChange={setIntegrateDialogOpen}
repoId={repoId}
sourceBranch={activeBranch}
/>
<ConfirmDestructiveDialog
open={!!branchToDelete}
onOpenChange={(open) => {
if (!open) closeDelete()
}}
onConfirm={handleDelete}
onCancel={closeDelete}
title={`Delete branch "${branchToDelete?.name ?? ''}"?`}
description="This removes the local branch. This action cannot be undone."
confirmLabel="Delete"
pendingLabel="Deleting..."
isPending={git.deleteBranch.isPending}
>
<div className="space-y-3">
<label className="flex items-center gap-2 text-sm cursor-pointer">
<Checkbox
checked={forceDelete}
onCheckedChange={(checked) => setForceDelete(checked === true)}
/>
Force delete unmerged branch
</label>
{branchToDelete?.upstream && (
<label className="flex items-center gap-2 text-sm cursor-pointer">
<Checkbox
checked={deleteRemote}
onCheckedChange={(checked) => setDeleteRemote(checked === true)}
/>
Also delete remote branch
</label>
)}
</div>
</ConfirmDestructiveDialog>
</div>
)
}
@@ -2,11 +2,12 @@ import { useState } from 'react'
import { useGitStatus } from '@/api/git'
import { useGit } from '@/hooks/useGit'
import { GitFlatFileList } from './GitFlatFileList'
import { RepoGitIdentitySelect } from './RepoGitIdentitySelect'
import { Button } from '@/components/ui/button'
import { Textarea } from '@/components/ui/textarea'
import { FileDiffView } from '@/components/file-browser/FileDiffView'
import { DiscardDialog } from '@/components/ui/discard-dialog'
import { Loader2, GitCommit, FileText, AlertCircle } from 'lucide-react'
import { Loader2, GitCommit, FileText, AlertCircle, Sparkles } from 'lucide-react'
interface ChangesTabProps {
repoId: number
@@ -60,6 +61,16 @@ export function ChangesTab({ repoId, onFileSelect, onClearFileSelection, selecte
setCommitMessage('')
}
const handleGenerateMessage = () => {
git.generateCommitMessage.mutate(undefined, {
onSuccess: ({ message }) => {
if (commitMessage.trim() === '' || window.confirm('Replace the current commit message?')) {
setCommitMessage(message)
}
},
})
}
if (isLoading) {
return (
<div className="flex items-center justify-center py-12">
@@ -129,17 +140,36 @@ export function ChangesTab({ repoId, onFileSelect, onClearFileSelection, selecte
{status.hasChanges && (
<div className="p-3 border-t border-border space-y-2 flex-shrink-0">
<Textarea
placeholder="Commit message..."
value={commitMessage}
onChange={(e) => setCommitMessage(e.target.value)}
className="min-h-[80px] md:text-sm resize-none"
onKeyDown={(e) => {
if ((e.metaKey || e.ctrlKey) && e.key === 'Enter' && canCommit) {
handleCommit()
}
}}
/>
<RepoGitIdentitySelect repoId={repoId} />
<div className="relative">
<Textarea
placeholder="Commit message..."
value={commitMessage}
onChange={(e) => setCommitMessage(e.target.value)}
className="min-h-[80px] md:text-sm resize-none pr-10"
onKeyDown={(e) => {
if ((e.metaKey || e.ctrlKey) && e.key === 'Enter' && canCommit) {
handleCommit()
}
}}
/>
<Button
type="button"
size="sm"
variant="ghost"
className="absolute top-1 right-1 h-7 w-7 p-0"
onClick={handleGenerateMessage}
disabled={stagedFiles.length === 0 || git.generateCommitMessage.isPending}
aria-label="Generate commit message"
title="Generate commit message with AI"
>
{git.generateCommitMessage.isPending ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : (
<Sparkles className="w-4 h-4" />
)}
</Button>
</div>
<Button
onClick={handleCommit}
disabled={!canCommit}
@@ -0,0 +1,114 @@
import { describe, it, expect, vi, beforeEach, beforeAll } from 'vitest'
import { render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import type { ReactNode } from 'react'
import type { GitOperationState } from '@opencode-manager/shared'
import { GitOperationBanner } from './GitOperationBanner'
const { continueMutate, abortMutate, resolveMutate } = vi.hoisted(() => ({
continueMutate: vi.fn(),
abortMutate: vi.fn(),
resolveMutate: vi.fn(),
}))
vi.mock('@/hooks/useGit', () => ({
useGit: () => ({
continueOperation: { mutate: continueMutate, isPending: false },
abortOperation: { mutate: abortMutate, isPending: false },
}),
}))
vi.mock('@/hooks/useResolveConflictsWithAgent', () => ({
useResolveConflictsWithAgent: () => ({ mutate: resolveMutate, isPending: false }),
}))
vi.mock('@/api/repos', () => ({
getRepo: vi.fn().mockResolvedValue({
id: 1,
fullPath: '/abs/repos/my-repo',
currentBranch: 'main',
defaultBranch: 'main',
}),
}))
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
function wrap(node: ReactNode) {
return <QueryClientProvider client={queryClient}>{node}</QueryClientProvider>
}
function renderBanner(operation: GitOperationState) {
return render(wrap(<GitOperationBanner repoId={1} operation={operation} />))
}
describe('GitOperationBanner', () => {
beforeAll(() => {
Element.prototype.hasPointerCapture ??= () => false
Element.prototype.setPointerCapture ??= () => {}
Element.prototype.releasePointerCapture ??= () => {}
})
beforeEach(() => {
vi.clearAllMocks()
})
it('shows the operation kind and conflicted files', () => {
renderBanner({ kind: 'merge', conflictedFiles: ['file.txt', 'other.ts'] })
expect(screen.getByText('Merge in progress')).toBeInTheDocument()
expect(screen.getByText('file.txt')).toBeInTheDocument()
expect(screen.getByText('other.ts')).toBeInTheDocument()
expect(screen.getByText('2 conflicts')).toBeInTheDocument()
})
it('disables continue while conflicts remain and enables it once resolved', () => {
const { rerender } = renderBanner({ kind: 'merge', conflictedFiles: ['file.txt'] })
expect(screen.getByRole('button', { name: /continue/i })).toBeDisabled()
rerender(wrap(<GitOperationBanner repoId={1} operation={{ kind: 'merge', conflictedFiles: [] }} />))
expect(screen.getByRole('button', { name: /continue/i })).toBeEnabled()
})
it('continues the operation when continue is clicked', async () => {
const user = userEvent.setup()
renderBanner({ kind: 'rebase', conflictedFiles: [] })
await user.click(screen.getByRole('button', { name: /continue/i }))
expect(continueMutate).toHaveBeenCalledTimes(1)
})
it('requires confirmation before aborting', async () => {
const user = userEvent.setup()
renderBanner({ kind: 'cherry-pick', conflictedFiles: ['file.txt'] })
await user.click(screen.getByRole('button', { name: /abort/i }))
expect(abortMutate).not.toHaveBeenCalled()
const dialog = await screen.findByRole('dialog')
await user.click(within(dialog).getByRole('button', { name: 'Abort' }))
expect(abortMutate).toHaveBeenCalledTimes(1)
})
it('only offers agent resolution while conflicts remain', () => {
const { rerender } = renderBanner({ kind: 'merge', conflictedFiles: [] })
expect(screen.queryByRole('button', { name: /resolve with agent/i })).not.toBeInTheDocument()
rerender(wrap(<GitOperationBanner repoId={1} operation={{ kind: 'merge', conflictedFiles: ['file.txt'] }} />))
expect(screen.getByRole('button', { name: /resolve with agent/i })).toBeEnabled()
})
it('starts agent resolution with the current operation and branch', async () => {
const user = userEvent.setup()
renderBanner({ kind: 'merge', conflictedFiles: ['file.txt'] })
await user.click(screen.getByRole('button', { name: /resolve with agent/i }))
expect(resolveMutate).toHaveBeenCalledWith({
operation: { kind: 'merge', conflictedFiles: ['file.txt'] },
branch: 'main',
})
})
})
@@ -0,0 +1,117 @@
import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { getRepo } from '@/api/repos'
import { useGit } from '@/hooks/useGit'
import { useResolveConflictsWithAgent } from '@/hooks/useResolveConflictsWithAgent'
import { Button } from '@/components/ui/button'
import { ConfirmDestructiveDialog } from '@/components/ui/confirm-destructive-dialog'
import { AlertTriangle, Loader2 } from 'lucide-react'
import type { GitOperationKind, GitOperationState } from '@opencode-manager/shared'
const OPERATION_LABELS: Record<GitOperationKind, string> = {
merge: 'Merge',
rebase: 'Rebase',
'cherry-pick': 'Cherry-pick',
revert: 'Revert',
}
interface GitOperationBannerProps {
repoId: number
operation: GitOperationState
}
export function GitOperationBanner({ repoId, operation }: GitOperationBannerProps) {
const git = useGit(repoId)
const { data: repo } = useQuery({
queryKey: ['repo', repoId],
queryFn: () => getRepo(repoId),
})
const resolveWithAgent = useResolveConflictsWithAgent({ id: repoId, fullPath: repo?.fullPath ?? '' })
const [confirmAbort, setConfirmAbort] = useState(false)
const conflictedFiles = operation.conflictedFiles
const hasConflicts = conflictedFiles.length > 0
const label = OPERATION_LABELS[operation.kind]
const busy = git.continueOperation.isPending || git.abortOperation.isPending || resolveWithAgent.isPending
const handleAbort = () => {
git.abortOperation.mutate(undefined, { onSuccess: () => setConfirmAbort(false) })
}
const handleResolveWithAgent = () => {
if (!repo) return
resolveWithAgent.mutate({ operation, branch: repo.currentBranch ?? repo.branch ?? '' })
}
return (
<div role="alert" className="flex-shrink-0 border-b border-warning/30 bg-warning/10 px-3 py-2">
<div className="flex items-center justify-between gap-2">
<div className="flex min-w-0 items-center gap-2">
<AlertTriangle className="h-4 w-4 flex-shrink-0 text-warning" />
<span className="truncate text-sm font-medium">{label} in progress</span>
{hasConflicts && (
<span className="text-xs text-muted-foreground">
{conflictedFiles.length} conflict{conflictedFiles.length === 1 ? '' : 's'}
</span>
)}
</div>
<div className="flex flex-shrink-0 items-center gap-1">
{hasConflicts && (
<Button
size="sm"
variant="outline"
className="h-7 px-2"
onClick={handleResolveWithAgent}
disabled={!repo || busy}
title="Open a session that resolves these conflicts with an agent"
>
{resolveWithAgent.isPending && <Loader2 className="mr-1 h-4 w-4 animate-spin" />}
Resolve with agent
</Button>
)}
<Button
size="sm"
variant="ghost"
className="h-7 px-2"
onClick={() => setConfirmAbort(true)}
disabled={busy}
>
{git.abortOperation.isPending && <Loader2 className="mr-1 h-4 w-4 animate-spin" />}
Abort
</Button>
<Button
size="sm"
className="h-7 px-2"
onClick={() => git.continueOperation.mutate()}
disabled={hasConflicts || busy}
title={hasConflicts ? 'Resolve all conflicts before continuing' : `Continue the ${operation.kind}`}
>
{git.continueOperation.isPending && <Loader2 className="mr-1 h-4 w-4 animate-spin" />}
Continue
</Button>
</div>
</div>
{hasConflicts && (
<ul className="mt-1 ml-6 space-y-0.5 text-xs text-muted-foreground">
{conflictedFiles.map((file) => (
<li key={file} className="truncate" title={file}>
{file}
</li>
))}
</ul>
)}
<ConfirmDestructiveDialog
open={confirmAbort}
onOpenChange={(open) => {
if (!open) setConfirmAbort(false)
}}
onConfirm={handleAbort}
onCancel={() => setConfirmAbort(false)}
title={`Abort ${operation.kind}?`}
description={`This cancels the ${operation.kind} in progress and restores the previous state.`}
confirmLabel="Abort"
pendingLabel="Aborting..."
isPending={git.abortOperation.isPending}
/>
</div>
)
}
@@ -0,0 +1,179 @@
import { describe, it, expect, vi, beforeEach, beforeAll } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import type { ReactNode } from 'react'
import { FetchError } from '@opencode-manager/shared'
import type { GitOperationState } from '@opencode-manager/shared'
import type { GitStatusResponse } from '@/types/git'
import { IntegrateBranchDialog } from './IntegrateBranchDialog'
const { integrateMutate, fetchStatus, continueMutate, abortMutate, resolveMutate } = vi.hoisted(() => ({
integrateMutate: vi.fn(),
fetchStatus: vi.fn(),
continueMutate: vi.fn(),
abortMutate: vi.fn(),
resolveMutate: vi.fn(),
}))
vi.mock('@/api/git', async () => {
const { useQuery } = await import('@tanstack/react-query')
return {
fetchGitStatus: fetchStatus,
getApiErrorMessage: (error: unknown) => (error instanceof Error ? error.message : String(error)),
useGitStatus: (repoId: number | undefined, options?: { refetchInterval?: number | false }) =>
useQuery({
queryKey: ['gitStatus', repoId],
queryFn: () => (repoId ? fetchStatus(repoId) : Promise.reject(new Error('No repo ID'))),
enabled: !!repoId,
refetchInterval: options?.refetchInterval ?? false,
}),
}
})
vi.mock('@/api/repos', () => ({
getRepo: vi.fn().mockResolvedValue({ id: 1, defaultBranch: 'main' }),
listBranches: vi.fn().mockResolvedValue({
branches: [
{ name: 'feature', type: 'local', current: true },
{ name: 'main', type: 'local', current: false },
],
status: { ahead: 0, behind: 0 },
}),
}))
vi.mock('@/hooks/useGit', () => ({
useGit: () => ({
integrateBranch: { mutate: integrateMutate, isPending: false },
continueOperation: { mutate: continueMutate, isPending: false },
abortOperation: { mutate: abortMutate, isPending: false },
}),
}))
vi.mock('@/hooks/useResolveConflictsWithAgent', () => ({
useResolveConflictsWithAgent: () => ({ mutate: resolveMutate, isPending: false }),
}))
vi.mock('@/lib/toast', () => ({
showToast: { success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn() },
}))
function createQueryClient() {
return new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } })
}
function wrap(node: ReactNode, queryClient: QueryClient) {
return <QueryClientProvider client={queryClient}>{node}</QueryClientProvider>
}
function targetStatus(operation: GitOperationState | null): GitStatusResponse {
return { branch: 'main', ahead: 0, behind: 0, files: [], hasChanges: false, operation }
}
function conflictError(operation: GitOperationState) {
return new FetchError('Integration stopped on conflicts', 409, 'MERGE_CONFLICT', undefined, {
details: { targetRepoId: 2, operation },
})
}
function failIntegration(operation: GitOperationState) {
integrateMutate.mockImplementation(
(_variables: unknown, options?: { onError?: (error: unknown) => void }) => {
options?.onError?.(conflictError(operation))
},
)
}
async function triggerConflict(user: ReturnType<typeof userEvent.setup>) {
await user.click(await screen.findByRole('button', { name: 'Integrate' }))
await screen.findByText('Merge in progress')
}
describe('IntegrateBranchDialog', () => {
beforeAll(() => {
Element.prototype.hasPointerCapture ??= () => false
Element.prototype.setPointerCapture ??= () => {}
Element.prototype.releasePointerCapture ??= () => {}
})
beforeEach(() => {
vi.clearAllMocks()
})
it('renders the operation banner for the target repo when integration stops on conflicts', async () => {
const user = userEvent.setup()
const queryClient = createQueryClient()
const operation = { kind: 'merge' as const, conflictedFiles: ['file.txt'] }
failIntegration(operation)
fetchStatus.mockResolvedValue(targetStatus(operation))
render(wrap(<IntegrateBranchDialog repoId={1} sourceBranch="feature" open onOpenChange={vi.fn()} />, queryClient))
await triggerConflict(user)
expect(screen.getByText('file.txt')).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Integrate' })).not.toBeInTheDocument()
expect(integrateMutate).toHaveBeenCalledWith({ targetBranch: 'main', strategy: 'merge' }, expect.any(Object))
})
it('writes the polled target status into the batched repo status cache when integration stops on conflicts', async () => {
const user = userEvent.setup()
const queryClient = createQueryClient()
const operation = { kind: 'merge' as const, conflictedFiles: ['file.txt'] }
failIntegration(operation)
const conflicted = targetStatus(operation)
fetchStatus.mockResolvedValue(conflicted)
queryClient.setQueryData(['reposGitStatus', [1, 2]], new Map<number, GitStatusResponse>([
[1, targetStatus(null)],
[2, targetStatus(null)],
]))
render(wrap(<IntegrateBranchDialog repoId={1} sourceBranch="feature" open onOpenChange={vi.fn()} />, queryClient))
await triggerConflict(user)
await waitFor(() => {
const batched = queryClient.getQueryData<Map<number, GitStatusResponse>>(['reposGitStatus', [1, 2]])
expect(batched?.get(2)).toEqual(conflicted)
})
const batched = queryClient.getQueryData<Map<number, GitStatusResponse>>(['reposGitStatus', [1, 2]])
expect(batched?.get(1)?.operation).toBeNull()
})
it('enables continue once the target status reports the conflicts resolved', async () => {
const user = userEvent.setup()
const queryClient = createQueryClient()
const operation = { kind: 'merge' as const, conflictedFiles: ['file.txt'] }
failIntegration(operation)
fetchStatus.mockResolvedValue(targetStatus(operation))
render(wrap(<IntegrateBranchDialog repoId={1} sourceBranch="feature" open onOpenChange={vi.fn()} />, queryClient))
await triggerConflict(user)
expect(screen.getByRole('button', { name: /continue/i })).toBeDisabled()
queryClient.setQueryData(['gitStatus', 2], targetStatus({ kind: 'merge', conflictedFiles: [] }))
await waitFor(() => expect(screen.getByRole('button', { name: /continue/i })).toBeEnabled())
})
it('removes the banner when continue clears the target operation', async () => {
const user = userEvent.setup()
const queryClient = createQueryClient()
const operation = { kind: 'merge' as const, conflictedFiles: [] }
failIntegration(operation)
fetchStatus.mockResolvedValue(targetStatus(operation))
continueMutate.mockImplementation(() => {
queryClient.setQueryData(['gitStatus', 2], targetStatus(null))
})
render(wrap(<IntegrateBranchDialog repoId={1} sourceBranch="feature" open onOpenChange={vi.fn()} />, queryClient))
await triggerConflict(user)
await user.click(screen.getByRole('button', { name: /continue/i }))
expect(continueMutate).toHaveBeenCalledTimes(1)
await waitFor(() => expect(screen.queryByText('Merge in progress')).not.toBeInTheDocument())
expect(screen.getByRole('button', { name: 'Integrate' })).toBeInTheDocument()
})
})
@@ -0,0 +1,200 @@
import { useEffect, useMemo, useState } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { RadioOptionGroup, type RadioOption } from '@/components/ui/radio-option-group'
import { GitMerge, Loader2 } from 'lucide-react'
import { getRepo, listBranches } from '@/api/repos'
import { getApiErrorMessage, useGitStatus } from '@/api/git'
import { FetchError } from '@/api/fetchWrapper'
import { showToast } from '@/lib/toast'
import { useGit } from '@/hooks/useGit'
import { setRepoGitStatusCaches } from '@/lib/queryInvalidation'
import { GitOperationBanner } from './GitOperationBanner'
import type { GitOperationState } from '@opencode-manager/shared'
type IntegrateStrategy = 'merge' | 'cherry-pick'
const INTEGRATE_STRATEGY_OPTIONS: Array<RadioOption<IntegrateStrategy>> = [
{ value: 'merge', label: 'Merge commit', description: 'Integrate all commits with a merge commit.' },
{ value: 'cherry-pick', label: 'Cherry-pick commits', description: 'Replay each commit onto the target branch.' },
]
const CONFLICT_STATUS_POLL_INTERVAL_MS = 2000
interface IntegrateBranchDialogProps {
repoId: number
sourceBranch: string
open: boolean
onOpenChange: (open: boolean) => void
}
export function IntegrateBranchDialog({ repoId, sourceBranch, open, onOpenChange }: IntegrateBranchDialogProps) {
const queryClient = useQueryClient()
const git = useGit(repoId)
const [targetBranch, setTargetBranch] = useState('')
const [strategy, setStrategy] = useState<IntegrateStrategy>('merge')
const [conflictTargetRepoId, setConflictTargetRepoId] = useState<number | null>(null)
const [conflictSnapshot, setConflictSnapshot] = useState<GitOperationState | null>(null)
const [conflictStartedAt, setConflictStartedAt] = useState(0)
const { data: repo } = useQuery({
queryKey: ['repo', repoId],
queryFn: () => getRepo(repoId),
enabled: open,
staleTime: 30000,
})
const { data: branchesData, isLoading: branchesLoading } = useQuery({
queryKey: ['branches', repoId],
queryFn: () => listBranches(repoId),
enabled: open,
staleTime: 30000,
})
const { data: targetStatus, dataUpdatedAt: targetStatusUpdatedAt } = useGitStatus(
conflictTargetRepoId ?? undefined,
{ refetchInterval: conflictTargetRepoId !== null ? CONFLICT_STATUS_POLL_INTERVAL_MS : false }
)
const hasFreshTargetStatus = conflictTargetRepoId !== null && targetStatusUpdatedAt >= conflictStartedAt
const activeOperation = hasFreshTargetStatus ? (targetStatus?.operation ?? null) : conflictSnapshot
const candidates = useMemo(
() => (branchesData?.branches ?? []).filter((branch) => branch.type === 'local' && branch.name !== sourceBranch),
[branchesData, sourceBranch]
)
useEffect(() => {
if (!open) {
setTargetBranch('')
setStrategy('merge')
setConflictTargetRepoId(null)
setConflictSnapshot(null)
return
}
if (targetBranch && candidates.some((branch) => branch.name === targetBranch)) return
const preferred = repo?.defaultBranch
setTargetBranch(candidates.find((branch) => branch.name === preferred)?.name ?? candidates[0]?.name ?? '')
}, [open, candidates, repo, targetBranch])
useEffect(() => {
if (conflictTargetRepoId === null || !hasFreshTargetStatus) return
if (targetStatus?.operation) return
setConflictTargetRepoId(null)
setConflictSnapshot(null)
}, [conflictTargetRepoId, hasFreshTargetStatus, targetStatus])
useEffect(() => {
if (conflictTargetRepoId === null || !hasFreshTargetStatus || !targetStatus) return
setRepoGitStatusCaches(queryClient, conflictTargetRepoId, targetStatus)
}, [queryClient, conflictTargetRepoId, hasFreshTargetStatus, targetStatus])
const handleIntegrate = () => {
git.integrateBranch.mutate(
{ targetBranch, strategy },
{
onSuccess: () => onOpenChange(false),
onError: (error) => {
if (error instanceof FetchError && error.code === 'MERGE_CONFLICT') {
const details = error.details as { targetRepoId?: number; operation?: GitOperationState } | undefined
if (details?.targetRepoId !== undefined && details.operation) {
setConflictTargetRepoId(details.targetRepoId)
setConflictSnapshot(details.operation)
setConflictStartedAt(Date.now())
return
}
}
showToast.error(getApiErrorMessage(error))
},
},
)
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[440px]">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<GitMerge className="w-4 h-4" />
Integrate {sourceBranch}
</DialogTitle>
<DialogDescription>
Integrate the commits from {sourceBranch} into another checked-out branch.
</DialogDescription>
</DialogHeader>
{conflictTargetRepoId !== null && activeOperation ? (
<div className="space-y-3">
<GitOperationBanner repoId={conflictTargetRepoId} operation={activeOperation} />
<div className="flex justify-end">
<Button variant="outline" className="border-border hover:bg-accent" onClick={() => onOpenChange(false)}>
Close
</Button>
</div>
</div>
) : (
<div className="space-y-4">
<div className="space-y-1.5">
<label className="text-sm font-medium" htmlFor="integrate-target-branch">
Target branch
</label>
<Select value={targetBranch} onValueChange={setTargetBranch} disabled={branchesLoading}>
<SelectTrigger
id="integrate-target-branch"
aria-label="Target branch"
className="bg-background border-border text-foreground"
>
<SelectValue placeholder={branchesLoading ? 'Loading branches...' : 'Select a target branch'} />
</SelectTrigger>
<SelectContent className="bg-popover border-border">
{candidates.map((branch) => (
<SelectItem key={branch.name} value={branch.name}>
{branch.name}
</SelectItem>
))}
</SelectContent>
</Select>
{!branchesLoading && candidates.length === 0 && (
<p className="text-xs text-muted-foreground">
No other local branches are available to integrate into.
</p>
)}
</div>
<fieldset className="space-y-2">
<legend className="text-sm font-medium">Strategy</legend>
<RadioOptionGroup
name="integrate-strategy"
value={strategy}
onChange={setStrategy}
options={INTEGRATE_STRATEGY_OPTIONS}
/>
</fieldset>
<div className="flex gap-2 justify-end">
<Button variant="outline" onClick={() => onOpenChange(false)} className="border-border hover:bg-accent">
Cancel
</Button>
<Button
onClick={handleIntegrate}
disabled={!targetBranch || git.integrateBranch.isPending}
className="bg-primary hover:bg-primary-hover disabled:opacity-50"
>
{git.integrateBranch.isPending ? (
<>
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
Integrating...
</>
) : (
'Integrate'
)}
</Button>
</div>
</div>
)}
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,146 @@
import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import type { ReactNode } from 'react'
import type { UserPreferences } from '@/api/types/settings'
import { useSettings } from '@/hooks/useSettings'
import { createUseSettingsMock } from '@/test/test-utils'
import { RepoGitIdentitySelect } from './RepoGitIdentitySelect'
const { getRepoGitIdentityMock, updateRepoGitIdentityMock, showToastMock } = vi.hoisted(() => ({
getRepoGitIdentityMock: vi.fn(),
updateRepoGitIdentityMock: vi.fn(),
showToastMock: { success: vi.fn(), error: vi.fn(), loading: vi.fn() },
}))
vi.mock('@/api/repos', () => ({
getRepoGitIdentity: getRepoGitIdentityMock,
updateRepoGitIdentity: updateRepoGitIdentityMock,
}))
vi.mock('@/api/git', () => ({
getApiErrorMessage: (error: unknown) => (error instanceof Error ? error.message : String(error)),
}))
vi.mock('@/lib/toast', () => ({ showToast: showToastMock }))
vi.mock('@/hooks/useSettings')
const preset = { id: 'a', name: 'Alpha', email: 'alpha@example.com' }
function buildPreferences(overrides: Partial<UserPreferences> = {}): UserPreferences {
return {
theme: 'dark',
mode: 'build',
autoScroll: true,
expandDiffs: true,
expandToolCalls: false,
showReasoning: false,
simpleChatMode: false,
keyboardShortcuts: {},
customCommands: [],
gitIdentities: [preset],
...overrides,
}
}
function renderSelect(preferences: Partial<UserPreferences> = {}) {
vi.mocked(useSettings).mockReturnValue(
createUseSettingsMock({ preferences: buildPreferences(preferences) }),
)
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
})
function Wrapper({ children }: { children: ReactNode }) {
return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
}
return render(<RepoGitIdentitySelect repoId={7} />, { wrapper: Wrapper })
}
function openSelect(user: ReturnType<typeof userEvent.setup>) {
return user.click(screen.getByRole('combobox', { name: 'Commit identity' }))
}
describe('RepoGitIdentitySelect', () => {
beforeAll(() => {
Element.prototype.hasPointerCapture ??= () => false
Element.prototype.setPointerCapture ??= () => {}
Element.prototype.releasePointerCapture ??= () => {}
})
beforeEach(() => {
vi.clearAllMocks()
})
it('shows the effective default identity and its Manager source', async () => {
getRepoGitIdentityMock.mockResolvedValue({ name: 'Ada', email: 'ada@example.com', scope: 'default', presetId: null })
renderSelect()
await waitFor(() =>
expect(screen.getByRole('combobox', { name: 'Commit identity' }))
.toHaveTextContent('Default — Ada <ada@example.com> (Manager default)'))
})
it('shows the global git config source and the not-configured fallback', async () => {
getRepoGitIdentityMock.mockResolvedValue({ name: 'Ada', email: 'ada@example.com', scope: 'global', presetId: null })
const { unmount } = renderSelect()
await waitFor(() =>
expect(screen.getByRole('combobox', { name: 'Commit identity' }))
.toHaveTextContent('Default — Ada <ada@example.com> (git global config)'))
unmount()
getRepoGitIdentityMock.mockResolvedValue({ name: null, email: null, scope: 'none', presetId: null })
renderSelect()
await waitFor(() =>
expect(screen.getByRole('combobox', { name: 'Commit identity' }))
.toHaveTextContent('Default — not configured'))
})
it('selects the matching preset for a repository identity', async () => {
getRepoGitIdentityMock.mockResolvedValue({ name: 'Alpha', email: 'alpha@example.com', scope: 'repository', presetId: 'a' })
renderSelect()
await waitFor(() =>
expect(screen.getByRole('combobox', { name: 'Commit identity' }))
.toHaveTextContent('Alpha <alpha@example.com>'))
})
it('shows a custom repository identity and confirms before replacing it', async () => {
const user = userEvent.setup()
const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(false)
getRepoGitIdentityMock.mockResolvedValue({ name: 'Custom', email: 'custom@example.com', scope: 'repository', presetId: null })
renderSelect()
await openSelect(user)
const customOption = screen.getByRole('option', { name: 'Custom (Custom <custom@example.com>)' })
expect(customOption).toHaveAttribute('data-disabled')
await user.click(screen.getByRole('option', { name: 'Alpha <alpha@example.com>' }))
expect(confirmSpy).toHaveBeenCalledWith(expect.stringContaining('Custom <custom@example.com>'))
expect(updateRepoGitIdentityMock).not.toHaveBeenCalled()
confirmSpy.mockReturnValue(true)
await openSelect(user)
await user.click(screen.getByRole('option', { name: 'Alpha <alpha@example.com>' }))
await waitFor(() => expect(updateRepoGitIdentityMock).toHaveBeenCalledWith(7, 'a'))
})
it('sends null when choosing Default and the preset id when choosing a preset', async () => {
const user = userEvent.setup()
getRepoGitIdentityMock.mockResolvedValue({ name: 'Alpha', email: 'alpha@example.com', scope: 'repository', presetId: 'a' })
updateRepoGitIdentityMock.mockResolvedValue({ name: null, email: null, scope: 'none', presetId: null })
renderSelect()
await openSelect(user)
await user.click(screen.getByRole('option', { name: 'Default' }))
await waitFor(() => expect(updateRepoGitIdentityMock).toHaveBeenCalledWith(7, null))
updateRepoGitIdentityMock.mockResolvedValue({ name: 'Alpha', email: 'alpha@example.com', scope: 'repository', presetId: 'a' })
await openSelect(user)
await user.click(screen.getByRole('option', { name: 'Alpha <alpha@example.com>' }))
await waitFor(() => expect(updateRepoGitIdentityMock).toHaveBeenCalledWith(7, 'a'))
})
})
@@ -0,0 +1,89 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { UserCog } from 'lucide-react'
import type { RepoGitIdentity } from '@opencode-manager/shared'
import { getRepoGitIdentity, updateRepoGitIdentity } from '@/api/repos'
import { getApiErrorMessage } from '@/api/git'
import { useSettings } from '@/hooks/useSettings'
import { showToast } from '@/lib/toast'
import { formatGitIdentity } from '@/lib/git-identity'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
const DEFAULT_VALUE = 'default'
const CUSTOM_VALUE = 'custom'
interface RepoGitIdentitySelectProps {
repoId: number
}
function defaultIdentityLabel(identity: RepoGitIdentity): string {
if (identity.scope === 'none') return 'Default — not configured'
if (identity.scope === 'default') return `Default — ${formatGitIdentity(identity)} (Manager default)`
if (identity.scope === 'global') return `Default — ${formatGitIdentity(identity)} (git global config)`
return 'Default'
}
export function RepoGitIdentitySelect({ repoId }: RepoGitIdentitySelectProps) {
const queryClient = useQueryClient()
const { data: identity } = useQuery({
queryKey: ['repoGitIdentity', repoId],
queryFn: () => getRepoGitIdentity(repoId),
})
const { preferences } = useSettings()
const identities = preferences?.gitIdentities ?? []
const repositoryPresetId = identity?.scope === 'repository' ? identity.presetId : null
const matchingPresetId = repositoryPresetId && identities.some((preset) => preset.id === repositoryPresetId)
? repositoryPresetId
: null
const isCustom = identity?.scope === 'repository' && !matchingPresetId
const selectedValue = matchingPresetId ?? (identity?.scope === 'repository' ? CUSTOM_VALUE : DEFAULT_VALUE)
const mutation = useMutation({
mutationFn: (identityId: string | null) => updateRepoGitIdentity(repoId, identityId),
onSuccess: (data) => {
queryClient.setQueryData(['repoGitIdentity', repoId], data)
},
onError: (error) => {
showToast.error(getApiErrorMessage(error))
},
})
const handleValueChange = (value: string) => {
if (value === CUSTOM_VALUE) return
if (isCustom && identity && !window.confirm(`Replace this repository's custom commit identity ${formatGitIdentity(identity)}?`)) {
return
}
mutation.mutate(value === DEFAULT_VALUE ? null : value)
}
return (
<div className="flex items-center gap-2">
<UserCog className="w-4 h-4 shrink-0 text-muted-foreground" />
<span className="text-xs text-muted-foreground shrink-0">Commit as</span>
<Select
value={selectedValue}
onValueChange={handleValueChange}
disabled={mutation.isPending}
>
<SelectTrigger className="h-8 text-xs" aria-label="Commit identity">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value={DEFAULT_VALUE}>
{identity ? defaultIdentityLabel(identity) : 'Default'}
</SelectItem>
{isCustom && identity && (
<SelectItem value={CUSTOM_VALUE} disabled>
Custom ({formatGitIdentity(identity)})
</SelectItem>
)}
{identities.map((preset) => (
<SelectItem key={preset.id} value={preset.id}>
{formatGitIdentity(preset)}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
)
}
@@ -8,8 +8,10 @@ import { useGit } from '@/hooks/useGit'
import { ChangesTab } from './ChangesTab'
import { CommitsTab } from './CommitsTab'
import { BranchesTab } from './BranchesTab'
import { StashTab } from './StashTab'
import { CommitDetailView } from './CommitDetailView'
import { GitErrorBanner } from './GitErrorBanner'
import { GitOperationBanner } from './GitOperationBanner'
import { FileDiffView } from '@/components/file-browser/FileDiffView'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
@@ -24,6 +26,7 @@ import {
ArrowDown,
RefreshCw,
ArrowDownFromLine,
Archive,
X,
} from 'lucide-react'
import { cn } from '@/lib/utils'
@@ -39,7 +42,7 @@ interface SourceControlPanelProps {
repoName?: string
}
type Tab = 'changes' | 'commits' | 'branches'
type Tab = 'changes' | 'commits' | 'branches' | 'stash'
type View = 'default' | 'commit-detail'
export function SourceControlPanel({
@@ -102,6 +105,7 @@ export function SourceControlPanel({
{ id: 'changes', label: 'Changes', icon: FileCode },
{ id: 'commits', label: 'Commits', icon: History },
{ id: 'branches', label: 'Branches', icon: GitBranch },
{ id: 'stash', label: 'Stash', icon: Archive },
]
const changesCount = status?.files.length || 0
@@ -176,6 +180,10 @@ export function SourceControlPanel({
</div>
</div>
{status?.operation && (
<GitOperationBanner repoId={repoId} operation={status.operation} />
)}
{gitError && (
<GitErrorBanner error={gitError} onDismiss={() => setGitError(null)} />
)}
@@ -235,6 +243,9 @@ export function SourceControlPanel({
{activeTab === 'branches' && currentView === 'default' && (
<BranchesTab repoId={repoId} currentBranch={displayBranch} />
)}
{activeTab === 'stash' && currentView === 'default' && (
<StashTab repoId={repoId} />
)}
{currentView === 'commit-detail' && selectedCommit && (
<div className="flex flex-1 min-h-0 overflow-hidden flex-col">
@@ -0,0 +1,95 @@
import { describe, it, expect, vi, beforeEach, beforeAll } from 'vitest'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import type { GitStashEntry } from '@opencode-manager/shared'
import { useGitStashes } from '@/api/git'
import { StashTab } from './StashTab'
const { stashPushMutate, stashApplyMutate, stashDropMutate } = vi.hoisted(() => ({
stashPushMutate: vi.fn(),
stashApplyMutate: vi.fn(),
stashDropMutate: vi.fn(),
}))
vi.mock('@/hooks/useGit', () => ({
useGit: () => ({
stashPush: { mutate: stashPushMutate, isPending: false },
stashApply: { mutate: stashApplyMutate, isPending: false },
stashDrop: { mutate: stashDropMutate, isPending: false },
}),
}))
vi.mock('@/api/git', () => ({
useGitStashes: vi.fn(),
}))
const stashEntry: GitStashEntry = {
index: 0,
ref: 'stash@{0}',
hash: 'abc123',
message: 'wip note',
branch: 'main',
date: '2024-01-01T00:00:00+00:00',
}
function mockStashes(stashes: GitStashEntry[]) {
vi.mocked(useGitStashes).mockReturnValue({
data: { stashes },
isLoading: false,
error: null,
} as unknown as ReturnType<typeof useGitStashes>)
}
function renderTab() {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
return render(
<QueryClientProvider client={queryClient}>
<StashTab repoId={1} />
</QueryClientProvider>,
)
}
describe('StashTab', () => {
beforeAll(() => {
Element.prototype.hasPointerCapture ??= () => false
Element.prototype.setPointerCapture ??= () => {}
Element.prototype.releasePointerCapture ??= () => {}
})
beforeEach(() => {
vi.clearAllMocks()
})
it('renders stash entries with the message and branch', () => {
mockStashes([stashEntry])
renderTab()
expect(screen.getByText('wip note')).toBeInTheDocument()
expect(screen.getByText(/main/)).toBeInTheDocument()
})
it('wires apply, pop, drop and stash actions to the mutations', async () => {
const user = userEvent.setup()
mockStashes([stashEntry])
renderTab()
await user.click(screen.getByRole('button', { name: /apply/i }))
expect(stashApplyMutate).toHaveBeenCalledWith({ index: 0, hash: 'abc123', pop: false })
await user.click(screen.getByRole('button', { name: /pop/i }))
expect(stashApplyMutate).toHaveBeenCalledWith({ index: 0, hash: 'abc123', pop: true })
await user.type(screen.getByRole('textbox', { name: 'Stash message' }), 'new stash')
expect(screen.getByRole('textbox', { name: 'Stash message' })).toHaveValue('new stash')
await user.click(screen.getByRole('button', { name: /stash changes/i }))
expect(stashPushMutate).toHaveBeenCalledWith(
{ message: 'new stash', includeUntracked: true },
expect.any(Object),
)
await user.click(screen.getByTitle('Drop stash'))
await user.click(await screen.findByRole('button', { name: 'Drop' }))
expect(stashDropMutate).toHaveBeenCalledWith({ index: 0, hash: 'abc123' }, expect.any(Object))
})
})
@@ -0,0 +1,172 @@
import { useState } from 'react'
import { useGitStashes } from '@/api/git'
import { useGit } from '@/hooks/useGit'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Checkbox } from '@/components/ui/checkbox'
import { ConfirmDestructiveDialog } from '@/components/ui/confirm-destructive-dialog'
import { Archive, ArchiveRestore, PackageOpen, Trash2, Loader2, AlertCircle } from 'lucide-react'
import type { GitStashEntry } from '@opencode-manager/shared'
interface StashTabProps {
repoId: number
}
function formatStashDate(date: string): string {
const parsed = new Date(date)
if (Number.isNaN(parsed.getTime())) {
return date
}
return parsed.toLocaleString()
}
export function StashTab({ repoId }: StashTabProps) {
const { data, isLoading, error } = useGitStashes(repoId)
const git = useGit(repoId)
const [message, setMessage] = useState('')
const [includeUntracked, setIncludeUntracked] = useState(true)
const [stashToDrop, setStashToDrop] = useState<GitStashEntry | null>(null)
const stashes = data?.stashes ?? []
const handleStash = () => {
git.stashPush.mutate(
{ message: message.trim() || undefined, includeUntracked },
{ onSuccess: () => setMessage('') },
)
}
const handleDrop = () => {
if (!stashToDrop) return
git.stashDrop.mutate(
{ index: stashToDrop.index, hash: stashToDrop.hash },
{ onSuccess: () => setStashToDrop(null) },
)
}
if (isLoading) {
return (
<div className="flex items-center justify-center py-12">
<Loader2 className="w-5 h-5 animate-spin text-muted-foreground" />
</div>
)
}
if (error) {
return (
<div className="text-center py-12 text-muted-foreground">
<AlertCircle className="w-8 h-8 mx-auto mb-2 opacity-50" />
<p className="text-sm">Failed to load stashes</p>
<p className="text-xs mt-1">{error.message}</p>
</div>
)
}
return (
<div className="flex flex-col h-full">
<div className="p-3 border-b border-border space-y-2 flex-shrink-0">
<Input
aria-label="Stash message"
placeholder="Stash message (optional)"
value={message}
onChange={(e) => setMessage(e.target.value)}
className="h-10 md:h-8 md:text-sm"
onKeyDown={(e) => {
if (e.key === 'Enter') handleStash()
}}
/>
<div className="flex items-center justify-between gap-2">
<label className="flex items-center gap-2 text-sm cursor-pointer">
<Checkbox
checked={includeUntracked}
onCheckedChange={(checked) => setIncludeUntracked(checked === true)}
/>
Include untracked
</label>
<Button
size="sm"
className="h-10 md:h-8"
onClick={handleStash}
disabled={git.stashPush.isPending}
>
{git.stashPush.isPending ? (
<Loader2 className="w-4 h-4 animate-spin mr-1" />
) : (
<Archive className="w-4 h-4 mr-1" />
)}
Stash changes
</Button>
</div>
</div>
<div className="flex-1 overflow-y-auto">
{stashes.length > 0 ? (
<div className="py-1">
{stashes.map((stash) => (
<div key={stash.ref} className="flex items-center gap-2 px-3 py-2 hover:bg-accent/50">
<Archive className="w-4 h-4 text-muted-foreground flex-shrink-0" />
<div className="flex-1 min-w-0">
<p className="text-sm truncate">{stash.message || 'No message'}</p>
<p className="text-xs text-muted-foreground truncate">
{stash.branch ?? 'unknown branch'} · {formatStashDate(stash.date)}
</p>
</div>
<Button
size="sm"
variant="ghost"
className="h-7 px-2"
onClick={() => git.stashApply.mutate({ index: stash.index, hash: stash.hash, pop: false })}
disabled={git.stashApply.isPending}
title="Apply stash"
>
<ArchiveRestore className="w-4 h-4 mr-1" />
Apply
</Button>
<Button
size="sm"
variant="ghost"
className="h-7 px-2"
onClick={() => git.stashApply.mutate({ index: stash.index, hash: stash.hash, pop: true })}
disabled={git.stashApply.isPending}
title="Pop stash"
>
<PackageOpen className="w-4 h-4 mr-1" />
Pop
</Button>
<Button
size="sm"
variant="ghost"
className="h-7 px-2 text-destructive hover:text-destructive"
onClick={() => setStashToDrop(stash)}
disabled={git.stashDrop.isPending}
title="Drop stash"
>
<Trash2 className="w-4 h-4" />
</Button>
</div>
))}
</div>
) : (
<div className="text-center py-12 text-muted-foreground">
<Archive className="w-8 h-8 mx-auto mb-2 opacity-50" />
<p className="text-sm">No stashes</p>
</div>
)}
</div>
<ConfirmDestructiveDialog
open={!!stashToDrop}
onOpenChange={(open) => {
if (!open) setStashToDrop(null)
}}
onConfirm={handleDrop}
onCancel={() => setStashToDrop(null)}
title={`Drop stash "${stashToDrop?.message || stashToDrop?.ref || ''}"?`}
description="This permanently removes the stashed changes. This action cannot be undone."
confirmLabel="Drop"
pendingLabel="Dropping..."
isPending={git.stashDrop.isPending}
/>
</div>
)
}