diff --git a/src/main/git/repo-clone-path.test.ts b/src/main/git/repo-clone-path.test.ts new file mode 100644 index 000000000..e651e1d96 --- /dev/null +++ b/src/main/git/repo-clone-path.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, it } from 'vitest' +import { mkdtemp, rm } from 'fs/promises' +import { tmpdir } from 'os' +import { join } from 'path' +import { deriveValidatedClonePath, getClonePathComparisonKey } from './repo-clone-path' + +describe('repo clone path helpers', () => { + it('allows safe repository names that start with two dots', async () => { + const destination = await mkdtemp(join(tmpdir(), 'orca-clone-path-')) + try { + expect( + deriveValidatedClonePath({ + url: 'https://example.com/..repo.git', + destination + }) + ).toBe(join(destination, '..repo')) + } finally { + await rm(destination, { recursive: true, force: true }) + } + }) + + it('rejects Windows-looking destinations on non-Windows hosts', async () => { + if (process.platform === 'win32') { + return + } + expect(() => + deriveValidatedClonePath({ + url: 'https://example.com/orca.git', + destination: 'C:\\Users\\me\\src' + }) + ).toThrow('Clone destination must be an absolute path') + expect(() => + deriveValidatedClonePath({ + url: 'https://example.com/orca.git', + destination: '\\\\server\\share' + }) + ).toThrow('Clone destination must be an absolute path') + expect(() => + deriveValidatedClonePath({ + url: 'https://example.com/orca.git', + destination: '//server/share' + }) + ).toThrow('Clone destination must be an absolute path') + expect(() => + deriveValidatedClonePath({ + url: 'https://example.com/orca.git', + destination: '//wsl.localhost/Ubuntu/home/me' + }) + ).toThrow('Clone destination must be an absolute path') + }) + + it('canonicalizes WSL UNC server aliases without folding Linux path casing', () => { + expect(getClonePathComparisonKey('\\\\wsl.localhost\\Ubuntu\\home\\User\\repo')).toBe( + getClonePathComparisonKey('\\\\wsl$\\ubuntu\\home\\User\\repo') + ) + expect(getClonePathComparisonKey('\\\\wsl.localhost\\Ubuntu\\home\\User\\repo\\')).toBe( + getClonePathComparisonKey('\\\\wsl$\\ubuntu\\home\\User\\repo') + ) + expect(getClonePathComparisonKey('\\\\wsl.localhost\\Ubuntu\\home\\User\\repo')).not.toBe( + getClonePathComparisonKey('\\\\wsl$\\ubuntu\\home\\user\\repo') + ) + }) +}) diff --git a/src/main/git/repo-clone-path.ts b/src/main/git/repo-clone-path.ts new file mode 100644 index 000000000..8c0c7df75 --- /dev/null +++ b/src/main/git/repo-clone-path.ts @@ -0,0 +1,127 @@ +import { isAbsolute, join, posix, relative, resolve, sep, win32 } from 'path' +import type { Stats } from 'fs' +import { lstat, mkdir, rm } from 'fs/promises' +import { + isWindowsAbsolutePathLike, + normalizeRuntimePathForComparison, + normalizeRuntimePathSeparators +} from '../../shared/cross-platform-path' + +export type ClaimedCloneTarget = { + canCleanup: boolean + ownedDirectoryIdentity: CloneDirectoryIdentity | null +} + +type CloneDirectoryIdentity = Pick + +export function deriveValidatedClonePath(args: { url: string; destination: string }): string { + if ( + !args.destination || + !isAbsolute(args.destination) || + (process.platform !== 'win32' && isWindowsAbsolutePathLike(args.destination)) + ) { + throw new Error('Clone destination must be an absolute path') + } + + // Why: direct callers can supply URLs whose default git clone folder would + // be "." or ".."; rejecting them prevents parent/destination deletion. + const source = args.url.replace(/\.git\/?$/, '') + const isWindowsLocalSource = /^[A-Za-z]:[\\/]/.test(source) || source.startsWith('\\\\') + const repoName = isWindowsLocalSource ? win32.basename(source) : posix.basename(source) + if (!repoName || repoName === '.' || repoName === '..') { + throw new Error('Invalid repository name derived from URL') + } + if (repoName.includes('/') || repoName.includes('\\')) { + throw new Error('Invalid repository name derived from URL') + } + + const clonePath = join(args.destination, repoName) + const resolvedDestination = resolve(args.destination) + const resolvedClonePath = resolve(clonePath) + const pathFromDestination = relative(resolvedDestination, resolvedClonePath) + if ( + pathFromDestination === '' || + pathFromDestination === '..' || + pathFromDestination.startsWith(`..${sep}`) || + isAbsolute(pathFromDestination) + ) { + throw new Error('Clone path must be inside the destination directory') + } + + return clonePath +} + +export function getClonePathComparisonKey(clonePath: string): string { + const resolvedClonePath = isWindowsAbsolutePathLike(clonePath) ? clonePath : resolve(clonePath) + const normalized = normalizeRuntimePathSeparators(resolvedClonePath) + const wslUncMatch = normalized.match(/^\/\/(?:wsl\.localhost|wsl\$)\/([^/]+)(\/.*)?$/i) + if (wslUncMatch) { + // Why: WSL UNC paths cross into a case-sensitive Linux filesystem, so only + // the Windows UNC server alias and distro segment should be case-folded. + const linuxPath = (wslUncMatch[2] ?? '').replace(/\/+$/, '') + return `//wsl/${wslUncMatch[1].toLowerCase()}${linuxPath}` + } + return normalizeRuntimePathForComparison(resolvedClonePath) +} + +export async function claimCloneTarget(clonePath: string): Promise { + try { + await mkdir(clonePath, { recursive: false }) + return { + canCleanup: true, + ownedDirectoryIdentity: cloneDirectoryIdentity(await lstat(clonePath)) + } + } catch (error) { + if (isErrnoCode(error, 'EEXIST')) { + return { canCleanup: false, ownedDirectoryIdentity: null } + } + throw error + } +} + +export async function cleanupClaimedCloneTarget( + clonePath: string, + claimedTarget: ClaimedCloneTarget +): Promise { + if (!claimedTarget.canCleanup || !claimedTarget.ownedDirectoryIdentity) { + return + } + + try { + const currentStats = await lstat(clonePath) + if (!currentStats.isDirectory()) { + return + } + if ( + !isSameCloneDirectoryIdentity( + claimedTarget.ownedDirectoryIdentity, + cloneDirectoryIdentity(currentStats) + ) + ) { + return + } + } catch { + return + } + + await rm(clonePath, { recursive: true, force: true }).catch(() => { + // Best-effort cleanup - do not mask the original clone failure. + }) +} + +function cloneDirectoryIdentity(stats: Stats): CloneDirectoryIdentity { + // Why: fast remove/recreate cycles can reuse an inode; birthtime keeps us + // from treating a replacement directory as the clone target we created. + return { dev: stats.dev, ino: stats.ino, birthtimeMs: stats.birthtimeMs } +} + +function isSameCloneDirectoryIdentity( + a: CloneDirectoryIdentity, + b: CloneDirectoryIdentity +): boolean { + return a.dev === b.dev && a.ino === b.ino && a.birthtimeMs === b.birthtimeMs +} + +function isErrnoCode(error: unknown, code: string): boolean { + return error instanceof Error && (error as NodeJS.ErrnoException).code === code +} diff --git a/src/main/ipc/repos-remote.test.ts b/src/main/ipc/repos-remote.test.ts index 4a240f9af..db1ece856 100644 --- a/src/main/ipc/repos-remote.test.ts +++ b/src/main/ipc/repos-remote.test.ts @@ -3,8 +3,12 @@ tests (addRemote, getBaseRefDefault envelope, searchBaseRefs SSH relay) so fixture setup and mock plumbing can be shared. Splitting by line count would duplicate the hoisted mocks and the `../git/repo` partial-real/partial-stub setup. */ -import { describe, expect, it, vi, beforeEach } from 'vitest' +import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest' import { EventEmitter } from 'events' +import { existsSync } from 'fs' +import { mkdir, mkdtemp, rm, writeFile } from 'fs/promises' +import { tmpdir } from 'os' +import { join } from 'path' import type * as RepoModule from '../git/repo' import { DEFAULT_REPO_BADGE_COLOR } from '../../shared/constants' @@ -564,12 +568,46 @@ describe('repos:addRemote', () => { }) }) +type MockCloneProcess = EventEmitter & { + stderr: EventEmitter + kill: ReturnType +} + +function createMockCloneProcess(): MockCloneProcess { + const proc = new EventEmitter() as MockCloneProcess + proc.stderr = new EventEmitter() + proc.kill = vi.fn().mockReturnValue(true) + return proc +} + +async function waitForAssertion(assertion: () => void): Promise { + const deadline = Date.now() + 2_000 + let lastError: unknown + while (Date.now() < deadline) { + try { + assertion() + return + } catch (error) { + lastError = error + await new Promise((resolve) => setTimeout(resolve, 10)) + } + } + throw lastError +} + describe('repos:add + repos:clone', () => { const handlers = new Map unknown>() const mockWindow = { isDestroyed: () => false, webContents: { send: vi.fn() } } + const tempRoots: string[] = [] + + const createTempRoot = async (): Promise => { + const root = await mkdtemp(join(tmpdir(), 'orca-repos-clone-')) + tempRoots.push(root) + return root + } beforeEach(() => { handlers.clear() @@ -583,8 +621,7 @@ describe('repos:add + repos:clone', () => { mockWindow.webContents.send.mockReset() gitSpawnMock.mockReset() gitSpawnMock.mockImplementation(() => { - const proc = new EventEmitter() as EventEmitter & { stderr: EventEmitter } - proc.stderr = new EventEmitter() + const proc = createMockCloneProcess() queueMicrotask(() => proc.emit('close', 0, null)) return proc }) @@ -592,6 +629,10 @@ describe('repos:add + repos:clone', () => { registerRepoHandlers(mockWindow as never, mockStore as never) }) + afterEach(async () => { + await Promise.all(tempRoots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) + }) + it('defaults repos:add badgeColor to DEFAULT_REPO_BADGE_COLOR for folder repos', async () => { const result = await handlers.get('repos:add')!(null, { path: '/tmp/from-add', kind: 'folder' }) @@ -638,14 +679,16 @@ describe('repos:add + repos:clone', () => { }) it('defaults repos:clone badgeColor to DEFAULT_REPO_BADGE_COLOR', async () => { + const destination = await createTempRoot() + const result = await handlers.get('repos:clone')!(null, { url: 'https://example.com/orca.git', - destination: '/tmp' + destination }) expect(mockStore.addRepo).toHaveBeenCalledWith( expect.objectContaining({ - path: '/tmp/orca', + path: join(destination, 'orca'), badgeColor: DEFAULT_REPO_BADGE_COLOR, kind: 'git', externalWorktreeVisibility: 'hide', @@ -657,9 +700,11 @@ describe('repos:add + repos:clone', () => { }) it('preserves existing badgeColor when repos:clone upgrades folder->git after dedupe', async () => { + const destination = await createTempRoot() + const clonePath = join(destination, 'orca') const existing = { id: 'folder-repo', - path: '/tmp/orca', + path: clonePath, displayName: 'orca', badgeColor: '#8b5cf6', addedAt: 1, @@ -671,7 +716,7 @@ describe('repos:add + repos:clone', () => { const result = await handlers.get('repos:clone')!(null, { url: 'https://example.com/orca.git', - destination: '/tmp' + destination }) expect(mockStore.updateRepo).toHaveBeenCalledWith(existing.id, { kind: 'git' }) @@ -679,6 +724,330 @@ describe('repos:add + repos:clone', () => { expect(result).toHaveProperty('badgeColor', '#8b5cf6') expect(mockStore.addRepo).not.toHaveBeenCalled() }) + + it('rejects a dot-segment URL before creating the destination or spawning git', async () => { + const tempRoot = await createTempRoot() + const destination = join(tempRoot, 'destination') + + await expect( + handlers.get('repos:clone')!(null, { + url: 'file:///tmp/source/.', + destination + }) + ).rejects.toThrow('Invalid repository name derived from URL') + + expect(existsSync(destination)).toBe(false) + expect(gitSpawnMock).not.toHaveBeenCalled() + }) + + it('rejects a parent-segment URL before creating the destination or spawning git', async () => { + const tempRoot = await createTempRoot() + const destination = join(tempRoot, 'destination') + + await expect( + handlers.get('repos:clone')!(null, { + url: 'file:///tmp/source/..', + destination + }) + ).rejects.toThrow('Invalid repository name derived from URL') + + expect(existsSync(destination)).toBe(false) + expect(gitSpawnMock).not.toHaveBeenCalled() + }) + + it('rejects a relative destination before creating directories or spawning git', async () => { + const destination = `relative-clone-destination-${Date.now()}` + + await expect( + handlers.get('repos:clone')!(null, { + url: 'https://example.com/orca.git', + destination + }) + ).rejects.toThrow('Clone destination must be an absolute path') + + expect(existsSync(destination)).toBe(false) + expect(gitSpawnMock).not.toHaveBeenCalled() + }) + + it('rejects URL-derived names containing Windows separators before spawning git', async () => { + const destination = await createTempRoot() + + await expect( + handlers.get('repos:clone')!(null, { + url: 'https://example.com/team\\orca.git', + destination + }) + ).rejects.toThrow('Invalid repository name derived from URL') + + expect(gitSpawnMock).not.toHaveBeenCalled() + }) + + it('accepts Windows local-path clone sources while validating the final segment', async () => { + const destination = await createTempRoot() + + const result = await handlers.get('repos:clone')!(null, { + url: 'C:\\src\\orca.git', + destination + }) + + expect(gitSpawnMock).toHaveBeenCalledWith( + ['clone', '--progress', '--', 'C:\\src\\orca.git', join(destination, 'orca')], + expect.objectContaining({ cwd: destination }) + ) + expect(result).toHaveProperty('path', join(destination, 'orca')) + }) + + it('treats cloneAbort with no active clone as a no-op', async () => { + await expect(handlers.get('repos:cloneAbort')!(null, undefined)).resolves.toBeUndefined() + }) + + it('does not remove an existing target directory when aborting a pending clone', async () => { + const destination = await createTempRoot() + const clonePath = join(destination, 'orca') + await mkdir(clonePath) + await writeFile(join(clonePath, 'user-file.txt'), 'keep me') + const proc = createMockCloneProcess() + gitSpawnMock.mockReturnValueOnce(proc) + + const clonePromise = handlers.get('repos:clone')!(null, { + url: 'https://example.com/orca.git', + destination + }) + await waitForAssertion(() => expect(gitSpawnMock).toHaveBeenCalledTimes(1)) + + await handlers.get('repos:cloneAbort')!(null, undefined) + proc.emit('close', null, 'SIGTERM') + await expect(clonePromise).rejects.toThrow('Clone aborted') + + expect(existsSync(clonePath)).toBe(true) + expect(existsSync(join(clonePath, 'user-file.txt'))).toBe(true) + }) + + it('does not remove an existing target file when aborting a pending clone', async () => { + const destination = await createTempRoot() + const clonePath = join(destination, 'orca') + await writeFile(clonePath, 'existing file') + const proc = createMockCloneProcess() + gitSpawnMock.mockReturnValueOnce(proc) + + const clonePromise = handlers.get('repos:clone')!(null, { + url: 'https://example.com/orca.git', + destination + }) + await waitForAssertion(() => expect(gitSpawnMock).toHaveBeenCalledTimes(1)) + + await handlers.get('repos:cloneAbort')!(null, undefined) + proc.emit('close', null, 'SIGTERM') + await expect(clonePromise).rejects.toThrow('Clone aborted') + + expect(existsSync(clonePath)).toBe(true) + }) + + it('removes a fresh clone target only after the aborted process closes unsuccessfully', async () => { + const destination = await createTempRoot() + const clonePath = join(destination, 'orca') + const proc = createMockCloneProcess() + gitSpawnMock.mockReturnValueOnce(proc) + + const clonePromise = handlers.get('repos:clone')!(null, { + url: 'https://example.com/orca.git', + destination + }) + await waitForAssertion(() => expect(gitSpawnMock).toHaveBeenCalledTimes(1)) + + await handlers.get('repos:cloneAbort')!(null, undefined) + expect(existsSync(clonePath)).toBe(true) + + proc.emit('close', null, 'SIGTERM') + await expect(clonePromise).rejects.toThrow('Clone aborted') + expect(existsSync(clonePath)).toBe(false) + }) + + it('removes an owned fresh clone target when git exits unsuccessfully', async () => { + const destination = await createTempRoot() + const clonePath = join(destination, 'orca') + const partialFile = join(clonePath, 'partial.txt') + const proc = createMockCloneProcess() + gitSpawnMock.mockReturnValueOnce(proc) + + const clonePromise = handlers.get('repos:clone')!(null, { + url: 'https://example.com/orca.git', + destination + }) + await waitForAssertion(() => expect(gitSpawnMock).toHaveBeenCalledTimes(1)) + await writeFile(partialFile, 'git wrote this before failing') + + proc.stderr.emit('data', Buffer.from('fatal: repository not found\n')) + proc.emit('close', 128, null) + await expect(clonePromise).rejects.toThrow('Clone failed: fatal: repository not found') + + expect(existsSync(clonePath)).toBe(false) + }) + + it('removes an owned fresh clone target when git spawn emits an error', async () => { + const destination = await createTempRoot() + const clonePath = join(destination, 'orca') + const partialFile = join(clonePath, 'partial.txt') + const proc = createMockCloneProcess() + gitSpawnMock.mockReturnValueOnce(proc) + + const clonePromise = handlers.get('repos:clone')!(null, { + url: 'https://example.com/orca.git', + destination + }) + await waitForAssertion(() => expect(gitSpawnMock).toHaveBeenCalledTimes(1)) + await writeFile(partialFile, 'git wrote this before spawn failure') + + proc.emit('error', new Error('spawn failed')) + await expect(clonePromise).rejects.toThrow('Clone failed: spawn failed') + + expect(existsSync(clonePath)).toBe(false) + }) + + it('keeps a fresh clone target when abort races with a successful close', async () => { + const destination = await createTempRoot() + const clonePath = join(destination, 'orca') + const proc = createMockCloneProcess() + gitSpawnMock.mockReturnValueOnce(proc) + + const clonePromise = handlers.get('repos:clone')!(null, { + url: 'https://example.com/orca.git', + destination + }) + await waitForAssertion(() => expect(gitSpawnMock).toHaveBeenCalledTimes(1)) + + await handlers.get('repos:cloneAbort')!(null, undefined) + proc.emit('close', 0, null) + await expect(clonePromise).resolves.toMatchObject({ + path: clonePath, + kind: 'git' + }) + + expect(existsSync(clonePath)).toBe(true) + }) + + it('dedupes retry when abort races with a successful clone close', async () => { + const destination = await createTempRoot() + const clonePath = join(destination, 'orca') + const repos: unknown[] = [] + mockStore.getRepos.mockImplementation(() => repos) + mockStore.addRepo.mockImplementation((repo: unknown) => { + repos.push(repo) + }) + const firstProc = createMockCloneProcess() + const secondProc = createMockCloneProcess() + gitSpawnMock.mockReturnValueOnce(firstProc).mockReturnValueOnce(secondProc) + + const firstClonePromise = handlers.get('repos:clone')!(null, { + url: 'https://example.com/orca.git', + destination + }) + await waitForAssertion(() => expect(gitSpawnMock).toHaveBeenCalledTimes(1)) + + await handlers.get('repos:cloneAbort')!(null, undefined) + const secondClonePromise = handlers.get('repos:clone')!(null, { + url: 'https://example.com/orca.git', + destination + }) + await new Promise((resolve) => setImmediate(resolve)) + expect(gitSpawnMock).toHaveBeenCalledTimes(1) + + firstProc.emit('close', 0, null) + await expect(firstClonePromise).resolves.toMatchObject({ path: clonePath, kind: 'git' }) + await expect(secondClonePromise).resolves.toMatchObject({ path: clonePath, kind: 'git' }) + + expect(gitSpawnMock).toHaveBeenCalledTimes(1) + expect(secondProc.kill).not.toHaveBeenCalled() + }) + + it('serializes concurrent clones for the same target', async () => { + const destination = await createTempRoot() + const clonePath = join(destination, 'orca') + const repos: unknown[] = [] + mockStore.getRepos.mockImplementation(() => repos) + mockStore.addRepo.mockImplementation((repo: unknown) => { + repos.push(repo) + }) + const firstProc = createMockCloneProcess() + gitSpawnMock.mockReturnValueOnce(firstProc) + + const firstClonePromise = handlers.get('repos:clone')!(null, { + url: 'https://example.com/orca.git', + destination + }) + const secondClonePromise = handlers.get('repos:clone')!(null, { + url: 'https://example.com/orca.git', + destination + }) + await waitForAssertion(() => expect(gitSpawnMock).toHaveBeenCalledTimes(1)) + + firstProc.emit('close', 0, null) + await expect(firstClonePromise).resolves.toMatchObject({ path: clonePath, kind: 'git' }) + await expect(secondClonePromise).resolves.toMatchObject({ path: clonePath, kind: 'git' }) + + expect(gitSpawnMock).toHaveBeenCalledTimes(1) + }) + + it('waits for pending abort cleanup before retrying the same clone target', async () => { + const destination = await createTempRoot() + const clonePath = join(destination, 'orca') + const partialFile = join(clonePath, 'partial.txt') + const firstProc = createMockCloneProcess() + const secondProc = createMockCloneProcess() + gitSpawnMock.mockReturnValueOnce(firstProc).mockReturnValueOnce(secondProc) + + const firstClonePromise = handlers.get('repos:clone')!(null, { + url: 'https://example.com/orca.git', + destination + }) + await waitForAssertion(() => expect(gitSpawnMock).toHaveBeenCalledTimes(1)) + await writeFile(partialFile, 'first clone wrote this before abort') + await handlers.get('repos:cloneAbort')!(null, undefined) + + const secondClonePromise = handlers.get('repos:clone')!(null, { + url: 'https://example.com/orca.git', + destination + }) + await new Promise((resolve) => setImmediate(resolve)) + expect(gitSpawnMock).toHaveBeenCalledTimes(1) + expect(existsSync(partialFile)).toBe(true) + + firstProc.emit('close', null, 'SIGTERM') + await expect(firstClonePromise).rejects.toThrow('Clone aborted') + await waitForAssertion(() => expect(gitSpawnMock).toHaveBeenCalledTimes(2)) + expect(existsSync(partialFile)).toBe(false) + + secondProc.emit('close', 0, null) + await expect(secondClonePromise).resolves.toMatchObject({ + path: clonePath, + kind: 'git' + }) + expect(existsSync(clonePath)).toBe(true) + }) + + it('skips abort cleanup when the claimed target is replaced before close', async () => { + const destination = await createTempRoot() + const clonePath = join(destination, 'orca') + const replacementFile = join(clonePath, 'replacement.txt') + const proc = createMockCloneProcess() + gitSpawnMock.mockReturnValueOnce(proc) + + const clonePromise = handlers.get('repos:clone')!(null, { + url: 'https://example.com/orca.git', + destination + }) + await waitForAssertion(() => expect(gitSpawnMock).toHaveBeenCalledTimes(1)) + + await handlers.get('repos:cloneAbort')!(null, undefined) + await rm(clonePath, { recursive: true, force: true }) + await mkdir(clonePath) + await writeFile(replacementFile, 'new owner') + + proc.emit('close', null, 'SIGTERM') + await expect(clonePromise).rejects.toThrow('Clone aborted') + + expect(existsSync(replacementFile)).toBe(true) + }) }) describe('repos:getBaseRefDefault envelope', () => { diff --git a/src/main/ipc/repos.ts b/src/main/ipc/repos.ts index 2ffb0fe2c..f51de2d25 100644 --- a/src/main/ipc/repos.ts +++ b/src/main/ipc/repos.ts @@ -23,8 +23,15 @@ import { invalidateAuthorizedRootsCache } from './filesystem-auth' import type { ChildProcess } from 'child_process' import { access, mkdir, readdir, rm } from 'fs/promises' import { gitExecFileAsync, gitSpawn } from '../git/runner' -import { basename, isAbsolute, join, posix } from 'path' +import { isAbsolute, join, posix } from 'path' import { normalizeRuntimePathForComparison } from '../../shared/cross-platform-path' +import { + cleanupClaimedCloneTarget, + claimCloneTarget, + deriveValidatedClonePath, + getClonePathComparisonKey +} from '../git/repo-clone-path' +import type { ClaimedCloneTarget } from '../git/repo-clone-path' import { getNextProjectGroupOrder } from '../../shared/project-groups' import { scanNestedRepos } from '../project-groups/nested-repo-discovery' import { @@ -75,11 +82,25 @@ function emitRepoAdded(method: RepoMethod, alreadyExisted: boolean): void { track('repo_added', { method, ...getCohortAtEmit() }) } +type ActiveCloneMetadata = { + path: string + pathKey: string + claimedTarget: ClaimedCloneTarget + process: ChildProcess + abortRequested: boolean + generation: number + pendingAbortCleanup: Promise | null + resolvePendingAbortCleanup: (() => void) | null +} + // Why: module-scoped so the abort handle survives window re-creation on macOS. // registerRepoHandlers is called again when a new BrowserWindow is created, // and a function-scoped variable would lose the reference to an in-flight clone. -let activeCloneProc: ChildProcess | null = null -let activeClonePath: string | null = null +let activeClone: ActiveCloneMetadata | null = null +let nextCloneGeneration = 1 +const latestCloneGenerationByPath = new Map() +const pendingAbortCleanupByPath = new Map>() +const cloneInFlightByPath = new Map>() const ProjectGroupCreateArgs = z.object({ name: z.string().min(1), @@ -148,6 +169,71 @@ function validateNestedRepoScanRoot(path: string, connectionId?: string): void { } } +async function cleanupOwnedCloneTarget(metadata: ActiveCloneMetadata): Promise { + if (!metadata.claimedTarget.canCleanup || !metadata.claimedTarget.ownedDirectoryIdentity) { + return + } + if (latestCloneGenerationByPath.get(metadata.pathKey) !== metadata.generation) { + return + } + // Why: an immediate retry can attach a newer process to the same target + // before the aborted process closes; the old close handler must not delete it. + if ( + activeClone && + activeClone.process !== metadata.process && + activeClone.pathKey === metadata.pathKey + ) { + return + } + + if (latestCloneGenerationByPath.get(metadata.pathKey) !== metadata.generation) { + return + } + await cleanupClaimedCloneTarget(metadata.path, metadata.claimedTarget) +} + +function markCloneAbortCleanupPending(metadata: ActiveCloneMetadata): void { + if (metadata.resolvePendingAbortCleanup) { + return + } + metadata.pendingAbortCleanup = new Promise((resolve) => { + metadata.resolvePendingAbortCleanup = resolve + }) + pendingAbortCleanupByPath.set(metadata.pathKey, metadata.pendingAbortCleanup) +} + +function settleCloneAbortCleanup(metadata: ActiveCloneMetadata): void { + if (pendingAbortCleanupByPath.get(metadata.pathKey) === metadata.pendingAbortCleanup) { + pendingAbortCleanupByPath.delete(metadata.pathKey) + } + metadata.resolvePendingAbortCleanup?.() + metadata.pendingAbortCleanup = null + metadata.resolvePendingAbortCleanup = null +} + +async function runWithClonePathLock(clonePathKey: string, task: () => Promise): Promise { + const previous = cloneInFlightByPath.get(clonePathKey) ?? Promise.resolve() + let release!: () => void + const current = new Promise((resolve) => { + release = resolve + }) + const tail = previous.then( + () => current, + () => current + ) + cloneInFlightByPath.set(clonePathKey, tail) + + try { + await previous + return await task() + } finally { + release() + if (cloneInFlightByPath.get(clonePathKey) === tail) { + cloneInFlightByPath.delete(clonePathKey) + } + } +} + function sanitizeNestedRepoImportError(context: string, error: unknown): string { console.warn(`[project-groups] ${context}`, error) return 'Repository could not be imported' @@ -976,19 +1062,12 @@ export function registerRepoHandlers(mainWindow: BrowserWindow, store: Store): v }) ipcMain.handle('repos:cloneAbort', async () => { - if (activeCloneProc) { - const pathToClean = activeClonePath - activeCloneProc.kill() - activeCloneProc = null - activeClonePath = null - // Why: git clone creates the target directory before it finishes. - // Without cleanup, retrying the same URL/destination fails with - // "destination path already exists and is not an empty directory". - if (pathToClean) { - await rm(pathToClean, { recursive: true, force: true }).catch(() => { - // Best-effort cleanup — don't fail the abort if removal fails - }) - } + if (activeClone) { + const clone = activeClone + clone.abortRequested = true + markCloneAbortCleanupPending(clone) + clone.process.kill() + activeClone = null } }) @@ -999,114 +1078,183 @@ export function registerRepoHandlers(mainWindow: BrowserWindow, store: Store): v // the repo folder name from the URL (e.g. "orca" from .../orca.git). // This matches the default git clone behavior where the last path segment // of the URL becomes the directory name. - const repoName = basename(args.url.replace(/\.git\/?$/, '')) - if (!repoName) { - throw new Error('Could not determine repository name from URL') - } - // Why: gitSpawn uses args.destination as cwd, so it must exist before - // spawn — fresh installs may have a defaulted parent dir that does not - // exist yet (e.g. ~/orca). recursive: true is a no-op when present. - await mkdir(args.destination, { recursive: true }) - const clonePath = join(args.destination, repoName) + const clonePath = deriveValidatedClonePath(args) + const clonePathKey = getClonePathComparisonKey(clonePath) + return runWithClonePathLock(clonePathKey, async () => { + await pendingAbortCleanupByPath.get(clonePathKey) + const existingAfterPendingClone = store + .getRepos() + .find((r) => getClonePathComparisonKey(r.path) === clonePathKey) + if (existingAfterPendingClone && !isFolderRepo(existingAfterPendingClone)) { + emitRepoAdded('clone_url', true) + return existingAfterPendingClone + } + // Why: gitSpawn uses args.destination as cwd, so it must exist before + // spawn — fresh installs may have a defaulted parent dir that does not + // exist yet (e.g. ~/orca). recursive: true is a no-op when present. + await mkdir(args.destination, { recursive: true }) + const claimedTarget = await claimCloneTarget(clonePath) - // Why: use spawn instead of execFile so there is no maxBuffer limit. - // git clone writes progress to stderr which can exceed Node's default - // 1 MB buffer on large or submodule-heavy repos. We only keep the tail - // of stderr for error reporting and discard stdout entirely. - // Why: use --progress to force git to emit progress even when stderr - // is not a TTY. Without it, git suppresses progress output when piped. - await new Promise((resolve, reject) => { - // Why: clone destination may be a WSL path (e.g. user picks a WSL - // directory). Use the parent destination as the cwd so the runner - // detects WSL and routes through wsl.exe. - // Why: use the '--' separator to isolate the URL argument and prevent - // malicious URLs from being interpreted as git flags (command injection). - const proc = gitSpawn(['clone', '--progress', '--', args.url, clonePath], { - cwd: args.destination, - stdio: ['ignore', 'ignore', 'pipe'] - }) - activeCloneProc = proc - activeClonePath = clonePath + // Why: use spawn instead of execFile so there is no maxBuffer limit. + // git clone writes progress to stderr which can exceed Node's default + // 1 MB buffer on large or submodule-heavy repos. We only keep the tail + // of stderr for error reporting and discard stdout entirely. + // Why: use --progress to force git to emit progress even when stderr + // is not a TTY. Without it, git suppresses progress output when piped. + const cloneMetadataRef: { current: ActiveCloneMetadata | null } = { current: null } + await new Promise((resolve, reject) => { + // Why: clone destination may be a WSL path (e.g. user picks a WSL + // directory). Use the parent destination as the cwd so the runner + // detects WSL and routes through wsl.exe. + // Why: use the '--' separator to isolate the URL argument and prevent + // malicious URLs from being interpreted as git flags (command injection). + let proc: ReturnType + try { + proc = gitSpawn(['clone', '--progress', '--', args.url, clonePath], { + cwd: args.destination, + stdio: ['ignore', 'ignore', 'pipe'] + }) + } catch (err) { + void cleanupClaimedCloneTarget(clonePath, claimedTarget).finally(() => { + const message = err instanceof Error ? err.message : String(err) + reject(new Error(`Clone failed: ${message}`)) + }) + return + } + const generation = nextCloneGeneration++ + latestCloneGenerationByPath.set(clonePathKey, generation) + const metadata: ActiveCloneMetadata = { + path: clonePath, + pathKey: clonePathKey, + claimedTarget, + process: proc, + abortRequested: false, + generation, + pendingAbortCleanup: null, + resolvePendingAbortCleanup: null + } + cloneMetadataRef.current = metadata + activeClone = metadata - let stderrTail = '' - proc.stderr!.on('data', (chunk: Buffer) => { - const text = chunk.toString() - stderrTail = (stderrTail + text).slice(-4096) + let stderrTail = '' + let settled = false + proc.stderr!.on('data', (chunk: Buffer) => { + const text = chunk.toString() + stderrTail = (stderrTail + text).slice(-4096) - // Why: git progress lines use \r to overwrite in-place. Split on - // both \r and \n to find the latest progress fragment, then extract - // the phase name and percentage for the renderer. - const lines = text.split(/[\r\n]+/) - for (const line of lines) { - const match = line.match(/^([\w\s]+):\s+(\d+)%/) - if (match && !mainWindow.isDestroyed()) { - mainWindow.webContents.send('repos:clone-progress', { - phase: match[1].trim(), - percent: parseInt(match[2], 10) - }) + // Why: git progress lines use \r to overwrite in-place. Split on + // both \r and \n to find the latest progress fragment, then extract + // the phase name and percentage for the renderer. + const lines = text.split(/[\r\n]+/) + for (const line of lines) { + const match = line.match(/^([\w\s]+):\s+(\d+)%/) + if (match && !mainWindow.isDestroyed()) { + mainWindow.webContents.send('repos:clone-progress', { + phase: match[1].trim(), + percent: parseInt(match[2], 10) + }) + } + } + }) + + const finishClone = async ( + code: number | null, + signal: NodeJS.Signals | null, + err?: Error + ) => { + if (settled) { + return + } + settled = true + // Why: only clear the ref if it still points to this process. + // A quick abort-and-retry can reassign activeClone to a new + // spawn before this handler fires, and nulling it would make the + // new clone unabortable. + if (activeClone?.process === proc) { + activeClone = null + } + + const cloneSucceeded = !err && code === 0 && !signal + if (!cloneSucceeded) { + // Why: only the process that created this target may remove it, + // and only after git reports the clone did not complete. + await cleanupOwnedCloneTarget(metadata) + } + if (metadata.abortRequested && !cloneSucceeded) { + settleCloneAbortCleanup(metadata) + } + if (latestCloneGenerationByPath.get(metadata.pathKey) === metadata.generation) { + latestCloneGenerationByPath.delete(metadata.pathKey) + } + + if (err) { + reject(new Error(`Clone failed: ${err.message}`)) + } else if (signal === 'SIGTERM') { + reject(new Error('Clone aborted')) + } else if (code === 0) { + resolve() + } else { + const lastLine = stderrTail.trim().split('\n').pop() ?? 'unknown error' + reject(new Error(`Clone failed: ${lastLine}`)) } } + + proc.on('error', (err) => { + void finishClone(null, null, err) + }) + + proc.on('close', (code, signal) => { + void finishClone(code, signal) + }) }) - proc.on('error', (err) => reject(new Error(`Clone failed: ${err.message}`))) - - proc.on('close', (code, signal) => { - // Why: only clear the ref if it still points to this process. - // A quick abort-and-retry can reassign activeCloneProc to a new - // spawn before this handler fires, and nulling it would make the - // new clone unabortable. - if (activeCloneProc === proc) { - activeCloneProc = null - activeClonePath = null + try { + // Why: check after clone (not before) because the path didn't exist + // before cloning. But if the user somehow had a folder repo at this path + // that git clone succeeded into (empty dir), reuse that entry and upgrade + // its kind to 'git' instead of creating a duplicate. + const existing = store + .getRepos() + .find((r) => getClonePathComparisonKey(r.path) === clonePathKey) + if (existing) { + if (isFolderRepo(existing)) { + const updated = store.updateRepo(existing.id, { kind: 'git' }) + if (updated) { + notifyReposChanged(mainWindow) + // Why: folder→git upgrade is a real new git repo provisioning event. + emitRepoAdded('clone_url', false) + return updated + } + } + emitRepoAdded('clone_url', true) + return existing } - if (signal === 'SIGTERM') { - reject(new Error('Clone aborted')) - } else if (code === 0) { - resolve() - } else { - const lastLine = stderrTail.trim().split('\n').pop() ?? 'unknown error' - reject(new Error(`Clone failed: ${lastLine}`)) - } - }) - }) - // Why: check after clone (not before) because the path didn't exist - // before cloning. But if the user somehow had a folder repo at this path - // that git clone succeeded into (empty dir), reuse that entry and upgrade - // its kind to 'git' instead of creating a duplicate. - const existing = store.getRepos().find((r) => r.path === clonePath) - if (existing) { - if (isFolderRepo(existing)) { - const updated = store.updateRepo(existing.id, { kind: 'git' }) - if (updated) { - notifyReposChanged(mainWindow) - // Why: folder→git upgrade is a real new git repo provisioning event. - emitRepoAdded('clone_url', false) - return updated + const repoIcon = await detectRepoIcon({ repoPath: clonePath, kind: 'git' }) + const repo: Repo = { + id: randomUUID(), + path: clonePath, + displayName: getRepoName(clonePath), + badgeColor: DEFAULT_REPO_BADGE_COLOR, + ...(repoIcon ? { repoIcon } : {}), + addedAt: Date.now(), + kind: 'git', + externalWorktreeVisibility: 'hide', + externalWorktreeVisibilityLegacy: false + } + + store.addRepo(repo) + invalidateAuthorizedRootsCache() + notifyReposChanged(mainWindow) + emitRepoAdded('clone_url', false) + return repo + } finally { + const metadata = cloneMetadataRef.current + if (metadata?.abortRequested) { + settleCloneAbortCleanup(metadata) } } - emitRepoAdded('clone_url', true) - return existing - } - - const repoIcon = await detectRepoIcon({ repoPath: clonePath, kind: 'git' }) - const repo: Repo = { - id: randomUUID(), - path: clonePath, - displayName: getRepoName(clonePath), - badgeColor: DEFAULT_REPO_BADGE_COLOR, - ...(repoIcon ? { repoIcon } : {}), - addedAt: Date.now(), - kind: 'git', - externalWorktreeVisibility: 'hide', - externalWorktreeVisibilityLegacy: false - } - - store.addRepo(repo) - invalidateAuthorizedRootsCache() - notifyReposChanged(mainWindow) - emitRepoAdded('clone_url', false) - return repo + }) } ) diff --git a/src/main/runtime/orca-runtime.test.ts b/src/main/runtime/orca-runtime.test.ts index df0907180..b317382d7 100644 --- a/src/main/runtime/orca-runtime.test.ts +++ b/src/main/runtime/orca-runtime.test.ts @@ -2116,6 +2116,167 @@ describe('OrcaRuntimeService', () => { } }) + it('rejects runtime cloneRepo dot-segment URLs before spawning git', async () => { + const spawnSpy = vi.spyOn(gitRunner, 'wslAwareSpawn') + const runtime = createRuntime() + const tempRoot = await mkdtemp(join(tmpdir(), 'orca-runtime-clone-')) + const destination = join(tempRoot, 'destination') + + try { + await expect(runtime.cloneRepo('file:///tmp/source/.', destination)).rejects.toThrow( + 'Invalid repository name derived from URL' + ) + expect(spawnSpy).not.toHaveBeenCalled() + } finally { + spawnSpy.mockRestore() + await rm(tempRoot, { recursive: true, force: true }) + } + }) + + it('rejects runtime cloneRepo parent-segment URLs before spawning git', async () => { + const spawnSpy = vi.spyOn(gitRunner, 'wslAwareSpawn') + const runtime = createRuntime() + const tempRoot = await mkdtemp(join(tmpdir(), 'orca-runtime-clone-')) + const destination = join(tempRoot, 'destination') + + try { + await expect(runtime.cloneRepo('file:///tmp/source/..', destination)).rejects.toThrow( + 'Invalid repository name derived from URL' + ) + expect(spawnSpy).not.toHaveBeenCalled() + } finally { + spawnSpy.mockRestore() + await rm(tempRoot, { recursive: true, force: true }) + } + }) + + it('removes an owned runtime clone target when git exits unsuccessfully', async () => { + const spawnSpy = vi.spyOn(gitRunner, 'wslAwareSpawn') + const proc = new EventEmitter() as EventEmitter & { stderr: EventEmitter } + proc.stderr = new EventEmitter() + spawnSpy.mockReturnValue(proc as never) + const runtime = createRuntime() + const destination = await mkdtemp(join(tmpdir(), 'orca-runtime-clone-')) + const clonePath = join(destination, 'repo-badge-color') + + try { + const clonePromise = runtime.cloneRepo( + 'https://example.com/repo-badge-color.git', + destination + ) + await vi.waitFor(() => expect(spawnSpy).toHaveBeenCalledTimes(1)) + await writeFile(join(clonePath, 'partial.txt'), 'git wrote this before failing') + proc.stderr.emit('data', Buffer.from('fatal: repository not found\n')) + proc.emit('close', 128, null) + + await expect(clonePromise).rejects.toThrow('Clone failed: fatal: repository not found') + await expect(lstat(clonePath)).rejects.toThrow() + } finally { + spawnSpy.mockRestore() + await rm(destination, { recursive: true, force: true }) + } + }) + + it('preserves an existing runtime clone target when git exits unsuccessfully', async () => { + const spawnSpy = vi.spyOn(gitRunner, 'wslAwareSpawn') + const proc = new EventEmitter() as EventEmitter & { stderr: EventEmitter } + proc.stderr = new EventEmitter() + spawnSpy.mockReturnValue(proc as never) + const runtime = createRuntime() + const destination = await mkdtemp(join(tmpdir(), 'orca-runtime-clone-')) + const clonePath = join(destination, 'repo-badge-color') + + try { + await mkdir(clonePath) + await writeFile(join(clonePath, 'user-file.txt'), 'keep me') + const clonePromise = runtime.cloneRepo( + 'https://example.com/repo-badge-color.git', + destination + ) + await vi.waitFor(() => expect(spawnSpy).toHaveBeenCalledTimes(1)) + proc.emit('close', 128, null) + + await expect(clonePromise).rejects.toThrow('Clone failed') + await expect(lstat(join(clonePath, 'user-file.txt'))).resolves.toBeTruthy() + } finally { + spawnSpy.mockRestore() + await rm(destination, { recursive: true, force: true }) + } + }) + + it('skips runtime clone failure cleanup when the owned target is replaced', async () => { + const spawnSpy = vi.spyOn(gitRunner, 'wslAwareSpawn') + const proc = new EventEmitter() as EventEmitter & { stderr: EventEmitter } + proc.stderr = new EventEmitter() + spawnSpy.mockReturnValue(proc as never) + const runtime = createRuntime() + const destination = await mkdtemp(join(tmpdir(), 'orca-runtime-clone-')) + const clonePath = join(destination, 'repo-badge-color') + const replacementFile = join(clonePath, 'replacement.txt') + + try { + const clonePromise = runtime.cloneRepo( + 'https://example.com/repo-badge-color.git', + destination + ) + await vi.waitFor(() => expect(spawnSpy).toHaveBeenCalledTimes(1)) + await rm(clonePath, { recursive: true, force: true }) + await mkdir(clonePath) + await writeFile(replacementFile, 'new owner') + proc.emit('close', 128, null) + + await expect(clonePromise).rejects.toThrow('Clone failed') + await expect(lstat(replacementFile)).resolves.toBeTruthy() + } finally { + spawnSpy.mockRestore() + await rm(destination, { recursive: true, force: true }) + } + }) + + it('serializes concurrent runtime clones for the same target', async () => { + const spawnSpy = vi.spyOn(gitRunner, 'wslAwareSpawn') + const firstProc = new EventEmitter() as EventEmitter & { stderr: EventEmitter } + firstProc.stderr = new EventEmitter() + spawnSpy.mockReturnValueOnce(firstProc as never) + const added: Record[] = [] + const colorStore = { + ...store, + getRepos: () => [...added] as never, + addRepo: (repo: Record) => { + added.push(repo) + }, + getRepo: (id: string) => added.find((repo) => repo.id === id) as never + } + const runtime = new OrcaRuntimeService(colorStore as never) + const destination = await mkdtemp(join(tmpdir(), 'orca-runtime-clone-')) + + try { + const firstClonePromise = runtime.cloneRepo( + 'https://example.com/repo-badge-color.git', + destination + ) + const secondClonePromise = runtime.cloneRepo( + 'https://example.com/repo-badge-color.git', + destination + ) + await vi.waitFor(() => expect(spawnSpy).toHaveBeenCalledTimes(1)) + await new Promise((resolve) => setImmediate(resolve)) + expect(spawnSpy).toHaveBeenCalledTimes(1) + + firstProc.emit('close', 0, null) + await expect(firstClonePromise).resolves.toMatchObject({ + path: join(destination, 'repo-badge-color') + }) + await expect(secondClonePromise).resolves.toMatchObject({ + path: join(destination, 'repo-badge-color') + }) + expect(spawnSpy).toHaveBeenCalledTimes(1) + } finally { + spawnSpy.mockRestore() + await rm(destination, { recursive: true, force: true }) + } + }) + it('associates controller PTYs with mixed-case Windows and UNC cwd paths', async () => { vi.mocked(listWorktrees).mockResolvedValue([ { diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index 112d8be58..345a6388d 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -9,9 +9,15 @@ import { import type { AgentStatus } from '../../shared/agent-detection' import type { AgentStatusOrchestrationContext } from '../../shared/agent-status-types' import { gitExecFileAsync, wslAwareSpawn } from '../git/runner' +import { + cleanupClaimedCloneTarget, + claimCloneTarget, + deriveValidatedClonePath, + getClonePathComparisonKey +} from '../git/repo-clone-path' import { isWslPath, parseWslPath, getWslHome } from '../wsl' import { createHash, randomUUID } from 'crypto' -import { basename, isAbsolute, join } from 'path' +import { isAbsolute, join } from 'path' import { mkdir, readFile, readdir, rm, stat } from 'fs/promises' import { OrchestrationDb } from './orchestration/db' import { formatMessagesForInjection } from './orchestration/formatter' @@ -1027,6 +1033,7 @@ export class OrcaRuntimeService { private resolvedWorktreeCache: ResolvedWorktreeCache | null = null private resolvedWorktreeInFlight: ResolvedWorktreeInFlight | null = null private resolvedWorktreeGeneration = 0 + private cloneInFlightByPath = new Map>() private agentDetector: AgentDetector | null = null private _orchestrationDb: OrchestrationDb | null = null private messageWaitersByHandle = new Map>() @@ -5451,30 +5458,92 @@ export class OrcaRuntimeService { } const trimmedUrl = url.trim() const trimmedDestination = destination.trim() - const repoName = basename(trimmedUrl.replace(/\.git\/?$/, '')) - if (!repoName) { - throw new Error('Could not determine repository name from URL') - } if (!trimmedDestination) { throw new Error('Clone destination is required') } - if (!isAbsolute(trimmedDestination)) { - throw new Error('Clone destination must be an absolute path') + const clonePath = deriveValidatedClonePath({ url: trimmedUrl, destination: trimmedDestination }) + const clonePathKey = getClonePathComparisonKey(clonePath) + const previous = this.cloneInFlightByPath.get(clonePathKey) ?? Promise.resolve() + let release!: () => void + const current = new Promise((resolve) => { + release = resolve + }) + const tail = previous.then( + () => current, + () => current + ) + this.cloneInFlightByPath.set(clonePathKey, tail) + + try { + await previous + return await this.cloneRepoAfterPathLock( + trimmedUrl, + trimmedDestination, + clonePath, + clonePathKey + ) + } finally { + release() + if (this.cloneInFlightByPath.get(clonePathKey) === tail) { + this.cloneInFlightByPath.delete(clonePathKey) + } } + } + + private async cloneRepoAfterPathLock( + trimmedUrl: string, + trimmedDestination: string, + clonePath: string, + clonePathKey: string + ): Promise { + if (!this.store) { + throw new Error('runtime_unavailable') + } + const existingBeforeClone = this.store + .getRepos() + .find((repo) => getClonePathComparisonKey(repo.path) === clonePathKey) + if (existingBeforeClone && !isFolderRepo(existingBeforeClone)) { + return existingBeforeClone + } + await mkdir(trimmedDestination, { recursive: true }) - const clonePath = join(trimmedDestination, repoName) + const claimedTarget = await claimCloneTarget(clonePath) await new Promise((resolve, reject) => { - const proc = wslAwareSpawn('git', ['clone', '--progress', '--', trimmedUrl, clonePath], { - cwd: trimmedDestination, - stdio: ['ignore', 'ignore', 'pipe'] - }) + let proc: ReturnType + try { + proc = wslAwareSpawn('git', ['clone', '--progress', '--', trimmedUrl, clonePath], { + cwd: trimmedDestination, + stdio: ['ignore', 'ignore', 'pipe'] + }) + } catch (err) { + void cleanupClaimedCloneTarget(clonePath, claimedTarget).finally(() => { + const message = err instanceof Error ? err.message : String(err) + reject(new Error(`Clone failed: ${message}`)) + }) + return + } let stderrTail = '' + let settled = false proc.stderr?.on('data', (chunk: Buffer) => { stderrTail = (stderrTail + chunk.toString()).slice(-4096) }) - proc.on('error', (error) => reject(new Error(`Clone failed: ${error.message}`))) - proc.on('close', (code, signal) => { - if (signal === 'SIGTERM') { + const finishClone = async ( + code: number | null, + signal: NodeJS.Signals | null, + error?: Error + ) => { + if (settled) { + return + } + settled = true + const cloneSucceeded = !error && code === 0 && !signal + if (!cloneSucceeded) { + await cleanupClaimedCloneTarget(clonePath, claimedTarget) + } + + if (error) { + reject(new Error(`Clone failed: ${error.message}`)) + } else if (signal === 'SIGTERM') { reject(new Error('Clone aborted')) } else if (code === 0) { resolve() @@ -5482,10 +5551,18 @@ export class OrcaRuntimeService { const lastLine = stderrTail.trim().split('\n').pop() ?? 'unknown error' reject(new Error(`Clone failed: ${lastLine}`)) } + } + proc.on('error', (error) => { + void finishClone(null, null, error) + }) + proc.on('close', (code, signal) => { + void finishClone(code, signal) }) }) - const existing = this.store.getRepos().find((repo) => runtimePathsEqual(repo.path, clonePath)) + const existing = this.store + .getRepos() + .find((repo) => getClonePathComparisonKey(repo.path) === clonePathKey) if (existing) { if (isFolderRepo(existing)) { const updated = this.store.updateRepo(existing.id, { kind: 'git' })