From 3c59c019fc66c9f8bdff25400d8623e2d3fbd49f Mon Sep 17 00:00:00 2001 From: Prethish Kumar <89143162+Prethish-Kumar@users.noreply.github.com> Date: Thu, 28 May 2026 02:02:52 +0530 Subject: [PATCH] fix(worktree): add SSH preflight check for dirty worktree before archive hooks (#2912) Co-authored-by: Orca Co-authored-by: Prethish-Complyance Co-authored-by: brennanb2025 --- src/main/ipc/worktrees.test.ts | 136 ++++++++++++++++++++- src/main/ipc/worktrees.ts | 14 ++- src/main/providers/ssh-git-provider.ts | 7 ++ src/main/providers/types.ts | 1 + src/relay/git-handler-worktree-ops.test.ts | 28 ++++- src/relay/git-handler-worktree-ops.ts | 10 ++ src/relay/git-handler.ts | 12 +- 7 files changed, 202 insertions(+), 6 deletions(-) diff --git a/src/main/ipc/worktrees.test.ts b/src/main/ipc/worktrees.test.ts index aac7c5ff3..473af7a9e 100644 --- a/src/main/ipc/worktrees.test.ts +++ b/src/main/ipc/worktrees.test.ts @@ -2779,6 +2779,10 @@ describe('registerWorktreeHandlers', () => { removeWorktree: vi.fn().mockImplementation(async () => { callOrder.push('remove') }), + worktreeIsClean: vi.fn().mockImplementation(async () => { + callOrder.push('preflight') + return { clean: true } + }), execNonInteractive: vi.fn().mockImplementation(async () => { callOrder.push('archive') return { stdout: '', stderr: '', exitCode: 0, timedOut: false } @@ -2813,10 +2817,130 @@ describe('registerWorktreeHandlers', () => { }) ) expect(provider.removeWorktree).toHaveBeenCalledWith('/remote/feature-wt', undefined) - expect(callOrder).toEqual(['archive', 'remove']) + expect(callOrder).toEqual(['archive', 'preflight', 'remove']) expect(runHookMock).not.toHaveBeenCalled() }) + it('runs SSH archive hooks before failing dirty non-force removal', async () => { + const repo = { + id: 'repo-ssh', + path: '/remote/repo', + displayName: 'ssh', + badgeColor: '#000', + addedAt: 0, + connectionId: 'conn-1', + worktreeBaseRef: null + } + const callOrder: string[] = [] + const provider = { + listWorktrees: vi.fn().mockResolvedValue([ + { + path: '/remote/repo', + head: 'main', + branch: 'main', + isBare: false, + isMainWorktree: true + }, + { + path: '/remote/feature-wt', + head: 'feature', + branch: 'feature', + isBare: false, + isMainWorktree: false + } + ]), + removeWorktree: vi.fn().mockImplementation(async () => { + callOrder.push('remove') + }), + worktreeIsClean: vi.fn().mockImplementation(async () => { + callOrder.push('preflight') + return { clean: false, stdout: ' M src/file.ts\n?? scratch.txt\n' } + }), + execNonInteractive: vi.fn().mockImplementation(async () => { + callOrder.push('archive') + return { stdout: '', stderr: '', exitCode: 0, timedOut: false } + }) + } + const fsProvider = { + readFile: vi.fn().mockResolvedValue({ + content: 'scripts:\n archive: echo archived\n', + isBinary: false + }) + } + store.getRepos.mockReturnValue([repo]) + store.getRepo.mockReturnValue(repo) + getSshGitProviderMock.mockReturnValue(provider) + getSshFilesystemProviderMock.mockReturnValue(fsProvider) + getEffectiveHooksFromConfigMock.mockReturnValue({ scripts: { archive: 'echo archived' } }) + + await expect( + handlers['worktrees:remove'](null, { + worktreeId: 'repo-ssh::/remote/feature-wt' + }) + ).rejects.toThrow('Worktree has uncommitted or untracked changes.') + + expect(callOrder).toEqual(['archive', 'preflight']) + expect(provider.removeWorktree).not.toHaveBeenCalled() + expect(store.removeWorktreeMeta).not.toHaveBeenCalled() + }) + + it('skips SSH dirty preflight for force removal', async () => { + const repo = { + id: 'repo-ssh', + path: '/remote/repo', + displayName: 'ssh', + badgeColor: '#000', + addedAt: 0, + connectionId: 'conn-1', + worktreeBaseRef: null + } + const provider = { + listWorktrees: vi.fn().mockResolvedValue([ + { + path: '/remote/repo', + head: 'main', + branch: 'main', + isBare: false, + isMainWorktree: true + }, + { + path: '/remote/feature-wt', + head: 'feature', + branch: 'feature', + isBare: false, + isMainWorktree: false + } + ]), + removeWorktree: vi.fn().mockResolvedValue(undefined), + worktreeIsClean: vi.fn(), + execNonInteractive: vi.fn().mockResolvedValue({ + stdout: '', + stderr: '', + exitCode: 0, + timedOut: false + }) + } + const fsProvider = { + readFile: vi.fn().mockResolvedValue({ + content: 'scripts:\n archive: echo archived\n', + isBinary: false + }) + } + store.getRepos.mockReturnValue([repo]) + store.getRepo.mockReturnValue(repo) + getSshGitProviderMock.mockReturnValue(provider) + getSshFilesystemProviderMock.mockReturnValue(fsProvider) + getEffectiveHooksFromConfigMock.mockReturnValue({ scripts: { archive: 'echo archived' } }) + + await handlers['worktrees:remove'](null, { + worktreeId: 'repo-ssh::/remote/feature-wt', + force: true + }) + + expect(provider.worktreeIsClean).not.toHaveBeenCalled() + expect(provider.removeWorktree).toHaveBeenCalledWith('/remote/feature-wt', true) + }) + it('continues SSH worktree removal when the archive hook fails', async () => { const repo = { id: 'repo-ssh', @@ -2846,6 +2970,7 @@ describe('registerWorktreeHandlers', () => { } ]), removeWorktree: vi.fn().mockResolvedValue(undefined), + worktreeIsClean: vi.fn().mockResolvedValue({ clean: true }), execNonInteractive: vi.fn().mockResolvedValue({ stdout: '', stderr: 'cleanup failed', @@ -2908,6 +3033,7 @@ describe('registerWorktreeHandlers', () => { } ]), removeWorktree: vi.fn().mockResolvedValue(undefined), + worktreeIsClean: vi.fn().mockResolvedValue({ clean: true }), execNonInteractive: vi.fn().mockRejectedValue(new Error('relay disconnected')) } const fsProvider = { @@ -2964,6 +3090,7 @@ describe('registerWorktreeHandlers', () => { } ]), removeWorktree: vi.fn().mockResolvedValue(undefined), + worktreeIsClean: vi.fn().mockResolvedValue({ clean: true }), execNonInteractive: vi.fn().mockResolvedValue({ stdout: '', stderr: '', @@ -3029,6 +3156,7 @@ describe('registerWorktreeHandlers', () => { } ]), removeWorktree: vi.fn().mockResolvedValue(undefined), + worktreeIsClean: vi.fn().mockResolvedValue({ clean: true }), execNonInteractive: vi.fn() } const fsProvider = { @@ -3310,7 +3438,8 @@ describe('registerWorktreeHandlers', () => { isBare: false, isMainWorktree: true } - ]) + ]), + worktreeIsClean: vi.fn().mockResolvedValue({ clean: true }) } store.getRepo.mockReturnValue(repo) store.getWorktreeMeta.mockReturnValue( @@ -3354,7 +3483,8 @@ describe('registerWorktreeHandlers', () => { isBare: false, isMainWorktree: true } - ]) + ]), + worktreeIsClean: vi.fn().mockResolvedValue({ clean: true }) } const fsProvider = { lstat: vi.fn().mockResolvedValue({ type: 'symlink' }), diff --git a/src/main/ipc/worktrees.ts b/src/main/ipc/worktrees.ts index 8f8565910..f8f9abdcc 100644 --- a/src/main/ipc/worktrees.ts +++ b/src/main/ipc/worktrees.ts @@ -1046,6 +1046,8 @@ export function registerWorktreeHandlers( const canonicalWorktreePath = registeredWorktree.path const deleteBranch = removedMeta?.preserveBranchOnDelete !== true + let shouldTearDownPtys = true + // Run archive hook before removal so teardown scripts still see the worktree directory. const hooks = await getArchiveHooksForRemoval(repo) if (hooks?.scripts.archive && !args.skipArchive) { @@ -1061,6 +1063,17 @@ export function registerWorktreeHandlers( } if (repo.connectionId) { + // Why: SSH deletion mirrors the local flow: hooks run while the + // directory is intact, then the clean check guards destructive removal. + if (!args.force) { + const { clean, stdout } = await provider!.worktreeIsClean(canonicalWorktreePath) + if (!clean) { + const error = new Error('Worktree has uncommitted or untracked changes.') + ;(error as Error & { stdout?: string }).stdout = stdout + throw error + } + } + await (deleteBranch ? provider!.removeWorktree(canonicalWorktreePath, args.force) : provider!.removeWorktree(canonicalWorktreePath, args.force, { deleteBranch })) @@ -1087,7 +1100,6 @@ export function registerWorktreeHandlers( await removeWorktreeSymlinks(canonicalWorktreePath, repo.symlinkPaths) } - let shouldTearDownPtys = true try { await assertWorktreeCleanForRemoval(canonicalWorktreePath, args.force ?? false) } catch (error) { diff --git a/src/main/providers/ssh-git-provider.ts b/src/main/providers/ssh-git-provider.ts index f99352b64..b0d51e54e 100644 --- a/src/main/providers/ssh-git-provider.ts +++ b/src/main/providers/ssh-git-provider.ts @@ -402,6 +402,13 @@ export class SshGitProvider implements IGitProvider { await this.mux.request('git.removeWorktree', { worktreePath, force, ...options }) } + async worktreeIsClean(worktreePath: string): Promise<{ clean: boolean; stdout?: string }> { + return (await this.mux.request('git.worktreeIsClean', { worktreePath })) as { + clean: boolean + stdout?: string + } + } + async exec(args: string[], cwd: string): Promise<{ stdout: string; stderr: string }> { return (await this.mux.request('git.exec', { args, cwd })) as { stdout: string diff --git a/src/main/providers/types.ts b/src/main/providers/types.ts index dca8544fe..71942515e 100644 --- a/src/main/providers/types.ts +++ b/src/main/providers/types.ts @@ -209,6 +209,7 @@ export type IGitProvider = { isGitRepoAsync(dirPath: string): Promise<{ isRepo: boolean; rootPath: string | null }> exec(args: string[], cwd: string): Promise<{ stdout: string; stderr: string }> getRemoteFileUrl(worktreePath: string, relativePath: string, line: number): Promise + worktreeIsClean(worktreePath: string): Promise<{ clean: boolean; stdout?: string }> } // ─── Provider Registry ────────────────────────────────────────────── diff --git a/src/relay/git-handler-worktree-ops.test.ts b/src/relay/git-handler-worktree-ops.test.ts index 63d118b53..707f916b1 100644 --- a/src/relay/git-handler-worktree-ops.test.ts +++ b/src/relay/git-handler-worktree-ops.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from 'vitest' import type { GitExec } from './git-handler-ops' -import { addWorktreeOp, removeWorktreeOp } from './git-handler-worktree-ops' +import { addWorktreeOp, removeWorktreeOp, worktreeIsCleanOp } from './git-handler-worktree-ops' function worktreeList(...entries: { path: string; branch?: string }[]): string { return entries @@ -218,3 +218,29 @@ describe('removeWorktreeOp', () => { expect(git).not.toHaveBeenCalledWith(['branch', '-D', 'feature/test'], expect.any(String)) }) }) + +describe('worktreeIsCleanOp', () => { + it('reports clean SSH worktrees without returning porcelain output', async () => { + const git = vi.fn(async () => ({ stdout: '\n', stderr: '' })) + + await expect(worktreeIsCleanOp(git, { worktreePath: '/repo-feature' })).resolves.toEqual({ + clean: true, + stdout: undefined + }) + + expect(git).toHaveBeenCalledWith( + ['status', '--porcelain', '--untracked-files=all'], + '/repo-feature' + ) + }) + + it('returns porcelain output for dirty SSH worktrees', async () => { + const stdout = ' M src/file.ts\n?? scratch.txt\n' + const git = vi.fn(async () => ({ stdout, stderr: '' })) + + await expect(worktreeIsCleanOp(git, { worktreePath: '/repo-feature' })).resolves.toEqual({ + clean: false, + stdout + }) + }) +}) diff --git a/src/relay/git-handler-worktree-ops.ts b/src/relay/git-handler-worktree-ops.ts index 7435b6e48..f032f66d2 100644 --- a/src/relay/git-handler-worktree-ops.ts +++ b/src/relay/git-handler-worktree-ops.ts @@ -208,6 +208,16 @@ function areRelayWorktreePathsEqual(leftPath: string, rightPath: string): boolea return process.platform === 'win32' ? left.toLowerCase() === right.toLowerCase() : left === right } +export async function worktreeIsCleanOp( + git: GitExec, + params: Record +): Promise<{ clean: boolean; stdout?: string }> { + const worktreePath = params.worktreePath as string + const { stdout } = await git(['status', '--porcelain', '--untracked-files=all'], worktreePath) + const clean = !stdout.trim() + return { clean, stdout: clean ? undefined : stdout } +} + // ─── Commit ────────────────────────────────────────────────────────── export async function commitChangesRelay( diff --git a/src/relay/git-handler.ts b/src/relay/git-handler.ts index 8a91781db..6bfda677e 100644 --- a/src/relay/git-handler.ts +++ b/src/relay/git-handler.ts @@ -16,7 +16,12 @@ import { validateGitExecArgs } from './git-handler-ops' import { commitCompare as commitCompareOp, commitDiffEntry } from './git-handler-commit-diff-ops' -import { commitChangesRelay, addWorktreeOp, removeWorktreeOp } from './git-handler-worktree-ops' +import { + commitChangesRelay, + addWorktreeOp, + removeWorktreeOp, + worktreeIsCleanOp +} from './git-handler-worktree-ops' import { checkIgnoredPathsOp, detectConflictOperation, getStatusOp } from './git-handler-status-ops' import { resolveRelayPushTarget } from './git-handler-push-target' import { normalizeGitErrorMessage, isNoUpstreamError } from '../shared/git-remote-error' @@ -72,6 +77,7 @@ export class GitHandler { this.dispatcher.onRequest('git.listWorktrees', (p) => this.listWorktrees(p)) this.dispatcher.onRequest('git.addWorktree', (p) => this.addWorktree(p)) this.dispatcher.onRequest('git.removeWorktree', (p) => this.removeWorktree(p)) + this.dispatcher.onRequest('git.worktreeIsClean', (p) => this.worktreeIsClean(p)) this.dispatcher.onRequest('git.exec', (p) => this.exec(p)) this.dispatcher.onRequest('git.isGitRepo', (p) => this.isGitRepo(p)) } @@ -529,4 +535,8 @@ export class GitHandler { private async removeWorktree(params: Record) { return removeWorktreeOp(this.git.bind(this), params) } + + private async worktreeIsClean(params: Record) { + return worktreeIsCleanOp(this.git.bind(this), params) + } }