diff --git a/src/main/git/status.test.ts b/src/main/git/status.test.ts index 079f1d7e6..2547f60b7 100644 --- a/src/main/git/status.test.ts +++ b/src/main/git/status.test.ts @@ -42,6 +42,7 @@ vi.mock('fs', () => ({ import { abortMerge, + abortRebase, bulkStageFiles, bulkDiscardChanges, bulkUnstageFiles, @@ -675,6 +676,20 @@ describe('abortMerge', () => { }) }) +describe('abortRebase', () => { + beforeEach(() => { + gitExecFileAsyncMock.mockReset() + }) + + it('runs git rebase --abort in the worktree', async () => { + gitExecFileAsyncMock.mockResolvedValueOnce({ stdout: '' }) + + await abortRebase('/repo') + + expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['rebase', '--abort'], { cwd: '/repo' }) + }) +}) + describe('getStagedCommitContext', () => { beforeEach(() => { gitExecFileAsyncMock.mockReset() diff --git a/src/main/git/status.ts b/src/main/git/status.ts index 02c2ea080..ed34cd56b 100644 --- a/src/main/git/status.ts +++ b/src/main/git/status.ts @@ -467,6 +467,10 @@ export async function abortMerge(worktreePath: string): Promise { await gitExecFileAsync(['merge', '--abort'], { cwd: worktreePath }) } +export async function abortRebase(worktreePath: string): Promise { + await gitExecFileAsync(['rebase', '--abort'], { cwd: worktreePath }) +} + export async function resolveGitDir(worktreePath: string): Promise { const dotGitPath = path.join(worktreePath, '.git') diff --git a/src/main/ipc/filesystem.test.ts b/src/main/ipc/filesystem.test.ts index ac36ca7f7..05a295f3e 100644 --- a/src/main/ipc/filesystem.test.ts +++ b/src/main/ipc/filesystem.test.ts @@ -16,6 +16,7 @@ const { commitChangesMock, getStatusMock, abortMergeMock, + abortRebaseMock, getDiffMock, getBranchCompareMock, getBranchDiffMock, @@ -48,6 +49,7 @@ const { commitChangesMock: vi.fn(), getStatusMock: vi.fn(), abortMergeMock: vi.fn(), + abortRebaseMock: vi.fn(), getDiffMock: vi.fn(), getBranchCompareMock: vi.fn(), getBranchDiffMock: vi.fn(), @@ -92,6 +94,7 @@ vi.mock('../git/status', () => ({ commitChanges: commitChangesMock, getStatus: getStatusMock, abortMerge: abortMergeMock, + abortRebase: abortRebaseMock, getDiff: getDiffMock, getBranchCompare: getBranchCompareMock, getBranchDiff: getBranchDiffMock, @@ -201,6 +204,8 @@ describe('registerFilesystemHandlers', () => { lstatMock, commitChangesMock, getStatusMock, + abortMergeMock, + abortRebaseMock, getDiffMock, getBranchCompareMock, getBranchDiffMock, @@ -603,6 +608,26 @@ describe('registerFilesystemHandlers', () => { expect(sshProvider.abortMerge).toHaveBeenCalledWith('/remote/repo') }) + it('routes abort rebase through local and SSH git providers', async () => { + registerWorktreeRootsForRepo(store as never, 'repo-1', [REPO_PATH, WORKTREE_FEATURE_PATH]) + abortRebaseMock.mockResolvedValue(undefined) + const sshProvider = { + abortRebase: vi.fn().mockResolvedValue(undefined) + } + getSshGitProviderMock.mockReturnValue(sshProvider) + + registerFilesystemHandlers(store as never) + + await handlers.get('git:abortRebase')!(null, { worktreePath: WORKTREE_FEATURE_PATH }) + await handlers.get('git:abortRebase')!(null, { + worktreePath: '/remote/repo', + connectionId: 'ssh-1' + }) + + expect(abortRebaseMock).toHaveBeenCalledWith(WORKTREE_FEATURE_PATH) + expect(sshProvider.abortRebase).toHaveBeenCalledWith('/remote/repo') + }) + it('rejects git file paths that escape the selected worktree', async () => { registerFilesystemHandlers(store as never) diff --git a/src/main/ipc/filesystem.ts b/src/main/ipc/filesystem.ts index aad4803f9..c564f0a42 100644 --- a/src/main/ipc/filesystem.ts +++ b/src/main/ipc/filesystem.ts @@ -33,6 +33,7 @@ import { import { getStatus, abortMerge, + abortRebase, detectConflictOperation, getDiff, commitChanges, @@ -711,6 +712,21 @@ export function registerFilesystemHandlers( } ) + ipcMain.handle( + 'git:abortRebase', + async (_event, args: { worktreePath: string; connectionId?: string }): Promise => { + if (args.connectionId) { + const provider = getSshGitProvider(args.connectionId) + if (!provider) { + throw new Error(`No git provider for connection "${args.connectionId}"`) + } + return provider.abortRebase(args.worktreePath) + } + const worktreePath = await resolveRegisteredWorktreePath(args.worktreePath, store) + await abortRebase(worktreePath) + } + ) + ipcMain.handle( 'git:diff', async ( diff --git a/src/main/providers/ssh-git-provider-merge.test.ts b/src/main/providers/ssh-git-provider-merge.test.ts index 2a6107c8a..7c7d0aa07 100644 --- a/src/main/providers/ssh-git-provider-merge.test.ts +++ b/src/main/providers/ssh-git-provider-merge.test.ts @@ -18,4 +18,21 @@ describe('SshGitProvider merge operations', () => { worktreePath: '/home/user/repo' }) }) + + it('abortRebase sends git.abortRebase request', async () => { + const mux = { + request: vi.fn().mockResolvedValue(undefined), + notify: vi.fn(), + onNotification: vi.fn(), + dispose: vi.fn(), + isDisposed: vi.fn().mockReturnValue(false) + } + const provider = new SshGitProvider('conn-1', mux as never) + + await provider.abortRebase('/home/user/repo') + + expect(mux.request).toHaveBeenCalledWith('git.abortRebase', { + worktreePath: '/home/user/repo' + }) + }) }) diff --git a/src/main/providers/ssh-git-provider.ts b/src/main/providers/ssh-git-provider.ts index a1a1ab4f1..61a44f3ae 100644 --- a/src/main/providers/ssh-git-provider.ts +++ b/src/main/providers/ssh-git-provider.ts @@ -285,6 +285,10 @@ export class SshGitProvider implements IGitProvider { await this.mux.request('git.abortMerge', { worktreePath }) } + async abortRebase(worktreePath: string): Promise { + await this.mux.request('git.abortRebase', { worktreePath }) + } + async getBranchCompare(worktreePath: string, baseRef: string): Promise { return (await this.mux.request('git.branchCompare', { worktreePath, diff --git a/src/main/providers/types.ts b/src/main/providers/types.ts index fdd50bcb9..3ae29d88e 100644 --- a/src/main/providers/types.ts +++ b/src/main/providers/types.ts @@ -174,6 +174,7 @@ export type IGitProvider = { bulkDiscardChanges(worktreePath: string, filePaths: string[]): Promise detectConflictOperation(worktreePath: string): Promise abortMerge(worktreePath: string): Promise + abortRebase(worktreePath: string): Promise getBranchCompare(worktreePath: string, baseRef: string): Promise getCommitCompare(worktreePath: string, commitId: string): Promise getUpstreamStatus(worktreePath: string, pushTarget?: GitPushTarget): Promise diff --git a/src/main/runtime/orca-runtime-git.test.ts b/src/main/runtime/orca-runtime-git.test.ts index 3f228f5b4..de567e5f9 100644 --- a/src/main/runtime/orca-runtime-git.test.ts +++ b/src/main/runtime/orca-runtime-git.test.ts @@ -9,6 +9,7 @@ import { RuntimeGitCommands, type ResolvedRuntimeGitWorktree } from './orca-runt const mocks = vi.hoisted(() => ({ abortMerge: vi.fn(), + abortRebase: vi.fn(), getStagedCommitContext: vi.fn(), generateCommitMessageFromContext: vi.fn(), resolveCommitMessageSettings: vi.fn(), @@ -18,6 +19,7 @@ const mocks = vi.hoisted(() => ({ vi.mock('../git/status', async () => ({ ...(await vi.importActual('../git/status')), abortMerge: mocks.abortMerge, + abortRebase: mocks.abortRebase, getStagedCommitContext: mocks.getStagedCommitContext })) @@ -60,6 +62,7 @@ function makeCommands(worktreePath: string): RuntimeGitCommands { describe('RuntimeGitCommands', () => { beforeEach(() => { mocks.abortMerge.mockReset() + mocks.abortRebase.mockReset() mocks.getStagedCommitContext.mockReset() mocks.generateCommitMessageFromContext.mockReset() mocks.resolveCommitMessageSettings.mockReset() @@ -100,6 +103,34 @@ describe('RuntimeGitCommands', () => { expect(mocks.abortMerge).not.toHaveBeenCalled() }) + it('aborts a local rebase through the resolved worktree', async () => { + const worktreePath = mkdtempSync(join(tmpdir(), 'orca-runtime-git-')) + tempDirs.push(worktreePath) + const commands = makeCommands(worktreePath) + mocks.abortRebase.mockResolvedValue(undefined) + + await expect(commands.abortRuntimeGitRebase('id:wt-1')).resolves.toEqual({ ok: true }) + + expect(mocks.abortRebase).toHaveBeenCalledWith(worktreePath) + }) + + it('aborts a remote rebase through the SSH git provider', async () => { + const provider = { abortRebase: vi.fn().mockResolvedValue(undefined) } + mocks.getSshGitProvider.mockReturnValue(provider) + const commands = new RuntimeGitCommands({ + resolveRuntimeGitTarget: async () => ({ + worktree: makeWorktree('/remote/repo'), + connectionId: 'conn-1' + }), + getRuntimeSettings: () => ({}) as GlobalSettings + }) + + await expect(commands.abortRuntimeGitRebase('id:wt-1')).resolves.toEqual({ ok: true }) + + expect(provider.abortRebase).toHaveBeenCalledWith('/remote/repo') + expect(mocks.abortRebase).not.toHaveBeenCalled() + }) + it('rejects slash-only git mutation paths before they can target the worktree root', async () => { const worktreePath = mkdtempSync(join(tmpdir(), 'orca-runtime-git-')) tempDirs.push(worktreePath) diff --git a/src/main/runtime/orca-runtime-git.ts b/src/main/runtime/orca-runtime-git.ts index 0c81af3df..f9a262025 100644 --- a/src/main/runtime/orca-runtime-git.ts +++ b/src/main/runtime/orca-runtime-git.ts @@ -21,6 +21,7 @@ import type { SourceControlAiOperation } from '../../shared/source-control-ai-ty import { getRemoteFileUrl } from '../git/repo' import { abortMerge, + abortRebase, bulkDiscardChanges, bulkStageFiles, bulkUnstageFiles, @@ -191,6 +192,20 @@ export class RuntimeGitCommands { return { ok: true } } + async abortRuntimeGitRebase(worktreeSelector: string): Promise<{ ok: true }> { + const target = await this.host.resolveRuntimeGitTarget(worktreeSelector) + const provider = target.connectionId ? getSshGitProvider(target.connectionId) : null + if (target.connectionId) { + if (!provider) { + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) + } + await provider.abortRebase(target.worktree.path) + return { ok: true } + } + await abortRebase(target.worktree.path) + return { ok: true } + } + async getRuntimeGitDiff( worktreeSelector: string, filePath: string, diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index cb01bdb11..dba34876f 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -2085,6 +2085,8 @@ export class OrcaRuntimeService { this.gitCommands.getRuntimeGitConflictOperation.bind(this.gitCommands) abortRuntimeGitMerge: RuntimeGitCommands['abortRuntimeGitMerge'] = this.gitCommands.abortRuntimeGitMerge.bind(this.gitCommands) + abortRuntimeGitRebase: RuntimeGitCommands['abortRuntimeGitRebase'] = + this.gitCommands.abortRuntimeGitRebase.bind(this.gitCommands) getRuntimeGitDiff: RuntimeGitCommands['getRuntimeGitDiff'] = this.gitCommands.getRuntimeGitDiff.bind(this.gitCommands) getRuntimeGitBranchCompare: RuntimeGitCommands['getRuntimeGitBranchCompare'] = diff --git a/src/main/runtime/rpc/methods/git.test.ts b/src/main/runtime/rpc/methods/git.test.ts index 0467f365d..d655a68a7 100644 --- a/src/main/runtime/rpc/methods/git.test.ts +++ b/src/main/runtime/rpc/methods/git.test.ts @@ -198,6 +198,7 @@ describe('git RPC methods', () => { }), cancelRuntimeGenerateCommitMessage: vi.fn().mockResolvedValue({ ok: true }), abortRuntimeGitMerge: vi.fn().mockResolvedValue({ ok: true }), + abortRuntimeGitRebase: vi.fn().mockResolvedValue({ ok: true }), pushRuntimeGit: vi.fn().mockResolvedValue({ ok: true }), getRuntimeGitRemoteFileUrl: vi.fn().mockResolvedValue('https://example.com/file#L3') } as unknown as OrcaRuntimeService @@ -218,6 +219,7 @@ describe('git RPC methods', () => { makeRequest('git.cancelGenerateCommitMessage', { worktree: 'id:wt-1' }) ) await dispatcher.dispatch(makeRequest('git.abortMerge', { worktree: 'id:wt-1' })) + await dispatcher.dispatch(makeRequest('git.abortRebase', { worktree: 'id:wt-1' })) await dispatcher.dispatch( makeRequest('git.push', { worktree: 'id:wt-1', @@ -240,6 +242,7 @@ describe('git RPC methods', () => { }) expect(runtime.cancelRuntimeGenerateCommitMessage).toHaveBeenCalledWith('id:wt-1') expect(runtime.abortRuntimeGitMerge).toHaveBeenCalledWith('id:wt-1') + expect(runtime.abortRuntimeGitRebase).toHaveBeenCalledWith('id:wt-1') expect(runtime.pushRuntimeGit).toHaveBeenCalledWith( 'id:wt-1', true, diff --git a/src/main/runtime/rpc/methods/git.ts b/src/main/runtime/rpc/methods/git.ts index c84216e61..ce770b1de 100644 --- a/src/main/runtime/rpc/methods/git.ts +++ b/src/main/runtime/rpc/methods/git.ts @@ -56,6 +56,11 @@ export const GIT_METHODS: RpcMethod[] = [ params: WorktreeSelector, handler: async (params, { runtime }) => runtime.abortRuntimeGitMerge(params.worktree) }), + defineMethod({ + name: 'git.abortRebase', + params: WorktreeSelector, + handler: async (params, { runtime }) => runtime.abortRuntimeGitRebase(params.worktree) + }), defineMethod({ name: 'git.diff', params: GitDiff, diff --git a/src/main/runtime/runtime-rpc.test.ts b/src/main/runtime/runtime-rpc.test.ts index bacf4b81d..59bb492b8 100644 --- a/src/main/runtime/runtime-rpc.test.ts +++ b/src/main/runtime/runtime-rpc.test.ts @@ -762,6 +762,7 @@ describe('OrcaRuntimeRpcServer', () => { .mockResolvedValue({ hasUpstream: true, ahead: 1, behind: 0 }) const rebaseRuntimeGitFromBase = vi.fn().mockResolvedValue({ ok: true }) const abortRuntimeGitMerge = vi.fn().mockResolvedValue({ ok: true }) + const abortRuntimeGitRebase = vi.fn().mockResolvedValue({ ok: true }) const bulkStageRuntimeGitPaths = vi.fn().mockResolvedValue({ ok: true }) const bulkUnstageRuntimeGitPaths = vi.fn().mockResolvedValue({ ok: true }) const getRuntimeGitDiff = vi.fn().mockResolvedValue({ @@ -844,6 +845,7 @@ describe('OrcaRuntimeRpcServer', () => { getRuntimeGitUpstreamStatus, rebaseRuntimeGitFromBase, abortRuntimeGitMerge, + abortRuntimeGitRebase, bulkStageRuntimeGitPaths, bulkUnstageRuntimeGitPaths, getRuntimeGitDiff, @@ -1412,6 +1414,16 @@ describe('OrcaRuntimeRpcServer', () => { (response) => replies.push(JSON.parse(response) as Record), () => {} ) + await server['handleWebSocketMessage']( + JSON.stringify({ + id: 'req_git_abort_rebase', + method: 'git.abortRebase', + deviceToken: mobile.token, + params: { worktree: 'id:wt-1' } + }), + (response) => replies.push(JSON.parse(response) as Record), + () => {} + ) await server['handleWebSocketMessage']( JSON.stringify({ id: 'req_git_bulk_unstage', @@ -1625,6 +1637,9 @@ describe('OrcaRuntimeRpcServer', () => { ) expect(replies).toContainEqual(expect.objectContaining({ id: 'req_git_bulk_stage', ok: true })) expect(replies).toContainEqual(expect.objectContaining({ id: 'req_git_abort_merge', ok: true })) + expect(replies).toContainEqual( + expect.objectContaining({ id: 'req_git_abort_rebase', ok: true }) + ) expect(replies).toContainEqual( expect.objectContaining({ id: 'req_git_bulk_unstage', ok: true }) ) @@ -1660,6 +1675,7 @@ describe('OrcaRuntimeRpcServer', () => { expect(getRuntimeGitUpstreamStatus).toHaveBeenCalledWith('id:wt-1') expect(bulkStageRuntimeGitPaths).toHaveBeenCalledWith('id:wt-1', ['a.ts', 'b.ts']) expect(abortRuntimeGitMerge).toHaveBeenCalledWith('id:wt-1') + expect(abortRuntimeGitRebase).toHaveBeenCalledWith('id:wt-1') expect(bulkUnstageRuntimeGitPaths).toHaveBeenCalledWith('id:wt-1', ['c.ts']) expect(openMobileDiff).toHaveBeenCalledWith('id:wt-1', 'docs/readme.md', true) expect(getRuntimeGitDiff).toHaveBeenCalledWith('id:wt-1', 'docs/readme.md', false, undefined) diff --git a/src/main/runtime/runtime-rpc.ts b/src/main/runtime/runtime-rpc.ts index 69a05660f..8cc6486c6 100644 --- a/src/main/runtime/runtime-rpc.ts +++ b/src/main/runtime/runtime-rpc.ts @@ -146,6 +146,7 @@ const MOBILE_RPC_METHOD_ALLOWLIST = new Set([ 'files.openDiff', 'files.read', 'git.abortMerge', + 'git.abortRebase', 'git.bulkStage', 'git.bulkUnstage', 'git.commit', diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index d0a63a30c..64ef7658b 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -1614,6 +1614,7 @@ export type PreloadApi = { connectionId?: string }) => Promise abortMerge: (args: { worktreePath: string; connectionId?: string }) => Promise + abortRebase: (args: { worktreePath: string; connectionId?: string }) => Promise diff: (args: { worktreePath: string filePath: string diff --git a/src/preload/index.ts b/src/preload/index.ts index d40637e19..c17c22395 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -2198,6 +2198,8 @@ const api = { ipcRenderer.invoke('git:conflictOperation', args), abortMerge: (args: { worktreePath: string; connectionId?: string }): Promise => ipcRenderer.invoke('git:abortMerge', args), + abortRebase: (args: { worktreePath: string; connectionId?: string }): Promise => + ipcRenderer.invoke('git:abortRebase', args), diff: (args: { worktreePath: string filePath: string diff --git a/src/relay/git-handler.test.ts b/src/relay/git-handler.test.ts index e46f62aa8..2f0680d91 100644 --- a/src/relay/git-handler.test.ts +++ b/src/relay/git-handler.test.ts @@ -46,6 +46,7 @@ describe('GitHandler', () => { expect(methods).toContain('git.bulkStage') expect(methods).toContain('git.bulkUnstage') expect(methods).toContain('git.abortMerge') + expect(methods).toContain('git.abortRebase') expect(methods).toContain('git.discard') expect(methods).toContain('git.bulkDiscard') expect(methods).toContain('git.conflictOperation') @@ -94,6 +95,37 @@ describe('GitHandler', () => { }) }) + describe('abortRebase', () => { + it('aborts an in-progress rebase', async () => { + gitInit(tmpDir) + writeFileSync(path.join(tmpDir, 'file.txt'), 'base\n') + gitCommit(tmpDir, 'initial') + const baseBranch = execFileSync('git', ['branch', '--show-current'], { + cwd: tmpDir, + encoding: 'utf-8', + stdio: 'pipe' + }).trim() + execFileSync('git', ['checkout', '-b', 'feature'], { cwd: tmpDir, stdio: 'pipe' }) + writeFileSync(path.join(tmpDir, 'file.txt'), 'feature\n') + gitCommit(tmpDir, 'feature change') + execFileSync('git', ['checkout', baseBranch], { cwd: tmpDir, stdio: 'pipe' }) + writeFileSync(path.join(tmpDir, 'file.txt'), 'main\n') + gitCommit(tmpDir, 'main change') + execFileSync('git', ['checkout', 'feature'], { cwd: tmpDir, stdio: 'pipe' }) + + expect(() => + execFileSync('git', ['rebase', baseBranch], { cwd: tmpDir, stdio: 'pipe' }) + ).toThrow() + await expect(fs.access(path.join(tmpDir, '.git', 'rebase-merge'))).resolves.toBeUndefined() + + await dispatcher.callRequest('git.abortRebase', { worktreePath: tmpDir }) + + await expect(fs.access(path.join(tmpDir, '.git', 'rebase-merge'))).rejects.toThrow() + await expect(fs.access(path.join(tmpDir, '.git', 'rebase-apply'))).rejects.toThrow() + await expect(fs.readFile(path.join(tmpDir, 'file.txt'), 'utf-8')).resolves.toBe('feature\n') + }) + }) + describe('renameCurrentBranch', () => { it('renames only the checked-out branch through the narrow RPC', async () => { gitInit(tmpDir) diff --git a/src/relay/git-handler.ts b/src/relay/git-handler.ts index 9e6511946..62ee18269 100644 --- a/src/relay/git-handler.ts +++ b/src/relay/git-handler.ts @@ -65,6 +65,7 @@ export class GitHandler { this.dispatcher.onRequest('git.bulkStage', (p) => this.bulkStage(p)) this.dispatcher.onRequest('git.bulkUnstage', (p) => this.bulkUnstage(p)) this.dispatcher.onRequest('git.abortMerge', (p) => this.abortMerge(p)) + this.dispatcher.onRequest('git.abortRebase', (p) => this.abortRebase(p)) this.dispatcher.onRequest('git.discard', (p) => this.discard(p)) this.dispatcher.onRequest('git.bulkDiscard', (p) => this.bulkDiscard(p)) this.dispatcher.onRequest('git.conflictOperation', (p) => this.conflictOperation(p)) @@ -192,6 +193,11 @@ export class GitHandler { await this.git(['merge', '--abort'], worktreePath) } + private async abortRebase(params: Record) { + const worktreePath = params.worktreePath as string + await this.git(['rebase', '--abort'], worktreePath) + } + private normalizeGitPathForCompare(filePath: string): string { return filePath.replace(/\\/g, '/').replace(/\/+$/, '') } diff --git a/src/renderer/src/components/right-sidebar/CommitArea.test.tsx b/src/renderer/src/components/right-sidebar/CommitArea.test.tsx index ab1448416..273926ce0 100644 --- a/src/renderer/src/components/right-sidebar/CommitArea.test.tsx +++ b/src/renderer/src/components/right-sidebar/CommitArea.test.tsx @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from 'vitest' import { renderToStaticMarkup } from 'react-dom/server' -import { CommitArea, ConflictSummaryCard } from './SourceControl' +import { CommitArea, ConflictSummaryCard, OperationBanner } from './SourceControl' import { resolvePrimaryAction, type PrimaryActionInputs } from './source-control-primary-action' import { resolveDropdownItems, type DropdownActionKind } from './source-control-dropdown-items' import { TooltipProvider } from '@/components/ui/tooltip' @@ -334,13 +334,13 @@ describe('ConflictSummaryCard', () => { expect(markup.indexOf('Resolve with AI')).toBeLessThan(markup.indexOf('Review conflicts')) }) - it('shows Abort merge only for merge conflicts', () => { + it('shows the matching abort action for merge and rebase conflicts only', () => { const mergeMarkup = renderToStaticMarkup( @@ -350,14 +350,28 @@ describe('ConflictSummaryCard', () => { conflictOperation="rebase" unresolvedCount={1} isResolvingWithAI={false} - onAbortMerge={vi.fn()} + onAbortOperation={vi.fn()} + onResolveWithAI={vi.fn()} + onReview={vi.fn()} + /> + ) + const cherryPickMarkup = renderToStaticMarkup( + ) expect(mergeMarkup).toContain('Abort merge') + expect(mergeMarkup).not.toContain('Abort rebase') + expect(rebaseMarkup).toContain('Abort rebase') expect(rebaseMarkup).not.toContain('Abort merge') + expect(cherryPickMarkup).not.toContain('Abort merge') + expect(cherryPickMarkup).not.toContain('Abort rebase') }) it('renders the Sparkles icon on the idle Resolve with AI button', () => { @@ -376,3 +390,22 @@ describe('ConflictSummaryCard', () => { expect(markup).not.toMatch(/\blucide-sparkle(?!s)\b/) }) }) + +describe('OperationBanner', () => { + it('shows abort actions for merge and rebase but not cherry-pick', () => { + const mergeMarkup = renderToStaticMarkup( + + ) + const rebaseMarkup = renderToStaticMarkup( + + ) + const cherryPickMarkup = renderToStaticMarkup( + + ) + + expect(mergeMarkup).toContain('Abort merge') + expect(rebaseMarkup).toContain('Abort rebase') + expect(cherryPickMarkup).not.toContain('Abort merge') + expect(cherryPickMarkup).not.toContain('Abort rebase') + }) +}) diff --git a/src/renderer/src/components/right-sidebar/SourceControl.tsx b/src/renderer/src/components/right-sidebar/SourceControl.tsx index 040d3f161..275034cee 100644 --- a/src/renderer/src/components/right-sidebar/SourceControl.tsx +++ b/src/renderer/src/components/right-sidebar/SourceControl.tsx @@ -118,6 +118,7 @@ import { import { getConnectionId } from '@/lib/connection-context' import { abortRuntimeGitMerge, + abortRuntimeGitRebase, bulkDiscardRuntimeGitPaths, bulkStageRuntimeGitPaths, bulkUnstageRuntimeGitPaths, @@ -178,7 +179,9 @@ import { getRepositorySourceControlAiSectionId } from '@/components/settings/rep import { hasExpandedCommitFailureDetails, summarizeCommitFailure } from './commit-failure-summary' export type SourceControlScope = 'all' | 'uncommitted' -type SourceControlActionError = { kind: RemoteOpKind | 'abort_merge'; message: string } +type AbortConflictOperation = Extract +type AbortActionErrorKind = 'abort_merge' | 'abort_rebase' +type SourceControlActionError = { kind: RemoteOpKind | AbortActionErrorKind; message: string } type SourceControlAiInstructionGuidance = { operation: SourceControlAiOperation repoBacked: boolean @@ -1132,10 +1135,10 @@ function SourceControlInner(): React.JSX.Element { const [commitInFlightByWorktree, setCommitInFlightByWorktree] = useState>( {} ) - const [abortMergeInFlightByWorktree, setAbortMergeInFlightByWorktree] = useState< + const [abortOperationInFlightByWorktree, setAbortOperationInFlightByWorktree] = useState< Record >({}) - const isAbortingMerge = abortMergeInFlightByWorktree[activeWorktreeId ?? ''] ?? false + const isAbortingOperation = abortOperationInFlightByWorktree[activeWorktreeId ?? ''] ?? false const confirmAction = useConfirmationDialog() const isCommitting = commitInFlightByWorktree[activeWorktreeId ?? ''] ?? false // Why: parallel state to commit. Same per-worktree shape so navigating between @@ -1747,7 +1750,7 @@ function SourceControlInner(): React.JSX.Element { setCommitErrors((prev) => pruneRecord(prev)) setRemoteActionErrors((prev) => pruneRecord(prev)) setCommitInFlightByWorktree((prev) => pruneRecord(prev)) - setAbortMergeInFlightByWorktree((prev) => pruneRecord(prev)) + setAbortOperationInFlightByWorktree((prev) => pruneRecord(prev)) setGenerateInFlightByWorktree((prev) => pruneRecord(prev)) setGenerateErrors((prev) => pruneRecord(prev)) setGitHistoryByWorktree((prev) => pruneRecord(prev)) @@ -2085,52 +2088,91 @@ function SourceControlInner(): React.JSX.Element { ] ) - const handleAbortMerge = useCallback(async (): Promise => { - if (!activeWorktreeId || !worktreePath || conflictOperation !== 'merge' || isAbortingMerge) { - return - } + const handleAbortOperation = useCallback( + async (requestedOperation: AbortConflictOperation): Promise => { + if ( + !activeWorktreeId || + !worktreePath || + conflictOperation !== requestedOperation || + isAbortingOperation + ) { + return + } - const confirmed = await confirmAction({ - title: 'Abort merge?', - description: - 'This cancels the merge in progress and can discard conflict resolutions made during this merge.', - confirmLabel: 'Abort merge', - confirmVariant: 'destructive' - }) - if (!confirmed) { - return - } - - const connectionId = getConnectionId(activeWorktreeId) ?? undefined - setAbortMergeInFlightByWorktree((prev) => ({ ...prev, [activeWorktreeId]: true })) - setRemoteActionErrors((prev) => ({ ...prev, [activeWorktreeId]: null })) - try { - await abortRuntimeGitMerge({ - settings: useAppStore.getState().settings, - worktreeId: activeWorktreeId, - worktreePath, - connectionId + const isRebase = requestedOperation === 'rebase' + const label = isRebase ? 'rebase' : 'merge' + const title = isRebase ? 'Abort rebase?' : 'Abort merge?' + const description = isRebase + ? 'This cancels the rebase in progress and can discard conflict resolutions made during this rebase.' + : 'This cancels the merge in progress and can discard conflict resolutions made during this merge.' + const confirmed = await confirmAction({ + title, + description, + confirmLabel: `Abort ${label}`, + confirmVariant: 'destructive' }) - await refreshActiveGitStatusAfterMutation() - void refreshGitHistoryRef.current() - } catch (error) { - const message = error instanceof Error ? error.message : 'Failed to abort merge' - toast.error('Abort merge failed', { description: message }) - setRemoteActionErrors((prev) => ({ - ...prev, - [activeWorktreeId]: { kind: 'abort_merge', message } - })) - } finally { - setAbortMergeInFlightByWorktree((prev) => ({ ...prev, [activeWorktreeId]: false })) - } - }, [ - activeWorktreeId, - confirmAction, - conflictOperation, - isAbortingMerge, - refreshActiveGitStatusAfterMutation, - worktreePath - ]) + if (!confirmed) { + return + } + + const connectionId = getConnectionId(activeWorktreeId) ?? undefined + setAbortOperationInFlightByWorktree((prev) => ({ ...prev, [activeWorktreeId]: true })) + setRemoteActionErrors((prev) => ({ ...prev, [activeWorktreeId]: null })) + try { + const context = { + settings: useAppStore.getState().settings, + worktreeId: activeWorktreeId, + worktreePath, + connectionId + } + const abortGitOperation = isRebase ? abortRuntimeGitRebase : abortRuntimeGitMerge + await abortGitOperation(context) + } catch (error) { + const message = error instanceof Error ? error.message : `Failed to abort ${label}` + toast.error(`Abort ${label} failed`, { description: message }) + setRemoteActionErrors((prev) => ({ + ...prev, + [activeWorktreeId]: { kind: isRebase ? 'abort_rebase' : 'abort_merge', message } + })) + } finally { + setAbortOperationInFlightByWorktree((prev) => ({ ...prev, [activeWorktreeId]: false })) + refreshSourceControlAfterRemoteAction({ + refreshGitStatus: refreshActiveGitStatusAfterMutation, + refreshBranchCompare: refreshBranchCompareRef.current, + refreshGitHistory: refreshGitHistoryRef.current + }) + } + }, + [ + activeWorktreeId, + confirmAction, + conflictOperation, + isAbortingOperation, + refreshActiveGitStatusAfterMutation, + worktreePath + ] + ) + + const handleAbortMerge = useCallback(async (): Promise => { + await handleAbortOperation('merge') + }, [handleAbortOperation]) + + const handleAbortRebase = useCallback(async (): Promise => { + await handleAbortOperation('rebase') + }, [handleAbortOperation]) + + const handleAbortOperationForConflict = useCallback( + (operation: GitConflictOperation): void => { + if (operation === 'merge') { + void handleAbortMerge() + return + } + if (operation === 'rebase') { + void handleAbortRebase() + } + }, + [handleAbortMerge, handleAbortRebase] + ) // Why: compound actions must commit first and only run the follow-up remote // op when the commit succeeds. handleCommit's return value carries that @@ -2631,7 +2673,7 @@ function SourceControlInner(): React.JSX.Element { hasMessage: commitMessage.trim().length > 0, hasUnresolvedConflicts: unresolvedConflicts.length > 0, isCommitting, - isRemoteOperationActive: isRemoteOperationActive || isAbortingMerge, + isRemoteOperationActive: isRemoteOperationActive || isAbortingOperation, upstreamStatus: remoteStatus, prState: hostedReview?.state ?? null, isPRStateLoading: isHostedReviewStateLoading, @@ -2649,7 +2691,7 @@ function SourceControlInner(): React.JSX.Element { hasUnstagedChanges, hasPartiallyStagedChanges, isCommitting, - isAbortingMerge, + isAbortingOperation, isRemoteOperationActive, inFlightRemoteOpKind, hostedReviewCreation, @@ -2671,7 +2713,7 @@ function SourceControlInner(): React.JSX.Element { hasMessage: commitMessage.trim().length > 0, hasUnresolvedConflicts: unresolvedConflicts.length > 0, isCommitting, - isRemoteOperationActive: isRemoteOperationActive || isAbortingMerge, + isRemoteOperationActive: isRemoteOperationActive || isAbortingOperation, conflictOperation, upstreamStatus: remoteStatus, prState: hostedReview?.state ?? null, @@ -2690,7 +2732,7 @@ function SourceControlInner(): React.JSX.Element { hasPartiallyStagedChanges, isCommitting, conflictOperation, - isAbortingMerge, + isAbortingOperation, isRemoteOperationActive, inFlightRemoteOpKind, hostedReviewCreation, @@ -2728,6 +2770,9 @@ function SourceControlInner(): React.JSX.Element { case 'abort_merge': void handleAbortMerge() return + case 'abort_rebase': + void handleAbortRebase() + return case 'create_pr': void handleCreatePullRequest() return @@ -2755,6 +2800,7 @@ function SourceControlInner(): React.JSX.Element { handleCommit, handleCreatePullRequest, handleAbortMerge, + handleAbortRebase, isCreatingPr, prGenerating, runCompoundCommitAction, @@ -4008,8 +4054,8 @@ function SourceControlInner(): React.JSX.Element { conflictOperation={conflictOperation} unresolvedCount={unresolvedConflictReviewEntries.length} isResolvingWithAI={isLaunchingConflictAgent} - isAbortingMerge={isAbortingMerge} - onAbortMerge={() => void handleAbortMerge()} + isAbortingOperation={isAbortingOperation} + onAbortOperation={handleAbortOperationForConflict} onResolveWithAI={() => { void handleResolveConflictsWithAI() }} @@ -4035,8 +4081,8 @@ function SourceControlInner(): React.JSX.Element {
void handleAbortMerge()} + isAbortingOperation={isAbortingOperation} + onAbortOperation={handleAbortOperationForConflict} />
)} @@ -4148,7 +4194,7 @@ function SourceControlInner(): React.JSX.Element { } stagedCount={grouped.staged.length} hasUnresolvedConflicts={unresolvedConflicts.length > 0} - isRemoteOperationActive={isRemoteOperationActive || isAbortingMerge} + isRemoteOperationActive={isRemoteOperationActive || isAbortingOperation} inFlightRemoteOpKind={inFlightRemoteOpKind} primaryAction={primaryAction} dropdownItems={dropdownItems} @@ -5857,16 +5903,16 @@ export function ConflictSummaryCard({ conflictOperation, unresolvedCount, isResolvingWithAI, - isAbortingMerge = false, - onAbortMerge, + isAbortingOperation = false, + onAbortOperation, onResolveWithAI, onReview }: { conflictOperation: GitConflictOperation unresolvedCount: number isResolvingWithAI: boolean - isAbortingMerge?: boolean - onAbortMerge?: () => void + isAbortingOperation?: boolean + onAbortOperation?: (operation: GitConflictOperation) => void onResolveWithAI: () => void onReview: () => void }): React.JSX.Element { @@ -5919,17 +5965,17 @@ export function ConflictSummaryCard({ Review conflicts - {conflictOperation === 'merge' && onAbortMerge ? ( + {(conflictOperation === 'merge' || conflictOperation === 'rebase') && onAbortOperation ? ( ) : null} @@ -5942,14 +5988,14 @@ export function ConflictSummaryCard({ // rebase steps, or after resolving all conflicts but before --continue. The // user needs to see the operation state so they know the worktree is mid-rebase // and that they should run `git rebase --continue` or `--abort`. -function OperationBanner({ +export function OperationBanner({ conflictOperation, - isAbortingMerge = false, - onAbortMerge + isAbortingOperation = false, + onAbortOperation }: { conflictOperation: GitConflictOperation - isAbortingMerge?: boolean - onAbortMerge?: () => void + isAbortingOperation?: boolean + onAbortOperation?: (operation: GitConflictOperation) => void }): React.JSX.Element { const label = conflictOperation === 'merge' @@ -5968,17 +6014,17 @@ function OperationBanner({ {label} - {conflictOperation === 'merge' && onAbortMerge ? ( + {(conflictOperation === 'merge' || conflictOperation === 'rebase') && onAbortOperation ? ( ) : null} diff --git a/src/renderer/src/components/right-sidebar/source-control-dropdown-items.test.ts b/src/renderer/src/components/right-sidebar/source-control-dropdown-items.test.ts index e7bb7607a..41bc6edcb 100644 --- a/src/renderer/src/components/right-sidebar/source-control-dropdown-items.test.ts +++ b/src/renderer/src/components/right-sidebar/source-control-dropdown-items.test.ts @@ -214,16 +214,25 @@ describe('resolveDropdownItems', () => { } }) - it('shows a destructive Abort merge item only while a merge is in progress', () => { + it('shows a destructive abort item only while merge or rebase is in progress', () => { const mergeItems = resolveDropdownItems( inputs({ conflictOperation: 'merge', upstreamStatus: { hasUpstream: true, ahead: 0, behind: 0 } }) ) + const rebaseItems = resolveDropdownItems( + inputs({ + conflictOperation: 'rebase', + upstreamStatus: { hasUpstream: true, ahead: 0, behind: 0 } + }) + ) const mergeByKind = Object.fromEntries( mergeItems.filter((e) => e.kind !== 'separator').map((e) => [e.kind, e]) ) + const rebaseByKind = Object.fromEntries( + rebaseItems.filter((e) => e.kind !== 'separator').map((e) => [e.kind, e]) + ) expect(mergeByKind.abort_merge).toMatchObject({ label: 'Abort merge', @@ -231,14 +240,23 @@ describe('resolveDropdownItems', () => { disabled: false, variant: 'destructive' }) + expect(rebaseByKind.abort_rebase).toMatchObject({ + label: 'Abort rebase', + title: 'Abort the rebase in progress', + disabled: false, + variant: 'destructive' + }) + expect(mergeByKind.abort_rebase).toBeUndefined() + expect(rebaseByKind.abort_merge).toBeUndefined() - for (const conflictOperation of ['unknown', 'rebase', 'cherry-pick'] as const) { + for (const conflictOperation of ['unknown', 'cherry-pick'] as const) { const items = resolveDropdownItems(inputs({ conflictOperation })) expect(items.some((entry) => entry.kind === 'abort_merge')).toBe(false) + expect(items.some((entry) => entry.kind === 'abort_rebase')).toBe(false) } }) - it('disables Abort merge while another action is busy', () => { + it('disables conflict abort actions while another action is busy', () => { const items = resolveDropdownItems( inputs({ conflictOperation: 'merge', @@ -246,12 +264,24 @@ describe('resolveDropdownItems', () => { upstreamStatus: { hasUpstream: true, ahead: 0, behind: 0 } }) ) + const rebaseItems = resolveDropdownItems( + inputs({ + conflictOperation: 'rebase', + isRemoteOperationActive: true, + upstreamStatus: { hasUpstream: true, ahead: 0, behind: 0 } + }) + ) const abortMerge = items.find((entry) => entry.kind === 'abort_merge') + const abortRebase = rebaseItems.find((entry) => entry.kind === 'abort_rebase') expect(abortMerge).toMatchObject({ disabled: true, title: 'Operation in progress…' }) + expect(abortRebase).toMatchObject({ + disabled: true, + title: 'Operation in progress…' + }) }) it('locks every item while a pull request operation is running', () => { diff --git a/src/renderer/src/components/right-sidebar/source-control-dropdown-items.ts b/src/renderer/src/components/right-sidebar/source-control-dropdown-items.ts index 07202822e..e636b9ab6 100644 --- a/src/renderer/src/components/right-sidebar/source-control-dropdown-items.ts +++ b/src/renderer/src/components/right-sidebar/source-control-dropdown-items.ts @@ -16,6 +16,7 @@ export type DropdownActionKind = | 'commit_push' | 'commit_sync' | 'abort_merge' + | 'abort_rebase' | 'create_pr' | 'push_create_pr' | 'push' @@ -419,13 +420,15 @@ export function resolveDropdownItems(inputs: DropdownActionInputs): DropdownEntr fetchItem, publishItem ] - if (conflictOperation === 'merge') { + if (conflictOperation === 'merge' || conflictOperation === 'rebase') { + const isRebase = conflictOperation === 'rebase' + const label = isRebase ? 'Abort rebase' : 'Abort merge' entries.push( { kind: 'separator' }, { - kind: 'abort_merge', - label: 'Abort merge', - title: globalBusy ? 'Operation in progress…' : 'Abort the merge in progress', + kind: isRebase ? 'abort_rebase' : 'abort_merge', + label, + title: globalBusy ? 'Operation in progress…' : `Abort the ${conflictOperation} in progress`, disabled: globalBusy, variant: 'destructive' } diff --git a/src/renderer/src/runtime/runtime-git-client-merge.test.ts b/src/renderer/src/runtime/runtime-git-client-merge.test.ts index ac49612f3..065669e04 100644 --- a/src/renderer/src/runtime/runtime-git-client-merge.test.ts +++ b/src/renderer/src/runtime/runtime-git-client-merge.test.ts @@ -3,10 +3,11 @@ import { createCompatibleRuntimeStatusResponseIfNeeded, type RuntimeEnvironmentCallRequest } from './runtime-compatibility-test-fixture' -import { abortRuntimeGitMerge } from './runtime-git-client' +import { abortRuntimeGitMerge, abortRuntimeGitRebase } from './runtime-git-client' import { clearRuntimeCompatibilityCacheForTests } from './runtime-rpc-client' const gitAbortMerge = vi.fn() +const gitAbortRebase = vi.fn() const runtimeEnvironmentCall = vi.fn() const runtimeEnvironmentTransportCall = vi.fn() const runtimeCall = vi.fn() @@ -14,6 +15,7 @@ const runtimeCall = vi.fn() beforeEach(() => { clearRuntimeCompatibilityCacheForTests() gitAbortMerge.mockReset() + gitAbortRebase.mockReset() runtimeEnvironmentCall.mockReset() runtimeEnvironmentTransportCall.mockReset() runtimeCall.mockReset() @@ -22,7 +24,7 @@ beforeEach(() => { }) vi.stubGlobal('window', { api: { - git: { abortMerge: gitAbortMerge }, + git: { abortMerge: gitAbortMerge, abortRebase: gitAbortRebase }, runtime: { call: runtimeCall }, runtimeEnvironments: { call: runtimeEnvironmentTransportCall } } @@ -65,4 +67,41 @@ describe('runtime git client merge operations', () => { }) expect(gitAbortMerge).not.toHaveBeenCalled() }) + + it('uses local git IPC when aborting a rebase without an active runtime', async () => { + gitAbortRebase.mockResolvedValue(undefined) + + await abortRuntimeGitRebase({ + settings: { activeRuntimeEnvironmentId: null }, + worktreeId: 'wt-1', + worktreePath: '/repo', + connectionId: 'ssh-1' + }) + + expect(gitAbortRebase).toHaveBeenCalledWith({ connectionId: 'ssh-1', worktreePath: '/repo' }) + expect(runtimeEnvironmentCall).not.toHaveBeenCalled() + }) + + it('routes abort rebase through the active runtime', async () => { + runtimeEnvironmentCall.mockResolvedValue({ + id: 'rpc-1', + ok: true, + result: { success: true }, + _meta: { runtimeId: 'remote-runtime' } + }) + + await abortRuntimeGitRebase({ + settings: { activeRuntimeEnvironmentId: 'env-1' }, + worktreeId: 'wt-1', + worktreePath: '/repo' + }) + + expect(runtimeEnvironmentCall).toHaveBeenCalledWith({ + selector: 'env-1', + method: 'git.abortRebase', + params: { worktree: 'wt-1' }, + timeoutMs: 30_000 + }) + expect(gitAbortRebase).not.toHaveBeenCalled() + }) }) diff --git a/src/renderer/src/runtime/runtime-git-client.ts b/src/renderer/src/runtime/runtime-git-client.ts index 59f2f9323..60d44d500 100644 --- a/src/renderer/src/runtime/runtime-git-client.ts +++ b/src/renderer/src/runtime/runtime-git-client.ts @@ -196,6 +196,23 @@ export async function abortRuntimeGitMerge(context: RuntimeGitContext): Promise< ) } +export async function abortRuntimeGitRebase(context: RuntimeGitContext): Promise { + const target = getActiveRuntimeTarget(context.settings) + if (target.kind === 'local' || !context.worktreeId) { + await window.api.git.abortRebase({ + worktreePath: context.worktreePath, + connectionId: context.connectionId + }) + return + } + await callRuntimeRpc( + target, + 'git.abortRebase', + { worktree: context.worktreeId }, + { timeoutMs: 30_000 } + ) +} + export async function getRuntimeGitDiff( context: RuntimeGitContext, args: { filePath: string; staged: boolean; compareAgainstHead?: boolean } diff --git a/src/renderer/src/web/web-preload-api.ts b/src/renderer/src/web/web-preload-api.ts index f569d5e07..630d5bc02 100644 --- a/src/renderer/src/web/web-preload-api.ts +++ b/src/renderer/src/web/web-preload-api.ts @@ -1073,6 +1073,10 @@ function createGitApi(): NonNullable['git']> { const worktree = await resolveRuntimeWorktreeByPath(worktreePath) await callRuntimeResult('git.abortMerge', { worktree: worktree.id }) }, + abortRebase: async ({ worktreePath }) => { + const worktree = await resolveRuntimeWorktreeByPath(worktreePath) + await callRuntimeResult('git.abortRebase', { worktree: worktree.id }) + }, diff: async ({ worktreePath, filePath, staged, compareAgainstHead }) => { const file = await resolveRuntimeFilePath(filePath, worktreePath) return callRuntimeResult('git.diff', {