mirror of
https://github.com/stablyai/orca.git
synced 2026-11-02 18:17:36 +00:00
* fix(repos): reuse a saved project only when git shows it's this clone A saved project outlived its folder, so Clone reported success without running git. Fixes #23563 * fix(repos): let a repeat clone of an empty repository reuse its project A clone of a repository with no commits leaves HEAD unborn, which `rev-parse --verify HEAD` rejects exactly like the `refs/heads/.invalid` HEAD a killed clone leaves. The saved-project check read both as "not a finished clone", so cloning a brand-new empty repo a second time — a double-clicked Clone, a re-run `orca project setup-clone`, or #2981's queued retry — fell through to git and died on "destination path already exists and is not an empty directory". Ask the two questions apart when `--verify` fails: `symbolic-ref HEAD` resolves an unborn branch but not a killed clone's HEAD. It is already on the relay's read-only allowlist. Probes also short-circuit once the clone is cancelled, so no probe after Cancel spawns git. * fix(repos): prepare the worktree root after re-cloning a project's folder The branch that re-clones into a saved project's folder returned the project without the two steps every sibling branch runs: the worktree root that vanished with the deleted folder is never re-created, and the authorized-roots cache keeps the answers it cached while the folder was missing. Creating a worktree or reading files in the recovered project then fails on a root that is not there. * fix(ssh): register the root after re-cloning a saved project's folder `addRemoteRepoFromPath` returns an existing project before it notifies `session.registerRoot`, which was unreachable before the saved-project check could re-clone into a project's own path. The relay therefore never learned the folder came back, so sessions under it stayed unregistered. Notify from the clone, mirroring the folder-to-git upgrade beside it. * fix(repos): say which reason refused a clone over a saved project One message covered both "that project holds a different repository" and "Orca has no record of what that project held", which need different things from the user. Name the recorded URL when there is one, and say plainly that there is no record when there isn't — the second is the case a project predating remote-identity enrichment lands in, and the user cannot act on it without being told why. Also drops the `upstream` remote-name check into a named binding: `origin` is the only stored remote that names a project's own repo, because `Repo.upstream` and the GitHub avatar derived from it both name the repo a fork came from. * fix(repos): bound saved-clone probes and prove empty clone completion * fix(repos): keep clone validation host-scoped and locale independent --------- Co-authored-by: Neil <neil@stably.ai> Co-authored-by: Neil <4138956+nwparker@users.noreply.github.com>
204 lines
7.1 KiB
TypeScript
204 lines
7.1 KiB
TypeScript
import { randomUUID } from 'node:crypto'
|
|
import { mkdir } from 'node:fs/promises'
|
|
import { DEFAULT_REPO_BADGE_COLOR } from '../../shared/constants'
|
|
import {
|
|
getRepoSshConnectionId,
|
|
LOCAL_EXECUTION_HOST_ID,
|
|
type ExecutionHostId
|
|
} from '../../shared/execution-host'
|
|
import type { Repo } from '../../shared/repo-types'
|
|
import { getGitCloneFailureMessage } from '../../shared/git-clone-failure-message'
|
|
import {
|
|
cleanupClaimedCloneTarget,
|
|
claimCloneTarget,
|
|
deriveValidatedClonePath,
|
|
getClonePathComparisonKey
|
|
} from '../git/repo-clone-path'
|
|
import { gitSpawnAfterWindowsEnvironmentReady, promptGuardGitEnv } from '../git/runner'
|
|
import { reuseSavedCloneTarget } from '../git/saved-clone-target'
|
|
import { runWithGitReadCacheInvalidation } from '../git/status'
|
|
import { invalidateAuthorizedRootsCache } from '../ipc/filesystem-auth'
|
|
import { isFolderRepo } from '../../shared/repo-kind'
|
|
import { detectRepoIconAndUpstream } from '../repo-icon-autodetect'
|
|
import { getRepoName } from '../git/repo'
|
|
import { prepareLocalWorktreeRootForRepo } from '../worktree-root-preparation'
|
|
import type { RuntimeStore } from './runtime-store-contract'
|
|
import { runtimeRepoMatchesExecutionHost } from './runtime-worktree-selection'
|
|
|
|
type RuntimeRepositoryCloneDependencies = {
|
|
getStore: () => RuntimeStore | null
|
|
invalidateResolvedWorktrees: () => void
|
|
invalidateWorktreeScan: (repoId: string) => void
|
|
notifyReposChanged: () => void
|
|
}
|
|
|
|
export class RuntimeRepositoryCloneController {
|
|
private readonly inFlightByPath = new Map<string, Promise<void>>()
|
|
|
|
constructor(private readonly deps: RuntimeRepositoryCloneDependencies) {}
|
|
|
|
async clone(
|
|
url: string,
|
|
destination: string,
|
|
executionHostId?: ExecutionHostId | null
|
|
): Promise<Repo> {
|
|
if (!this.deps.getStore()) {
|
|
throw new Error('runtime_unavailable')
|
|
}
|
|
const trimmedUrl = url.trim()
|
|
const trimmedDestination = destination.trim()
|
|
if (!trimmedDestination) {
|
|
throw new Error('Clone destination is required')
|
|
}
|
|
const clonePath = deriveValidatedClonePath({ url: trimmedUrl, destination: trimmedDestination })
|
|
const clonePathKey = getClonePathComparisonKey(clonePath)
|
|
const previous = this.inFlightByPath.get(clonePathKey) ?? Promise.resolve()
|
|
let release!: () => void
|
|
const current = new Promise<void>((resolve) => {
|
|
release = resolve
|
|
})
|
|
const tail = previous.then(
|
|
() => current,
|
|
() => current
|
|
)
|
|
this.inFlightByPath.set(clonePathKey, tail)
|
|
try {
|
|
await previous
|
|
return await runWithGitReadCacheInvalidation(() =>
|
|
this.cloneAfterPathLock(
|
|
trimmedUrl,
|
|
trimmedDestination,
|
|
clonePath,
|
|
clonePathKey,
|
|
executionHostId
|
|
)
|
|
)
|
|
} finally {
|
|
release()
|
|
if (this.inFlightByPath.get(clonePathKey) === tail) {
|
|
this.inFlightByPath.delete(clonePathKey)
|
|
}
|
|
}
|
|
}
|
|
|
|
private async cloneAfterPathLock(
|
|
trimmedUrl: string,
|
|
trimmedDestination: string,
|
|
clonePath: string,
|
|
clonePathKey: string,
|
|
executionHostId?: ExecutionHostId | null
|
|
): Promise<Repo> {
|
|
const store = this.deps.getStore()
|
|
if (!store) {
|
|
throw new Error('runtime_unavailable')
|
|
}
|
|
// Why: git runs in this process, so an SSH project at the same path string is another machine's.
|
|
const findSaved = (): Repo | undefined =>
|
|
store.getRepos().find((repo) => {
|
|
return (
|
|
getClonePathComparisonKey(repo.path) === clonePathKey &&
|
|
runtimeRepoMatchesExecutionHost(repo, executionHostId) &&
|
|
!getRepoSshConnectionId(repo)
|
|
)
|
|
})
|
|
const reused = await reuseSavedCloneTarget(findSaved, trimmedUrl, LOCAL_EXECUTION_HOST_ID)
|
|
if (reused) {
|
|
return reused
|
|
}
|
|
|
|
await mkdir(trimmedDestination, { recursive: true })
|
|
const claimedTarget = await claimCloneTarget(clonePath)
|
|
let proc: Awaited<ReturnType<typeof gitSpawnAfterWindowsEnvironmentReady>>
|
|
try {
|
|
proc = await gitSpawnAfterWindowsEnvironmentReady(
|
|
['clone', '--progress', '--', trimmedUrl, clonePath],
|
|
{
|
|
cwd: trimmedDestination,
|
|
admissionTier: 'interactive',
|
|
env: promptGuardGitEnv(),
|
|
stdio: ['ignore', 'ignore', 'pipe']
|
|
}
|
|
)
|
|
} catch (error) {
|
|
await cleanupClaimedCloneTarget(clonePath, claimedTarget)
|
|
const message = error instanceof Error ? error.message : String(error)
|
|
throw new Error(`Clone failed: ${message}`)
|
|
}
|
|
await new Promise<void>((resolve, reject) => {
|
|
let stderrTail = ''
|
|
let settled = false
|
|
proc.stderr?.on('data', (chunk: Buffer) => {
|
|
stderrTail = (stderrTail + chunk.toString()).slice(-4096)
|
|
})
|
|
const finish = async (code: number | null, signal: NodeJS.Signals | null, error?: Error) => {
|
|
if (settled) {
|
|
return
|
|
}
|
|
settled = true
|
|
if (error || code !== 0 || signal) {
|
|
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()
|
|
} else {
|
|
reject(new Error(`Clone failed: ${getGitCloneFailureMessage(stderrTail, { clonePath })}`))
|
|
}
|
|
}
|
|
proc.on('error', (error) => void finish(null, null, error))
|
|
proc.on('close', (code, signal) => void finish(code, signal))
|
|
})
|
|
|
|
const existing = findSaved()
|
|
if (existing) {
|
|
if (isFolderRepo(existing)) {
|
|
const updated = store.updateRepo(existing.id, { kind: 'git' })
|
|
if (updated) {
|
|
await prepareLocalWorktreeRootForRepo(store, updated)
|
|
invalidateAuthorizedRootsCache()
|
|
this.invalidate(updated.id)
|
|
return updated
|
|
}
|
|
}
|
|
// Why: git re-created this project's folder, so its worktree root is gone with it and the
|
|
// authorized-roots cache still holds the answers from before the folder came back.
|
|
await prepareLocalWorktreeRootForRepo(store, existing)
|
|
invalidateAuthorizedRootsCache()
|
|
this.invalidate(existing.id)
|
|
return existing
|
|
}
|
|
// `cloneRepo` ran `git clone` in this process (see `assertCloneHostIsSupported`), so the
|
|
// checkout is here regardless of the host id stamped on the row.
|
|
const detected = await detectRepoIconAndUpstream({
|
|
repoPath: clonePath,
|
|
kind: 'git',
|
|
executionHostId: LOCAL_EXECUTION_HOST_ID
|
|
})
|
|
const repo: Repo = {
|
|
id: randomUUID(),
|
|
path: clonePath,
|
|
displayName: getRepoName(clonePath),
|
|
badgeColor: DEFAULT_REPO_BADGE_COLOR,
|
|
...(executionHostId != null ? { executionHostId } : {}),
|
|
...detected,
|
|
addedAt: Date.now(),
|
|
kind: 'git',
|
|
externalWorktreeVisibilityLegacy: false
|
|
}
|
|
store.addRepo(repo)
|
|
await prepareLocalWorktreeRootForRepo(store, repo)
|
|
invalidateAuthorizedRootsCache()
|
|
this.invalidate(repo.id)
|
|
return store.getRepo(repo.id) ?? repo
|
|
}
|
|
|
|
private invalidate(repoId: string): void {
|
|
this.deps.invalidateResolvedWorktrees()
|
|
this.deps.invalidateWorktreeScan(repoId)
|
|
this.deps.notifyReposChanged()
|
|
}
|
|
}
|