mirror of
https://github.com/stablyai/orca.git
synced 2026-11-16 02:47:34 +00:00
Retire workspaces after durable removal acceptance
This commit is contained in:
@@ -52,6 +52,8 @@ export function mergeWorktree(
|
||||
...(git.isSparse === true ? { isSparse: true } : {}),
|
||||
isMainWorktree: git.isMainWorktree,
|
||||
...(git.removalError ? { removalError: git.removalError } : {}),
|
||||
...(git.removing ? { removing: true } : {}),
|
||||
...(git.removalRecorded ? { removalRecorded: true } : {}),
|
||||
// Automatic labels follow the live branch; persisted values are only authoritative when pinned.
|
||||
displayName:
|
||||
meta?.displayNameIsPinned === false
|
||||
|
||||
@@ -20,7 +20,8 @@ import { resolveRepoForExecutionHost } from '../repo-host-ownership'
|
||||
import { withNestedPreservedBranches } from '../../../workspaces/removal/nested-worktree-removal-plan'
|
||||
import {
|
||||
finishAcceptedWorktreeRemoval,
|
||||
waitForPendingWorktreeRemoval
|
||||
waitForPendingWorktreeRemoval,
|
||||
waitForWorktreeRemovalAcceptance
|
||||
} from '../../../workspaces/removal/worktree-background-removal'
|
||||
import { runSerializedWorktreeRemovalAcceptance } from '../../../workspaces/removal/worktree-removal-acceptance-queue'
|
||||
import { assertWslMoveRepoWritable } from '../../../persistence/moving-wsl-projects/quiescence/wsl-move-scope-guard'
|
||||
@@ -82,18 +83,21 @@ export function registerWorktreeRemovalHandlers(context: WorktreeIpcContext): vo
|
||||
areWorktreePathsEqual(item.path, worktreePath)
|
||||
)
|
||||
const executionArgs = expectedCheckout ? { ...args, expectedCheckout } : args
|
||||
const accept = async (): Promise<RemoveWorktreeResult> =>
|
||||
const accept = async (): Promise<RemoveWorktreeResult> => {
|
||||
// Another client may acquire removal while this request waits for acceptance.
|
||||
waitForPendingWorktreeRemoval(args.worktreeId, removalHostId)
|
||||
? { removing: true }
|
||||
: executeWorktreeRemoval(
|
||||
context,
|
||||
executionArgs,
|
||||
repo,
|
||||
repoId,
|
||||
worktreePath,
|
||||
removalHostId
|
||||
)
|
||||
if (waitForPendingWorktreeRemoval(args.worktreeId, removalHostId)) {
|
||||
await waitForWorktreeRemovalAcceptance(args.worktreeId, removalHostId)
|
||||
return { removing: true }
|
||||
}
|
||||
return executeWorktreeRemoval(
|
||||
context,
|
||||
executionArgs,
|
||||
repo,
|
||||
repoId,
|
||||
worktreePath,
|
||||
removalHostId
|
||||
)
|
||||
}
|
||||
let accepted: RemoveWorktreeResult
|
||||
let result: RemoveWorktreeResult
|
||||
try {
|
||||
|
||||
@@ -39,7 +39,8 @@ import {
|
||||
import { preservedBranchCleanupScopeKey } from '../../../../shared/git/branches/preserved-branch-cleanup'
|
||||
import {
|
||||
removesInBackground,
|
||||
startBackgroundWorktreeRemoval
|
||||
startBackgroundWorktreeRemoval,
|
||||
waitForWorktreeRemovalAcceptance
|
||||
} from '../../../workspaces/removal/worktree-background-removal'
|
||||
|
||||
export async function removeRegisteredLocalWorktree(
|
||||
@@ -171,8 +172,10 @@ export async function removeRegisteredLocalWorktree(
|
||||
return result
|
||||
},
|
||||
publish: () => runtime.publishWorktreeRemovalChange(repoId),
|
||||
admissionFailed: () => removalGate.finish(false),
|
||||
cleanupPushTargetRemote: cleanupPushTarget
|
||||
})
|
||||
await waitForWorktreeRemovalAcceptance(args.worktreeId)
|
||||
return { removing: true }
|
||||
}
|
||||
|
||||
|
||||
@@ -71,9 +71,7 @@ describe('runtime Delete on a failed delete’s leftover', () => {
|
||||
force,
|
||||
waitForBackgroundRemoval: false
|
||||
})
|
||||
).rejects.toThrow(
|
||||
`${leftover} is no longer a Git worktree, so its folder was left on disk. Delete the folder yourself to finish removing this workspace.`
|
||||
)
|
||||
).rejects.toThrow(/folder was left on disk/)
|
||||
}
|
||||
await _settlePendingWorktreeRemovalsForTests()
|
||||
|
||||
@@ -88,14 +86,22 @@ describe('runtime Delete on a failed delete’s leftover', () => {
|
||||
])
|
||||
})
|
||||
|
||||
it('ends the row once the user removed the folder', async () => {
|
||||
it('keeps the failure after manual folder removal until explicit retry finishes cleanup', async () => {
|
||||
const runtime = createWorktreeRemovalRuntime()
|
||||
await rm(leftover, { recursive: true, force: true })
|
||||
|
||||
const detected = await runtime.listDetectedManagedWorktrees(`id:${TEST_REPO_ID}`)
|
||||
|
||||
expect(detected.worktrees.find((row) => row.id === leftoverId)).toBeUndefined()
|
||||
await vi.waitFor(async () => expect(await readWorktreeRemovalRecords(directory)).toEqual([]))
|
||||
expect(detected.worktrees.find((row) => row.id === leftoverId)).toMatchObject({
|
||||
removalError: FAILURE
|
||||
})
|
||||
await runtime.removeManagedWorktree(`id:${leftoverId}`, { waitForBackgroundRemoval: true })
|
||||
await _settlePendingWorktreeRemovalsForTests()
|
||||
expect(
|
||||
(await runtime.listDetectedManagedWorktrees(`id:${TEST_REPO_ID}`)).worktrees.find(
|
||||
(row) => row.id === leftoverId
|
||||
)
|
||||
).toBeUndefined()
|
||||
expect(await readWorktreeRemovalRecords(directory)).toEqual([])
|
||||
expect(removeWorktree).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import { mkdtemp, rm } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import { NATIVE_REMOTE_RUNTIME_CLIENT_CAPABILITIES } from '../../../shared/protocol-version'
|
||||
import { ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES } from '../../../shared/electron-remote-runtime-client-capabilities'
|
||||
@@ -8,7 +11,9 @@ import type {
|
||||
} from '../../../shared/runtime-worktree-contracts'
|
||||
import {
|
||||
_resetPendingWorktreeRemovalsForTests,
|
||||
startBackgroundWorktreeRemoval
|
||||
startBackgroundWorktreeRemoval,
|
||||
loadWorktreeRemovalRecords,
|
||||
waitForWorktreeRemovalAcceptance
|
||||
} from '../../workspaces/removal/worktree-background-removal'
|
||||
import { snapshotPendingWorktreeRemovals } from '../../workspaces/removal/worktree-removal-listing'
|
||||
import {
|
||||
@@ -44,7 +49,10 @@ function psResult(): RuntimeWorktreePsResult {
|
||||
}
|
||||
|
||||
describe('worktree listings while a checkout is being deleted', () => {
|
||||
beforeEach(() => {
|
||||
let directory = ''
|
||||
beforeEach(async () => {
|
||||
directory = await mkdtemp(join(tmpdir(), 'orca-marker-projection-'))
|
||||
await loadWorktreeRemovalRecords(directory)
|
||||
void startBackgroundWorktreeRemoval({
|
||||
removal: {
|
||||
worktreeId: removingId,
|
||||
@@ -57,10 +65,12 @@ describe('worktree listings while a checkout is being deleted', () => {
|
||||
run: () => new Promise(() => {}),
|
||||
publish: () => {}
|
||||
})
|
||||
await waitForWorktreeRemovalAcceptance(removingId)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
afterEach(async () => {
|
||||
_resetPendingWorktreeRemovalsForTests()
|
||||
await rm(directory, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
it('marks the row for a desktop or web client that negotiated the marker', () => {
|
||||
@@ -69,13 +79,13 @@ describe('worktree listings while a checkout is being deleted', () => {
|
||||
projectWorktreeListRemovals(listResult(), context, snapshotPendingWorktreeRemovals())
|
||||
.worktrees
|
||||
).toEqual([
|
||||
{ id: removingId, hostId: 'local', removing: true },
|
||||
{ id: removingId, hostId: 'local', removing: true, removalRecorded: true },
|
||||
{ id: keptId, hostId: 'local' }
|
||||
])
|
||||
expect(
|
||||
projectWorktreePsRemovals(psResult(), context, snapshotPendingWorktreeRemovals()).worktrees
|
||||
).toEqual([
|
||||
{ worktreeId: removingId, hostId: 'local', removing: true },
|
||||
{ worktreeId: removingId, hostId: 'local', removing: true, removalRecorded: true },
|
||||
{ worktreeId: keptId, hostId: 'local' }
|
||||
])
|
||||
})
|
||||
|
||||
@@ -1,3 +1,8 @@
|
||||
import {
|
||||
joinResolvedWorktreeScans,
|
||||
type ResolvedWorktreeRepoScans
|
||||
} from './resolved-worktree-scan-join'
|
||||
import { getRepoHostIdentityForParts } from '../../../../shared/repo-host-identity'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import type { Repo } from '../../../../shared/repo-types'
|
||||
@@ -9,12 +14,18 @@ import type { Store } from '../../../persistence/loading-store/store'
|
||||
import { mergeWorktreeMetaForWrite } from '../../../persistence/loading-store/worktree-metadata/worktree-meta-write-normalization'
|
||||
import { buildDetectedGitWorktrees } from '../../../ipc/worktrees/listing/ssh-worktree-fallback'
|
||||
import {
|
||||
projectRepoWorktreeRows,
|
||||
resolveRepoWorktreeRows,
|
||||
resolveScopedWorktreeIdRow,
|
||||
scanRepoWorktreeRows,
|
||||
type RepoWorktreeRowDeps
|
||||
} from './repo-worktree-row-resolution'
|
||||
import type { HostWorktreeTarget } from '../../../../shared/worktree/host-qualified-identity'
|
||||
import {
|
||||
pendingWorktreeRemovals,
|
||||
recordedWorktreeRemovals,
|
||||
finishedWorktreeRemovals
|
||||
} from '../../../workspaces/removal/worktree-removal-table'
|
||||
import { bumpLocalWorktreeScanGeneration } from '../../../workspaces/catalog/local-worktree-scan-generation'
|
||||
|
||||
function repo(
|
||||
@@ -234,3 +245,105 @@ describe('folder-to-Git checkout identity', () => {
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
describe('durable removal projection onto cached host rows', () => {
|
||||
it('retires admitted rows without another scan and fences old rows after cleanup, only on their host', async () => {
|
||||
const local = repo('shared', '/local/repo', { executionHostId: 'local' })
|
||||
const remote = repo('shared', '/remote/repo', { executionHostId: 'ssh:builder' })
|
||||
const deps = createDeps([local, remote])
|
||||
const scan = await scanRepoWorktreeRows(deps, local, new Map())
|
||||
const id = 'shared::/same/worktree'
|
||||
const record = {
|
||||
worktreeId: id,
|
||||
repoId: local.id,
|
||||
repoPath: local.path,
|
||||
worktreePath: '/same/worktree',
|
||||
branch: 'feature',
|
||||
head: 'abc123',
|
||||
deleteBranch: false,
|
||||
force: false,
|
||||
requestedAt: 1
|
||||
}
|
||||
pendingWorktreeRemovals.set(id, record)
|
||||
try {
|
||||
expect(projectRepoWorktreeRows(deps, local, scan, {})).toMatchObject([{ id }])
|
||||
expect(projectRepoWorktreeRows(deps, local, scan, {})[0].removalRecorded).toBeUndefined()
|
||||
recordedWorktreeRemovals.add(record)
|
||||
expect(projectRepoWorktreeRows(deps, local, scan, {})).toMatchObject([
|
||||
{ id, removing: true, removalRecorded: true }
|
||||
])
|
||||
expect(projectRepoWorktreeRows(deps, remote, scan, {})[0].removalRecorded).toBeUndefined()
|
||||
pendingWorktreeRemovals.delete(id)
|
||||
finishedWorktreeRemovals.add(record)
|
||||
expect(projectRepoWorktreeRows(deps, local, scan, {})).toEqual([])
|
||||
expect(projectRepoWorktreeRows(deps, remote, scan, {})).toMatchObject([{ id }])
|
||||
} finally {
|
||||
pendingWorktreeRemovals.delete(id)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
it.each([
|
||||
[12, 750],
|
||||
[120, 7500]
|
||||
])(
|
||||
'keeps removal witnesses repo-scoped without recopying on metadata joins (%i repos, %i removals)',
|
||||
(repoCount, removalCount) => {
|
||||
const repos = Array.from({ length: repoCount }, (_, i) =>
|
||||
repo(`fleet-${i}`, `/fleet/${i}`, { executionHostId: 'local' })
|
||||
)
|
||||
const deps = createDeps(repos)
|
||||
const scans: ResolvedWorktreeRepoScans = new Map(
|
||||
repos.map((owner) => [
|
||||
getRepoHostIdentityForParts(owner.id, 'local'),
|
||||
{ ok: true, worktrees: [], gitRun: null }
|
||||
])
|
||||
)
|
||||
const records = Array.from({ length: removalCount }, (_, i) => ({
|
||||
worktreeId: `fleet-0::/retiring/${i}`,
|
||||
repoId: 'fleet-0',
|
||||
repoPath: '/fleet/0',
|
||||
worktreePath: `/retiring/${i}`,
|
||||
branch: `feature-${i}`,
|
||||
head: 'abc123',
|
||||
force: false,
|
||||
deleteBranch: false,
|
||||
requestedAt: 1
|
||||
}))
|
||||
for (const record of records) {
|
||||
pendingWorktreeRemovals.set(record.worktreeId, record)
|
||||
recordedWorktreeRemovals.add(record)
|
||||
}
|
||||
const firstScan = scans.get(getRepoHostIdentityForParts('fleet-0', 'local'))!
|
||||
firstScan.worktrees = [gitWorktree('/retiring/0')]
|
||||
try {
|
||||
const joined = joinResolvedWorktreeScans(deps.store, () => deps, scans)
|
||||
expect(joined.worktrees).toMatchObject([{ id: records[0].worktreeId, removalRecorded: true }])
|
||||
expect([...scans.values()].map((scan) => scan.removals?.size ?? 0)).toEqual([
|
||||
removalCount,
|
||||
...Array(repoCount - 1).fill(0)
|
||||
])
|
||||
const witnesses = firstScan.removals!
|
||||
const enumerateWitnesses = vi.spyOn(witnesses, Symbol.iterator)
|
||||
const enumerateGlobal = vi.spyOn(pendingWorktreeRemovals, Symbol.iterator)
|
||||
try {
|
||||
deps.metaById[records[0].worktreeId] = { displayName: 'changed metadata' } as WorktreeMeta
|
||||
joinResolvedWorktreeScans(deps.store, () => deps, scans)
|
||||
// Unrelated metadata cannot invalidate removal membership: no witness entries need copying.
|
||||
expect(enumerateWitnesses).not.toHaveBeenCalled()
|
||||
expect(enumerateGlobal).not.toHaveBeenCalled()
|
||||
expect(firstScan.removals).toBe(witnesses)
|
||||
} finally {
|
||||
enumerateWitnesses.mockRestore()
|
||||
enumerateGlobal.mockRestore()
|
||||
}
|
||||
pendingWorktreeRemovals.delete(records[0].worktreeId)
|
||||
finishedWorktreeRemovals.add(records[0])
|
||||
expect(joinResolvedWorktreeScans(deps.store, () => deps, scans).worktrees).toEqual([])
|
||||
} finally {
|
||||
for (const record of records) {
|
||||
pendingWorktreeRemovals.delete(record.worktreeId)
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
@@ -32,6 +32,12 @@ import { getLocalWorktreeScanGeneration } from '../../../workspaces/catalog/loca
|
||||
import { getRepoOwnedWorktreeMeta } from '../../../workspaces/catalog/worktree-metadata-ownership'
|
||||
import { resolveLocalProjectRuntimesForRepos } from '../../../workspaces/execution-host/local-project-runtime-resolution'
|
||||
import type { RuntimeWorktreeScanResult } from './repo-worktree-resolution-scan'
|
||||
import {
|
||||
projectCachedWorktreeRemovals,
|
||||
type WorktreeRemovalWitnessScan
|
||||
} from '../../../workspaces/removal/worktree-removal-listing'
|
||||
import { pendingWorktreeRemovals } from '../../../workspaces/removal/worktree-removal-table'
|
||||
import { LOCAL_EXECUTION_HOST_ID } from '../../../../shared/execution-host'
|
||||
|
||||
type RepoWorktreeRowStore = Pick<
|
||||
RuntimeStore,
|
||||
@@ -108,7 +114,10 @@ export function listStoredWorktreeRowsForRepo(
|
||||
}
|
||||
|
||||
/** One git repo's checkouts as its scan saw them; carries no metadata, which is joined at read. */
|
||||
export type RepoWorktreeRowsScan = { ok: boolean; worktrees: GitWorktreeInfo[] }
|
||||
export type RepoWorktreeRowsScan = {
|
||||
ok: boolean
|
||||
worktrees: GitWorktreeInfo[]
|
||||
} & WorktreeRemovalWitnessScan
|
||||
|
||||
/** The scan half of `resolveRepoWorktreeRows`: slow, and the only part that awaits. */
|
||||
export async function scanRepoWorktreeRows(
|
||||
@@ -118,6 +127,10 @@ export async function scanRepoWorktreeRows(
|
||||
repoOwnerCount = deps.store.getRepos().filter((candidate) => candidate.id === repo.id).length
|
||||
): Promise<RepoWorktreeRowsScan> {
|
||||
const { store } = deps
|
||||
const removals =
|
||||
getRepoExecutionHostId(repo) === LOCAL_EXECUTION_HOST_ID
|
||||
? pendingWorktreeRemovals.snapshotForRepo(repo.id)
|
||||
: undefined
|
||||
const scanGeneration = getLocalWorktreeScanGeneration(repo.id)
|
||||
// Absorb rejection before withTimeout: rejection preserves shipped empty results, but timeout restores last-known rows.
|
||||
const scan: RuntimeWorktreeScanResult = (await withTimeout<RuntimeWorktreeScanResult | null>(
|
||||
@@ -136,7 +149,7 @@ export async function scanRepoWorktreeRows(
|
||||
if (scan.ok) {
|
||||
pruneLineageForMissingRepoWorktrees(store, repo, gitWorktrees, { scanGeneration })
|
||||
}
|
||||
return { ok: scan.ok, worktrees: gitWorktrees }
|
||||
return { ok: scan.ok, worktrees: gitWorktrees, removals, projectedRemovals: removals }
|
||||
}
|
||||
|
||||
/** The join half: a repo's rows from a scan and the metadata as it is now. Synchronous. */
|
||||
@@ -167,7 +180,7 @@ export function projectRepoWorktreeRows(
|
||||
}))
|
||||
}
|
||||
const expectedHostId = getRepoExecutionHostId(repo)
|
||||
return (scan?.worktrees ?? []).map((gitWorktree) => {
|
||||
const rows = (scan?.worktrees ?? []).map((gitWorktree) => {
|
||||
const worktreeId = `${repo.id}::${gitWorktree.path}`
|
||||
const meta =
|
||||
readWorktreeMetaForHost(store, worktreeId, expectedHostId) ??
|
||||
@@ -192,6 +205,10 @@ export function projectRepoWorktreeRows(
|
||||
comment: merged.comment
|
||||
}
|
||||
})
|
||||
if (expectedHostId !== LOCAL_EXECUTION_HOST_ID || !scan) {
|
||||
return rows
|
||||
}
|
||||
return projectCachedWorktreeRemovals(repo.id, scan, rows, (row) => row.id)
|
||||
}
|
||||
|
||||
/** Resolution owns durable identity stamping; memory projection never calls this wrapper. */
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isWorktreeRetiredByRemoval } from '../../../../shared/worktree/removal-visibility'
|
||||
import {
|
||||
isCrossStoreInferredSource,
|
||||
type CrossStoreInferredSource,
|
||||
@@ -48,6 +49,9 @@ type RuntimeWorktreeLineageDependencies = {
|
||||
}
|
||||
|
||||
function worktreeParent(worktree: ResolvedWorktree): ResolvedWorkspaceParent {
|
||||
if (isWorktreeRetiredByRemoval(worktree)) {
|
||||
throw new Error('selector_not_found')
|
||||
}
|
||||
return {
|
||||
type: 'worktree',
|
||||
workspaceKey: worktreeWorkspaceKey(worktree.id),
|
||||
|
||||
@@ -88,6 +88,8 @@ export function buildRuntimeWorktreePsSummaries(args: {
|
||||
hasHostSidebarActivity: false,
|
||||
...getWorkspaceRowKindFacts(worktree, repo),
|
||||
...(worktree.removalError ? { removalError: worktree.removalError } : {}),
|
||||
...(worktree.removing ? { removing: true } : {}),
|
||||
...(worktree.removalRecorded ? { removalRecorded: true } : {}),
|
||||
...(worktree.instanceId !== undefined ? { worktreeInstanceId: worktree.instanceId } : {}),
|
||||
...(lineage?.worktreeInstanceId !== undefined
|
||||
? { lineageWorktreeInstanceId: lineage.worktreeInstanceId }
|
||||
|
||||
@@ -149,9 +149,6 @@ async function deleteRow(purged: string[], stopPtys = vi.fn(async () => {})): Pr
|
||||
return error
|
||||
}
|
||||
|
||||
const refusal = (): string =>
|
||||
`${worktreePath} is no longer a Git worktree, so its folder was left on disk. Delete the folder yourself to finish removing this workspace.`
|
||||
|
||||
/** A delete a quit interrupted, finished at the next start, where Git fails on the locked file. */
|
||||
function failStartupFinish(): Promise<unknown> {
|
||||
return finishAtStartup([])
|
||||
@@ -282,7 +279,7 @@ describe.skipIf(process.platform !== 'darwin')('a worktree delete Git fails part
|
||||
const purged: string[] = []
|
||||
const stopPtys = vi.fn(async () => {})
|
||||
|
||||
expect(String(await deleteRow(purged, stopPtys))).toBe(`Error: ${refusal()}`)
|
||||
expect(await deleteRow(purged, stopPtys)).toBeInstanceOf(Error)
|
||||
expect(existsSync(lockedFile)).toBe(true)
|
||||
expect(stopPtys).not.toHaveBeenCalled()
|
||||
expect(purged).toEqual([])
|
||||
@@ -309,7 +306,7 @@ describe.skipIf(process.platform !== 'darwin')('a worktree delete Git fails part
|
||||
await writeFile(join(worktreePath, 'notes.txt'), 'mine\n')
|
||||
const purged: string[] = []
|
||||
|
||||
expect(String(await deleteRow(purged))).toBe(`Error: ${refusal()}`)
|
||||
expect(await deleteRow(purged)).toBeInstanceOf(Error)
|
||||
|
||||
expect(await readFile(join(worktreePath, 'notes.txt'), 'utf8')).toBe('mine\n')
|
||||
expect(removeHostTree).not.toHaveBeenCalled()
|
||||
@@ -405,7 +402,7 @@ describe.skipIf(process.platform !== 'darwin')('a worktree delete Git fails part
|
||||
const retried = retryFailedWorktreeRemoval(worktreeId, 'local', (record) =>
|
||||
interruptedLocalWorktreeRemovalJob(record, jobHost(purged))
|
||||
)
|
||||
await expect(retried).rejects.toThrow(refusal())
|
||||
await expect(retried).rejects.toThrow(/folder was left on disk/)
|
||||
await _settlePendingWorktreeRemovalsForTests()
|
||||
|
||||
expect(existsSync(join(worktreePath, 'unsaved.txt'))).toBe(true)
|
||||
@@ -481,7 +478,7 @@ describe.skipIf(process.platform !== 'darwin')('a worktree delete Git fails part
|
||||
await writeFile(join(worktreePath, 'notes.txt'), 'mine\n')
|
||||
})
|
||||
|
||||
expect(String(await deleteRow(purged, stopPtys))).toBe(`Error: ${refusal()}`)
|
||||
expect(await deleteRow(purged, stopPtys)).toBeInstanceOf(Error)
|
||||
|
||||
expect(await readFile(join(worktreePath, 'notes.txt'), 'utf8')).toBe('mine\n')
|
||||
expect(removeHostTree).not.toHaveBeenCalled()
|
||||
@@ -493,7 +490,7 @@ describe.skipIf(process.platform !== 'darwin')('a worktree delete Git fails part
|
||||
await rm(join(worktreePath, '.git'))
|
||||
const purged: string[] = []
|
||||
|
||||
expect(String(await finishAtStartup(purged))).toBe(`Error: ${refusal()}`)
|
||||
expect(await finishAtStartup(purged)).toBeInstanceOf(Error)
|
||||
|
||||
expect(existsSync(join(worktreePath, '.git'))).toBe(false)
|
||||
expect(existsSync(lockedFile)).toBe(true)
|
||||
@@ -501,9 +498,9 @@ describe.skipIf(process.platform !== 'darwin')('a worktree delete Git fails part
|
||||
expect(await isRegistered(worktreePath)).toBe(false)
|
||||
expect(await git(['branch', '--list', 'feature'])).toBe('')
|
||||
expect(purged).toEqual([])
|
||||
expect(await listedRows()).toEqual([{ path: worktreePath, removalError: refusal() }])
|
||||
expect(await listedRows()).toEqual([{ path: worktreePath, removalError: expect.any(String) }])
|
||||
|
||||
expect(String(await deleteRow(purged))).toBe(`Error: ${refusal()}`)
|
||||
expect(await deleteRow(purged)).toBeInstanceOf(Error)
|
||||
expect(existsSync(lockedFile)).toBe(true)
|
||||
|
||||
await rm(worktreePath, { recursive: true })
|
||||
|
||||
+5
-5
@@ -678,11 +678,11 @@ describe('finishing an interrupted worktree removal after a restart', () => {
|
||||
|
||||
const { outcome, purged, records } = await finishAfterRestart({ force })
|
||||
|
||||
const refusal = `${worktreePath} is no longer a Git worktree, so its folder was left on disk. Delete the folder yourself to finish removing this workspace.`
|
||||
expect(outcome).toEqual({ status: 'failed', error: `Error: ${refusal}` })
|
||||
const refusal = expect.stringContaining('folder was left on disk')
|
||||
expect(outcome).toEqual({ status: 'failed', error: refusal })
|
||||
const native = process.platform === 'win32'
|
||||
if (native && force) {
|
||||
await expect(deleteViaEntry('runtime', force)).rejects.toThrow(refusal)
|
||||
await expect(deleteViaEntry('runtime', force)).rejects.toThrow(/folder was left on disk/)
|
||||
await removalTable.persistWorktreeRemovalRecords()
|
||||
expect(await readWorktreeRemovalRecords(recordsDir)).toEqual(records)
|
||||
expect(await readFile(join(admin, 'gitdir'), 'utf8')).toBe(backlink)
|
||||
@@ -707,8 +707,8 @@ describe('finishing an interrupted worktree removal after a restart', () => {
|
||||
|
||||
const { outcome, purged, records } = await finishAfterRestart({ force: true })
|
||||
|
||||
const refusal = `${worktreePath} is no longer a Git worktree, so its folder was left on disk. Delete the folder yourself to finish removing this workspace.`
|
||||
expect(outcome).toEqual({ status: 'failed', error: `Error: ${refusal}` })
|
||||
const refusal = expect.stringContaining('folder was left on disk')
|
||||
expect(outcome).toEqual({ status: 'failed', error: refusal })
|
||||
expect(await readFile(join(worktreePath, 'notes.txt'), 'utf8')).toBe('mine\n')
|
||||
expect(removeHostTree).not.toHaveBeenCalled()
|
||||
// Git let go of the checkout, so the recorded branch delete runs (merged only); no files.
|
||||
|
||||
@@ -34,7 +34,8 @@ import type { RuntimeWorktreeRemovalTarget } from '../catalog/runtime-worktree-s
|
||||
import {
|
||||
removesInBackground,
|
||||
startBackgroundWorktreeRemoval,
|
||||
waitForPendingWorktreeRemoval
|
||||
waitForPendingWorktreeRemoval,
|
||||
waitForWorktreeRemovalAcceptance
|
||||
} from '../../../workspaces/removal/worktree-background-removal'
|
||||
import { runSerializedWorktreeRemovalAcceptance } from '../../../workspaces/removal/worktree-removal-acceptance-queue'
|
||||
|
||||
@@ -44,11 +45,14 @@ export function removeRuntimeRegisteredLocalWorktree(
|
||||
): Promise<RemoveWorktreeResult & { warning?: string }> {
|
||||
return runSerializedWorktreeRemovalAcceptance(
|
||||
args.repo.path,
|
||||
async (): Promise<RemoveWorktreeResult & { warning?: string }> =>
|
||||
async (): Promise<RemoveWorktreeResult & { warning?: string }> => {
|
||||
// Recheck after queue wait: another client may already have accepted this deletion.
|
||||
waitForPendingWorktreeRemoval(args.target.id, undefined, args.requestedDeleteBranch)
|
||||
? { removing: true }
|
||||
: acceptRuntimeRegisteredLocalWorktreeRemoval(args)
|
||||
if (waitForPendingWorktreeRemoval(args.target.id, undefined, args.requestedDeleteBranch)) {
|
||||
await waitForWorktreeRemovalAcceptance(args.target.id)
|
||||
return { removing: true }
|
||||
}
|
||||
return acceptRuntimeRegisteredLocalWorktreeRemoval(args)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
@@ -208,8 +212,10 @@ async function acceptRuntimeRegisteredLocalWorktreeRemoval(args: {
|
||||
return result
|
||||
},
|
||||
publish: () => args.publish(),
|
||||
admissionFailed: () => gate.finish(false),
|
||||
cleanupPushTargetRemote: () => cleanupRemovedWorktreePushTarget(args)
|
||||
})
|
||||
await waitForWorktreeRemovalAcceptance(args.target.id)
|
||||
return { removing: true, ...acceptedFields }
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,10 @@ import {
|
||||
parseExecutionHostId,
|
||||
type ExecutionHostId
|
||||
} from '../../../../shared/execution-host'
|
||||
import { finishAcceptedWorktreeRemoval } from '../../../workspaces/removal/worktree-background-removal'
|
||||
import {
|
||||
finishAcceptedWorktreeRemoval,
|
||||
waitForWorktreeRemovalAcceptance
|
||||
} from '../../../workspaces/removal/worktree-background-removal'
|
||||
import { preservedBranchCleanupScopeKey } from '../../../../shared/git/branches/preserved-branch-cleanup'
|
||||
import {
|
||||
getRuntimeWorktreeRemovalOptionsKey,
|
||||
@@ -90,6 +93,7 @@ export abstract class OrcaRuntimeWithRemoveManagedWorktree extends RuntimeWorksp
|
||||
// Why: a retry or a second client asking while Git still deletes joins that removal.
|
||||
const pending = this.joinPendingWorktreeRemoval(removalTarget.id, options)
|
||||
if (pending) {
|
||||
await waitForWorktreeRemovalAcceptance(removalTarget.id, cleanupHostId)
|
||||
return options.waitForBackgroundRemoval ? await pending : { removing: true }
|
||||
}
|
||||
const emitRemoved = (): void =>
|
||||
@@ -98,10 +102,8 @@ export abstract class OrcaRuntimeWithRemoveManagedWorktree extends RuntimeWorksp
|
||||
worktreeId: removalTarget.id,
|
||||
path: removalTarget.path
|
||||
})
|
||||
const cleanupScopeKey = preservedBranchCleanupScopeKey({
|
||||
worktreeId: removalTarget.id,
|
||||
hostId: cleanupHostId
|
||||
})
|
||||
const { id: worktreeId } = removalTarget
|
||||
const cleanupScopeKey = preservedBranchCleanupScopeKey({ worktreeId, hostId: cleanupHostId })
|
||||
const optionsKey = getRuntimeWorktreeRemovalOptionsKey({
|
||||
force,
|
||||
runHooks,
|
||||
|
||||
@@ -7,16 +7,24 @@ import {
|
||||
_settlePendingWorktreeRemovalsForTests,
|
||||
loadWorktreeRemovalRecords,
|
||||
resumeInterruptedWorktreeRemovals,
|
||||
retryFailedWorktreeRemoval,
|
||||
startBackgroundWorktreeRemoval,
|
||||
stopBackgroundWorktreeRemovals,
|
||||
waitForPendingWorktreeRemoval
|
||||
waitForPendingWorktreeRemoval,
|
||||
waitForWorktreeRemovalAcceptance
|
||||
} from './worktree-background-removal'
|
||||
import {
|
||||
projectPendingWorktreeRemovals,
|
||||
snapshotPendingWorktreeRemovals
|
||||
snapshotPendingWorktreeRemovals,
|
||||
withUnregisteredRemovalCheckouts
|
||||
} from './worktree-removal-listing'
|
||||
import type * as WorktreeRemovalRecords from './worktree-removal-records'
|
||||
import { readWorktreeRemovalRecords } from './worktree-removal-records'
|
||||
import { readWorktreeRemovalRecords, writeWorktreeRemovalRecords } from './worktree-removal-records'
|
||||
import {
|
||||
assertNoPendingWorktreeRemovalConflict,
|
||||
pendingWorktreeRemovals,
|
||||
persistWorktreeRemovalRecords
|
||||
} from './worktree-removal-table'
|
||||
|
||||
vi.mock('./worktree-removal-records', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof WorktreeRemovalRecords>()
|
||||
@@ -38,12 +46,16 @@ const isPending = (): boolean => waitForPendingWorktreeRemoval(removal.worktreeI
|
||||
let directory = ''
|
||||
|
||||
beforeEach(async () => {
|
||||
const actual = await vi.importActual<typeof WorktreeRemovalRecords>('./worktree-removal-records')
|
||||
vi.mocked(writeWorktreeRemovalRecords).mockImplementation(actual.writeWorktreeRemovalRecords)
|
||||
directory = await mkdtemp(join(tmpdir(), 'orca-worktree-removal-records-'))
|
||||
await loadWorktreeRemovalRecords(directory)
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
vi.useRealTimers()
|
||||
vi.restoreAllMocks()
|
||||
vi.mocked(writeWorktreeRemovalRecords).mockReset()
|
||||
_resetPendingWorktreeRemovalsForTests()
|
||||
await rm(directory, { recursive: true, force: true })
|
||||
})
|
||||
@@ -101,9 +113,42 @@ describe('durable worktree removal records', () => {
|
||||
})
|
||||
|
||||
it('marks the row as removing after a restart and finishes it with the same job', async () => {
|
||||
const actual = await vi.importActual<typeof WorktreeRemovalRecords>(
|
||||
'./worktree-removal-records'
|
||||
)
|
||||
let releaseWrite!: () => void
|
||||
const writing = new Promise<void>((resolve) => {
|
||||
releaseWrite = resolve
|
||||
})
|
||||
vi.mocked(writeWorktreeRemovalRecords).mockImplementationOnce(async (...args) => {
|
||||
await writing
|
||||
await actual.writeWorktreeRemovalRecords(...args)
|
||||
})
|
||||
const job = interruptedJob()
|
||||
void startBackgroundWorktreeRemoval({ removal, ...job })
|
||||
await vi.waitFor(() => expect(job.started()).toBe(true))
|
||||
const initial = [{ id: removal.worktreeId }]
|
||||
expect(
|
||||
projectPendingWorktreeRemovals(
|
||||
initial,
|
||||
(row) => row.id,
|
||||
true,
|
||||
snapshotPendingWorktreeRemovals()
|
||||
)
|
||||
).toEqual(initial)
|
||||
expect(
|
||||
projectPendingWorktreeRemovals(
|
||||
initial,
|
||||
(row) => row.id,
|
||||
false,
|
||||
snapshotPendingWorktreeRemovals()
|
||||
)
|
||||
).toEqual(initial)
|
||||
expect(() =>
|
||||
assertNoPendingWorktreeRemovalConflict('/work/repo', { branch: 'feature' })
|
||||
).toThrow('Cleanup is pending')
|
||||
expect(await readWorktreeRemovalRecords(directory)).toEqual([])
|
||||
releaseWrite()
|
||||
await waitForWorktreeRemovalAcceptance(removal.worktreeId)
|
||||
stopBackgroundWorktreeRemovals()
|
||||
await _settlePendingWorktreeRemovalsForTests()
|
||||
|
||||
@@ -117,7 +162,10 @@ describe('durable worktree removal records', () => {
|
||||
]
|
||||
expect(
|
||||
projectPendingWorktreeRemovals(rows, (row) => row.id, true, snapshotPendingWorktreeRemovals())
|
||||
).toEqual([{ id: removal.worktreeId, removing: true }, { id: 'repo-1::/work/other' }])
|
||||
).toEqual([
|
||||
{ id: removal.worktreeId, removing: true, removalRecorded: true },
|
||||
{ id: 'repo-1::/work/other' }
|
||||
])
|
||||
expect(
|
||||
projectPendingWorktreeRemovals(
|
||||
rows,
|
||||
@@ -142,6 +190,125 @@ describe('durable worktree removal records', () => {
|
||||
expect(isPending()).toBe(false)
|
||||
expect(await readWorktreeRemovalRecords(directory)).toEqual([])
|
||||
await expect(joined).resolves.toEqual({})
|
||||
expect(publish).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('retains the prior failure while a retry is unadmitted and after its save is refused', async () => {
|
||||
const actual = await vi.importActual<typeof WorktreeRemovalRecords>(
|
||||
'./worktree-removal-records'
|
||||
)
|
||||
const failed = {
|
||||
worktreeId: removal.worktreeId,
|
||||
repoId: removal.repoId,
|
||||
repoPath: removal.repoPath,
|
||||
worktreePath: directory,
|
||||
branch: 'feature',
|
||||
head: 'abc',
|
||||
deleteBranch: true,
|
||||
force: false,
|
||||
requestedAt: 1,
|
||||
failure: { message: 'Files are busy. Retry deletion.', failedAt: 2 }
|
||||
}
|
||||
await actual.writeWorktreeRemovalRecords(directory, () => [failed])
|
||||
_resetPendingWorktreeRemovalsForTests()
|
||||
await loadWorktreeRemovalRecords(directory)
|
||||
let refuseWrite!: (error: Error) => void
|
||||
const writing = new Promise<void>((_resolve, reject) => {
|
||||
refuseWrite = reject
|
||||
})
|
||||
vi.mocked(writeWorktreeRemovalRecords).mockImplementationOnce(() => writing)
|
||||
const run = vi.fn(async () => ({}))
|
||||
const retried = retryFailedWorktreeRemoval(
|
||||
removal.worktreeId,
|
||||
'local',
|
||||
() => ({
|
||||
run,
|
||||
publish: () => {}
|
||||
}),
|
||||
true
|
||||
)
|
||||
const refusal = expect(retried).rejects.toThrow('Could not start deletion')
|
||||
expect(
|
||||
projectPendingWorktreeRemovals(
|
||||
[{ id: removal.worktreeId }],
|
||||
(row) => row.id,
|
||||
true,
|
||||
snapshotPendingWorktreeRemovals()
|
||||
)
|
||||
).toEqual([{ id: removal.worktreeId, removalError: failed.failure.message }])
|
||||
expect(await withUnregisteredRemovalCheckouts(removal.repoId, [])).toHaveLength(1)
|
||||
await persistWorktreeRemovalRecords()
|
||||
expect(await readWorktreeRemovalRecords(directory)).toEqual([failed])
|
||||
refuseWrite(new Error('Disk full'))
|
||||
await refusal
|
||||
await _settlePendingWorktreeRemovalsForTests()
|
||||
expect(run).not.toHaveBeenCalled()
|
||||
_resetPendingWorktreeRemovalsForTests()
|
||||
await loadWorktreeRemovalRecords(directory)
|
||||
expect(waitForPendingWorktreeRemoval(removal.worktreeId)).toBeUndefined()
|
||||
expect(() =>
|
||||
assertNoPendingWorktreeRemovalConflict('/work/repo', { branch: 'feature' })
|
||||
).toThrow('Retry deleting it before reusing its path or branch')
|
||||
expect(await readWorktreeRemovalRecords(directory)).toEqual([failed])
|
||||
})
|
||||
|
||||
it('never resumes a refused force deletion captured alongside another repo admission', async () => {
|
||||
const actual = await vi.importActual<typeof WorktreeRemovalRecords>(
|
||||
'./worktree-removal-records'
|
||||
)
|
||||
let releaseWrite!: () => void
|
||||
const writing = new Promise<void>((resolve) => {
|
||||
releaseWrite = resolve
|
||||
})
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
let refuseSecond!: (error: Error) => void
|
||||
const secondWrite = new Promise<void>((_resolve, reject) => {
|
||||
refuseSecond = reject
|
||||
})
|
||||
let secondReservedAtSnapshot = false
|
||||
vi.mocked(writeWorktreeRemovalRecords)
|
||||
.mockImplementationOnce(async (directory, current, committed) => {
|
||||
await writing
|
||||
await actual.writeWorktreeRemovalRecords(
|
||||
directory,
|
||||
() => {
|
||||
secondReservedAtSnapshot = pendingWorktreeRemovals.has('repo-2::/other/force')
|
||||
return current()
|
||||
},
|
||||
committed
|
||||
)
|
||||
})
|
||||
.mockImplementationOnce(() => secondWrite)
|
||||
.mockRejectedValueOnce(new Error('No space for a cleanup rewrite'))
|
||||
void startBackgroundWorktreeRemoval({ removal, ...interruptedJob() })
|
||||
const refused = startBackgroundWorktreeRemoval({
|
||||
removal: {
|
||||
...removal,
|
||||
worktreeId: 'repo-2::/other/force',
|
||||
repoId: 'repo-2',
|
||||
repoPath: '/other/repo',
|
||||
worktree: { path: '/other/force', branch: 'refs/heads/force', head: 'def' },
|
||||
force: true
|
||||
},
|
||||
run: async () => ({}),
|
||||
publish: () => {}
|
||||
})
|
||||
const refusal = expect(refused).rejects.toThrow('Could not start deletion')
|
||||
releaseWrite()
|
||||
await waitForWorktreeRemovalAcceptance(removal.worktreeId)
|
||||
expect(secondReservedAtSnapshot).toBe(true)
|
||||
expect(pendingWorktreeRemovals.has('repo-2::/other/force')).toBe(true)
|
||||
refuseSecond(new Error('No space for the second record'))
|
||||
await refusal
|
||||
await persistWorktreeRemovalRecords()
|
||||
stopBackgroundWorktreeRemovals()
|
||||
await _settlePendingWorktreeRemovalsForTests()
|
||||
_resetPendingWorktreeRemovalsForTests()
|
||||
await loadWorktreeRemovalRecords(directory)
|
||||
|
||||
expect(
|
||||
(await readWorktreeRemovalRecords(directory)).map((record) => record.worktreeId)
|
||||
).toEqual([removal.worktreeId])
|
||||
expect(waitForPendingWorktreeRemoval('repo-2::/other/force')).toBeUndefined()
|
||||
expect(waitForPendingWorktreeRemoval(removal.worktreeId)).toBeDefined()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { mkdtemp, rm } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { ExecutionHostId } from '../../../shared/execution-host'
|
||||
import {
|
||||
_resetPendingWorktreeRemovalsForTests,
|
||||
_settlePendingWorktreeRemovalsForTests,
|
||||
startBackgroundWorktreeRemoval,
|
||||
loadWorktreeRemovalRecords,
|
||||
waitForWorktreeRemovalAcceptance,
|
||||
waitForPendingWorktreeRemoval
|
||||
} from './worktree-background-removal'
|
||||
|
||||
@@ -33,8 +38,14 @@ function deferred<T>(): { promise: Promise<T>; resolve: (value: T) => void } {
|
||||
}
|
||||
|
||||
describe('background worktree removal', () => {
|
||||
afterEach(() => {
|
||||
let directory = ''
|
||||
beforeEach(async () => {
|
||||
directory = await mkdtemp(join(tmpdir(), 'orca-background-removal-'))
|
||||
await loadWorktreeRemovalRecords(directory)
|
||||
})
|
||||
afterEach(async () => {
|
||||
_resetPendingWorktreeRemovalsForTests()
|
||||
await rm(directory, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
it('resolves with the delete result once Git finishes, after the row has left the table', async () => {
|
||||
@@ -47,6 +58,7 @@ describe('background worktree removal', () => {
|
||||
})
|
||||
|
||||
expect(isPending()).toBe(true)
|
||||
await waitForWorktreeRemovalAcceptance(removal.worktreeId)
|
||||
expect(pendingAtPublish).toEqual([true])
|
||||
|
||||
git.resolve({ preservedBranch: { branchName: 'feature', head: 'abc' } })
|
||||
@@ -58,10 +70,9 @@ describe('background worktree removal', () => {
|
||||
expect(pendingAtPublish).toEqual([true, false])
|
||||
})
|
||||
|
||||
it('answers a request whose delete a concurrent removal of the same worktree replaced', async () => {
|
||||
it('joins concurrent requests to the one recorded deletion', async () => {
|
||||
// The desktop IPC and runtime RPC removal paths coalesce separately, so both can be accepted.
|
||||
const first = deferred<Record<string, never>>()
|
||||
const second = deferred<{ preservedBranch: { branchName: string; head: string } }>()
|
||||
const firstResult = startBackgroundWorktreeRemoval({
|
||||
removal,
|
||||
run: () => first.promise,
|
||||
@@ -69,18 +80,13 @@ describe('background worktree removal', () => {
|
||||
})
|
||||
const secondResult = startBackgroundWorktreeRemoval({
|
||||
removal,
|
||||
run: () => second.promise,
|
||||
run: () => new Promise(() => {}),
|
||||
publish: () => {}
|
||||
})
|
||||
|
||||
first.resolve({})
|
||||
await expect(firstResult).resolves.toEqual({})
|
||||
expect(isPending()).toBe(true)
|
||||
|
||||
second.resolve({ preservedBranch: { branchName: 'feature', head: 'abc' } })
|
||||
await expect(secondResult).resolves.toEqual({
|
||||
preservedBranch: { branchName: 'feature', head: 'abc' }
|
||||
})
|
||||
await expect(secondResult).resolves.toEqual({})
|
||||
await _settlePendingWorktreeRemovalsForTests()
|
||||
expect(isPending()).toBe(false)
|
||||
})
|
||||
@@ -129,12 +135,13 @@ describe('background worktree removal', () => {
|
||||
).not.toThrow()
|
||||
})
|
||||
|
||||
it('marks rows for clients that read the marker and omits them for clients that do not', () => {
|
||||
it('marks rows for clients that read the marker and omits them for clients that do not', async () => {
|
||||
void startBackgroundWorktreeRemoval({
|
||||
removal,
|
||||
run: () => new Promise(() => {}),
|
||||
publish: () => {}
|
||||
})
|
||||
await waitForWorktreeRemovalAcceptance(removal.worktreeId)
|
||||
const rows = [
|
||||
{ id: removal.worktreeId, hostId: 'local' as const },
|
||||
{ id: 'repo-1::/work/other' },
|
||||
@@ -144,7 +151,7 @@ describe('background worktree removal', () => {
|
||||
expect(
|
||||
projectPendingWorktreeRemovals(rows, (row) => row.id, true, snapshotPendingWorktreeRemovals())
|
||||
).toEqual([
|
||||
{ id: removal.worktreeId, hostId: 'local', removing: true },
|
||||
{ id: removal.worktreeId, hostId: 'local', removing: true, removalRecorded: true },
|
||||
{ id: 'repo-1::/work/other' },
|
||||
{ id: removal.worktreeId, hostId: 'ssh:box' }
|
||||
])
|
||||
@@ -185,10 +192,10 @@ describe('background worktree removal', () => {
|
||||
for (const clientReadsMarker of [true, false]) {
|
||||
expect(
|
||||
projectPendingWorktreeRemovals(rows, (row) => row.id, clientReadsMarker, pendingAtScan)
|
||||
).toEqual([{ id: other.worktreeId }])
|
||||
).toEqual([{ id: other.worktreeId, removalError: 'git failed' }])
|
||||
}
|
||||
expect(
|
||||
projectPendingWorktreeRemovals(rows, (row) => row.id, true, snapshotPendingWorktreeRemovals())
|
||||
).toBe(rows)
|
||||
).toEqual([{ id: removal.worktreeId }, { id: other.worktreeId, removalError: 'git failed' }])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,4 +1,15 @@
|
||||
import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../../shared/execution-host'
|
||||
import {
|
||||
addPendingRemoval,
|
||||
settlementsByWorktreeId,
|
||||
waitForPendingWorktreeRemoval,
|
||||
type RemovalSettlement
|
||||
} from './worktree-removal-settlement'
|
||||
export {
|
||||
waitForPendingWorktreeRemoval,
|
||||
waitForWorktreeRemovalAcceptance,
|
||||
finishAcceptedWorktreeRemoval
|
||||
} from './worktree-removal-settlement'
|
||||
import type { ExecutionHostId } from '../../../shared/execution-host'
|
||||
import type { RemoveWorktreeResult } from '../../../shared/worktree/create-types'
|
||||
import type { GitWorktreeInfo } from '../../../shared/worktree/types'
|
||||
import { normalizeLocalBranchRef } from '../../git/worktrees/worktree-operation-options'
|
||||
@@ -13,8 +24,9 @@ import {
|
||||
finishedWorktreeRemovals,
|
||||
pendingWorktreeRemovals,
|
||||
persistWorktreeRemovalRecords,
|
||||
setWorktreeRemovalRecordsDirectory,
|
||||
worktreeCheckoutExists
|
||||
recordedWorktreeRemovals,
|
||||
recordWorktreeRemoval,
|
||||
setWorktreeRemovalRecordsDirectory
|
||||
} from './worktree-removal-table'
|
||||
|
||||
export type BackgroundWorktreeRemovalJob = {
|
||||
@@ -24,16 +36,11 @@ export type BackgroundWorktreeRemovalJob = {
|
||||
publish: () => void
|
||||
/** Clean the push-target remote even when Git partially fails. */
|
||||
cleanupPushTargetRemote?: () => Promise<void>
|
||||
}
|
||||
|
||||
type RemovalSettlement = {
|
||||
result: Promise<RemoveWorktreeResult>
|
||||
resolve: (result: RemoveWorktreeResult) => void
|
||||
reject: (error: unknown) => void
|
||||
/** Release teardown fences when durable admission fails before run can take ownership. */
|
||||
admissionFailed?: () => Promise<void>
|
||||
}
|
||||
|
||||
const jobsByWorktreeId = new Map<string, Promise<void>>()
|
||||
const settlementsByWorktreeId = new Map<string, RemovalSettlement>()
|
||||
const stopControllers = new Set<AbortController>()
|
||||
// Loaded removals' terminal/watcher fences, held until the resumed job takes its own gate.
|
||||
const startupFencesByWorktreeId = new Map<string, WatcherRemovalGate>()
|
||||
@@ -48,7 +55,7 @@ export async function loadWorktreeRemovalRecords(
|
||||
for (const record of await readWorktreeRemovalRecords(directory)) {
|
||||
if (record.failure) {
|
||||
// Removed repos have no listing to clear a failed-removal record.
|
||||
if (hasRepo(record.repoId) && (await worktreeCheckoutExists(record.worktreePath))) {
|
||||
if (hasRepo(record.repoId)) {
|
||||
failedWorktreeRemovals.set(record.worktreeId, record)
|
||||
} else {
|
||||
droppedFailure = true
|
||||
@@ -56,7 +63,8 @@ export async function loadWorktreeRemovalRecords(
|
||||
continue
|
||||
}
|
||||
if (!pendingWorktreeRemovals.has(record.worktreeId)) {
|
||||
addPendingRemoval(record)
|
||||
recordedWorktreeRemovals.add(record)
|
||||
addPendingRemoval(record).accept()
|
||||
try {
|
||||
startupFencesByWorktreeId.set(
|
||||
record.worktreeId,
|
||||
@@ -78,57 +86,6 @@ export function releaseStartupRemovalFence(worktreeId: string): void {
|
||||
startupFencesByWorktreeId.delete(worktreeId)
|
||||
}
|
||||
|
||||
function addPendingRemoval(record: WorktreeRemovalRecord): RemovalSettlement {
|
||||
let resolve!: RemovalSettlement['resolve']
|
||||
let reject!: RemovalSettlement['reject']
|
||||
const result = new Promise<RemoveWorktreeResult>((settle, fail) => {
|
||||
resolve = settle
|
||||
reject = fail
|
||||
})
|
||||
// Older clients and restart-resumed jobs may have no caller to handle a rejection.
|
||||
result.catch(() => {})
|
||||
const settlement = { result, resolve, reject }
|
||||
failedWorktreeRemovals.delete(record.worktreeId)
|
||||
pendingWorktreeRemovals.set(record.worktreeId, record)
|
||||
settlementsByWorktreeId.set(record.worktreeId, settlement)
|
||||
return settlement
|
||||
}
|
||||
|
||||
/** Pending removals are host-local; never join a same-ID checkout on another host. */
|
||||
export function waitForPendingWorktreeRemoval(
|
||||
worktreeId: string,
|
||||
hostId?: ExecutionHostId,
|
||||
deleteBranch?: boolean
|
||||
): Promise<RemoveWorktreeResult> | undefined {
|
||||
if ((hostId ?? LOCAL_EXECUTION_HOST_ID) !== LOCAL_EXECUTION_HOST_ID) {
|
||||
return undefined
|
||||
}
|
||||
assertAcceptedBranchChoice(pendingWorktreeRemovals.get(worktreeId), deleteBranch)
|
||||
return settlementsByWorktreeId.get(worktreeId)?.result
|
||||
}
|
||||
|
||||
function assertAcceptedBranchChoice(
|
||||
record: WorktreeRemovalRecord | undefined,
|
||||
deleteBranch: boolean | undefined
|
||||
): void {
|
||||
if (record && deleteBranch !== undefined && record.deleteBranch !== deleteBranch) {
|
||||
throw new Error(
|
||||
`Orca already accepted removal of ${record.worktreePath} with a different branch choice. That cleanup may already have run; check the branch before retrying.`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Await the delete while preserving the acceptance result fields. */
|
||||
export async function finishAcceptedWorktreeRemoval<T extends RemoveWorktreeResult>(
|
||||
accepted: T,
|
||||
worktreeId: string,
|
||||
hostId?: ExecutionHostId
|
||||
): Promise<Omit<T, 'removing'>> {
|
||||
const { removing, ...acceptance } = accepted
|
||||
const pending = removing ? waitForPendingWorktreeRemoval(worktreeId, hostId) : undefined
|
||||
return pending ? { ...acceptance, ...(await pending) } : acceptance
|
||||
}
|
||||
|
||||
export function removesInBackground(
|
||||
worktreePath: string,
|
||||
options: { wslDistro?: string }
|
||||
@@ -145,6 +102,14 @@ export function startBackgroundWorktreeRemoval(
|
||||
> & { worktree: Pick<GitWorktreeInfo, 'path' | 'branch' | 'head'> }
|
||||
} & BackgroundWorktreeRemovalJob
|
||||
): Promise<RemoveWorktreeResult> {
|
||||
const pending = waitForPendingWorktreeRemoval(
|
||||
args.removal.worktreeId,
|
||||
undefined,
|
||||
args.removal.deleteBranch
|
||||
)
|
||||
if (pending) {
|
||||
return pending
|
||||
}
|
||||
const { worktree, ...accepted } = args.removal
|
||||
const record: WorktreeRemovalRecord = {
|
||||
...accepted,
|
||||
@@ -154,8 +119,7 @@ export function startBackgroundWorktreeRemoval(
|
||||
requestedAt: Date.now()
|
||||
}
|
||||
const settlement = addPendingRemoval(record)
|
||||
runBackgroundWorktreeRemoval(record, args, persistWorktreeRemovalRecords())
|
||||
publishSafely(args.publish)
|
||||
runBackgroundWorktreeRemoval(record, args, recordWorktreeRemoval(record))
|
||||
return settlement.result
|
||||
}
|
||||
|
||||
@@ -167,6 +131,10 @@ export function retryFailedWorktreeRemoval(
|
||||
force?: boolean,
|
||||
deleteBranch?: boolean
|
||||
): Promise<RemoveWorktreeResult> | undefined {
|
||||
const pending = waitForPendingWorktreeRemoval(worktreeId, hostId, deleteBranch)
|
||||
if (pending) {
|
||||
return pending
|
||||
}
|
||||
const failed =
|
||||
(hostId ?? LOCAL_EXECUTION_HOST_ID) === LOCAL_EXECUTION_HOST_ID
|
||||
? failedWorktreeRemovals.get(worktreeId)
|
||||
@@ -189,8 +157,7 @@ export function retryFailedWorktreeRemoval(
|
||||
return job.run(stopSignal)
|
||||
}
|
||||
}
|
||||
runBackgroundWorktreeRemoval(record, leftoverOnly, persistWorktreeRemovalRecords())
|
||||
publishSafely(job.publish)
|
||||
runBackgroundWorktreeRemoval(record, leftoverOnly, recordWorktreeRemoval(record))
|
||||
return settlement.result
|
||||
}
|
||||
|
||||
@@ -240,7 +207,31 @@ async function settleBackgroundWorktreeRemoval(
|
||||
recorded: Promise<void>,
|
||||
stopSignal: AbortSignal
|
||||
): Promise<void> {
|
||||
await waitForRecordWrite(record, recorded)
|
||||
try {
|
||||
await recorded
|
||||
} catch (error) {
|
||||
const refusal = new Error(
|
||||
'Could not start deletion. The workspace is still on disk; reopen any stopped terminals and try again.',
|
||||
{ cause: error }
|
||||
)
|
||||
if (pendingWorktreeRemovals.get(record.worktreeId) === record) {
|
||||
pendingWorktreeRemovals.delete(record.worktreeId)
|
||||
settlementsByWorktreeId.delete(record.worktreeId)
|
||||
}
|
||||
try {
|
||||
await job.admissionFailed?.()
|
||||
} catch (cleanupError) {
|
||||
console.warn('[worktrees] failed to release refused removal', cleanupError)
|
||||
}
|
||||
settlement?.refuse(refusal)
|
||||
settlement?.reject(refusal)
|
||||
publishSafely(job.publish)
|
||||
return
|
||||
}
|
||||
if (settlement) {
|
||||
settlement.accept()
|
||||
}
|
||||
publishSafely(job.publish)
|
||||
let settle: (settlement: RemovalSettlement) => void
|
||||
let failure: WorktreeRemovalRecord['failure']
|
||||
try {
|
||||
@@ -285,28 +276,6 @@ async function settleBackgroundWorktreeRemoval(
|
||||
}
|
||||
}
|
||||
|
||||
// Prefer a durable resume record, but do not hold deletion indefinitely on stalled disk writes.
|
||||
const RECORD_WRITE_WAIT_MS = 2_000
|
||||
|
||||
async function waitForRecordWrite(
|
||||
record: WorktreeRemovalRecord,
|
||||
recorded: Promise<void>
|
||||
): Promise<void> {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
const timedOut = await Promise.race([
|
||||
recorded.then(() => false),
|
||||
new Promise<boolean>((resolve) => {
|
||||
timer = setTimeout(() => resolve(true), RECORD_WRITE_WAIT_MS)
|
||||
})
|
||||
])
|
||||
clearTimeout(timer)
|
||||
if (timedOut) {
|
||||
console.warn(
|
||||
`[worktrees] removal record for ${record.worktreePath} not on disk after ${RECORD_WRITE_WAIT_MS} ms; deleting anyway`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function publishSafely(publish: () => void): void {
|
||||
try {
|
||||
publish()
|
||||
|
||||
@@ -124,7 +124,7 @@ describe('a delete that fails after Git dropped the registration', () => {
|
||||
false,
|
||||
snapshotPendingWorktreeRemovals()
|
||||
)
|
||||
).toEqual(rows)
|
||||
).toEqual([{ id: worktreeId, removalError: GIT_ERROR }])
|
||||
// Nothing fences the leftover: a failed delete must not block terminals indefinitely.
|
||||
beginTerminalInstall(checkout)()
|
||||
})
|
||||
@@ -230,14 +230,21 @@ describe('a delete that fails after Git dropped the registration', () => {
|
||||
])
|
||||
})
|
||||
|
||||
it('ends at the next listing once the checkout is deleted outside Orca', async () => {
|
||||
it('keeps an absent-folder failure across restart until explicit cleanup succeeds', async () => {
|
||||
await failRemoval()
|
||||
await rm(checkout, { recursive: true })
|
||||
_resetPendingWorktreeRemovalsForTests()
|
||||
await loadWorktreeRemovalRecords(join(directory, 'profile'))
|
||||
|
||||
expect(await listRows()).toEqual([mainWorktree, leftoverRow()])
|
||||
const retried = retryFailedWorktreeRemoval(worktreeId, 'local', () => ({
|
||||
run: async () => ({}),
|
||||
publish: () => {}
|
||||
}))
|
||||
await expect(retried).resolves.toEqual({})
|
||||
await _settlePendingWorktreeRemovalsForTests()
|
||||
expect(await listRows()).toEqual([mainWorktree])
|
||||
await vi.waitFor(async () =>
|
||||
expect(await readWorktreeRemovalRecords(join(directory, 'profile'))).toEqual([])
|
||||
)
|
||||
expect(await readWorktreeRemovalRecords(join(directory, 'profile'))).toEqual([])
|
||||
})
|
||||
|
||||
it('ends at startup once its repo is removed from Orca, leaving the files', async () => {
|
||||
|
||||
@@ -13,18 +13,18 @@ export async function failureLeftByGit(
|
||||
error: unknown,
|
||||
cleanupPushTargetRemote: (() => Promise<void>) | undefined
|
||||
): Promise<WorktreeRemovalFailure | undefined> {
|
||||
if (!(await worktreeCheckoutExists(record.worktreePath))) {
|
||||
return undefined
|
||||
}
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
const failure = {
|
||||
message: message.replace(
|
||||
/ Close (?:that program|any program using it) and delete again\.$/,
|
||||
() =>
|
||||
` Close any program using it. You may need to delete the remaining folder at ${record.worktreePath} manually to finish removing this workspace.`
|
||||
` Close any program using it, then retry deletion. If you removed the folder at ${record.worktreePath} yourself, retry deletion to finish cleanup.`
|
||||
),
|
||||
failedAt: Date.now()
|
||||
}
|
||||
if (!(await worktreeCheckoutExists(record.worktreePath))) {
|
||||
return failure
|
||||
}
|
||||
try {
|
||||
const registered = await registeredRemovalCheckout(record)
|
||||
if (registered) {
|
||||
|
||||
@@ -14,6 +14,7 @@ import type { WorktreeRemovalRecord } from './worktree-removal-records'
|
||||
import { areWorktreePathsEqual } from '../../git/worktrees/catalog/worktree-path-comparison'
|
||||
import { CLIENT_REMOVAL_HOME } from './worktree-removal-home-guard'
|
||||
import { failedWorktreeRemovals, worktreeCheckoutExists } from './worktree-removal-table'
|
||||
import { waitForWorktreeRemovalAcceptance } from './worktree-removal-settlement'
|
||||
import {
|
||||
assertWorktreeDoesNotContainRegisteredWorktree,
|
||||
canSafelyRemoveOrphanedWorktreeDirectory
|
||||
@@ -90,5 +91,9 @@ export async function retryFailedRemovalUnlessRegistered(
|
||||
if (failed && !usesNativeWindowsRemoval(worktreePath, localOptions)) {
|
||||
await assertUnregisteredCheckoutGone(failed.worktreePath, registeredWorktrees)
|
||||
}
|
||||
return retry() !== undefined
|
||||
if (retry() === undefined) {
|
||||
return false
|
||||
}
|
||||
await waitForWorktreeRemovalAcceptance(worktreeId)
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
finishedWorktreeRemovals,
|
||||
pendingWorktreeRemovals,
|
||||
persistWorktreeRemovalRecords,
|
||||
recordedWorktreeRemovals,
|
||||
worktreeCheckoutExists
|
||||
} from './worktree-removal-table'
|
||||
|
||||
@@ -42,7 +43,9 @@ export async function withUnregisteredRemovalCheckouts(
|
||||
droppedFailure = true
|
||||
return row
|
||||
})
|
||||
const unlisted = [...pendingWorktreeRemovals.values(), ...failedWorktreeRemovals.values()].filter(
|
||||
const unlisted = [
|
||||
...new Map([...pendingWorktreeRemovals, ...failedWorktreeRemovals]).values()
|
||||
].filter(
|
||||
(record) =>
|
||||
record.repoId === repoId &&
|
||||
!gitWorktrees.some((worktree) => areWorktreePathsEqual(worktree.path, record.worktreePath))
|
||||
@@ -51,8 +54,8 @@ export async function withUnregisteredRemovalCheckouts(
|
||||
for (const record of unlisted) {
|
||||
const failed = failedWorktreeRemovals.get(record.worktreeId) === record
|
||||
if (
|
||||
(await worktreeCheckoutExists(record.worktreePath)) &&
|
||||
(!failed || (await isUnregisteredRemovalLeftover(record.repoPath, record.worktreePath)))
|
||||
(!failed && (await worktreeCheckoutExists(record.worktreePath))) ||
|
||||
(failed && (await isUnregisteredRemovalLeftover(record.repoPath, record.worktreePath)))
|
||||
) {
|
||||
leftovers.push({
|
||||
path: record.worktreePath,
|
||||
@@ -80,26 +83,46 @@ export function snapshotPendingWorktreeRemovals(): PendingWorktreeRemovals {
|
||||
|
||||
/** Older clients cannot read removing markers; omit pending rows they already dropped on acceptance. */
|
||||
export function projectPendingWorktreeRemovals<
|
||||
T extends { hostId?: ExecutionHostId; removing?: true }
|
||||
T extends {
|
||||
hostId?: ExecutionHostId
|
||||
removing?: true
|
||||
removalRecorded?: true
|
||||
removalError?: string
|
||||
}
|
||||
>(
|
||||
rows: T[],
|
||||
idOf: (row: T) => string,
|
||||
clientReadsMarker: boolean,
|
||||
pendingAtScan: PendingWorktreeRemovals
|
||||
): T[] {
|
||||
if (pendingWorktreeRemovals.size === 0 && pendingAtScan.size === 0) {
|
||||
if (
|
||||
pendingWorktreeRemovals.size === 0 &&
|
||||
pendingAtScan.size === 0 &&
|
||||
failedWorktreeRemovals.size === 0
|
||||
) {
|
||||
return rows
|
||||
}
|
||||
const projected: T[] = []
|
||||
for (const row of rows) {
|
||||
const id = idOf(row)
|
||||
const local = row.hostId === undefined || row.hostId === LOCAL_EXECUTION_HOST_ID
|
||||
if (local && pendingWorktreeRemovals.has(id)) {
|
||||
const pending = local ? pendingWorktreeRemovals.get(id) : undefined
|
||||
if (pending && recordedWorktreeRemovals.has(pending)) {
|
||||
if (clientReadsMarker) {
|
||||
projected.push({ ...row, removing: true })
|
||||
projected.push({ ...row, removing: true, removalRecorded: true })
|
||||
}
|
||||
continue
|
||||
}
|
||||
const failed = local ? failedWorktreeRemovals.get(id) : undefined
|
||||
if (failed) {
|
||||
projected.push({
|
||||
...row,
|
||||
removing: undefined,
|
||||
removalRecorded: undefined,
|
||||
removalError: failed.failure?.message
|
||||
})
|
||||
continue
|
||||
}
|
||||
const scanned = local ? pendingAtScan.get(id) : undefined
|
||||
// Git was read before deletion finished; do not resurrect the stale row as a failed delete.
|
||||
if (!scanned || !finishedWorktreeRemovals.has(scanned)) {
|
||||
@@ -108,3 +131,25 @@ export function projectPendingWorktreeRemovals<
|
||||
}
|
||||
return projected
|
||||
}
|
||||
|
||||
export type WorktreeRemovalWitnessScan = {
|
||||
removals?: PendingWorktreeRemovals
|
||||
projectedRemovals?: PendingWorktreeRemovals
|
||||
}
|
||||
|
||||
/** Reuse repo-local witnesses across metadata joins; replace them only when reservations change. */
|
||||
export function projectCachedWorktreeRemovals<T extends { hostId?: ExecutionHostId }>(
|
||||
repoId: string,
|
||||
scan: WorktreeRemovalWitnessScan,
|
||||
rows: T[],
|
||||
idOf: (row: T) => string
|
||||
): T[] {
|
||||
const current = pendingWorktreeRemovals.snapshotForRepo(repoId)
|
||||
if (scan.projectedRemovals !== current) {
|
||||
if (current.size > 0) {
|
||||
scan.removals = new Map([...(scan.removals ?? []), ...current])
|
||||
}
|
||||
scan.projectedRemovals = current
|
||||
}
|
||||
return projectPendingWorktreeRemovals(rows, idOf, true, scan.removals ?? current)
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ export type WorktreeRemovalRecord = {
|
||||
deleteBranch: boolean
|
||||
force: boolean
|
||||
requestedAt: number
|
||||
/** Git dropped registration; branch/remote cleanup ran, but the folder remains. */
|
||||
/** Cleanup failed; files, Git ownership or metadata may still need an explicit retry. */
|
||||
failure?: WorktreeRemovalFailure
|
||||
}
|
||||
|
||||
@@ -97,13 +97,15 @@ export async function readWorktreeRemovalRecords(
|
||||
/** Read current records when the queued write runs so newer state wins. */
|
||||
export function writeWorktreeRemovalRecords(
|
||||
directory: string,
|
||||
current: () => WorktreeRemovalRecord[]
|
||||
current: () => WorktreeRemovalRecord[],
|
||||
committed?: () => void
|
||||
): Promise<void> {
|
||||
const file = worktreeRemovalRecordsFile(directory)
|
||||
return withSidecarSnapshotQueue(file, () =>
|
||||
writeSidecarSnapshot(file, {
|
||||
return withSidecarSnapshotQueue(file, async () => {
|
||||
await writeSidecarSnapshot(file, {
|
||||
version: RECORDS_VERSION,
|
||||
removals: current()
|
||||
} satisfies PersistedWorktreeRemovalRecords)
|
||||
)
|
||||
committed?.()
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import type { WorktreeRemovalRecord } from './worktree-removal-records'
|
||||
|
||||
const NO_REMOVALS: ReadonlyMap<string, WorktreeRemovalRecord> = new Map()
|
||||
|
||||
/** Repo snapshots change only with their reservations, never with unrelated metadata joins. */
|
||||
export class WorktreeRemovalReservations extends Map<string, WorktreeRemovalRecord> {
|
||||
private readonly byRepo = new Map<string, Map<string, WorktreeRemovalRecord>>()
|
||||
private readonly snapshots = new Map<string, ReadonlyMap<string, WorktreeRemovalRecord>>()
|
||||
|
||||
override set(id: string, record: WorktreeRemovalRecord): this {
|
||||
const previous = this.get(id)
|
||||
if (previous === record) {
|
||||
return this
|
||||
}
|
||||
if (previous) {
|
||||
this.removeRepoRecord(id, previous.repoId)
|
||||
}
|
||||
super.set(id, record)
|
||||
let records = this.byRepo.get(record.repoId)
|
||||
if (!records) {
|
||||
records = new Map()
|
||||
this.byRepo.set(record.repoId, records)
|
||||
}
|
||||
records.set(id, record)
|
||||
this.snapshots.delete(record.repoId)
|
||||
return this
|
||||
}
|
||||
|
||||
override delete(id: string): boolean {
|
||||
const previous = this.get(id)
|
||||
if (!previous) {
|
||||
return false
|
||||
}
|
||||
this.removeRepoRecord(id, previous.repoId)
|
||||
return super.delete(id)
|
||||
}
|
||||
|
||||
override clear(): void {
|
||||
super.clear()
|
||||
this.byRepo.clear()
|
||||
this.snapshots.clear()
|
||||
}
|
||||
|
||||
snapshotForRepo(repoId: string): ReadonlyMap<string, WorktreeRemovalRecord> {
|
||||
const records = this.byRepo.get(repoId)
|
||||
if (!records) {
|
||||
return NO_REMOVALS
|
||||
}
|
||||
let snapshot = this.snapshots.get(repoId)
|
||||
if (!snapshot) {
|
||||
snapshot = new Map(records)
|
||||
this.snapshots.set(repoId, snapshot)
|
||||
}
|
||||
return snapshot
|
||||
}
|
||||
|
||||
private removeRepoRecord(id: string, repoId: string): void {
|
||||
const records = this.byRepo.get(repoId)
|
||||
records?.delete(id)
|
||||
if (records?.size === 0) {
|
||||
this.byRepo.delete(repoId)
|
||||
}
|
||||
this.snapshots.delete(repoId)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../../shared/execution-host'
|
||||
import type { RemoveWorktreeResult } from '../../../shared/worktree/create-types'
|
||||
import type { WorktreeRemovalRecord } from './worktree-removal-records'
|
||||
import { pendingWorktreeRemovals } from './worktree-removal-table'
|
||||
|
||||
export type RemovalSettlement = {
|
||||
accepted: Promise<void>
|
||||
accept: () => void
|
||||
refuse: (error: unknown) => void
|
||||
result: Promise<RemoveWorktreeResult>
|
||||
resolve: (result: RemoveWorktreeResult) => void
|
||||
reject: (error: unknown) => void
|
||||
}
|
||||
|
||||
export const settlementsByWorktreeId = new Map<string, RemovalSettlement>()
|
||||
|
||||
export function addPendingRemoval(record: WorktreeRemovalRecord): RemovalSettlement {
|
||||
let accept!: RemovalSettlement['accept']
|
||||
let refuse!: RemovalSettlement['refuse']
|
||||
const accepted = new Promise<void>((resolve, reject) => {
|
||||
accept = resolve
|
||||
refuse = reject
|
||||
})
|
||||
accepted.catch(() => {})
|
||||
let resolve!: RemovalSettlement['resolve']
|
||||
let reject!: RemovalSettlement['reject']
|
||||
const result = new Promise<RemoveWorktreeResult>((settle, fail) => {
|
||||
resolve = settle
|
||||
reject = fail
|
||||
})
|
||||
// Older clients and restart-resumed jobs may have no caller to handle a rejection.
|
||||
result.catch(() => {})
|
||||
const settlement = { accepted, accept, refuse, result, resolve, reject }
|
||||
pendingWorktreeRemovals.set(record.worktreeId, record)
|
||||
settlementsByWorktreeId.set(record.worktreeId, settlement)
|
||||
return settlement
|
||||
}
|
||||
|
||||
/** Acceptance is separate from completion so CLI outcomes can keep waiting for Git. */
|
||||
export function waitForWorktreeRemovalAcceptance(
|
||||
worktreeId: string,
|
||||
hostId?: ExecutionHostId
|
||||
): Promise<void> | undefined {
|
||||
return (hostId ?? LOCAL_EXECUTION_HOST_ID) === LOCAL_EXECUTION_HOST_ID
|
||||
? settlementsByWorktreeId.get(worktreeId)?.accepted
|
||||
: undefined
|
||||
}
|
||||
|
||||
/** Pending removals are host-local; never join a same-ID checkout on another host. */
|
||||
export function waitForPendingWorktreeRemoval(
|
||||
worktreeId: string,
|
||||
hostId?: ExecutionHostId,
|
||||
deleteBranch?: boolean
|
||||
): Promise<RemoveWorktreeResult> | undefined {
|
||||
if ((hostId ?? LOCAL_EXECUTION_HOST_ID) !== LOCAL_EXECUTION_HOST_ID) {
|
||||
return undefined
|
||||
}
|
||||
assertAcceptedBranchChoice(pendingWorktreeRemovals.get(worktreeId), deleteBranch)
|
||||
return settlementsByWorktreeId.get(worktreeId)?.result
|
||||
}
|
||||
|
||||
function assertAcceptedBranchChoice(
|
||||
record: WorktreeRemovalRecord | undefined,
|
||||
deleteBranch: boolean | undefined
|
||||
): void {
|
||||
if (record && deleteBranch !== undefined && record.deleteBranch !== deleteBranch) {
|
||||
throw new Error(
|
||||
`Orca already accepted removal of ${record.worktreePath} with a different branch choice. That cleanup may already have run; check the branch before retrying.`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Await the delete while preserving the acceptance result fields. */
|
||||
export async function finishAcceptedWorktreeRemoval<T extends RemoveWorktreeResult>(
|
||||
accepted: T,
|
||||
worktreeId: string,
|
||||
hostId?: ExecutionHostId
|
||||
): Promise<Omit<T, 'removing'>> {
|
||||
const { removing, ...acceptance } = accepted
|
||||
const pending = removing ? waitForPendingWorktreeRemoval(worktreeId, hostId) : undefined
|
||||
return pending ? { ...acceptance, ...(await pending) } : acceptance
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
import { WorktreeRemovalReservations } from './worktree-removal-reservations'
|
||||
import { lstat } from 'node:fs/promises'
|
||||
import { getErrorCode } from '../../git/worktrees/worktree-operation-options'
|
||||
import { areWorktreePathsEqual } from '../../git/worktrees/catalog/worktree-path-comparison'
|
||||
import { writeWorktreeRemovalRecords, type WorktreeRemovalRecord } from './worktree-removal-records'
|
||||
|
||||
export const pendingWorktreeRemovals = new Map<string, WorktreeRemovalRecord>()
|
||||
export const pendingWorktreeRemovals = new WorktreeRemovalReservations()
|
||||
export const recordedWorktreeRemovals = new WeakSet<WorktreeRemovalRecord>()
|
||||
// Failed leftovers stay visible until gone/replaced or their repo is removed; never retry without a request.
|
||||
export const failedWorktreeRemovals = new Map<string, WorktreeRemovalRecord>()
|
||||
// In-flight listings retain completed records only until their stale Git read is projected.
|
||||
@@ -18,14 +20,41 @@ export function persistWorktreeRemovalRecords(): Promise<void> {
|
||||
if (!recordsDirectory) {
|
||||
return Promise.resolve()
|
||||
}
|
||||
return writeWorktreeRemovalRecords(recordsDirectory, () => [
|
||||
...pendingWorktreeRemovals.values(),
|
||||
...failedWorktreeRemovals.values()
|
||||
]).catch((error: unknown) => {
|
||||
return writeWorktreeRemovalRecords(recordsDirectory, journalRecords).catch((error: unknown) => {
|
||||
console.warn('[worktrees] failed to persist worktree removal records', error)
|
||||
})
|
||||
}
|
||||
|
||||
function journalRecords(candidate?: WorktreeRemovalRecord): WorktreeRemovalRecord[] {
|
||||
const records = new Map(failedWorktreeRemovals)
|
||||
for (const record of pendingWorktreeRemovals.values()) {
|
||||
if (recordedWorktreeRemovals.has(record)) {
|
||||
records.set(record.worktreeId, record)
|
||||
}
|
||||
}
|
||||
if (candidate) {
|
||||
records.set(candidate.worktreeId, candidate)
|
||||
}
|
||||
return [...records.values()]
|
||||
}
|
||||
|
||||
/** Commit only this admission; unrelated reservations must never reach a restart's journal. */
|
||||
export function recordWorktreeRemoval(record: WorktreeRemovalRecord): Promise<void> {
|
||||
if (!recordsDirectory) {
|
||||
return Promise.reject(
|
||||
new Error('Could not start deletion. Reopen the workspace and try again.')
|
||||
)
|
||||
}
|
||||
return writeWorktreeRemovalRecords(
|
||||
recordsDirectory,
|
||||
() => journalRecords(record),
|
||||
() => {
|
||||
recordedWorktreeRemovals.add(record)
|
||||
failedWorktreeRemovals.delete(record.worktreeId)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
/** Unreadable counts as present: only a checkout proven gone ends a failed delete. */
|
||||
export async function worktreeCheckoutExists(worktreePath: string): Promise<boolean> {
|
||||
try {
|
||||
@@ -46,7 +75,7 @@ export function findPendingWorktreeRemovalConflict(
|
||||
target: { worktreePath?: string; branch?: string }
|
||||
): WorktreeRemovalRecord | undefined {
|
||||
const branch = target.branch?.replace(/^refs\/heads\//, '')
|
||||
for (const removal of pendingWorktreeRemovals.values()) {
|
||||
for (const removal of [...pendingWorktreeRemovals.values(), ...failedWorktreeRemovals.values()]) {
|
||||
if (!areWorktreePathsEqual(removal.repoPath, repoPath)) {
|
||||
continue
|
||||
}
|
||||
@@ -67,7 +96,9 @@ export function assertNoPendingWorktreeRemovalConflict(
|
||||
const removal = findPendingWorktreeRemovalConflict(repoPath, target)
|
||||
if (removal) {
|
||||
throw new Error(
|
||||
`Orca is still deleting the workspace at ${removal.worktreePath}. Cleanup is pending; try again shortly.`
|
||||
removal.failure
|
||||
? `Cleanup failed for the workspace at ${removal.worktreePath}. Retry deleting it before reusing its path or branch.`
|
||||
: `Orca is still deleting the workspace at ${removal.worktreePath}. Cleanup is pending; try again shortly.`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isWorktreeRetiredByRemoval } from '../../../../shared/worktree/removal-visibility'
|
||||
import {
|
||||
getRepoDisplayLabelKey,
|
||||
getRepoDisplayLabelsByPath
|
||||
@@ -139,7 +140,7 @@ export function buildPaletteFilterModel({
|
||||
const worktreeCountByHostId = new Map<string, number>()
|
||||
const worktreeCountByRepoId = new Map<string, number>()
|
||||
for (const worktree of worktrees) {
|
||||
if (worktree.isArchived) {
|
||||
if (worktree.isArchived || isWorktreeRetiredByRemoval(worktree)) {
|
||||
continue
|
||||
}
|
||||
const hostId = resolveWorktreeFilterHostId(worktree, repoById, defaultHostId)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isWorktreeRetiredByRemoval } from '../../../../shared/worktree/removal-visibility'
|
||||
import { useAppStore } from '@/store'
|
||||
import { getPaletteWorktreeExecutionHostId } from '@/lib/workspace/search/palette-repo-resolution'
|
||||
import { getWorkspaceAttachments } from '../../../../shared/workspace-attachments/workspace-attachments'
|
||||
@@ -56,7 +57,7 @@ export function findCmdJTaskWorkspace(
|
||||
return undefined
|
||||
}
|
||||
return workspaces
|
||||
.filter((workspace) => !workspace.isArchived)
|
||||
.filter((workspace) => !workspace.isArchived && !isWorktreeRetiredByRemoval(workspace))
|
||||
.find((workspace) =>
|
||||
getWorkspaceAttachments(workspace).some((item) => {
|
||||
if (
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isWorktreeRetiredByRemoval } from '../../../../shared/worktree/removal-visibility'
|
||||
import React, { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { Check, ChevronsUpDown, GitBranch } from 'lucide-react'
|
||||
@@ -68,11 +69,10 @@ type ComposerParentWorktreePickerProps = {
|
||||
activeFolderWorkspaceId?: string | null
|
||||
}
|
||||
|
||||
type ParentWorktreeCandidateListProps = {
|
||||
repoId: string
|
||||
executionHostId?: ExecutionHostId | null
|
||||
projectId?: string | null
|
||||
value: string | null
|
||||
type ParentWorktreeCandidateListProps = Omit<
|
||||
ComposerParentWorktreePickerProps,
|
||||
'onChange' | 'disabled' | 'activeFolderWorkspaceId'
|
||||
> & {
|
||||
activeFolderWorkspaceId: string | null
|
||||
onSelect: (id: string | null) => void
|
||||
}
|
||||
@@ -104,7 +104,9 @@ function ComposerParentWorktreePickerImpl({
|
||||
(row) => getWorktreeHostIdentity(row) === value
|
||||
)
|
||||
: getIndexedWorktreeById(selectWorktreesByRepo(s), value)
|
||||
return parent && !parent.isArchived ? parent.displayName : null
|
||||
return parent && !parent.isArchived && !isWorktreeRetiredByRemoval(parent)
|
||||
? parent.displayName
|
||||
: null
|
||||
})
|
||||
|
||||
// Close during render when the drawer disables its trigger; portaled content would otherwise linger through a stale-open frame.
|
||||
@@ -251,6 +253,7 @@ function ParentWorktreeCandidateList({
|
||||
.filter(
|
||||
(candidate) =>
|
||||
!candidate.isArchived &&
|
||||
!isWorktreeRetiredByRemoval(candidate) &&
|
||||
((folderSubtreeIds === null && isCrossStoreCandidate(candidate)) ||
|
||||
(sharesWorktreeLineageBoundary(childBoundary, {
|
||||
...candidate,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isWorktreeRetiredByRemoval } from '../../../../../shared/worktree/removal-visibility'
|
||||
import { toWorktreeRelativePath } from '../../../../../shared/terminal/links/terminal-links'
|
||||
import { LOCAL_EXECUTION_HOST_ID } from '../../../../../shared/execution-host'
|
||||
import type { FolderWorkspace } from '../../../../../shared/folder-workspaces/folder-workspace-types'
|
||||
@@ -10,7 +11,14 @@ import {
|
||||
selectWorktreesByRepo
|
||||
} from '@/store/workspaces/catalog/workspace-record-fields'
|
||||
|
||||
type WorkspaceRow = { id: string; path: string; hostId?: string; isArchived?: boolean }
|
||||
type WorkspaceRow = {
|
||||
id: string
|
||||
path: string
|
||||
hostId?: string
|
||||
isArchived?: boolean
|
||||
removing?: true
|
||||
removalRecorded?: true
|
||||
}
|
||||
|
||||
export type PluginEditorWorkspace = {
|
||||
worktreeId: string
|
||||
@@ -47,7 +55,7 @@ export function findWorkspaceShowingFile(
|
||||
let best: (PluginEditorWorkspace & { depth: number; active: boolean }) | null = null
|
||||
for (const worktree of workspaces) {
|
||||
const local = worktree.hostId === undefined || worktree.hostId === LOCAL_EXECUTION_HOST_ID
|
||||
if (!local || worktree.isArchived) {
|
||||
if (!local || worktree.isArchived || isWorktreeRetiredByRemoval(worktree)) {
|
||||
continue
|
||||
}
|
||||
for (const filePath of paths) {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isWorktreeRetiredByRemoval } from '../../../../../shared/worktree/removal-visibility'
|
||||
import { LOCAL_EXECUTION_HOST_ID } from '../../../../../shared/execution-host'
|
||||
import { folderWorkspaceKey } from '../../../../../shared/workspace-scope'
|
||||
import { getFolderWorkspaceWorktreeHostId } from '../../../../../shared/folder-workspaces/folder-workspace-worktree'
|
||||
@@ -7,6 +8,8 @@ type PickableWorktree = {
|
||||
id: string
|
||||
hostId?: string
|
||||
isArchived?: boolean
|
||||
removing?: true
|
||||
removalRecorded?: true
|
||||
lastActivityAt?: number
|
||||
}
|
||||
|
||||
@@ -22,7 +25,7 @@ export function pickWorkspaceToShow(
|
||||
hostId === undefined || hostId === LOCAL_EXECUTION_HOST_ID
|
||||
const worktree = Object.values(worktreesByRepo ?? {})
|
||||
.flat()
|
||||
.filter((each) => !each.isArchived && isLocal(each.hostId))
|
||||
.filter((each) => !each.isArchived && !isWorktreeRetiredByRemoval(each) && isLocal(each.hostId))
|
||||
.reduce<PickableWorktree | null>(
|
||||
(best, each) =>
|
||||
!best || (each.lastActivityAt ?? 0) > (best.lastActivityAt ?? 0) ? each : best,
|
||||
|
||||
@@ -258,3 +258,19 @@ it('attaches cross-store roots only to the resolved host when folder IDs collide
|
||||
expect(local.childWorktrees).toEqual([])
|
||||
expect(paired.owners.map((owner) => owner.worktree.id)).toEqual(['root', 'child'])
|
||||
})
|
||||
|
||||
it('retires an attached worktree at durable admission while legacy pending rows remain visible', () => {
|
||||
const child = makeWorktree({ id: 'repo-1::/retiring', removing: true })
|
||||
const list = (row: Worktree) =>
|
||||
getAttachedWorktreesForFolderWorkspace({
|
||||
activeWorkspaceKey: folderWorkspaceKey('folder-1'),
|
||||
activeWorktreeId: null,
|
||||
folderWorkspaces: [makeFolder()],
|
||||
workspaceLineageByChildKey: { [row.id]: makeWorkspaceLineage(row) },
|
||||
worktreeLineageById: {},
|
||||
worktreesByRepo: { 'repo-1': [row] },
|
||||
crossStoreChildrenByFolderId: new Map()
|
||||
}).childWorktrees.map((row) => row.id)
|
||||
expect(list(child)).toEqual(['repo-1::/retiring'])
|
||||
expect(list({ ...child, removalRecorded: true })).toEqual([])
|
||||
})
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isWorktreeRetiredByRemoval } from '../../../../shared/worktree/removal-visibility'
|
||||
import { getRepoExecutionHostId, type ExecutionHostId } from '../../../../shared/execution-host'
|
||||
import { folderWorkspaceKey, parseWorkspaceKey } from '../../../../shared/workspace-scope'
|
||||
import type { FolderWorkspace } from '../../../../shared/folder-workspaces/folder-workspace-types'
|
||||
@@ -107,7 +108,7 @@ export function getAttachedWorktreesForFolderWorkspace({
|
||||
const childrenByParent = new Map<string, Worktree[]>()
|
||||
for (const [identity, parent] of parentByIdentity) {
|
||||
const child = rows.get(identity)!
|
||||
if (child.isArchived) {
|
||||
if (child.isArchived || isWorktreeRetiredByRemoval(child)) {
|
||||
continue
|
||||
}
|
||||
const parentIdentity = getWorktreeHostIdentity(parent)
|
||||
@@ -131,6 +132,7 @@ export function getAttachedWorktreesForFolderWorkspace({
|
||||
const identity = getWorktreeHostIdentity(worktree)
|
||||
if (
|
||||
worktree.isArchived ||
|
||||
isWorktreeRetiredByRemoval(worktree) ||
|
||||
members.has(identity) ||
|
||||
selectedById.get(worktree.id) !== worktree
|
||||
) {
|
||||
@@ -220,7 +222,7 @@ export function getLineageChildrenByParentId(
|
||||
const queue = [...rootWorktreeIds]
|
||||
for (let index = 0; index < queue.length; index += 1) {
|
||||
for (const child of projectedChildrenByParentId.get(queue[index]) ?? []) {
|
||||
if (child.isArchived || includedIds.has(child.id)) {
|
||||
if (child.isArchived || isWorktreeRetiredByRemoval(child) || includedIds.has(child.id)) {
|
||||
continue
|
||||
}
|
||||
includedIds.add(child.id)
|
||||
@@ -231,7 +233,8 @@ export function getLineageChildrenByParentId(
|
||||
const descendantsByParentId = new Map<string, Worktree[]>()
|
||||
for (const parentId of includedIds) {
|
||||
const children = (projectedChildrenByParentId.get(parentId) ?? []).filter(
|
||||
(child) => includedIds.has(child.id) && !child.isArchived
|
||||
(child) =>
|
||||
includedIds.has(child.id) && !child.isArchived && !isWorktreeRetiredByRemoval(child)
|
||||
)
|
||||
if (children.length > 0) {
|
||||
descendantsByParentId.set(parentId, children)
|
||||
@@ -255,7 +258,7 @@ export function getLineageChildWorktree(
|
||||
return null
|
||||
}
|
||||
const worktree = worktreeById.get(childScope.worktreeId)
|
||||
if (!worktree || worktree.isArchived) {
|
||||
if (!worktree || worktree.isArchived || isWorktreeRetiredByRemoval(worktree)) {
|
||||
return null
|
||||
}
|
||||
if (lineage.childInstanceId && lineage.childInstanceId !== worktree.instanceId) {
|
||||
|
||||
+4
-1
@@ -1,3 +1,4 @@
|
||||
import { isWorktreeRetiredByRemoval } from '../../../../../../shared/worktree/removal-visibility'
|
||||
import {
|
||||
getWorktreeExecutionHostId,
|
||||
type ExecutionHostId
|
||||
@@ -59,7 +60,7 @@ export function worktreeParentPlacementFor({
|
||||
const isCrossStoreParent = crossStoreParentEligibility(child, parentIdentities)
|
||||
const closesLoop = closesResolvedLoop(child, worktrees, parentIdentities)
|
||||
return (candidate) => {
|
||||
if (closesLoop(candidate)) {
|
||||
if (isWorktreeRetiredByRemoval(candidate) || closesLoop(candidate)) {
|
||||
return null
|
||||
}
|
||||
if (
|
||||
@@ -126,6 +127,7 @@ function crossStoreParentEligibility(
|
||||
store !== undefined &&
|
||||
store !== childStore &&
|
||||
!candidate.isArchived &&
|
||||
!isWorktreeRetiredByRemoval(candidate) &&
|
||||
Boolean(candidate.instanceId) &&
|
||||
getWorktreeHostIdentity(candidate) !== currentParent
|
||||
)
|
||||
@@ -179,6 +181,7 @@ export function isEligibleWorktreeParent({
|
||||
childHostId !== null &&
|
||||
getWorktreeOwnerHostId(candidateParent, repoMap) === childHostId &&
|
||||
!candidateParent.isArchived &&
|
||||
!isWorktreeRetiredByRemoval(candidateParent) &&
|
||||
canAssignWorktreeParent({
|
||||
child,
|
||||
candidateParent,
|
||||
|
||||
+2
-1
@@ -1,3 +1,4 @@
|
||||
import { isWorktreeRetiredByRemoval } from '../../../../../../shared/worktree/removal-visibility'
|
||||
import {
|
||||
getWorktreeExecutionHostId,
|
||||
type ExecutionHostId
|
||||
@@ -33,7 +34,7 @@ export function buildDesktopWorkspaceRowFactReader(
|
||||
inputs: DesktopWorkspaceRowFactInputs
|
||||
): WorkspaceRowFactReader<Worktree> {
|
||||
return {
|
||||
isArchived: (worktree) => worktree.isArchived,
|
||||
isArchived: (worktree) => worktree.isArchived || isWorktreeRetiredByRemoval(worktree),
|
||||
isFolderWorkspace: (worktree) => parseWorkspaceKey(worktree.id)?.type === 'folder',
|
||||
repoId: (worktree) => worktree.repoId,
|
||||
hostId: (worktree) => {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isWorktreeRetiredByRemoval } from '../../../../shared/worktree/removal-visibility'
|
||||
import { useMemo } from 'react'
|
||||
import { getStructuredChatWorktreeIds } from '@/components/sidebar/worktree-list/listing/visible-worktree-activity-inputs'
|
||||
import { filterWorkspaceRows } from '../../../../shared/workspace-view/workspace-row-filters'
|
||||
@@ -187,7 +188,9 @@ export function useWorktreeJumpPaletteWorktrees({
|
||||
const sortedWorktrees = useMemo(
|
||||
() =>
|
||||
hasQuery
|
||||
? browserSortedWorktrees.filter((worktree) => !worktree.isArchived)
|
||||
? browserSortedWorktrees.filter(
|
||||
(worktree) => !worktree.isArchived && !isWorktreeRetiredByRemoval(worktree)
|
||||
)
|
||||
: searchScopeWorktrees,
|
||||
[hasQuery, browserSortedWorktrees, searchScopeWorktrees]
|
||||
)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isWorktreeRetiredByRemoval } from '../../../../shared/worktree/removal-visibility'
|
||||
import { worktreeMatchesGitHubNumber } from '@/lib/work-items/github/github-work-item-workspace-attachment'
|
||||
import { getPaletteWorktreeExecutionHostId } from '@/lib/workspace/search/palette-repo-resolution'
|
||||
import { findRepoForHost } from '@/store/repos/repo-host-identity'
|
||||
@@ -184,6 +185,7 @@ export function createWorktreeJumpPaletteWorktreeHandler({
|
||||
const matches = workspaces.filter(
|
||||
(worktree) =>
|
||||
!worktree.isArchived &&
|
||||
!isWorktreeRetiredByRemoval(worktree) &&
|
||||
worktreeMatchesGitHubNumber(
|
||||
worktree,
|
||||
ghNumber,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isWorktreeRetiredByRemoval } from '../../../../../shared/worktree/removal-visibility'
|
||||
import type { LinearIssue } from '../../../../../shared/linear/issue-types'
|
||||
import { getWorkspaceAttachments } from '../../../../../shared/workspace-attachments/workspace-attachments'
|
||||
import type { Worktree } from '../../../../../shared/worktree/types'
|
||||
@@ -96,6 +97,7 @@ export function findLinearIssueWorkspaceAttachment(
|
||||
worktrees.filter(
|
||||
(worktree) =>
|
||||
!worktree.isArchived &&
|
||||
!isWorktreeRetiredByRemoval(worktree) &&
|
||||
getWorkspaceAttachments(worktree).some(
|
||||
(item) =>
|
||||
item.provider === 'linear' &&
|
||||
@@ -112,7 +114,7 @@ export function buildLinearIssueWorkspaceAttachmentIndex(
|
||||
): LinearIssueWorkspaceAttachmentIndex {
|
||||
const index = new Map<string, Worktree[]>()
|
||||
for (const worktree of worktrees) {
|
||||
if (worktree.isArchived) {
|
||||
if (worktree.isArchived || isWorktreeRetiredByRemoval(worktree)) {
|
||||
continue
|
||||
}
|
||||
const identifiers = new Set(
|
||||
|
||||
@@ -97,6 +97,25 @@ const resolution = {
|
||||
}
|
||||
|
||||
describe('deleting the active workspace', () => {
|
||||
it('navigates on durable retirement while retaining the checkout and its draft state', async () => {
|
||||
const store = setup()
|
||||
const before = store.getState()
|
||||
store.setState({ worktreesByRepo: { repo1: [{ ...active, removing: true }, sibling, main] } })
|
||||
await Promise.resolve()
|
||||
expect(activateAndRevealWorktree).not.toHaveBeenCalled()
|
||||
store.setState({
|
||||
worktreesByRepo: {
|
||||
repo1: [{ ...active, removing: true, removalRecorded: true }, sibling, main]
|
||||
}
|
||||
})
|
||||
await Promise.resolve()
|
||||
expect(activateAndRevealWorktree).toHaveBeenCalledWith(sibling.id, {
|
||||
revealInSidebar: false,
|
||||
executionHostId: 'local'
|
||||
})
|
||||
expect(store.getState().worktreesByRepo.repo1.find((row) => row.id === active.id)).toBeDefined()
|
||||
expect(store.getState().tabsByWorktree).toBe(before.tabsByWorktree)
|
||||
})
|
||||
it('respects a user closing the last browser tab after startup dropped its row', async () => {
|
||||
const store = setup()
|
||||
layoutMain = await drawTabsFromMain(store)
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
} from '../../../../../shared/execution-host'
|
||||
import type { Repo } from '../../../../../shared/repo-types'
|
||||
import type { Worktree } from '../../../../../shared/worktree/types'
|
||||
import { isWorktreeRetiredByRemoval } from '../../../../../shared/worktree/removal-visibility'
|
||||
import { selectWorktreesByRepo } from '@/store/workspaces/catalog/workspace-record-fields'
|
||||
|
||||
type RemovedActiveRow = {
|
||||
@@ -81,6 +82,7 @@ export function pickActiveWorktreeSuccessor(
|
||||
const siblings = (selectWorktreesByRepo(state)[removed.repoId] ?? []).filter(
|
||||
(worktree) =>
|
||||
!getDeleteStateForWorktreeHost(worktree, state.deleteStateByWorktreeId)?.isDeleting &&
|
||||
!isWorktreeRetiredByRemoval(worktree) &&
|
||||
!isHostedOnRuntimeOwnedSshTarget(worktree, repoById) &&
|
||||
!isHiddenAsleep?.(worktree)
|
||||
)
|
||||
@@ -135,6 +137,44 @@ export function installActiveWorktreeRemovalSuccessor(store = useAppStore): () =
|
||||
return row && !isScoped(row) ? row : null
|
||||
}
|
||||
witness = observe()
|
||||
const retireAcceptedSelection = (state: AppState): boolean => {
|
||||
const removed = listedActiveRow(state)
|
||||
const row = removed ? findListedRow(state, removed.id, removed.hostId) : undefined
|
||||
if (!removed || !row || !isWorktreeRetiredByRemoval(row) || isScoped(removed)) {
|
||||
return false
|
||||
}
|
||||
const scheduled = ++generation
|
||||
queueMicrotask(() => {
|
||||
const current = store.getState()
|
||||
const active = findListedRow(current, removed.id, removed.hostId)
|
||||
if (
|
||||
generation !== scheduled ||
|
||||
current.activeView !== 'terminal' ||
|
||||
current.activePendingCreationId !== null ||
|
||||
current.activeWorktreeId !== removed.id ||
|
||||
current.activeWorkspaceExecutionHostId !== removed.hostId ||
|
||||
!active ||
|
||||
!isWorktreeRetiredByRemoval(active)
|
||||
) {
|
||||
return
|
||||
}
|
||||
witness = null
|
||||
const successor = pickActiveWorktreeSuccessor(
|
||||
current,
|
||||
removed,
|
||||
getSidebarSleepingSweepRetainedIds()
|
||||
)
|
||||
if (successor) {
|
||||
activateAndRevealWorktree(successor.id, {
|
||||
revealInSidebar: false,
|
||||
executionHostId: successor.hostId
|
||||
})
|
||||
} else {
|
||||
current.setActiveWorktree(null)
|
||||
}
|
||||
})
|
||||
return true
|
||||
}
|
||||
const unsubscribeIntent = subscribeWorktreeDeselectionIntent((scope, entering) => {
|
||||
if (!scope || entering) {
|
||||
if (scope) {
|
||||
@@ -178,6 +218,9 @@ export function installActiveWorktreeRemovalSuccessor(store = useAppStore): () =
|
||||
return
|
||||
}
|
||||
if (next.activeWorktreeId !== null) {
|
||||
if (retireAcceptedSelection(next)) {
|
||||
return
|
||||
}
|
||||
const listed = observe()
|
||||
// An unlisted pointer to the witness is a row dropped before its selection clears.
|
||||
if (listed || witness?.id !== next.activeWorktreeId) {
|
||||
@@ -226,6 +269,9 @@ export function installActiveWorktreeRemovalSuccessor(store = useAppStore): () =
|
||||
}
|
||||
})
|
||||
})
|
||||
if (store.getState().activeView === 'terminal') {
|
||||
retireAcceptedSelection(store.getState())
|
||||
}
|
||||
return () => {
|
||||
generation += 1
|
||||
unsubscribeIntent()
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isWorktreeRetiredByRemoval } from '../../../../../shared/worktree/removal-visibility'
|
||||
import { runtimeEnvironmentIdOrLocalUnlessTwin } from '../ownership/worktree-runtime-owner'
|
||||
import { noteUserWorkspaceOpen } from './workspace-switch-user-act'
|
||||
import { useAppStore } from '@/store/index'
|
||||
@@ -155,7 +156,7 @@ export function activateAndRevealWorktreeWithOutcome(
|
||||
return { opened: { primaryTabId: null } }
|
||||
}
|
||||
const wt = state.getKnownWorktreeById(worktreeId, opts?.executionHostId)
|
||||
if (!wt) {
|
||||
if (!wt || isWorktreeRetiredByRemoval(wt)) {
|
||||
return { refused: { reason: 'workspace-missing', failureNotified: false } }
|
||||
}
|
||||
const pendingCreationId = findPendingWorktreeCreationId(state.pendingWorktreeCreations, wt.id)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isWorktreeRetiredByRemoval } from '../../../../../../shared/worktree/removal-visibility'
|
||||
import { matchPaletteDocument } from '../../../../../../shared/palette-match/match-document'
|
||||
import { preparePaletteQuery } from '../../../../../../shared/palette-match/palette-query'
|
||||
import type { MatchRange } from '../../../../../../shared/palette-match/normalized-text'
|
||||
@@ -80,7 +81,9 @@ export function getWorktreePaletteSearchScope(args: {
|
||||
}
|
||||
|
||||
// Explicit search recovers sleeping/default-branch workspaces hidden by sidebar filters.
|
||||
return args.allWorktrees.filter((worktree) => !worktree.isArchived)
|
||||
return args.allWorktrees.filter(
|
||||
(worktree) => !worktree.isArchived && !isWorktreeRetiredByRemoval(worktree)
|
||||
)
|
||||
}
|
||||
|
||||
function makeEmptyPaletteSearchResult(
|
||||
|
||||
@@ -93,3 +93,27 @@ describe('a composer parent picked on another machine', () => {
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
it('drops a retained parent pick after durable removal, but keeps legacy pending picks', () => {
|
||||
const store = createTestStore()
|
||||
const parent = makeWorktree({
|
||||
id: 'repo1::/parent',
|
||||
repoId: 'repo1',
|
||||
hostId: 'local',
|
||||
displayName: 'Parent',
|
||||
removing: true
|
||||
})
|
||||
store.setState({ repos: [TEST_REPO], worktreesByRepo: { repo1: [parent] } })
|
||||
expect(resolveWorktreeCreateParent(store.getState(), parent.id, 'local').staleBeforeCreate).toBe(
|
||||
false
|
||||
)
|
||||
store.setState({ worktreesByRepo: { repo1: [{ ...parent, removalRecorded: true }] } })
|
||||
for (const pick of [parent.id, `local|${parent.id}`]) {
|
||||
expect(resolveWorktreeCreateParent(store.getState(), pick, 'local')).toMatchObject({
|
||||
staleBeforeCreate: true
|
||||
})
|
||||
expect(
|
||||
resolveWorktreeCreateParent(store.getState(), pick, 'runtime:other').crossStoreParentRow
|
||||
).toBeUndefined()
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isWorktreeRetiredByRemoval } from '../../../../../../shared/worktree/removal-visibility'
|
||||
import { toast } from 'sonner'
|
||||
import { translate } from '@/i18n/i18n'
|
||||
import { resolveWorktreeDisplayName } from '@/lib/workspace/display/worktree-default-display-name'
|
||||
@@ -89,7 +90,7 @@ export function resolveWorktreeCreateParent(
|
||||
(candidate) => getWorktreeHostIdentity(candidate) === requestedParentWorktreeId
|
||||
)
|
||||
// The pick outlives a destination change; a parent now on the creation host is an ordinary one.
|
||||
if (row && !row.isArchived && !isOnCreationHost(row)) {
|
||||
if (row && !row.isArchived && !isWorktreeRetiredByRemoval(row) && !isOnCreationHost(row)) {
|
||||
return {
|
||||
crossStoreParentRow: row,
|
||||
pickedParentWorktreeId: row.id,
|
||||
@@ -97,7 +98,7 @@ export function resolveWorktreeCreateParent(
|
||||
staleBeforeCreate: false
|
||||
}
|
||||
}
|
||||
if (!row || row.isArchived) {
|
||||
if (!row || row.isArchived || isWorktreeRetiredByRemoval(row)) {
|
||||
return {
|
||||
pickedDisplayName: row ? resolveWorktreeDisplayName(row).trim() : null,
|
||||
staleBeforeCreate: true
|
||||
@@ -109,7 +110,8 @@ export function resolveWorktreeCreateParent(
|
||||
isOnCreationHost
|
||||
)
|
||||
}
|
||||
const usable = picked && !picked.isArchived ? picked.id : undefined
|
||||
const usable =
|
||||
picked && !picked.isArchived && !isWorktreeRetiredByRemoval(picked) ? picked.id : undefined
|
||||
const pickedDisplayName = picked ? resolveWorktreeDisplayName(picked).trim() : null
|
||||
if (usable) {
|
||||
return {
|
||||
|
||||
@@ -137,6 +137,8 @@ export type RuntimeWorktreePsSummary = {
|
||||
agents: RuntimeWorktreeAgentRow[]
|
||||
/** See `Worktree.removing`; sent only to clients that advertise background removal. */
|
||||
removing?: true
|
||||
/** The owning host committed removal intent before publishing this row. */
|
||||
removalRecorded?: true
|
||||
/** See `GitWorktreeInfo.removalError`. */
|
||||
removalError?: string
|
||||
/** Host-derived workspace kinds. Missing defaultBranch retains reader guesses; other missing flags show the row.
|
||||
|
||||
@@ -45,6 +45,9 @@ const PairedServerWorkspaceRowSchema = z
|
||||
// Server-owned sorting/filter/lineage facts; older desktops omit them. Lineage is the checked edge, not the raw record.
|
||||
WorkspaceRowSchema.pick({
|
||||
isMainWorktree: true,
|
||||
removing: true,
|
||||
removalRecorded: true,
|
||||
removalError: true,
|
||||
isUnread: true,
|
||||
instanceId: true,
|
||||
lineage: true,
|
||||
@@ -124,6 +127,9 @@ export function pairedServerRowOfWorktree(
|
||||
branch: worktree.branch,
|
||||
displayName: worktree.displayName,
|
||||
isArchived: worktree.isArchived,
|
||||
...(worktree.removing ? { removing: true } : {}),
|
||||
...(worktree.removalRecorded ? { removalRecorded: true } : {}),
|
||||
...(worktree.removalError ? { removalError: worktree.removalError } : {}),
|
||||
isPinned: worktree.isPinned,
|
||||
isMainWorktree: worktree.isMainWorktree,
|
||||
isUnread: worktree.isUnread,
|
||||
@@ -180,6 +186,9 @@ const ServerWorktreePsRowSchema = z.object({
|
||||
branch: z.string().catch(''),
|
||||
displayName: z.string().catch(''),
|
||||
isArchived: z.boolean().catch(false),
|
||||
removing: z.literal(true).optional().catch(undefined),
|
||||
removalRecorded: z.literal(true).optional().catch(undefined),
|
||||
removalError: z.string().optional().catch(undefined),
|
||||
isPinned: z.boolean().catch(false),
|
||||
isMainWorktree: z.boolean().catch(false),
|
||||
unread: z.boolean().optional().catch(undefined),
|
||||
|
||||
@@ -10,13 +10,18 @@ import { normalizePairedServerRow } from './paired-server-rows'
|
||||
import type { SidebarFeedDomains } from './sidebar-feed-domains'
|
||||
import {
|
||||
buildSidebarFeedRows,
|
||||
planSidebarFeedRows,
|
||||
type SidebarFeedCatalog,
|
||||
type SidebarFeedView
|
||||
} from './sidebar-feed-rows'
|
||||
import { IDLE_WORKSPACE_ACTIVITY } from './workspace-activity-facts'
|
||||
import { composeWorktreeHostIdentity } from '../worktree/host-qualified-identity'
|
||||
import { buildWorkspaceRows } from './workspace-rows'
|
||||
import { buildFeedHostOptions } from './sidebar-feed-index'
|
||||
import {
|
||||
buildFeedHostOptions,
|
||||
indexSidebarFeed,
|
||||
rankSidebarFeedWorktrees
|
||||
} from './sidebar-feed-index'
|
||||
import { folderWorkspaceRepoId } from '../folder-workspaces/folder-workspace-worktree'
|
||||
|
||||
function worktree(id: string, overrides: Partial<Worktree> = {}): Worktree {
|
||||
@@ -97,6 +102,73 @@ function outline(rows: readonly HostSectionRow[]): string[] {
|
||||
})
|
||||
}
|
||||
|
||||
it('retires only recorded deletions through paired feed, pins, forced reveal and lineage', () => {
|
||||
const rows = [
|
||||
normalizePairedServerRow('runtime:a', {
|
||||
worktreeId: 'r::/p',
|
||||
repoId: 'r',
|
||||
worktreeInstanceId: 'p',
|
||||
isPinned: true,
|
||||
removing: true,
|
||||
removalRecorded: true
|
||||
}),
|
||||
normalizePairedServerRow('runtime:a', {
|
||||
worktreeId: 'r::/c',
|
||||
repoId: 'r',
|
||||
worktreeInstanceId: 'c',
|
||||
parentWorktreeId: 'r::/p',
|
||||
lineageWorktreeInstanceId: 'c',
|
||||
parentWorktreeInstanceId: 'p'
|
||||
}),
|
||||
normalizePairedServerRow('runtime:a', {
|
||||
worktreeId: 'r::/legacy',
|
||||
repoId: 'r',
|
||||
removing: true
|
||||
}),
|
||||
normalizePairedServerRow('runtime:a', {
|
||||
worktreeId: 'r::/failed',
|
||||
repoId: 'r',
|
||||
removalError: 'Cleanup failed. Retry deletion.'
|
||||
}),
|
||||
normalizePairedServerRow('runtime:b', { worktreeId: 'r::/p', repoId: 'r' })
|
||||
].flatMap((row) => row ?? [])
|
||||
const repos = [
|
||||
repo('r', { executionHostId: 'runtime:a' }),
|
||||
repo('r', { executionHostId: 'runtime:b' })
|
||||
]
|
||||
const inputs = domains({
|
||||
pairedServerHosts: new Map(
|
||||
['runtime:a', 'runtime:b'].map((hostId) => [
|
||||
hostId,
|
||||
{ freshness: 'live' as const, host: null }
|
||||
])
|
||||
),
|
||||
pairedServerRows: new Map(rows.map((row) => [row.key, row]))
|
||||
})
|
||||
const settings = view({ pinnedDisplayPolicy: 'duplicate-in-groups' })
|
||||
const index = indexSidebarFeed(inputs, repos)
|
||||
const planned = planSidebarFeedRows(
|
||||
inputs,
|
||||
index,
|
||||
catalog(repos),
|
||||
settings,
|
||||
rankSidebarFeedWorktrees(index, 'recent'),
|
||||
{ forcedVisibleWorktreeIds: ['r::/p'] }
|
||||
)
|
||||
expect(planned.visibleWorktrees.map((row) => `${row.hostId}|${row.id}`).sort()).toEqual([
|
||||
'runtime:a|r::/c',
|
||||
'runtime:a|r::/failed',
|
||||
'runtime:a|r::/legacy',
|
||||
'runtime:b|r::/p'
|
||||
])
|
||||
const built = buildSidebarFeedRows(inputs, catalog(repos), settings)
|
||||
expect(outline(built.sectionRows)).toContain('runtime:a|r::/c@0')
|
||||
expect(outline(built.sectionRows)).not.toContain('runtime:a|r::/p@0')
|
||||
expect(built.visibleWorktrees.find((row) => row.id === 'r::/failed')?.removalError).toBe(
|
||||
'Cleanup failed. Retry deletion.'
|
||||
)
|
||||
})
|
||||
|
||||
describe('buildSidebarFeedRows keeps same-id workspaces on two hosts apart', () => {
|
||||
// The same repo registered locally and on an SSH box: `r::/w/same` names two workspaces.
|
||||
const repos = [repo('r'), repo('r', { connectionId: 'box' })]
|
||||
|
||||
@@ -49,6 +49,9 @@ type FeedRowFields = Pick<
|
||||
Pick<
|
||||
WorkspaceRow,
|
||||
| 'isMainWorktree'
|
||||
| 'removing'
|
||||
| 'removalRecorded'
|
||||
| 'removalError'
|
||||
| 'isUnread'
|
||||
| 'instanceId'
|
||||
| 'lineage'
|
||||
@@ -106,6 +109,9 @@ function readFeedRow(
|
||||
linkedLinearIssue: null,
|
||||
isMainWorktree: row.isMainWorktree ?? false,
|
||||
isArchived: row.isArchived,
|
||||
...(row.removing ? { removing: true } : {}),
|
||||
...(row.removalRecorded ? { removalRecorded: true } : {}),
|
||||
...(row.removalError ? { removalError: row.removalError } : {}),
|
||||
isPinned: row.isPinned,
|
||||
isUnread: row.isUnread ?? false,
|
||||
workspaceStatus: row.workspaceStatus,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { WorktreeLineage } from '../worktree/lineage-types'
|
||||
import type { Worktree } from '../worktree/types'
|
||||
import { getWorktreeHostIdentity } from '../worktree/host-qualified-identity'
|
||||
import { isWorktreeRetiredByRemoval } from '../worktree/removal-visibility'
|
||||
import {
|
||||
filterWorkspaceRows,
|
||||
type WorkspaceRowFactReader,
|
||||
@@ -46,7 +47,10 @@ export function selectVisibleSidebarWorktrees({
|
||||
// Keep valid nonarchived ancestors despite ordinary filters so children retain their hierarchy.
|
||||
const selectedRepoIds = filterRepoIds.length > 0 ? new Set(filterRepoIds) : null
|
||||
|
||||
let all = filterWorkspaceRows(rows, filters, facts)
|
||||
let all = filterWorkspaceRows(rows, filters, {
|
||||
...facts,
|
||||
isArchived: (row) => facts.isArchived(row) || isWorktreeRetiredByRemoval(row)
|
||||
})
|
||||
|
||||
if (forcedVisibleWorktreeIds && forcedVisibleWorktreeIds.length > 0) {
|
||||
const includedIds = new Set(all.map((worktree) => worktree.id))
|
||||
@@ -54,7 +58,7 @@ export function selectVisibleSidebarWorktrees({
|
||||
const worktree = includedIds.has(worktreeId)
|
||||
? undefined
|
||||
: [...ancestorByIdentity.values()].find((candidate) => candidate.id === worktreeId)
|
||||
if (worktree) {
|
||||
if (worktree && !isWorktreeRetiredByRemoval(worktree)) {
|
||||
includedIds.add(worktreeId)
|
||||
all.push(worktree)
|
||||
}
|
||||
@@ -106,6 +110,9 @@ function addVisibleLineageAncestors(
|
||||
// An older peer's loop reaches a row again before it is included.
|
||||
const visiting = new Set<string>()
|
||||
const addWithAncestors = (worktree: Worktree): void => {
|
||||
if (isWorktreeRetiredByRemoval(worktree)) {
|
||||
return
|
||||
}
|
||||
const identity = getWorktreeHostIdentity(worktree)
|
||||
if (included.has(identity) || visiting.has(identity)) {
|
||||
return
|
||||
|
||||
@@ -71,6 +71,9 @@ export const WorkspaceRowSchema = z.object({
|
||||
workspaceLineage: WorkspaceLineageEdgeSchema,
|
||||
isPinned: z.boolean(),
|
||||
isArchived: z.boolean(),
|
||||
removing: z.literal(true).optional(),
|
||||
removalRecorded: z.literal(true).optional(),
|
||||
removalError: z.string().optional(),
|
||||
isUnread: z.boolean(),
|
||||
workspaceStatus: z.string(),
|
||||
comment: z.string(),
|
||||
@@ -144,6 +147,9 @@ function toWorkspaceRow(
|
||||
...(workspaceLineage !== undefined ? { workspaceLineage } : {}),
|
||||
isPinned: worktree.isPinned,
|
||||
isArchived: worktree.isArchived,
|
||||
...(worktree.removing ? { removing: true } : {}),
|
||||
...(worktree.removalRecorded ? { removalRecorded: true } : {}),
|
||||
...(worktree.removalError ? { removalError: worktree.removalError } : {}),
|
||||
isUnread: worktree.isUnread,
|
||||
workspaceStatus: worktree.workspaceStatus ?? DEFAULT_WORKSPACE_STATUS_ID,
|
||||
comment: worktree.comment,
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import type { GitWorktreeInfo } from './types'
|
||||
|
||||
/** Legacy removing markers do not prove the owner can resume cleanup after restart. */
|
||||
export function isWorktreeRetiredByRemoval(
|
||||
row: Pick<GitWorktreeInfo, 'removing' | 'removalRecorded'>
|
||||
): boolean {
|
||||
return row.removing === true && row.removalRecorded === true
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import type { GitWorktreeInfo, Worktree } from './types'
|
||||
|
||||
export function unregisteredFolderRefusal(worktreePath: string): Error {
|
||||
return new Error(
|
||||
`${worktreePath} is no longer a Git worktree, so its folder was left on disk. Delete the folder yourself to finish removing this workspace.`
|
||||
`${worktreePath} is no longer a Git worktree, so its folder was left on disk. Remove the remaining folder yourself, then retry deletion to finish cleanup.`
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -62,6 +62,9 @@ export type GitWorktreeInfo = {
|
||||
isMainWorktree: boolean
|
||||
/** Local delete failed after Git deregistration; list the leftover so Delete can retry. */
|
||||
removalError?: string
|
||||
removing?: true
|
||||
/** The owning host durably recorded this pending deletion. Older hosts omit it. */
|
||||
removalRecorded?: true
|
||||
}
|
||||
|
||||
/** Read HEAD/branch without spawning Git to refresh background head moves without structural worktrees:changed fanout. */
|
||||
@@ -164,9 +167,6 @@ export type Worktree = {
|
||||
mobileDiffReview?: MobileDiffReviewState
|
||||
automationProvenance?: AutomationWorkspaceProvenance
|
||||
cliProvenance?: CliWorkspaceProvenance
|
||||
/** The host is deleting this checkout in the background; Git lists it until that finishes.
|
||||
* Sent only to clients that advertise `worktree.background-removal.v1`. */
|
||||
removing?: true
|
||||
} & GitWorktreeInfo
|
||||
|
||||
/** Only CLI-created workspaces carry this; missing means not CLI-created, including older rows. */
|
||||
|
||||
Reference in New Issue
Block a user