Merge pull request #380 from feat/git-workflow-core into beta

feat(git): extend source control with worktrees, stashes, conflicts and identities
This commit is contained in:
Chris Scott committed 2026-10-03 22:20:56 -04:00
commit da3821b0d4
89 files changed
+7704 -793

No files matched your search

@@ -0,0 +1,142 @@
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 { CreateWorktreeDialog } from './CreateWorktreeDialog'
import { createRepo, listBranches } from '@/api/repos'
vi.mock('@/api/repos', () => ({
createRepo: vi.fn(),
listBranches: vi.fn(),
}))
vi.mock('@/lib/toast', () => ({
showToast: { success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn() },
}))
const repoUrl = 'git@example.com:org/repo.git'
function renderDialog() {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
})
return render(
<QueryClientProvider client={queryClient}>
<CreateWorktreeDialog open onOpenChange={vi.fn()} repoId={1} repoUrl={repoUrl} />
</QueryClientProvider>,
)
}
describe('CreateWorktreeDialog', () => {
beforeAll(() => {
Element.prototype.hasPointerCapture ??= () => false
Element.prototype.setPointerCapture ??= () => {}
Element.prototype.releasePointerCapture ??= () => {}
Element.prototype.scrollIntoView ??= () => {}
})
beforeEach(() => {
vi.clearAllMocks()
vi.mocked(listBranches).mockResolvedValue({
branches: [
{ name: 'main', type: 'local', current: true },
{ name: 'feature', type: 'local', current: false },
{ name: 'wt-branch', type: 'local', current: false, isWorktree: true },
{ name: 'remotes/origin/feature', type: 'remote', current: false },
{ name: 'remotes/origin/release', type: 'remote', current: false },
],
status: { ahead: 0, behind: 0 },
})
vi.mocked(createRepo).mockResolvedValue({} as never)
})
it('lists only non-current, non-worktree local branches and remote-only branches in existing mode', async () => {
const user = userEvent.setup()
renderDialog()
await user.click(await screen.findByRole('button', { name: 'Existing branch' }))
await user.click(screen.getByRole('combobox', { name: 'Branch to check out' }))
expect(screen.getByRole('option', { name: 'feature' })).toBeInTheDocument()
expect(screen.getByRole('option', { name: /release/ })).toBeInTheDocument()
expect(screen.queryByRole('option', { name: /main/ })).not.toBeInTheDocument()
expect(screen.queryByRole('option', { name: /wt-branch/ })).not.toBeInTheDocument()
})
it('creates a worktree for an existing remote-only branch without a base branch', async () => {
const user = userEvent.setup()
renderDialog()
await user.click(await screen.findByRole('button', { name: 'Existing branch' }))
await user.click(screen.getByRole('combobox', { name: 'Branch to check out' }))
await user.click(screen.getByRole('option', { name: /release/ }))
await user.click(screen.getByRole('button', { name: 'Create Worktree' }))
await waitFor(() => expect(createRepo).toHaveBeenCalledTimes(1))
expect(createRepo).toHaveBeenCalledWith({ repoUrl, branch: 'release', useWorktree: true })
expect(vi.mocked(createRepo).mock.calls[0][0]).not.toHaveProperty('baseBranch')
})
it('does not offer remote-only branches from non-origin remotes', async () => {
vi.mocked(listBranches).mockResolvedValue({
branches: [
{ name: 'main', type: 'local', current: true },
{ name: 'remotes/upstream/release', type: 'remote', current: false },
],
status: { ahead: 0, behind: 0 },
})
const user = userEvent.setup()
renderDialog()
await user.click(await screen.findByRole('button', { name: 'Existing branch' }))
await user.click(screen.getByRole('combobox', { name: 'Branch to check out' }))
expect(screen.queryByRole('option', { name: /release/ })).not.toBeInTheDocument()
})
it('deduplicates remote candidates that share a short name across remotes', async () => {
vi.mocked(listBranches).mockResolvedValue({
branches: [
{ name: 'main', type: 'local', current: true },
{ name: 'remotes/origin/release', type: 'remote', current: false },
{ name: 'remotes/upstream/release', type: 'remote', current: false },
],
status: { ahead: 0, behind: 0 },
})
const user = userEvent.setup()
renderDialog()
await user.click(await screen.findByRole('button', { name: 'Existing branch' }))
await user.click(screen.getByRole('combobox', { name: 'Branch to check out' }))
expect(screen.getAllByRole('option', { name: /release/ })).toHaveLength(1)
})
it('creates a worktree for a new branch with the selected base branch', async () => {
const user = userEvent.setup()
renderDialog()
await user.type(screen.getByPlaceholderText('feature/my-branch'), 'my-new-branch')
await user.click(screen.getByRole('combobox'))
await user.click(screen.getByRole('option', { name: /main/ }))
await user.click(screen.getByRole('button', { name: 'Create Worktree' }))
await waitFor(() => expect(createRepo).toHaveBeenCalledTimes(1))
expect(createRepo).toHaveBeenCalledWith({
repoUrl,
branch: 'my-new-branch',
useWorktree: true,
baseBranch: 'main',
})
})
it('prompts to use existing mode when a new branch name already exists', async () => {
const user = userEvent.setup()
renderDialog()
await user.type(screen.getByPlaceholderText('feature/my-branch'), 'feature')
expect(await screen.findByText('Use Existing branch instead')).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Create Worktree' })).toBeDisabled()
})
})
@@ -5,7 +5,7 @@ import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { AlertCircle, GitBranch, Loader2 } from 'lucide-react'
import { createRepo, listBranches } from '@/api/repos'
import { createRepo, listBranches, type CreateRepoOptions } from '@/api/repos'
import { showToast } from '@/lib/toast'
import { invalidateRepoGitCaches } from '@/lib/queryInvalidation'
@@ -18,6 +18,13 @@ interface CreateWorktreeDialogProps {
onCreated?: () => void
}
type WorktreeMode = 'new' | 'existing'
interface WorktreePayload {
branch: string
base?: string
}
export function CreateWorktreeDialog({
open,
onOpenChange,
@@ -27,8 +34,10 @@ export function CreateWorktreeDialog({
onCreated,
}: CreateWorktreeDialogProps) {
const queryClient = useQueryClient()
const [mode, setMode] = useState<WorktreeMode>('new')
const [branchName, setBranchName] = useState('')
const [baseBranch, setBaseBranch] = useState<string>('')
const [existingBranch, setExistingBranch] = useState<string>('')
const [error, setError] = useState<string | null>(null)
const canCreate = Boolean(repoUrl)
@@ -41,15 +50,41 @@ export function CreateWorktreeDialog({
})
const localBranches = (branchesData?.branches ?? []).filter((b) => b.type === 'local')
const seenRemoteNames = new Set<string>()
const remoteBranches = (branchesData?.branches ?? [])
.filter((b) => b.type === 'remote')
.map((b) => ({ ...b, shortName: b.name.replace(/^remotes\/[^/]+\//, '') }))
.filter((b) => b.type === 'remote' && b.name.startsWith('remotes/origin/'))
.map((b) => ({ ...b, shortName: b.name.slice('remotes/origin/'.length) }))
.filter((b) => b.shortName.length > 0)
.filter((b) => !localBranches.some((lb) => lb.name === b.shortName))
.filter((b) => {
if (seenRemoteNames.has(b.shortName)) return false
seenRemoteNames.add(b.shortName)
return true
})
const checkoutCandidates = [
...localBranches
.filter((b) => !b.current && !b.isWorktree)
.map((b) => ({ name: b.name, remote: false })),
...remoteBranches.map((b) => ({ name: b.shortName, remote: true })),
]
const existingBranchNames = new Set([
...localBranches.map((b) => b.name),
...remoteBranches.map((b) => b.shortName),
])
const trimmedBranchName = branchName.trim()
const newBranchConflict =
mode === 'new' && trimmedBranchName.length > 0 && existingBranchNames.has(trimmedBranchName)
useEffect(() => {
if (!open) {
setMode('new')
setBranchName('')
setBaseBranch('')
setExistingBranch('')
setError(null)
return
}
@@ -59,13 +94,17 @@ export function CreateWorktreeDialog({
}, [open, defaultBaseBranch])
const worktreeMutation = useMutation({
mutationFn: (payload: { branch: string; base: string }) =>
createRepo({
mutationFn: (payload: WorktreePayload) => {
const options: CreateRepoOptions = {
repoUrl: repoUrl || undefined,
branch: payload.branch,
useWorktree: true,
baseBranch: payload.base,
}),
}
if (payload.base) {
options.baseBranch = payload.base
}
return createRepo(options)
},
onSuccess: () => {
invalidateRepoGitCaches(queryClient, repoId)
showToast.success('Worktree created')
@@ -78,19 +117,44 @@ export function CreateWorktreeDialog({
})
const handleCreate = () => {
const trimmed = branchName.trim()
if (!trimmed) {
if (mode === 'existing') {
if (!existingBranch) {
setError('Select a branch to check out')
return
}
setError(null)
worktreeMutation.mutate({ branch: existingBranch })
return
}
if (!trimmedBranchName) {
setError('Branch name is required')
return
}
if (newBranchConflict) {
setError('Use Existing branch instead')
return
}
if (!baseBranch) {
setError('Base branch is required')
return
}
setError(null)
worktreeMutation.mutate({ branch: trimmed, base: baseBranch })
worktreeMutation.mutate({ branch: trimmedBranchName, base: baseBranch })
}
const selectMode = (nextMode: WorktreeMode) => {
setMode(nextMode)
setError(null)
}
const canSubmit =
canCreate &&
!worktreeMutation.isPending &&
(mode === 'new'
? Boolean(trimmedBranchName) && Boolean(baseBranch) && !newBranchConflict
: Boolean(existingBranch))
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[440px]">
@@ -100,7 +164,7 @@ export function CreateWorktreeDialog({
Create Worktree
</DialogTitle>
<DialogDescription>
Create a separate workspace for a new branch. The worktree is managed as its own repo entry.
Create a separate workspace for a new or existing branch. The worktree is managed as its own repo entry.
</DialogDescription>
</DialogHeader>
@@ -114,56 +178,121 @@ export function CreateWorktreeDialog({
</div>
) : (
<>
<div className="space-y-1.5">
<label className="text-sm font-medium">New branch name</label>
<Input
placeholder="feature/my-branch"
value={branchName}
onChange={(e) => setBranchName(e.target.value)}
autoFocus
onKeyDown={(e) => {
if (e.key === 'Enter' && !worktreeMutation.isPending) handleCreate()
}}
/>
<div className="grid grid-cols-2 gap-1 rounded-md border border-border p-1">
<Button
type="button"
variant={mode === 'new' ? 'secondary' : 'ghost'}
size="sm"
aria-pressed={mode === 'new'}
onClick={() => selectMode('new')}
>
New branch
</Button>
<Button
type="button"
variant={mode === 'existing' ? 'secondary' : 'ghost'}
size="sm"
aria-pressed={mode === 'existing'}
onClick={() => selectMode('existing')}
>
Existing branch
</Button>
</div>
<div className="space-y-1.5">
<label className="text-sm font-medium">Base branch</label>
<Select value={baseBranch} onValueChange={setBaseBranch} disabled={branchesLoading}>
<SelectTrigger className="bg-background border-border text-foreground">
<SelectValue placeholder={branchesLoading ? 'Loading branches...' : 'Select a base branch'} />
</SelectTrigger>
<SelectContent className="bg-popover border-border">
{localBranches.length > 0 && (
<>
{localBranches.map((branch) => (
<SelectItem key={`local-${branch.name}`} value={branch.name}>
{mode === 'new' ? (
<>
<div className="space-y-1.5">
<label className="text-sm font-medium">New branch name</label>
<Input
placeholder="feature/my-branch"
value={branchName}
onChange={(e) => setBranchName(e.target.value)}
autoFocus
onKeyDown={(e) => {
if (e.key === 'Enter' && !worktreeMutation.isPending) handleCreate()
}}
/>
{newBranchConflict && (
<p className="text-xs text-destructive">Use Existing branch instead</p>
)}
</div>
<div className="space-y-1.5">
<label className="text-sm font-medium">Base branch</label>
<Select value={baseBranch} onValueChange={setBaseBranch} disabled={branchesLoading}>
<SelectTrigger className="bg-background border-border text-foreground">
<SelectValue placeholder={branchesLoading ? 'Loading branches...' : 'Select a base branch'} />
</SelectTrigger>
<SelectContent className="bg-popover border-border">
{localBranches.length > 0 && (
<>
{localBranches.map((branch) => (
<SelectItem key={`local-${branch.name}`} value={branch.name}>
<div className="flex items-center gap-2">
<GitBranch className="w-3.5 h-3.5" />
<span>{branch.name}</span>
{branch.current && (
<span className="text-xs text-muted-foreground">(current)</span>
)}
</div>
</SelectItem>
))}
</>
)}
{remoteBranches.map((branch) => (
<SelectItem key={`remote-${branch.name}`} value={branch.shortName}>
<div className="flex items-center gap-2">
<GitBranch className="w-3.5 h-3.5" />
<span>{branch.name}</span>
{branch.current && (
<span className="text-xs text-muted-foreground">(current)</span>
)}
<GitBranch className="w-3.5 h-3.5 text-info" />
<span>{branch.shortName}</span>
<span className="text-xs text-muted-foreground">(remote)</span>
</div>
</SelectItem>
))}
</>
)}
{remoteBranches.map((branch) => (
<SelectItem key={`remote-${branch.name}`} value={branch.shortName}>
<div className="flex items-center gap-2">
<GitBranch className="w-3.5 h-3.5 text-info" />
<span>{branch.shortName}</span>
<span className="text-xs text-muted-foreground">(remote)</span>
</div>
</SelectItem>
))}
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">
The new branch will be created from this branch. Ignored if the branch name already exists locally or on the remote.
</p>
</div>
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">
The new branch will be created from this branch.
</p>
</div>
</>
) : (
<div className="space-y-1.5">
<label className="text-sm font-medium">Branch to check out</label>
<Select
value={existingBranch}
onValueChange={setExistingBranch}
disabled={branchesLoading}
>
<SelectTrigger
aria-label="Branch to check out"
className="bg-background border-border text-foreground"
>
<SelectValue
placeholder={branchesLoading ? 'Loading branches...' : 'Select a branch to check out'}
/>
</SelectTrigger>
<SelectContent className="bg-popover border-border">
{checkoutCandidates.map((branch) => (
<SelectItem
key={`${branch.remote ? 'remote' : 'local'}-${branch.name}`}
value={branch.name}
>
<div className="flex items-center gap-2">
<GitBranch className={`w-3.5 h-3.5${branch.remote ? ' text-info' : ''}`} />
<span>{branch.name}</span>
{branch.remote && (
<span className="text-xs text-muted-foreground">(remote)</span>
)}
</div>
</SelectItem>
))}
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">
The worktree will check out the selected branch. Remote branches are limited to origin.
</p>
</div>
)}
</>
)}
@@ -184,7 +313,7 @@ export function CreateWorktreeDialog({
</Button>
<Button
onClick={handleCreate}
disabled={!canCreate || !branchName.trim() || !baseBranch || worktreeMutation.isPending}
disabled={!canSubmit}
className="bg-primary hover:bg-primary-hover disabled:opacity-50"
>
{worktreeMutation.isPending ? (
@@ -110,6 +110,7 @@ describe('RepoCard', () => {
behind: 0,
files: [{ path: 'file.txt', status: 'modified' as const, staged: false }],
hasChanges: true,
operation: null,
},
}
const { container } = renderWithRouter(<RepoCard {...props} />)
@@ -127,6 +128,7 @@ describe('RepoCard', () => {
behind: 1,
files: [],
hasChanges: false,
operation: null,
},
}
renderWithRouter(<RepoCard {...props} />)
+47 -9
View File
@@ -3,9 +3,10 @@ import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
import { DndContext, closestCenter, KeyboardSensor, MouseSensor, TouchSensor, useSensor, useSensors, type DragEndEvent } from "@dnd-kit/core"
import { arrayMove, SortableContext, sortableKeyboardCoordinates, verticalListSortingStrategy, useSortable } from "@dnd-kit/sortable"
import { CSS } from "@dnd-kit/utilities"
import { listRepos, deleteRepo, updateRepoOrder } from "@/api/repos"
import { listRepos, deleteRepo, updateRepoOrder, type DeleteBranchChoice } from "@/api/repos"
import { fetchReposGitStatus } from "@/api/git"
import { DeleteDialog } from "@/components/ui/delete-dialog"
import { RadioOptionGroup, type RadioOption } from "@/components/ui/radio-option-group"
import { GitBranch, Search, GripVertical } from "lucide-react"
import type { Repo } from "@/api/types"
import type { GitStatusResponse } from "@/types/git"
@@ -25,9 +26,16 @@ import {
} from "./repo-list-state"
import { RepoListControls } from "./RepoListControls"
import { invalidateRepoListCaches } from "@/lib/queryInvalidation"
import { showToast } from "@/lib/toast"
import { formatShortRelativeTime } from "@/lib/utils"
import { ASSISTANT_REPO_ID } from "@opencode-manager/shared/utils"
const DELETE_BRANCH_OPTIONS: Array<RadioOption<DeleteBranchChoice>> = [
{ value: 'none', label: 'Keep branch', description: 'Leave the branch in the parent repository.' },
{ value: 'local', label: 'Delete local branch', description: 'Remove the branch from the parent repository.' },
{ value: 'local-and-remote', label: 'Delete local and remote branch', description: 'Also delete the branch from origin.' },
]
interface RepoCardWrapperProps {
repo: Repo
onDelete: (id: number) => void
@@ -133,6 +141,7 @@ export function RepoList() {
const { preferences, updateSettings } = useSettings()
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
const [repoToDelete, setRepoToDelete] = useState<number | null>(null)
const [deleteBranchChoice, setDeleteBranchChoice] = useState<DeleteBranchChoice>('none')
const [selectedRepos, setSelectedRepos] = useState<Set<number>>(new Set())
const [selectionMode, setSelectionMode] = useState(false)
const [searchQuery, setSearchQuery] = useState("")
@@ -209,11 +218,18 @@ export function RepoList() {
}, [viewModels])
const deleteMutation = useMutation({
mutationFn: deleteRepo,
onSuccess: () => {
mutationFn: (id: number) =>
deleteRepo(id, repoForDelete?.isWorktree ? { deleteBranch: deleteBranchChoice } : undefined),
onSuccess: (result) => {
invalidateRepoListCaches(queryClient)
setDeleteDialogOpen(false)
setRepoToDelete(null)
setDeleteBranchChoice('none')
if (result.branch?.error) {
showToast.warning(`Deleted the worktree but failed to delete branch "${result.branch.name}"`, {
description: result.branch.error,
})
}
},
})
@@ -483,7 +499,12 @@ export function RepoList() {
<DeleteDialog
open={deleteDialogOpen}
onOpenChange={setDeleteDialogOpen}
onOpenChange={(open) => {
setDeleteDialogOpen(open)
if (!open) {
setDeleteBranchChoice('none')
}
}}
onConfirm={() => {
if (selectedRepos.size > 0) {
batchDeleteMutation.mutate(Array.from(selectedRepos))
@@ -494,6 +515,7 @@ export function RepoList() {
onCancel={() => {
setDeleteDialogOpen(false)
setRepoToDelete(null)
setDeleteBranchChoice('none')
if (selectedRepos.size > 0) {
setSelectedRepos(new Set())
setSelectionMode(false)
@@ -505,9 +527,11 @@ export function RepoList() {
? "Unlink Multiple Repositories"
: "Delete Multiple Repositories"
: repoForDelete
? repoForDelete.isLocal
? "Unlink Repository"
: "Delete Repository"
? repoForDelete.isWorktree
? "Delete Worktree"
: repoForDelete.isLocal
? "Unlink Repository"
: "Delete Repository"
: "Delete Repository"
}
description={
@@ -517,7 +541,9 @@ export function RepoList() {
: hasLocalRepos && !hasClonedRepos
? `Are you sure you want to unlink ${selectedRepos.size} repositor${selectedRepos.size === 1 ? "y" : "ies"}? Only workspace references will be removed. Your original files will not be affected.`
: `Are you sure you want to delete ${selectedRepos.size} repositor${selectedRepos.size === 1 ? "y" : "ies"}? Cloned repositories will have their local files removed. Locally discovered repositories will only have their workspace references removed — original files will not be affected.`
: repoForDelete?.isLocal
: repoForDelete?.isWorktree
? "Are you sure you want to delete this worktree? This will remove all local files. This action cannot be undone."
: repoForDelete?.isLocal
? (
<>
Are you sure you want to unlink this repository? Only the workspace reference will be removed.
@@ -533,7 +559,19 @@ export function RepoList() {
: "Are you sure you want to delete this repository? This will remove all local files. This action cannot be undone."
}
isDeleting={deleteMutation.isPending || batchDeleteMutation.isPending}
/>
>
{selectedRepos.size === 0 && repoForDelete?.isWorktree && (
<div>
<span className="mb-1.5 block text-sm font-medium text-foreground">Branch</span>
<RadioOptionGroup
name="delete-worktree-branch"
value={deleteBranchChoice}
onChange={setDeleteBranchChoice}
options={DELETE_BRANCH_OPTIONS}
/>
</div>
)}
</DeleteDialog>
</>
)
}
@@ -36,6 +36,7 @@ const createMockGitStatus = (overrides: Partial<GitStatusResponse> = {}): GitSta
behind: 0,
files: [],
hasChanges: false,
operation: null,
...overrides,
})
@@ -0,0 +1,247 @@
import { describe, it, expect, vi, beforeEach, afterEach } 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 { GitSettings } from './GitSettings'
import type { UserPreferences } from '@/api/types/settings'
const {
getSettingsMock,
updateSettingsMock,
listReposMock,
updateRepoGitCredentialMock,
showToastMock,
} = vi.hoisted(() => ({
getSettingsMock: vi.fn(),
updateSettingsMock: vi.fn(),
listReposMock: vi.fn(),
updateRepoGitCredentialMock: vi.fn(),
showToastMock: { success: vi.fn(), error: vi.fn(), loading: vi.fn() },
}))
vi.mock('@/api/settings', () => ({
settingsApi: {
getSettings: getSettingsMock,
updateSettings: updateSettingsMock,
},
}))
vi.mock('@/api/repos', () => ({
listRepos: listReposMock,
updateRepoGitCredential: updateRepoGitCredentialMock,
}))
vi.mock('@/lib/toast', () => ({ showToast: showToastMock }))
vi.mock('@/hooks/useOpenCodeServerActions', () => ({
useOpenCodeServerActions: () => ({
restartServerMutation: { isPending: false },
confirmOpen: false,
setConfirmOpen: vi.fn(),
activeSessionCount: 0,
requestRestart: vi.fn(),
confirmRestart: vi.fn(),
}),
}))
vi.mock('./GitCredentialDialog', () => ({
GitCredentialDialog: ({
open,
onSave,
}: {
open: boolean
onSave: (credential: unknown, options: unknown) => Promise<void>
}) =>
open ? (
<button
type="button"
onClick={() =>
void onSave(
{ name: 'Work', host: 'github.com', type: 'pat', token: 'tok' },
{ makeDefault: false, repoIds: [] },
)
}
>
Confirm credential save
</button>
) : null,
}))
function buildPreferences(overrides: Partial<UserPreferences> = {}): UserPreferences {
return {
theme: 'dark',
mode: 'build',
autoScroll: true,
expandDiffs: true,
expandToolCalls: false,
showReasoning: false,
simpleChatMode: false,
keyboardShortcuts: {},
customCommands: [],
gitCredentials: [],
gitIdentity: { name: '', email: '' },
gitIdentities: [],
...overrides,
}
}
let serverPreferences: UserPreferences
function setupServer(initial: UserPreferences) {
serverPreferences = initial
getSettingsMock.mockImplementation(async () => ({ preferences: serverPreferences, updatedAt: Date.now() }))
updateSettingsMock.mockImplementation(async (request: { preferences: Partial<UserPreferences> }) => {
serverPreferences = { ...serverPreferences, ...request.preferences }
return { preferences: serverPreferences, updatedAt: Date.now() }
})
}
function renderGitSettings(repos: unknown[] = []) {
listReposMock.mockResolvedValue(repos)
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
})
function Wrapper({ children }: { children: ReactNode }) {
return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
}
return { queryClient, ...render(<GitSettings />, { wrapper: Wrapper }) }
}
function defaultIdentityNameInput() {
return screen.getByLabelText('Name', { selector: 'input#git-name' })
}
function savedIdentityNameInput(index = 0) {
return screen.getByLabelText('Name', { selector: `input#git-identity-${index}-name` })
}
describe('GitSettings draft preservation', () => {
beforeEach(() => {
vi.clearAllMocks()
})
afterEach(() => {
vi.restoreAllMocks()
})
it('keeps default identity edits when a saved identity is removed', async () => {
const user = userEvent.setup()
setupServer(
buildPreferences({
gitIdentity: { name: 'Old Name', email: 'old@example.com' },
gitIdentities: [{ id: 'a', name: 'Alpha', email: 'alpha@example.com' }],
}),
)
renderGitSettings()
const nameInput = await screen.findByLabelText('Name', { selector: 'input#git-name' })
await user.clear(nameInput)
await user.type(nameInput, 'New Name')
expect(nameInput).toHaveValue('New Name')
await user.click(screen.getByTitle('Delete'))
await waitFor(() => expect(screen.queryByText('Alpha')).not.toBeInTheDocument())
expect(defaultIdentityNameInput()).toHaveValue('New Name')
expect(screen.getByRole('button', { name: /save changes/i })).toBeInTheDocument()
})
it('keeps saved identity drafts when a credential is saved', async () => {
const user = userEvent.setup()
setupServer(buildPreferences())
renderGitSettings()
await screen.findByLabelText('Name', { selector: 'input#git-name' })
await user.click(screen.getAllByRole('button', { name: 'Add' })[1])
const identityNameInput = await screen.findByLabelText('Name', { selector: 'input#git-identity-0-name' })
await user.type(identityNameInput, 'Draft Person')
await user.click(screen.getAllByRole('button', { name: 'Add' })[0])
await user.click(await screen.findByRole('button', { name: 'Confirm credential save' }))
await waitFor(() => expect(updateSettingsMock).toHaveBeenCalled())
expect(savedIdentityNameInput()).toHaveValue('Draft Person')
expect(screen.getByRole('button', { name: /save changes/i })).toBeInTheDocument()
})
it('keeps saved identity drafts when a credential is deleted', async () => {
const user = userEvent.setup()
setupServer(
buildPreferences({
gitCredentials: [{ id: 'cred-1', name: 'Work', host: 'github.com', type: 'pat', token: 'tok' }],
}),
)
renderGitSettings()
await screen.findByLabelText('Name', { selector: 'input#git-name' })
await user.click(screen.getAllByRole('button', { name: 'Add' })[1])
const identityNameInput = await screen.findByLabelText('Name', { selector: 'input#git-identity-0-name' })
await user.type(identityNameInput, 'Draft Person')
await user.click(screen.getAllByTitle('Delete')[0])
await waitFor(() => expect(updateSettingsMock).toHaveBeenCalled())
expect(savedIdentityNameInput()).toHaveValue('Draft Person')
expect(screen.getByRole('button', { name: /save changes/i })).toBeInTheDocument()
})
it('removes a saved identity without touching repositories', async () => {
const user = userEvent.setup()
const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(true)
setupServer(
buildPreferences({
gitIdentities: [{ id: 'a', name: 'Alpha', email: 'alpha@example.com' }],
}),
)
renderGitSettings([
{
id: 1,
localPath: 'repo-one',
fullPath: '/workspace/repo-one',
defaultBranch: 'main',
cloneStatus: 'ready',
clonedAt: Date.now(),
},
])
await screen.findByLabelText('Name', { selector: 'input#git-name' })
await user.click(await screen.findByTitle('Delete'))
await waitFor(() => expect(screen.queryByText('Alpha')).not.toBeInTheDocument())
expect(confirmSpy).not.toHaveBeenCalled()
expect(updateRepoGitCredentialMock).not.toHaveBeenCalled()
expect(listReposMock).toHaveBeenCalledTimes(1)
})
it('invalidates the repo git identity cache after saving', async () => {
const user = userEvent.setup()
setupServer(buildPreferences())
const { queryClient } = renderGitSettings()
const invalidateSpy = vi.spyOn(queryClient, 'invalidateQueries')
const nameInput = await screen.findByLabelText('Name', { selector: 'input#git-name' })
await user.type(nameInput, 'New Name')
await user.click(screen.getByRole('button', { name: /save changes/i }))
await waitFor(() => expect(invalidateSpy).toHaveBeenCalledWith({ queryKey: ['repoGitIdentity'] }))
})
it('retains identity drafts when saving fails', async () => {
const user = userEvent.setup()
setupServer(buildPreferences())
updateSettingsMock.mockRejectedValueOnce(new Error('network down'))
renderGitSettings()
const nameInput = await screen.findByLabelText('Name', { selector: 'input#git-name' })
await user.type(nameInput, 'Draft Name')
await user.click(screen.getByRole('button', { name: /save changes/i }))
await waitFor(() => expect(showToastMock.error).toHaveBeenCalled())
expect(defaultIdentityNameInput()).toHaveValue('Draft Name')
expect(screen.getByRole('button', { name: /save changes/i })).toBeInTheDocument()
})
})
+130 -14
View File
@@ -1,7 +1,7 @@
import { useState, useEffect } from 'react'
import { useState, useEffect, useRef } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { useSettings } from '@/hooks/useSettings'
import { Loader2, Plus, Trash2, Save, User, Key, Pencil } from 'lucide-react'
import { Loader2, Plus, Trash2, Save, User, Users, Key, Pencil } from 'lucide-react'
import { showToast } from '@/lib/toast'
import { GitCredentialDialog, type GitCredentialSaveOptions } from './GitCredentialDialog'
import { RestartServerDialog } from './RestartServerDialog'
@@ -9,7 +9,7 @@ import { Label } from '@/components/ui/label'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { randomId } from '@/lib/utils'
import type { GitCredential, GitIdentity, UserPreferences } from '@/api/types/settings'
import type { GitCredential, GitIdentity, GitIdentityProfile, UserPreferences } from '@/api/types/settings'
import { listRepos, updateRepoGitCredential } from '@/api/repos'
import { useOpenCodeServerActions } from '@/hooks/useOpenCodeServerActions'
@@ -22,11 +22,13 @@ export function GitSettings() {
const queryClient = useQueryClient()
const [gitCredentials, setGitCredentials] = useState<GitCredential[]>([])
const [gitIdentity, setGitIdentity] = useState<GitIdentity>({ name: '', email: '' })
const [gitIdentities, setGitIdentities] = useState<GitIdentityProfile[]>([])
const [defaultGitCredentialId, setDefaultGitCredentialId] = useState<string | undefined>()
const [isSaving, setIsSaving] = useState(false)
const [hasChanges, setHasChanges] = useState(false)
const [isCredentialDialogOpen, setIsCredentialDialogOpen] = useState(false)
const [editingCredentialIndex, setEditingCredentialIndex] = useState<number | null>(null)
const identityDirtyRef = useRef(false)
const { data: repos = [] } = useQuery({
queryKey: ['repos'],
@@ -58,16 +60,25 @@ export function GitSettings() {
useEffect(() => {
if (preferences) {
setGitCredentials(preferences.gitCredentials || [])
setGitIdentity(preferences.gitIdentity || { name: '', email: '' })
setDefaultGitCredentialId(preferences.defaultGitCredentialId)
setHasChanges(false)
if (!identityDirtyRef.current) {
setGitIdentity(preferences.gitIdentity || { name: '', email: '' })
setGitIdentities(preferences.gitIdentities || [])
setHasChanges(false)
}
}
}, [preferences])
const checkForIdentityChanges = (newIdentity: GitIdentity) => {
const identityListsEqual = (a: GitIdentityProfile[], b: GitIdentityProfile[]) =>
a.length === b.length && a.every((entry, index) =>
entry.id === b[index]?.id && entry.name === b[index]?.name && entry.email === b[index]?.email)
const checkForIdentityChanges = (newIdentity: GitIdentity, newIdentities: GitIdentityProfile[]) => {
const currentIdentity = preferences?.gitIdentity || { name: '', email: '' }
const identityChanged = currentIdentity.name !== newIdentity.name || currentIdentity.email !== newIdentity.email
setHasChanges(identityChanged)
const identitiesChanged = !identityListsEqual(preferences?.gitIdentities || [], newIdentities)
identityDirtyRef.current = identityChanged || identitiesChanged
setHasChanges(identityChanged || identitiesChanged)
}
const openAddCredentialDialog = () => {
@@ -122,7 +133,7 @@ export function GitSettings() {
try {
await saveGitSettings(
{ gitCredentials: newCredentials, defaultGitCredentialId: nextDefaultGitCredentialId, gitIdentity },
{ gitCredentials: newCredentials, defaultGitCredentialId: nextDefaultGitCredentialId },
{
successMessage: 'Credential saved',
afterSave: () => syncRepoAssignments(nextCredential.id!, options.repoIds),
@@ -144,7 +155,7 @@ export function GitSettings() {
try {
await saveGitSettings(
{ gitCredentials: newCredentials, defaultGitCredentialId: nextDefaultGitCredentialId, gitIdentity },
{ gitCredentials: newCredentials, defaultGitCredentialId: nextDefaultGitCredentialId },
{
successMessage: 'Credential deleted',
afterSave: removedCredentialId ? () => syncRepoAssignments(removedCredentialId, []) : undefined,
@@ -158,7 +169,25 @@ export function GitSettings() {
const updateIdentity = (field: keyof GitIdentity, value: string) => {
const newIdentity = { ...gitIdentity, [field]: value }
setGitIdentity(newIdentity)
checkForIdentityChanges(newIdentity)
checkForIdentityChanges(newIdentity, gitIdentities)
}
const updateSavedIdentity = (index: number, field: keyof GitIdentity, value: string) => {
const newIdentities = gitIdentities.map((identity, i) => i === index ? { ...identity, [field]: value } : identity)
setGitIdentities(newIdentities)
checkForIdentityChanges(gitIdentity, newIdentities)
}
const addIdentity = () => {
const newIdentities = [...gitIdentities, { id: randomId(), name: '', email: '' }]
setGitIdentities(newIdentities)
checkForIdentityChanges(gitIdentity, newIdentities)
}
const removeIdentity = (index: number) => {
const newIdentities = gitIdentities.filter((_, i) => i !== index)
setGitIdentities(newIdentities)
checkForIdentityChanges(gitIdentity, newIdentities)
}
const saveAll = async () => {
@@ -166,9 +195,14 @@ export function GitSettings() {
try {
showToast.loading('Saving git configuration...', { id: 'git-config' })
await saveGitSettings(
{ gitCredentials, defaultGitCredentialId, gitIdentity },
{ successMessage: 'Git configuration saved', toastId: 'git-config' }
{ gitCredentials, defaultGitCredentialId, gitIdentity, gitIdentities },
{
successMessage: 'Git configuration saved',
toastId: 'git-config',
}
)
await queryClient.invalidateQueries({ queryKey: ['repoGitIdentity'] })
identityDirtyRef.current = false
setHasChanges(false)
} catch {
showToast.error('Failed to save git configuration', { id: 'git-config' })
@@ -212,7 +246,7 @@ export function GitSettings() {
<div className="min-w-0 space-y-4">
<div className="flex items-center gap-3">
<User className="w-4 h-4 shrink-0 text-muted-foreground" />
<span className="font-medium">Identity</span>
<span className="font-medium">Default identity</span>
<span className="ml-auto min-w-0 truncate text-xs text-muted-foreground">
{gitIdentity.name || gitIdentity.email ? `${gitIdentity.name || 'No name'} <${gitIdentity.email || 'No email'}>` : 'Not configured'}
</span>
@@ -220,7 +254,7 @@ export function GitSettings() {
<div className="space-y-4 sm:ml-7">
<p className="text-sm text-muted-foreground">
Author identity used for git commits. Leave empty to use system defaults.
Used for commits by Manager and agents in repositories that have no identity of their own. Applies without restarting.
</p>
<div className="space-y-4">
<div className="space-y-2">
@@ -346,6 +380,88 @@ export function GitSettings() {
</div>
</div>
<div className="border-t border-border p-4 sm:p-6">
<div className="flex items-center gap-3">
<Users className="w-4 h-4 shrink-0 text-muted-foreground" />
<span className="font-medium">Saved identities</span>
<span className="ml-auto text-xs text-muted-foreground">
{gitIdentities.length} saved
</span>
</div>
<div className="space-y-4 sm:ml-7">
<div className="flex items-center justify-between">
<p className="text-sm text-muted-foreground">
Presets you can apply to a repository from the commit box's "Commit as" selector. This writes the repository's local git config, shared by its worktrees.
</p>
<Button
type="button"
variant="outline"
size="sm"
onClick={addIdentity}
disabled={isSaving}
>
<Plus className="h-4 w-4 mr-2" />
Add
</Button>
</div>
{gitIdentities.length === 0 ? (
<div className="rounded-lg border border-dashed border-border p-4 text-center">
<p className="text-sm text-muted-foreground">
No saved identities. Click "Add" to create one.
</p>
</div>
) : (
<div className="space-y-3">
{gitIdentities.map((identity, index) => (
<div key={identity.id} className="space-y-3 rounded-lg border border-border p-3">
<div className="flex items-center justify-between">
<span className="text-xs font-medium text-muted-foreground">Identity {index + 1}</span>
<Button
type="button"
variant="ghost"
size="sm"
className="h-7 w-7 p-0 text-destructive hover:text-destructive"
onClick={() => removeIdentity(index)}
disabled={isSaving}
title="Delete"
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
</div>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
<div className="space-y-2">
<Label htmlFor={`git-identity-${index}-name`}>Name</Label>
<Input
id={`git-identity-${index}-name`}
placeholder="Your Name"
value={identity.name}
onChange={(e) => updateSavedIdentity(index, 'name', e.target.value)}
disabled={isSaving}
className="bg-background border-border text-foreground placeholder:text-muted-foreground"
/>
</div>
<div className="space-y-2">
<Label htmlFor={`git-identity-${index}-email`}>Email</Label>
<Input
id={`git-identity-${index}-email`}
type="email"
placeholder="you@example.com"
value={identity.email}
onChange={(e) => updateSavedIdentity(index, 'email', e.target.value)}
disabled={isSaving}
className="bg-background border-border text-foreground placeholder:text-muted-foreground"
/>
</div>
</div>
</div>
))}
</div>
)}
</div>
</div>
<GitCredentialDialog
open={isCredentialDialogOpen}
onOpenChange={setIsCredentialDialogOpen}
@@ -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>
)
}
@@ -12,6 +12,7 @@ interface ConfirmDestructiveDialogProps {
title: string
description: ReactNode
warning?: ReactNode
children?: ReactNode
confirmLabel: string
pendingLabel?: string
cancelLabel?: string
@@ -26,6 +27,7 @@ export function ConfirmDestructiveDialog({
title,
description,
warning,
children,
confirmLabel,
pendingLabel,
cancelLabel = 'Cancel',
@@ -46,6 +48,8 @@ export function ConfirmDestructiveDialog({
</Alert>
)}
{children}
<DialogFooter className="gap-2">
<Button
variant="outline"
+6 -2
View File
@@ -10,6 +10,7 @@ interface DeleteDialogProps {
description: ReactNode
itemName?: string
isDeleting?: boolean
children?: ReactNode
}
export function DeleteDialog({
@@ -20,7 +21,8 @@ export function DeleteDialog({
title,
description,
itemName,
isDeleting = false
isDeleting = false,
children
}: DeleteDialogProps) {
return (
<ConfirmDestructiveDialog
@@ -36,6 +38,8 @@ export function DeleteDialog({
confirmLabel={title.includes('Configuration') ? 'Delete Configuration' : 'Delete'}
pendingLabel="Deleting..."
isPending={isDeleting}
/>
>
{children}
</ConfirmDestructiveDialog>
)
}
@@ -0,0 +1,42 @@
export interface RadioOption<T extends string> {
value: T
label: string
description?: string
}
interface RadioOptionGroupProps<T extends string> {
name: string
value: T
onChange: (value: T) => void
options: Array<RadioOption<T>>
}
export function RadioOptionGroup<T extends string>({
name,
value,
onChange,
options,
}: RadioOptionGroupProps<T>) {
return (
<div className="space-y-2">
{options.map((option) => (
<label key={option.value} className="flex items-start gap-2 text-sm cursor-pointer">
<input
type="radio"
name={name}
value={option.value}
checked={value === option.value}
onChange={() => onChange(option.value)}
className="mt-0.5"
/>
<span>
<span className="block">{option.label}</span>
{option.description && (
<span className="block text-xs text-muted-foreground">{option.description}</span>
)}
</span>
</label>
))}
</div>
)
}