From 7def1c7f00c6961eceb5d6a50ccebeff2b9f3647 Mon Sep 17 00:00:00 2001 From: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Date: Fri, 22 May 2026 23:02:39 -0700 Subject: [PATCH] fix: run SSH archive hook before worktree removal (#2665) --- src/main/ipc/worktrees.test.ts | 304 ++++++++++++++++++++ src/main/ipc/worktrees.ts | 98 ++++++- src/main/providers/ssh-git-provider.test.ts | 34 +++ src/main/providers/ssh-git-provider.ts | 7 +- 4 files changed, 429 insertions(+), 14 deletions(-) diff --git a/src/main/ipc/worktrees.test.ts b/src/main/ipc/worktrees.test.ts index aecabfc27..b02022700 100644 --- a/src/main/ipc/worktrees.test.ts +++ b/src/main/ipc/worktrees.test.ts @@ -2474,6 +2474,310 @@ describe('registerWorktreeHandlers', () => { ) }) + it('runs the archive hook before removing an SSH worktree', 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') + }), + 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 handlers['worktrees:remove'](null, { + worktreeId: 'repo-ssh::/remote/feature-wt' + }) + + expect(fsProvider.readFile).toHaveBeenCalledWith('/remote/repo/orca.yaml') + expect(provider.execNonInteractive).toHaveBeenCalledWith( + '/bin/bash', + ['-lc', 'echo archived'], + '/remote/feature-wt', + 120_000, + undefined, + expect.objectContaining({ + ORCA_ROOT_PATH: '/remote/repo', + ORCA_WORKTREE_PATH: '/remote/feature-wt' + }) + ) + expect(provider.removeWorktree).toHaveBeenCalledWith('/remote/feature-wt', undefined) + expect(callOrder).toEqual(['archive', 'remove']) + expect(runHookMock).not.toHaveBeenCalled() + }) + + it('continues SSH worktree removal when the archive hook fails', async () => { + const repo = { + id: 'repo-ssh', + path: '/remote/repo', + displayName: 'ssh', + badgeColor: '#000', + addedAt: 0, + connectionId: 'conn-1', + worktreeBaseRef: null + } + const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + 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), + execNonInteractive: vi.fn().mockResolvedValue({ + stdout: '', + stderr: 'cleanup failed', + exitCode: 7, + timedOut: false + }) + } + const fsProvider = { + readFile: vi.fn().mockResolvedValue({ + content: 'scripts:\n archive: exit 7\n', + isBinary: false + }) + } + store.getRepos.mockReturnValue([repo]) + store.getRepo.mockReturnValue(repo) + getSshGitProviderMock.mockReturnValue(provider) + getSshFilesystemProviderMock.mockReturnValue(fsProvider) + getEffectiveHooksFromConfigMock.mockReturnValue({ scripts: { archive: 'exit 7' } }) + + try { + await handlers['worktrees:remove'](null, { + worktreeId: 'repo-ssh::/remote/feature-wt' + }) + expect(provider.removeWorktree).toHaveBeenCalledWith('/remote/feature-wt', undefined) + expect(consoleErrorSpy).toHaveBeenCalledWith( + '[hooks] archive hook failed for /remote/feature-wt:', + expect.stringContaining('archive hook exited 7') + ) + } finally { + consoleErrorSpy.mockRestore() + } + }) + + it('continues SSH worktree removal when archive hook execution rejects', async () => { + const repo = { + id: 'repo-ssh', + path: '/remote/repo', + displayName: 'ssh', + badgeColor: '#000', + addedAt: 0, + connectionId: 'conn-1', + worktreeBaseRef: null + } + const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + 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), + execNonInteractive: vi.fn().mockRejectedValue(new Error('relay disconnected')) + } + 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' } }) + + try { + await handlers['worktrees:remove'](null, { + worktreeId: 'repo-ssh::/remote/feature-wt' + }) + expect(provider.removeWorktree).toHaveBeenCalledWith('/remote/feature-wt', undefined) + expect(consoleErrorSpy).toHaveBeenCalledWith( + '[hooks] archive hook failed for /remote/feature-wt:', + 'relay disconnected' + ) + } finally { + consoleErrorSpy.mockRestore() + } + }) + + it('uses cmd.exe for archive hooks on Windows-like SSH worktree paths', async () => { + const repo = { + id: 'repo-ssh', + path: 'C:\\remote\\repo', + displayName: 'ssh', + badgeColor: '#000', + addedAt: 0, + connectionId: 'conn-1', + worktreeBaseRef: null + } + const provider = { + listWorktrees: vi.fn().mockResolvedValue([ + { + path: 'C:\\remote\\repo', + head: 'main', + branch: 'main', + isBare: false, + isMainWorktree: true + }, + { + path: 'C:\\remote\\feature-wt', + head: 'feature', + branch: 'feature', + isBare: false, + isMainWorktree: false + } + ]), + removeWorktree: vi.fn().mockResolvedValue(undefined), + 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::C:\\remote\\feature-wt' + }) + + expect(fsProvider.readFile).toHaveBeenCalledWith('C:\\remote\\repo\\orca.yaml') + expect(provider.execNonInteractive).toHaveBeenCalledWith( + 'cmd.exe', + ['/d', '/s', '/c', 'echo archived'], + 'C:\\remote\\feature-wt', + 120_000, + undefined, + expect.objectContaining({ + ORCA_ROOT_PATH: 'C:\\remote\\repo', + ORCA_WORKTREE_PATH: 'C:\\remote\\feature-wt' + }) + ) + }) + + it('skips the archive hook before removing an SSH worktree when skipArchive is true', 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), + execNonInteractive: vi.fn() + } + 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', + skipArchive: true + }) + + expect(provider.execNonInteractive).not.toHaveBeenCalled() + expect(provider.removeWorktree).toHaveBeenCalledWith('/remote/feature-wt', undefined) + }) + it('preserves the branch on remove for worktrees created from an existing local branch', async () => { mockKnownFeatureWorktree() removeWorktreeMock.mockResolvedValue(undefined) diff --git a/src/main/ipc/worktrees.ts b/src/main/ipc/worktrees.ts index 6401186f7..b82e1d403 100644 --- a/src/main/ipc/worktrees.ts +++ b/src/main/ipc/worktrees.ts @@ -12,6 +12,7 @@ import type { CreateWorktreeResult, GitPushTarget, GitWorktreeInfo, + OrcaHooks, Repo, WorktreeMeta } from '../../shared/types' @@ -30,6 +31,8 @@ import { getSshFilesystemProvider } from '../providers/ssh-filesystem-dispatch' import { createIssueCommandRunnerScript, getEffectiveHooks, + getEffectiveHooksFromConfig, + getSetupRunnerEnvVars, loadHooks, parseOrcaYaml, readIssueCommand, @@ -72,6 +75,9 @@ import { findRegisteredDeletableWorktree, isWorktreePathMissing } from '../worktree-removal-safety' +import { isWindowsAbsolutePathLike } from '../../shared/cross-platform-path' + +const WORKTREE_ARCHIVE_HOOK_TIMEOUT_MS = 120_000 // Why: worktrees discovered on disk (not created via Orca's UI) have no // persisted WorktreeMeta, so mergeWorktree falls back to `lastActivityAt: 0`. @@ -111,6 +117,72 @@ function getWorktreeRemovalOptionsKey(args: { force?: boolean; skipArchive?: boo return `${forceKey}:${archiveKey}` } +async function getArchiveHooksForRemoval(repo: Repo): Promise { + if (!repo.connectionId) { + return getEffectiveHooks(repo) + } + + const fsProvider = getSshFilesystemProvider(repo.connectionId) + if (!fsProvider) { + return getEffectiveHooksFromConfig(repo, null) + } + + try { + const result = await fsProvider.readFile(joinWorktreeRelativePath(repo.path, 'orca.yaml')) + const yamlHooks = result.isBinary ? null : parseOrcaYaml(result.content) + return getEffectiveHooksFromConfig(repo, yamlHooks) + } catch { + return getEffectiveHooksFromConfig(repo, null) + } +} + +async function runRemoteArchiveHook( + repo: Repo, + worktreePath: string, + script: string +): Promise<{ success: boolean; output: string }> { + if (!repo.connectionId) { + return { success: true, output: '' } + } + + const provider = requireSshGitProvider(repo.connectionId) + const env = getSetupRunnerEnvVars(repo, worktreePath) + const isWindowsRemote = isWindowsAbsolutePathLike(worktreePath) + const result = await provider + .execNonInteractive( + isWindowsRemote ? 'cmd.exe' : '/bin/bash', + isWindowsRemote ? ['/d', '/s', '/c', script] : ['-lc', script], + worktreePath, + WORKTREE_ARCHIVE_HOOK_TIMEOUT_MS, + undefined, + env + ) + .catch((error) => ({ + stdout: '', + stderr: '', + exitCode: null, + timedOut: false, + spawnError: error instanceof Error ? error.message : String(error) + })) + const output = [ + result.stdout, + result.stderr, + result.spawnError, + result.timedOut ? 'archive hook timed out' : null, + typeof result.exitCode === 'number' && result.exitCode !== 0 + ? `archive hook exited ${result.exitCode}` + : null + ] + .filter((part): part is string => Boolean(part)) + .join('\n') + .trim() + + return { + success: !result.spawnError && !result.timedOut && result.exitCode === 0, + output + } +} + type WorktreeRemovalInFlight = { optionsKey: string promise: Promise @@ -606,6 +678,20 @@ export function registerWorktreeHandlers( const canonicalWorktreePath = registeredWorktree.path const deleteBranch = removedMeta?.preserveBranchOnDelete !== 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) { + const result = repo.connectionId + ? await runRemoteArchiveHook(repo, canonicalWorktreePath, hooks.scripts.archive) + : await runHook('archive', canonicalWorktreePath, repo) + if (!result.success) { + console.error( + `[hooks] archive hook failed for ${canonicalWorktreePath}:`, + result.output + ) + } + } + if (repo.connectionId) { await (deleteBranch ? provider!.removeWorktree(canonicalWorktreePath, args.force) @@ -624,18 +710,6 @@ export function registerWorktreeHandlers( return } - // Run archive hook before removal - const hooks = getEffectiveHooks(repo) - if (hooks?.scripts.archive && !args.skipArchive) { - const result = await runHook('archive', canonicalWorktreePath, repo) - if (!result.success) { - console.error( - `[hooks] archive hook failed for ${canonicalWorktreePath}:`, - result.output - ) - } - } - // Why: `git worktree remove` (non-force) refuses to delete a worktree // that has untracked files, and a symlink pointing into the primary // checkout looks untracked to git. Unlink the user-configured symlinks diff --git a/src/main/providers/ssh-git-provider.test.ts b/src/main/providers/ssh-git-provider.test.ts index eda35bc89..d5e0cb733 100644 --- a/src/main/providers/ssh-git-provider.test.ts +++ b/src/main/providers/ssh-git-provider.test.ts @@ -136,6 +136,40 @@ describe('SshGitProvider', () => { expect(result).toEqual(execResult) }) + it('execNonInteractive forwards environment variables to the relay', async () => { + const execResult = { + stdout: '', + stderr: '', + exitCode: 0, + timedOut: false + } + mux.request.mockResolvedValue(execResult) + + await provider.execNonInteractive( + '/bin/bash', + ['-lc', 'echo "$ORCA_WORKTREE_PATH"'], + '/home/user/repo', + 120_000, + undefined, + { + ORCA_ROOT_PATH: '/home/user/repo', + ORCA_WORKTREE_PATH: '/home/user/repo-feature' + } + ) + + expect(mux.request).toHaveBeenCalledWith('agent.execNonInteractive', { + binary: '/bin/bash', + args: ['-lc', 'echo "$ORCA_WORKTREE_PATH"'], + cwd: '/home/user/repo', + stdin: null, + timeoutMs: 120_000, + env: { + ORCA_ROOT_PATH: '/home/user/repo', + ORCA_WORKTREE_PATH: '/home/user/repo-feature' + } + }) + }) + it('cancelNonInteractiveExec sends best-effort relay cancellation', async () => { await provider.cancelNonInteractiveExec('/home/user/repo') diff --git a/src/main/providers/ssh-git-provider.ts b/src/main/providers/ssh-git-provider.ts index c632972c9..f99352b64 100644 --- a/src/main/providers/ssh-git-provider.ts +++ b/src/main/providers/ssh-git-provider.ts @@ -121,7 +121,8 @@ export class SshGitProvider implements IGitProvider { args: string[], cwd: string, timeoutMs: number, - signal?: AbortSignal + signal?: AbortSignal, + env?: Record ): Promise { return this.runQueuedNonInteractiveExec( cwd, @@ -130,7 +131,8 @@ export class SshGitProvider implements IGitProvider { args, cwd, stdin: null, - timeoutMs + timeoutMs, + ...(env ? { env } : {}) }, signal ) @@ -168,6 +170,7 @@ export class SshGitProvider implements IGitProvider { cwd: string stdin: string | null timeoutMs: number + env?: Record }, signal?: AbortSignal ): Promise {