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

+91 -2
View File
@@ -1,6 +1,7 @@
import { useQuery } from '@tanstack/react-query'
import { fetchWrapper, FetchError } from './fetchWrapper'
import { API_BASE_URL } from '@/config'
import type { DeleteBranchRequest, DeleteBranchResult, GitStashEntry, IntegrateBranchRequest, IntegrateBranchResult, RenameBranchRequest, StashApplyRequest, StashDropRequest, StashPushRequest } from '@opencode-manager/shared'
import type { GitStatusResponse, FileDiffResponse, GitCommit, CommitDetails } from '@/types/git'
export async function fetchGitStatus(repoId: number): Promise<GitStatusResponse> {
@@ -73,6 +74,12 @@ export async function gitCommit(repoId: number, message: string, stagedPaths?: s
})
}
export async function gitGenerateCommitMessage(repoId: number): Promise<{ message: string }> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/commit-message`, {
method: 'POST',
})
}
export async function gitStageFiles(repoId: number, paths: string[]): Promise<GitStatusResponse> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/stage`, {
method: 'POST',
@@ -105,12 +112,94 @@ export async function gitReset(repoId: number, commitHash: string): Promise<GitS
})
}
export function useGitStatus(repoId: number | undefined) {
export async function gitRenameBranch(repoId: number, request: RenameBranchRequest): Promise<GitStatusResponse> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/branches/rename`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(request),
})
}
export async function gitDeleteBranch(
repoId: number,
request: DeleteBranchRequest
): Promise<DeleteBranchResult & { status: GitStatusResponse }> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/branches`, {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(request),
})
}
async function fetchGitStashes(repoId: number): Promise<{ stashes: GitStashEntry[] }> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/stash`)
}
export async function gitStashPush(repoId: number, request: StashPushRequest): Promise<GitStatusResponse> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/stash`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(request),
})
}
export async function gitStashApply(repoId: number, index: number, request: StashApplyRequest): Promise<GitStatusResponse> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/stash/${index}/apply`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(request),
})
}
export async function gitStashDrop(repoId: number, index: number, request: StashDropRequest): Promise<GitStatusResponse> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/stash/${index}`, {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(request),
})
}
export async function gitContinueOperation(repoId: number): Promise<GitStatusResponse> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/operation/continue`, {
method: 'POST',
})
}
export async function gitAbortOperation(repoId: number): Promise<GitStatusResponse> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/operation/abort`, {
method: 'POST',
})
}
export async function gitIntegrateBranch(
repoId: number,
request: IntegrateBranchRequest
): Promise<IntegrateBranchResult & { targetStatus: GitStatusResponse }> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/integrate`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(request),
})
}
interface GitStatusQueryOptions {
refetchInterval?: number | false
}
export function useGitStatus(repoId: number | undefined, options: GitStatusQueryOptions = {}) {
return useQuery({
queryKey: ['gitStatus', repoId],
queryFn: () => repoId ? fetchGitStatus(repoId) : Promise.reject(new Error('No repo ID')),
enabled: !!repoId,
refetchInterval: false,
refetchInterval: options.refetchInterval ?? false,
})
}
export function useGitStashes(repoId: number | undefined) {
return useQuery({
queryKey: ['gitStashes', repoId],
queryFn: () => repoId ? fetchGitStashes(repoId) : Promise.reject(new Error('No repo ID')),
enabled: !!repoId,
})
}
+43
View File
@@ -9,6 +9,7 @@ import {
compactSession,
createSession,
createSessionWithContext,
createSessionWithPrompt,
deleteSession,
findFiles,
forkSession,
@@ -215,6 +216,48 @@ describe('OpenCode facade', () => {
expect((deleteInit as RequestInit).method).toBe('DELETE')
})
it('creates a session in a directory and sends a prompt', async () => {
fetchMock
.mockResolvedValueOnce(jsonResponse({ data: sessionInfo('ses_new', '/abs/repos/my-repo') }))
.mockResolvedValueOnce(
jsonResponse({
data: {
id: 'msg_1',
sessionID: 'ses_new',
time: { created: 1000 },
type: 'user',
payload: { text: 'Fix conflicts' },
},
}),
)
const session = await createSessionWithPrompt(
{ directory: '/abs/repos/my-repo', title: 'Resolve merge conflicts' },
'Fix conflicts',
)
expect(session.id).toBe('ses_new')
const [createUrl] = fetchMock.mock.calls[0] ?? []
expect(String(createUrl)).toBe('http://localhost/api/opencode/api/session')
const [promptUrl, promptInit] = fetchMock.mock.calls[1] ?? []
expect(String(promptUrl)).toBe('http://localhost/api/opencode/api/session/ses_new/prompt')
expect((promptInit as RequestInit).method).toBe('POST')
expect((promptInit as RequestInit).body).toBe(JSON.stringify({ text: 'Fix conflicts' }))
})
it('deletes the new session when sending the prompt fails', async () => {
fetchMock
.mockResolvedValueOnce(jsonResponse({ data: sessionInfo('ses_new', '/abs/repos/my-repo') }))
.mockResolvedValueOnce(new Response('nope', { status: 400 }))
.mockResolvedValueOnce(new Response(null, { status: 204 }))
await expect(createSessionWithPrompt({ directory: '/abs/repos/my-repo' }, 'Fix conflicts')).rejects.toBeInstanceOf(FetchError)
const [deleteUrl, deleteInit] = fetchMock.mock.calls[2] ?? []
expect(String(deleteUrl)).toBe('http://localhost/api/opencode/api/session/ses_new')
expect((deleteInit as RequestInit).method).toBe('DELETE')
})
it('finds files through the V2 filesystem route and returns paths', async () => {
fetchMock.mockResolvedValue(
jsonResponse({
+13 -2
View File
@@ -140,10 +140,13 @@ export async function addSessionContext(sessionID: string, text: string): Promis
await callOpenCode((api) => api.session.synthetic({ sessionID, text, resume: false }))
}
export async function createSessionWithContext(input: CreateSessionInput, context: string): Promise<SessionInfo> {
async function createSessionThen(
input: CreateSessionInput,
step: (session: SessionInfo) => Promise<unknown>,
): Promise<SessionInfo> {
const session = await createSession(input)
try {
await addSessionContext(session.id, context)
await step(session)
} catch (error) {
await deleteSession(session.id).catch(() => undefined)
throw error
@@ -151,6 +154,14 @@ export async function createSessionWithContext(input: CreateSessionInput, contex
return session
}
export async function createSessionWithContext(input: CreateSessionInput, context: string): Promise<SessionInfo> {
return createSessionThen(input, (session) => addSessionContext(session.id, context))
}
export async function createSessionWithPrompt(input: CreateSessionInput, text: string): Promise<SessionInfo> {
return createSessionThen(input, (session) => sendPrompt({ sessionID: session.id, text }))
}
export async function switchSessionModel(sessionID: string, model: ModelRef): Promise<void> {
await callOpenCode((api) => api.session.switchModel({ sessionID, model }))
}
+24 -3
View File
@@ -2,7 +2,7 @@ import type { Repo } from './types'
import { FetchError, fetchWrapper, fetchWrapperVoid, fetchWrapperBlob } from './fetchWrapper'
import { API_BASE_URL } from '@/config'
import { saveFile } from '@/lib/download'
import type { DiscoverReposResponse, AssistantModeStatus, AssistantModeInitRequest } from '@opencode-manager/shared/types'
import type { DiscoverReposResponse, AssistantModeStatus, AssistantModeInitRequest, DeleteRepoRequest, DeleteRepoResult, RepoGitIdentity } from '@opencode-manager/shared/types'
export interface CreateRepoOptions {
repoUrl?: string
@@ -69,9 +69,18 @@ export async function createRepoWorkspace(repoId: number): Promise<RepoWorktree>
})
}
export async function deleteRepo(id: number): Promise<void> {
return fetchWrapperVoid(`${API_BASE_URL}/api/repos/${id}`, {
export type DeleteBranchChoice = NonNullable<DeleteRepoRequest['deleteBranch']>
export interface DeleteRepoOptions {
deleteBranch?: DeleteBranchChoice
}
export async function deleteRepo(id: number, options?: DeleteRepoOptions): Promise<DeleteRepoResult> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${id}`, {
method: 'DELETE',
...(options
? { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(options) }
: {}),
})
}
@@ -83,6 +92,18 @@ export async function updateRepoGitCredential(id: number, credentialId?: string)
})
}
export async function getRepoGitIdentity(id: number): Promise<RepoGitIdentity> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${id}/git-identity`)
}
export async function updateRepoGitIdentity(id: number, identityId: string | null): Promise<RepoGitIdentity> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${id}/git-identity`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ identityId }),
})
}
export async function renameRepo(id: number, name: string | null): Promise<Repo> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${id}`, {
method: 'PATCH',
+1 -1
View File
@@ -27,7 +27,7 @@ import type { NotificationPreferences } from '@opencode-manager/shared/types'
import { saveFile } from '@/lib/download'
export type { TTSConfig, STTConfig, OpenCodeConfigFile, OpenCodeConfigSourceFile, OpenCodeConfigSourceName, UpdateOpenCodeConfigRequest, ModelConfig, ProviderConfig, SandboxPreferences, NotificationPreferences, SkillFileInfo, CreateSkillRequest, UpdateSkillRequest, SkillScope, InstallSkillFromGithubRequest, InstallSkillResponse }
export type { UserPreferences, UpdateSettingsRequest, CustomCommand, GitCredential, GitIdentity } from '@opencode-manager/shared'
export type { UserPreferences, UpdateSettingsRequest, CustomCommand, GitCredential, GitIdentity, GitIdentityProfile } from '@opencode-manager/shared'
export { DEFAULT_TTS_CONFIG, DEFAULT_STT_CONFIG, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_USER_PREFERENCES, DEFAULT_LEADER_KEY, BLOCKED_SERVER_ENV_KEYS }
export { isOpenCodeConfigSourceName } from '@opencode-manager/shared'
@@ -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>
)
}
+312 -6
View File
@@ -15,11 +15,19 @@ vi.mock('../api/git', () => ({
gitUnstageFiles: vi.fn(),
gitDiscardFiles: vi.fn(),
gitReset: vi.fn(),
gitRenameBranch: vi.fn(),
gitDeleteBranch: vi.fn(),
gitStashPush: vi.fn(),
gitStashApply: vi.fn(),
gitStashDrop: vi.fn(),
gitContinueOperation: vi.fn(),
gitAbortOperation: vi.fn(),
gitGenerateCommitMessage: vi.fn(),
gitIntegrateBranch: vi.fn(),
fetchGitStatus: vi.fn(),
fetchGitLog: vi.fn(),
fetchGitDiff: vi.fn(),
createBranch: vi.fn(),
switchBranch: vi.fn(),
getApiErrorMessage: vi.fn((error: unknown) => typeof error === 'string' ? error : String(error)),
}))
vi.mock('../lib/toast', () => ({
@@ -38,23 +46,42 @@ const mockInvalidateQueries = vi.fn()
const mockSetQueryData = vi.fn()
const mockSetQueriesData = vi.fn()
const mockRealQueryClient = vi.hoisted(() => ({ current: null as unknown }))
const mockGitStatus: GitStatusResponse = {
branch: 'main',
ahead: 0,
behind: 0,
files: [],
hasChanges: false,
operation: null,
}
vi.mock('@tanstack/react-query', async () => {
const actual = await vi.importActual('@tanstack/react-query')
return {
...actual,
useQueryClient: vi.fn(() => ({
invalidateQueries: mockInvalidateQueries,
setQueryData: mockSetQueryData,
setQueriesData: mockSetQueriesData,
}))
useQueryClient: vi.fn(() => {
const real = mockRealQueryClient.current as {
invalidateQueries: (...args: unknown[]) => unknown
setQueryData: (...args: unknown[]) => unknown
setQueriesData: (...args: unknown[]) => unknown
} | null
return {
invalidateQueries: (...args: unknown[]) => {
mockInvalidateQueries(...args)
return real?.invalidateQueries(...args)
},
setQueryData: (...args: unknown[]) => {
mockSetQueryData(...args)
return real?.setQueryData(...args)
},
setQueriesData: (...args: unknown[]) => {
mockSetQueriesData(...args)
return real?.setQueriesData(...args)
},
}
})
}
})
@@ -74,6 +101,9 @@ describe('useGit', () => {
beforeEach(() => {
vi.clearAllMocks()
mockInvalidateQueries.mockClear()
mockRealQueryClient.current = new QueryClient({
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
})
vi.mocked(gitApi.gitFetch).mockResolvedValue(mockGitStatus)
vi.mocked(gitApi.gitPull).mockResolvedValue(mockGitStatus)
vi.mocked(gitApi.gitPush).mockResolvedValue(mockGitStatus)
@@ -82,6 +112,15 @@ describe('useGit', () => {
vi.mocked(gitApi.gitUnstageFiles).mockResolvedValue(mockGitStatus)
vi.mocked(gitApi.gitDiscardFiles).mockResolvedValue(mockGitStatus)
vi.mocked(gitApi.gitReset).mockResolvedValue(mockGitStatus)
vi.mocked(gitApi.gitRenameBranch).mockResolvedValue(mockGitStatus)
vi.mocked(gitApi.gitDeleteBranch).mockResolvedValue({ remoteDeleted: false, status: mockGitStatus })
vi.mocked(gitApi.gitStashPush).mockResolvedValue(mockGitStatus)
vi.mocked(gitApi.gitStashApply).mockResolvedValue(mockGitStatus)
vi.mocked(gitApi.gitStashDrop).mockResolvedValue(mockGitStatus)
vi.mocked(gitApi.gitContinueOperation).mockResolvedValue(mockGitStatus)
vi.mocked(gitApi.gitAbortOperation).mockResolvedValue(mockGitStatus)
vi.mocked(gitApi.gitGenerateCommitMessage).mockResolvedValue({ message: 'generated message' })
vi.mocked(gitApi.gitIntegrateBranch).mockResolvedValue({ targetRepoId: 2, integratedCommits: 1, targetStatus: mockGitStatus })
vi.mocked(gitApi.fetchGitStatus).mockResolvedValue(mockGitStatus)
})
@@ -293,4 +332,271 @@ describe('useGit', () => {
expect(toast.showToast.error).toHaveBeenCalledWith('Unstage failed')
})
})
describe('renameBranch mutation', () => {
it('calls correct API and updates the status cache on success', async () => {
const { result } = renderHook(() => useGit(1), { wrapper: createWrapper() })
await waitFor(() => {
result.current.renameBranch.mutateAsync({ from: 'main', to: 'renamed' })
})
expect(gitApi.gitRenameBranch).toHaveBeenCalledWith(1, { from: 'main', to: 'renamed' })
expectTargetedStatusCacheUpdate()
expect(toast.showToast.success).toHaveBeenCalledWith('Branch renamed')
})
it('shows toast error on failure', async () => {
vi.mocked(gitApi.gitRenameBranch).mockRejectedValue('Rename failed')
const { result } = renderHook(() => useGit(1), { wrapper: createWrapper() })
await waitFor(() => {
result.current.renameBranch.mutateAsync({ from: 'main', to: 'renamed' }).catch(() => {})
})
expect(toast.showToast.error).toHaveBeenCalledWith('Rename failed')
})
})
describe('deleteBranch mutation', () => {
it('calls correct API, updates the status cache and shows success toast', async () => {
const { result } = renderHook(() => useGit(1), { wrapper: createWrapper() })
await waitFor(() => {
result.current.deleteBranch.mutateAsync({ name: 'feature', force: false, deleteRemote: false })
})
expect(gitApi.gitDeleteBranch).toHaveBeenCalledWith(1, { name: 'feature', force: false, deleteRemote: false })
expectTargetedStatusCacheUpdate()
expect(mockInvalidateQueries).toHaveBeenCalledWith({ queryKey: ['branches', 1] })
expect(mockInvalidateQueries).not.toHaveBeenCalledWith({ queryKey: ['repos'] })
expect(mockInvalidateQueries).not.toHaveBeenCalledWith({ queryKey: ['repo', 1] })
expect(toast.showToast.success).toHaveBeenCalledWith('Branch deleted')
})
it('shows toast error on failure', async () => {
vi.mocked(gitApi.gitDeleteBranch).mockRejectedValue('Delete failed')
const { result } = renderHook(() => useGit(1), { wrapper: createWrapper() })
await waitFor(() => {
result.current.deleteBranch
.mutateAsync({ name: 'feature', force: false, deleteRemote: false })
.catch(() => {})
})
expect(toast.showToast.error).toHaveBeenCalledWith('Delete failed')
})
})
describe('stashPush mutation', () => {
it('invalidates the shared stash list prefix and updates the status cache', async () => {
const { result } = renderHook(() => useGit(1), { wrapper: createWrapper() })
await waitFor(() => {
result.current.stashPush.mutateAsync({ message: 'wip', includeUntracked: true })
})
expect(gitApi.gitStashPush).toHaveBeenCalledWith(1, { message: 'wip', includeUntracked: true })
expectTargetedStatusCacheUpdate()
expect(mockInvalidateQueries).toHaveBeenCalledWith({ queryKey: ['gitStashes'] })
expect(toast.showToast.success).toHaveBeenCalledWith('Changes stashed')
})
it('shows toast error on failure', async () => {
vi.mocked(gitApi.gitStashPush).mockRejectedValue('Stash failed')
const { result } = renderHook(() => useGit(1), { wrapper: createWrapper() })
await waitFor(() => {
result.current.stashPush.mutateAsync({ message: 'wip', includeUntracked: true }).catch(() => {})
})
expect(toast.showToast.error).toHaveBeenCalledWith('Stash failed')
})
})
describe('stashApply success', () => {
it('sends the hash and pop flag, invalidates the shared stash list prefix and shows the pop toast', async () => {
const { result } = renderHook(() => useGit(1), { wrapper: createWrapper() })
await waitFor(() => {
result.current.stashApply.mutateAsync({ index: 0, hash: 'abc123', pop: true })
})
expect(gitApi.gitStashApply).toHaveBeenCalledWith(1, 0, { hash: 'abc123', pop: true })
expectTargetedStatusCacheUpdate()
expect(mockInvalidateQueries).toHaveBeenCalledWith({ queryKey: ['gitStashes'] })
expect(toast.showToast.success).toHaveBeenCalledWith('Stash popped')
})
})
describe('stashDrop mutation', () => {
it('sends the hash, invalidates the shared stash list prefix and updates the status cache', async () => {
const { result } = renderHook(() => useGit(1), { wrapper: createWrapper() })
await waitFor(() => {
result.current.stashDrop.mutateAsync({ index: 0, hash: 'abc123' })
})
expect(gitApi.gitStashDrop).toHaveBeenCalledWith(1, 0, { hash: 'abc123' })
expectTargetedStatusCacheUpdate()
expect(mockInvalidateQueries).toHaveBeenCalledWith({ queryKey: ['gitStashes'] })
expect(toast.showToast.success).toHaveBeenCalledWith('Stash dropped')
})
})
describe('generateCommitMessage mutation', () => {
it('calls the API and returns the generated message', async () => {
const { result } = renderHook(() => useGit(1), { wrapper: createWrapper() })
await expect(result.current.generateCommitMessage.mutateAsync()).resolves.toEqual({
message: 'generated message',
})
expect(gitApi.gitGenerateCommitMessage).toHaveBeenCalledWith(1)
})
it('shows toast error on failure', async () => {
vi.mocked(gitApi.gitGenerateCommitMessage).mockRejectedValue('Generation failed')
const { result } = renderHook(() => useGit(1), { wrapper: createWrapper() })
await waitFor(() => {
result.current.generateCommitMessage.mutateAsync().catch(() => {})
})
expect(toast.showToast.error).toHaveBeenCalledWith('Generation failed')
})
})
describe('integrateBranch mutation', () => {
it('writes the target status cache and refreshes the repo list without invalidating the source or batched status', async () => {
const { result } = renderHook(() => useGit(1), { wrapper: createWrapper() })
await waitFor(() => {
result.current.integrateBranch.mutateAsync({ targetBranch: 'main', strategy: 'merge' })
})
expect(gitApi.gitIntegrateBranch).toHaveBeenCalledWith(1, { targetBranch: 'main', strategy: 'merge' })
expect(toast.showToast.success).toHaveBeenCalledWith('Integrated 1 commit into main')
expect(mockSetQueryData).toHaveBeenCalledWith(['gitStatus', 2], mockGitStatus)
expect(mockInvalidateQueries).not.toHaveBeenCalledWith({ queryKey: ['gitStatus', 1] })
expect(mockInvalidateQueries).not.toHaveBeenCalledWith({ queryKey: ['gitStatus', 2] })
expect(mockInvalidateQueries).not.toHaveBeenCalledWith({ queryKey: ['reposGitStatus'] })
expect(mockInvalidateQueries).toHaveBeenCalledWith({ queryKey: ['repos'] })
expect(mockInvalidateQueries).toHaveBeenCalledWith({ queryKey: ['gitLog', 2] })
expect(mockInvalidateQueries).toHaveBeenCalledWith({ queryKey: ['fileDiff', 2] })
})
})
describe('stashApply mutation', () => {
it('invalidates the cached working-tree state and refreshes the stash list when apply conflicts', async () => {
const realClient = mockRealQueryClient.current as QueryClient
realClient.setQueryData(['gitStatus', 1], mockGitStatus)
realClient.setQueryData(['fileDiff', 1, 'file.txt', undefined], { path: 'file.txt', diff: 'cached' })
vi.mocked(gitApi.gitStashApply).mockRejectedValue(
'CONFLICT (content): Merge conflict in file.txt',
)
const { result } = renderHook(() => useGit(1), { wrapper: createWrapper() })
await waitFor(() => {
result.current.stashApply.mutateAsync({ index: 0, hash: 'abc123', pop: false }).catch(() => {})
})
expect(gitApi.gitStashApply).toHaveBeenCalledWith(1, 0, { hash: 'abc123', pop: false })
expect(realClient.getQueryState(['gitStatus', 1])?.isInvalidated).toBe(true)
expect(realClient.getQueryState(['fileDiff', 1, 'file.txt', undefined])?.isInvalidated).toBe(true)
expect(mockInvalidateQueries).toHaveBeenCalledWith({ queryKey: ['gitStashes'] })
const aggregateCall = mockInvalidateQueries.mock.calls.find(
([arg]) => (arg as { queryKey?: unknown[] } | undefined)?.queryKey?.[0] === 'reposGitStatus',
)
expect(aggregateCall).toBeDefined()
const predicate = (aggregateCall![0] as { predicate: (query: { queryKey: unknown[] }) => boolean }).predicate
expect(predicate({ queryKey: ['reposGitStatus', [1, 2]] })).toBe(true)
expect(predicate({ queryKey: ['reposGitStatus', [2, 3]] })).toBe(false)
expect(toast.showToast.error).toHaveBeenCalledWith('CONFLICT (content): Merge conflict in file.txt')
expect(toast.showToast.success).not.toHaveBeenCalled()
expect(gitApi.gitStashDrop).not.toHaveBeenCalled()
})
})
describe('continueOperation mutation', () => {
it('calls the API, updates the status cache and shows success', async () => {
const { result } = renderHook(() => useGit(1), { wrapper: createWrapper() })
await waitFor(() => {
result.current.continueOperation.mutateAsync()
})
expect(gitApi.gitContinueOperation).toHaveBeenCalledWith(1)
expectTargetedStatusCacheUpdate()
expect(toast.showToast.success).toHaveBeenCalledWith('Operation continued')
})
it('shows a toast error on failure', async () => {
vi.mocked(gitApi.gitContinueOperation).mockRejectedValue('Continue failed')
const { result } = renderHook(() => useGit(1), { wrapper: createWrapper() })
await waitFor(() => {
result.current.continueOperation.mutateAsync().catch(() => {})
})
expect(toast.showToast.error).toHaveBeenCalledWith('Continue failed')
})
it('invalidates cached working-tree state and surfaces the error when continue stops on a later conflict', async () => {
const realClient = mockRealQueryClient.current as QueryClient
realClient.setQueryData(['gitStatus', 1], mockGitStatus)
realClient.setQueryData(['fileDiff', 1, 'file.txt', undefined], { path: 'file.txt', diff: 'cached' })
vi.mocked(gitApi.gitContinueOperation).mockRejectedValue(
'CONFLICT (content): Merge conflict in other.txt',
)
const { result } = renderHook(() => useGit(1), { wrapper: createWrapper() })
await waitFor(() => {
result.current.continueOperation.mutateAsync().catch(() => {})
})
expect(gitApi.gitContinueOperation).toHaveBeenCalledWith(1)
expect(realClient.getQueryState(['gitStatus', 1])?.isInvalidated).toBe(true)
expect(realClient.getQueryState(['fileDiff', 1, 'file.txt', undefined])?.isInvalidated).toBe(true)
const aggregateCall = mockInvalidateQueries.mock.calls.find(
([arg]) => (arg as { queryKey?: unknown[] } | undefined)?.queryKey?.[0] === 'reposGitStatus',
)
expect(aggregateCall).toBeDefined()
const predicate = (aggregateCall![0] as { predicate: (query: { queryKey: unknown[] }) => boolean }).predicate
expect(predicate({ queryKey: ['reposGitStatus', [1, 2]] })).toBe(true)
expect(predicate({ queryKey: ['reposGitStatus', [2, 3]] })).toBe(false)
expect(toast.showToast.error).toHaveBeenCalledWith('CONFLICT (content): Merge conflict in other.txt')
expect(toast.showToast.success).not.toHaveBeenCalled()
})
})
describe('abortOperation mutation', () => {
it('calls the API, updates the status cache and shows success', async () => {
const { result } = renderHook(() => useGit(1), { wrapper: createWrapper() })
await waitFor(() => {
result.current.abortOperation.mutateAsync()
})
expect(gitApi.gitAbortOperation).toHaveBeenCalledWith(1)
expectTargetedStatusCacheUpdate()
expect(toast.showToast.success).toHaveBeenCalledWith('Operation aborted')
})
it('shows a toast error on failure', async () => {
vi.mocked(gitApi.gitAbortOperation).mockRejectedValue('Abort failed')
const { result } = renderHook(() => useGit(1), { wrapper: createWrapper() })
await waitFor(() => {
result.current.abortOperation.mutateAsync().catch(() => {})
})
expect(toast.showToast.error).toHaveBeenCalledWith('Abort failed')
})
})
})
+189 -18
View File
@@ -1,9 +1,45 @@
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { gitFetch, gitPull, gitPush, gitCommit, gitStageFiles, gitUnstageFiles, gitDiscardFiles, fetchGitLog, fetchGitDiff, gitReset, getApiErrorMessage, fetchGitStatus } from '@/api/git'
import { createBranch, switchBranch } from '@/api/repos'
import type { QueryClient } from '@tanstack/react-query'
import { gitFetch, gitPull, gitPush, gitCommit, gitStageFiles, gitUnstageFiles, gitDiscardFiles, fetchGitLog, fetchGitDiff, gitReset, gitRenameBranch, gitDeleteBranch, gitStashPush, gitStashApply, gitStashDrop, gitContinueOperation, gitAbortOperation, gitGenerateCommitMessage, gitIntegrateBranch, getApiErrorMessage, fetchGitStatus } from '@/api/git'
import { createBranch } from '@/api/repos'
import type { DeleteBranchRequest, DeleteBranchResult, IntegrateBranchRequest, RenameBranchRequest, StashPushRequest } from '@opencode-manager/shared'
import type { GitStatusResponse } from '@/types/git'
import { showToast } from '@/lib/toast'
import { invalidateRepoGitCaches, setRepoGitStatusCaches } from '@/lib/queryInvalidation'
interface RepoGitMutationConfig<TData, TVariables> {
mutationFn: (repoId: number, variables: TVariables) => Promise<TData>
successMessage?: string | ((data: TData, variables: TVariables) => string)
statusFromData?: (data: TData) => GitStatusResponse | undefined
invalidate?: (queryClient: QueryClient, repoId: number, data: TData, variables: TVariables) => void
onError?: ((error: unknown) => void) | null
}
function useRepoGitMutation<TData, TVariables>(
repoId: number | undefined,
queryClient: QueryClient,
handleError: (error: unknown) => void,
{ mutationFn, successMessage, statusFromData, invalidate, onError }: RepoGitMutationConfig<TData, TVariables>,
) {
return useMutation({
mutationFn: (variables: TVariables) => {
if (!repoId) throw new Error('No repo ID')
return mutationFn(repoId, variables)
},
onSuccess: (data, variables) => {
if (repoId) {
const status = statusFromData?.(data)
if (status) setRepoGitStatusCaches(queryClient, repoId, status)
invalidate?.(queryClient, repoId, data, variables)
}
if (successMessage) {
showToast.success(typeof successMessage === 'function' ? successMessage(data, variables) : successMessage)
}
},
onError: onError === null ? undefined : (onError ?? handleError),
})
}
export function useGit(repoId: number | undefined, onError?: (error: unknown) => void) {
const queryClient = useQueryClient()
@@ -135,20 +171,6 @@ export function useGit(repoId: number | undefined, onError?: (error: unknown) =>
onError: handleError,
})
const switchBranchMutation = useMutation({
mutationFn: async (branchName: string) => {
if (!repoId) throw new Error('No repo ID')
await switchBranch(repoId, branchName)
return fetchGitStatus(repoId)
},
onSuccess: (data) => {
if (repoId) setRepoGitStatusCaches(queryClient, repoId, data)
invalidateRepoGitCaches(queryClient, repoId, { invalidateStatus: false })
showToast.success('Switched to branch')
},
onError: handleError,
})
const resetMutation = useMutation({
mutationFn: (commitHash: string) => {
if (!repoId) throw new Error('No repo ID')
@@ -162,6 +184,147 @@ export function useGit(repoId: number | undefined, onError?: (error: unknown) =>
onError: handleError,
})
const renameBranchMutation = useRepoGitMutation<GitStatusResponse, RenameBranchRequest>(
repoId,
queryClient,
handleError,
{
mutationFn: gitRenameBranch,
statusFromData: (data) => data,
invalidate: (client, id) => invalidateRepoGitCaches(client, id, { invalidateStatus: false }),
successMessage: 'Branch renamed',
},
)
const deleteBranchMutation = useRepoGitMutation<DeleteBranchResult & { status: GitStatusResponse }, DeleteBranchRequest>(
repoId,
queryClient,
handleError,
{
mutationFn: gitDeleteBranch,
statusFromData: (data) => data.status,
invalidate: (client, id) => {
client.invalidateQueries({ queryKey: ['branches', id] })
invalidateRepoGitCaches(client, id, { invalidateStatus: false, invalidateRepoMeta: false })
},
successMessage: 'Branch deleted',
},
)
const stashPushMutation = useRepoGitMutation<GitStatusResponse, StashPushRequest>(
repoId,
queryClient,
handleError,
{
mutationFn: gitStashPush,
statusFromData: (data) => data,
invalidate: (client, id) => invalidateRepoGitCaches(client, id, {
invalidateStatus: false,
invalidateRepoMeta: false,
invalidateStashes: true,
}),
successMessage: 'Changes stashed',
},
)
const handleStashActionError = (error: unknown) => {
if (repoId) {
invalidateRepoGitCaches(queryClient, repoId, {
invalidateRepoListStatus: true,
invalidateStashes: true,
})
}
handleError(error)
}
const stashApplyMutation = useRepoGitMutation<GitStatusResponse, { index: number; hash: string; pop: boolean }>(
repoId,
queryClient,
handleError,
{
mutationFn: (id, { index, hash, pop }) => gitStashApply(id, index, { hash, pop }),
statusFromData: (data) => data,
invalidate: (client, id) => invalidateRepoGitCaches(client, id, {
invalidateStatus: false,
invalidateRepoMeta: false,
invalidateStashes: true,
}),
successMessage: (_data, variables) => (variables.pop ? 'Stash popped' : 'Stash applied'),
onError: handleStashActionError,
},
)
const stashDropMutation = useRepoGitMutation<GitStatusResponse, { index: number; hash: string }>(
repoId,
queryClient,
handleError,
{
mutationFn: (id, { index, hash }) => gitStashDrop(id, index, { hash }),
statusFromData: (data) => data,
invalidate: (client, id) => invalidateRepoGitCaches(client, id, {
invalidateStatus: false,
invalidateRepoMeta: false,
invalidateStashes: true,
}),
successMessage: 'Stash dropped',
onError: handleStashActionError,
},
)
const continueOperationMutation = useRepoGitMutation<GitStatusResponse, void>(
repoId,
queryClient,
handleError,
{
mutationFn: (id) => gitContinueOperation(id),
statusFromData: (data) => data,
invalidate: (client, id) => invalidateRepoGitCaches(client, id, { invalidateStatus: false, invalidateRepoMeta: false }),
successMessage: 'Operation continued',
onError: (error) => {
if (repoId) invalidateRepoGitCaches(queryClient, repoId, { invalidateRepoListStatus: true })
handleError(error)
},
},
)
const abortOperationMutation = useRepoGitMutation<GitStatusResponse, void>(
repoId,
queryClient,
handleError,
{
mutationFn: (id) => gitAbortOperation(id),
statusFromData: (data) => data,
invalidate: (client, id) => invalidateRepoGitCaches(client, id, { invalidateStatus: false, invalidateRepoMeta: false }),
successMessage: 'Operation aborted',
},
)
const generateCommitMessageMutation = useRepoGitMutation<{ message: string }, void>(
repoId,
queryClient,
handleError,
{
mutationFn: (id) => gitGenerateCommitMessage(id),
},
)
const integrateBranchMutation = useMutation({
mutationFn: (request: IntegrateBranchRequest) => {
if (!repoId) throw new Error('No repo ID')
return gitIntegrateBranch(repoId, request)
},
onSuccess: (data, request) => {
setRepoGitStatusCaches(queryClient, data.targetRepoId, data.targetStatus)
invalidateRepoGitCaches(queryClient, data.targetRepoId, {
invalidateStatus: false,
invalidateRepoMeta: false,
})
queryClient.invalidateQueries({ queryKey: ['repos'] })
const noun = data.integratedCommits === 1 ? 'commit' : 'commits'
showToast.success(`Integrated ${data.integratedCommits} ${noun} into ${request.targetBranch}`)
},
})
return {
fetch,
pull,
@@ -173,7 +336,15 @@ export function useGit(repoId: number | undefined, onError?: (error: unknown) =>
log,
diff,
createBranch: createBranchMutation,
switchBranch: switchBranchMutation,
reset: resetMutation
reset: resetMutation,
renameBranch: renameBranchMutation,
deleteBranch: deleteBranchMutation,
stashPush: stashPushMutation,
stashApply: stashApplyMutation,
stashDrop: stashDropMutation,
continueOperation: continueOperationMutation,
abortOperation: abortOperationMutation,
generateCommitMessage: generateCommitMessageMutation,
integrateBranch: integrateBranchMutation,
}
}
@@ -0,0 +1,100 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { renderHook, waitFor, act } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { MemoryRouter, useLocation } from 'react-router-dom'
import { useEffect, type ReactNode } from 'react'
import { useResolveConflictsWithAgent } from './useResolveConflictsWithAgent'
const mocks = vi.hoisted(() => ({
createSessionWithPrompt: vi.fn(),
}))
vi.mock('@/api/opencode', () => ({
createSessionWithPrompt: mocks.createSessionWithPrompt,
}))
const toastMocks = vi.hoisted(() => ({ error: vi.fn() }))
vi.mock('@/lib/toast', () => ({
showToast: { error: toastMocks.error },
}))
const locationRef: { current: string } = { current: '' }
function LocationProbe() {
const location = useLocation()
useEffect(() => {
locationRef.current = location.pathname
})
return null
}
function createWrapper(queryClient: QueryClient) {
return function Wrapper({ children }: { children: ReactNode }) {
return (
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={['/repos/1']}>
<LocationProbe />
{children}
</MemoryRouter>
</QueryClientProvider>
)
}
}
describe('useResolveConflictsWithAgent', () => {
let queryClient: QueryClient
beforeEach(() => {
vi.clearAllMocks()
locationRef.current = '/repos/1'
queryClient = new QueryClient({
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
})
mocks.createSessionWithPrompt.mockResolvedValue({ id: 'ses_new' })
})
const renderResolve = () =>
renderHook(() => useResolveConflictsWithAgent({ id: 1, fullPath: '/abs/repos/my-repo' }), {
wrapper: createWrapper(queryClient),
})
it('creates one session in the repo directory, sends one prompt, and navigates to it', async () => {
const { result } = renderResolve()
await act(async () => {
await result.current.mutateAsync({
operation: { kind: 'rebase', conflictedFiles: ['src/a.ts'] },
branch: 'main',
})
})
expect(mocks.createSessionWithPrompt).toHaveBeenCalledTimes(1)
expect(mocks.createSessionWithPrompt).toHaveBeenCalledWith(
{
directory: '/abs/repos/my-repo',
title: 'Resolve rebase conflicts',
},
expect.stringContaining('GIT_EDITOR=true git rebase --continue'),
)
await waitFor(() => expect(locationRef.current).toBe('/repos/1/sessions/ses_new'))
})
it('shows an error without navigating when creating the session fails', async () => {
mocks.createSessionWithPrompt.mockRejectedValue(new Error('gateway timeout'))
const { result } = renderResolve()
await act(async () => {
await expect(
result.current.mutateAsync({
operation: { kind: 'merge', conflictedFiles: ['file.txt'] },
branch: 'main',
}),
).rejects.toThrow('gateway timeout')
})
expect(mocks.createSessionWithPrompt).toHaveBeenCalledTimes(1)
expect(toastMocks.error).toHaveBeenCalledTimes(1)
expect(locationRef.current).toBe('/repos/1')
})
})
@@ -0,0 +1,44 @@
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useNavigate } from 'react-router-dom'
import { createSessionWithPrompt } from '@/api/opencode'
import { buildConflictResolutionPrompt } from '@/lib/git-conflict-prompt'
import { getSessionPath } from '@/lib/navigation'
import { invalidateSessionListCaches } from '@/lib/queryInvalidation'
import { showToast } from '@/lib/toast'
import type { GitOperationState } from '@opencode-manager/shared'
interface ResolveConflictsInput {
operation: GitOperationState
branch: string
}
interface ResolveConflictsRepo {
id: number
fullPath: string
}
export function useResolveConflictsWithAgent(repo: ResolveConflictsRepo) {
const queryClient = useQueryClient()
const navigate = useNavigate()
return useMutation({
mutationFn: async ({ operation, branch }: ResolveConflictsInput) => {
return createSessionWithPrompt(
{
directory: repo.fullPath,
title: `Resolve ${operation.kind} conflicts`,
},
buildConflictResolutionPrompt({ operation, branch }),
)
},
onSuccess: (session) => {
invalidateSessionListCaches(queryClient)
navigate(getSessionPath(repo.id, session.id))
},
onError: (error) => {
showToast.error(
`Could not start conflict resolution: ${error instanceof Error ? error.message : 'Unknown error'}`,
)
},
})
}
@@ -0,0 +1,59 @@
import { describe, it, expect } from 'vitest'
import { buildConflictResolutionPrompt } from './git-conflict-prompt'
describe('buildConflictResolutionPrompt', () => {
it('names the operation, branch, and every conflicted file', () => {
const prompt = buildConflictResolutionPrompt({
operation: { kind: 'merge', conflictedFiles: ['src/a.ts', 'src/b.ts'] },
branch: 'feature/x',
})
expect(prompt).toContain('git merge')
expect(prompt).toContain('feature/x')
expect(prompt).toContain('- src/a.ts')
expect(prompt).toContain('- src/b.ts')
})
it('preserves exact unicode and special-character conflicted file names', () => {
const prompt = buildConflictResolutionPrompt({
operation: { kind: 'merge', conflictedFiles: ['café.txt', 'a b"c.txt'] },
branch: 'feature/x',
})
expect(prompt).toContain('- café.txt')
expect(prompt).toContain('- a b"c.txt')
expect(prompt).not.toContain('\\303')
expect(prompt).not.toContain('"a b\\"c.txt"')
})
it('instructs the agent to confirm the strategy before editing', () => {
const prompt = buildConflictResolutionPrompt({
operation: { kind: 'rebase', conflictedFiles: ['file.txt'] },
branch: 'main',
})
expect(prompt).toContain('Wait for the user to confirm')
expect(prompt).toContain('before editing')
})
it('uses the kind-specific continue command with a non-interactive editor', () => {
const prompt = buildConflictResolutionPrompt({
operation: { kind: 'cherry-pick', conflictedFiles: ['file.txt'] },
branch: 'main',
})
expect(prompt).toContain('GIT_EDITOR=true git cherry-pick --continue')
expect(prompt).toContain('git add')
})
it('forbids abort and force-push unless the user asks', () => {
const prompt = buildConflictResolutionPrompt({
operation: { kind: 'revert', conflictedFiles: ['file.txt'] },
branch: 'main',
})
expect(prompt).toContain('git revert --abort')
expect(prompt).toContain('force-push')
expect(prompt).toContain('unless the user explicitly asks')
})
})
+26
View File
@@ -0,0 +1,26 @@
import type { GitOperationState } from '@opencode-manager/shared'
interface ConflictResolutionPromptInput {
operation: GitOperationState
branch: string
}
export function buildConflictResolutionPrompt({ operation, branch }: ConflictResolutionPromptInput): string {
const conflictedFiles = operation.conflictedFiles.map((file) => `- ${file}`).join('\n')
return [
`A git ${operation.kind} is in progress on branch \`${branch}\` and stopped with merge conflicts.`,
'',
'Conflicted files:',
conflictedFiles,
'',
'Work through this in order:',
'1. Inspect each conflicted file and understand both sides of every conflict.',
'2. Propose a per-file resolution strategy with your reasoning.',
'3. Wait for the user to confirm the strategy before editing any file.',
'',
`After the user confirms, resolve the conflicts, stage each resolved file with \`git add\`, and finish the operation with \`GIT_EDITOR=true git ${operation.kind} --continue\`.`,
'',
`Do not run \`git ${operation.kind} --abort\` and do not force-push unless the user explicitly asks.`,
].join('\n')
}
+24
View File
@@ -0,0 +1,24 @@
import { describe, it, expect } from 'vitest'
import { formatGitIdentity } from './git-identity'
describe('formatGitIdentity', () => {
it('formats a complete identity as Name <email>', () => {
expect(formatGitIdentity({ name: 'Ada Lovelace', email: 'ada@example.com' }))
.toBe('Ada Lovelace <ada@example.com>')
})
it('falls back to No name when the name is missing', () => {
expect(formatGitIdentity({ name: null, email: 'ada@example.com' }))
.toBe('No name <ada@example.com>')
})
it('falls back to No email when the email is missing', () => {
expect(formatGitIdentity({ name: 'Ada Lovelace', email: null }))
.toBe('Ada Lovelace <No email>')
})
it('reports Not configured when nothing is set', () => {
expect(formatGitIdentity({ name: null, email: null })).toBe('Not configured')
expect(formatGitIdentity({})).toBe('Not configured')
})
})
+15
View File
@@ -0,0 +1,15 @@
export interface GitIdentityValues {
name?: string | null
email?: string | null
}
/**
* Formats a git identity as `Name <email>`, using explicit placeholders when a
* part is missing and a single fallback when nothing is configured.
*/
export function formatGitIdentity(identity: GitIdentityValues): string {
const name = identity.name
const email = identity.email
if (!name && !email) return 'Not configured'
return `${name || 'No name'} <${email || 'No email'}>`
}
@@ -5,6 +5,7 @@ import {
invalidateProviderCaches,
invalidateProviderCachesDebounced,
invalidateQueryKeysDebounced,
invalidateRepoGitCaches,
invalidateSessionListCachesDebounced,
refreshOpenCodeServerCaches,
} from './queryInvalidation'
@@ -57,6 +58,30 @@ describe('invalidateConfigCaches', () => {
})
})
describe('invalidateRepoGitCaches', () => {
it('invalidates the shared stash list prefix across every repo when requested', () => {
const queryClient = new QueryClient()
queryClient.setQueryData(['gitStashes', 1], { stashes: [] })
queryClient.setQueryData(['gitStashes', 2], { stashes: [] })
invalidateRepoGitCaches(queryClient, 1, { invalidateStashes: true })
expect(queryClient.getQueryState(['gitStashes', 1])?.isInvalidated).toBe(true)
expect(queryClient.getQueryState(['gitStashes', 2])?.isInvalidated).toBe(true)
})
it('invalidates the repo list status for the repo when requested', () => {
const queryClient = new QueryClient()
const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')
invalidateRepoGitCaches(queryClient, 1, { invalidateRepoListStatus: true })
expect(invalidateQueries).toHaveBeenCalledWith(
expect.objectContaining({ queryKey: ['reposGitStatus'], predicate: expect.any(Function) }),
)
})
})
describe('invalidateProviderCaches', () => {
it('invalidates only the provider query keys that have active queries', () => {
const queryClient = new QueryClient()
+16
View File
@@ -87,6 +87,8 @@ export function invalidateRepoListCaches(queryClient: QueryClient) {
interface RepoGitInvalidationOptions {
invalidateStatus?: boolean
invalidateRepoMeta?: boolean
invalidateStashes?: boolean
invalidateRepoListStatus?: boolean
}
export function invalidateRepoGitCaches(
@@ -94,6 +96,10 @@ export function invalidateRepoGitCaches(
repoId?: number | null,
options: RepoGitInvalidationOptions = {},
) {
if (options.invalidateStashes) {
queryClient.invalidateQueries({ queryKey: ['gitStashes'] })
}
if (!repoId) {
invalidateRepoListCaches(queryClient)
queryClient.invalidateQueries({ queryKey: ['repo'] })
@@ -112,6 +118,9 @@ export function invalidateRepoGitCaches(
if (options.invalidateStatus ?? true) {
queryClient.invalidateQueries({ queryKey: ['gitStatus', repoId] })
}
if (options.invalidateRepoListStatus) {
invalidateReposGitStatusCacheForRepo(queryClient, repoId)
}
queryClient.invalidateQueries({ queryKey: ['gitLog', repoId] })
queryClient.invalidateQueries({ queryKey: ['fileDiff', repoId] })
}
@@ -121,6 +130,13 @@ function reposGitStatusQueryIncludesRepo(queryKey: readonly unknown[], repoId: n
return queryKey[0] === 'reposGitStatus' && Array.isArray(repoIds) && repoIds.includes(repoId)
}
export function invalidateReposGitStatusCacheForRepo(queryClient: QueryClient, repoId: number) {
queryClient.invalidateQueries({
queryKey: ['reposGitStatus'],
predicate: (query) => reposGitStatusQueryIncludesRepo(query.queryKey, repoId),
})
}
export function setRepoGitStatusCaches(queryClient: QueryClient, repoId: number, data: GitStatusResponse) {
queryClient.setQueryData(['gitStatus', repoId], data)
queryClient.setQueriesData<Map<number, GitStatusResponse>>(
+3
View File
@@ -1,3 +1,5 @@
import type { GitOperationState } from '@opencode-manager/shared'
export type GitFileStatusType = 'modified' | 'added' | 'deleted' | 'renamed' | 'untracked' | 'copied'
export interface GitFileStatus {
@@ -36,6 +38,7 @@ export interface GitStatusResponse {
behind: number
files: GitFileStatus[]
hasChanges: boolean
operation: GitOperationState | null
}
export interface FileDiffResponse {