Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions src/main/workspaces/cleanup/workspace-cleanup-removal-step.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ export async function removeWorkspaceForCleanup(args: {
globalRules: () => WorkspaceCleanupRules
workspace: WorkspaceCleanupWorkspace
now: () => number
/** The other checkouts of the same folder workspace; they must stay removable right now too. */
folderMemberWorktreeIds?: readonly string[]
signal?: AbortSignal
}): Promise<RemovalOutcome> {
const { runtime, store, workspace } = args
Expand All @@ -99,6 +101,31 @@ export async function removeWorkspaceForCleanup(args: {
if (recheck.action === 'keep') {
return { ...keptRunOutcome(recheck), keptOnRecheck: true }
}
// A folder workspace cleans as one unit: a sibling that is being used right now keeps this
// checkout in place too, on evidence read at this moment rather than the run's scan (#44715).
for (const memberId of args.folderMemberWorktreeIds ?? []) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Stability & Availability · Quick win

Re-check the selected workspace's unsaved-editor protection right before the delete.

The selected workspace is decided before the sibling loop starts, and the loop awaits evidence collection for each sibling. An unsaved editor buffer that appears during that wait is not seen. The removal then runs on the earlier decision. The inspected removal path does not check unsaved editor state, and Git's non-forced refusal does not cover editor buffers. The gap existed before this change, but the sibling loop widens it.

The delete must not rely on a protection decision that is older than the delete itself. Re-decide the selected workspace after the sibling loop and before queueing the removal, or enforce the unsaved-editor protection in the removal path. A re-check alone narrows the window but does not close it.

const [member] = await collectWorkspaceCleanupWorkspaces({
store,
runtime,
globalRules: args.globalRules(),
now: args.now(),
worktreeId: memberId,
signal: args.signal
})
if (!member) {
return {
...keptRunOutcome({ action: 'keep', cause: 'folder-mate-in-use' }),
keptOnRecheck: true
}
}
const memberDecision = await decideWorkspaceCleanup(runtime, member, args.now())
if (memberDecision.action === 'keep') {
return {
...keptRunOutcome({ action: 'keep', cause: 'folder-mate-in-use' }),
keptOnRecheck: true
}
}
}
if (args.signal?.aborted) {
return { outcome: 'failed', error: 'Cleanup stopped before removing this workspace.' }
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ export type WorkspaceCleanupWorkspace = {
input: WorkspaceCleanupEvaluationInput
paneAgentStates: WorkspaceCleanupPaneAgentStates
removing: boolean
/** The folder workspace this checkout is attached to; siblings clean as one unit (#44715). */
folderParentKey?: string
}

/** Repos whose checkouts this process owns; a host served by its own orcad is that server's to clean. */
Expand Down Expand Up @@ -238,7 +240,10 @@ export async function collectWorkspaceCleanupWorkspaces(args: {
dirtyEditors.has(worktreeIdentityKey(summary.worktreeId))
),
paneAgentStates,
removing: summary.removing === true
removing: summary.removing === true,
...(summary.workspaceLineage?.parentWorkspaceKey
? { folderParentKey: summary.workspaceLineage.parentWorkspaceKey }
: {})
}
})
}
28 changes: 27 additions & 1 deletion src/main/workspaces/cleanup/workspace-cleanup-runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import {
type WorkspaceCleanupWorkspace
} from './workspace-cleanup-run-evidence'
import { decideWorkspaceCleanup, removeWorkspaceForCleanup } from './workspace-cleanup-removal-step'
import { applyFolderWorkspaceCleanupGroupVeto } from '../../../shared/workspace-cleanup/workspace-cleanup-folder-group'
import {
keptRunOutcome,
summarizeWorkspaceCleanupRun,
Expand Down Expand Up @@ -261,7 +262,14 @@ export class WorkspaceCleanupRunner {
evaluation: await decideWorkspaceCleanup(this.deps.runtime, workspace, now)
})
}
return decided
// A folder workspace cleans as one unit: any member that keeps vetoes its siblings (#44715).
const evaluations = applyFolderWorkspaceCleanupGroupVeto(
decided.map(({ workspace, evaluation }) => ({
...(workspace.folderParentKey ? { folderParentKey: workspace.folderParentKey } : {}),
evaluation
}))
)
return decided.map((row, index) => ({ ...row, evaluation: evaluations[index]! }))
}

private async readSizes(): Promise<Map<string, number>> {
Expand Down Expand Up @@ -293,16 +301,34 @@ export class WorkspaceCleanupRunner {
}
// Nested checkouts first, so a parent's removal never sweeps a child it did not re-check.
removals.sort((a, b) => b.ref.path.length - a.ref.path.length)
// Folder siblings must stay removable at this moment too, not just at scan time (#44715).
const folderMembers = new Map<string, string[]>()
for (const { workspace } of decided) {
const parent = workspace.folderParentKey
if (parent !== undefined) {
const ids = folderMembers.get(parent) ?? []
ids.push(workspace.ref.worktreeId)
folderMembers.set(parent, ids)
}
}
for (const { workspace, ref, reason } of removals) {
if (this.abort.signal.aborted) {
break
}
const parent = workspace.folderParentKey
const outcome = await removeWorkspaceForCleanup({
runtime: this.deps.runtime,
store: this.deps.store,
globalRules: () => this.globalRules(),
workspace,
now: () => Date.now(),
...(parent !== undefined
? {
folderMemberWorktreeIds: (folderMembers.get(parent) ?? []).filter(
(id) => id !== workspace.ref.worktreeId
Comment on lines +327 to +328

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major · Functional Correctness · Quick win

Exclude successfully removed folder members from later sibling checks.

After a folder member is removed, its ID stays in folderMemberWorktreeIds for the remaining members. The sibling re-check then finds no row for that ID, or finds it in removing state, and returns folder-mate-in-use. The remaining members are kept even though they are otherwise removable. This can leave a folder with only one cleaned checkout. The keep reason is also inaccurate, because the blocking member was removed successfully.

Track the IDs of successful removals during the run and exclude them from the sibling list. Failed and kept members stay in the list.

Suggested fix

       const folderMembers = new Map<string, string[]>()
+      const removedWorktreeIds = new Set<string>()
       for (const { workspace } of decided) {
...
                 folderMemberWorktreeIds: (folderMembers.get(parent) ?? []).filter(
-                  (id) => id !== workspace.ref.worktreeId
+                  (id) => id !== workspace.ref.worktreeId && !removedWorktreeIds.has(id)
                 )
               }
             : {}),
           signal: this.abort.signal
         })
+        if (outcome.outcome === 'removed') {
+          removedWorktreeIds.add(workspace.ref.worktreeId)
+        }
         rows.push({ ...ref, reason, ...outcome })

)
}
: {}),
signal: this.abort.signal
})
rows.push({ ...ref, reason, ...outcome })
Expand Down
2 changes: 2 additions & 0 deletions src/shared/workspace-cleanup/workspace-cleanup-evaluation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ export type WorkspaceCleanupKeepCause =
| 'archive-unavailable'
| 'archive-script'
| 'removing'
/** A sibling checkout of the same folder workspace must keep, and the folder cleans as one unit. */
| 'folder-mate-in-use'

export type WorkspaceCleanupWaiting = { elapsedDays: number; afterDays: number }

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// @vitest-environment node
import { describe, expect, it } from 'vitest'
import type { WorkspaceCleanupEvaluation } from './workspace-cleanup-evaluation'
import { applyFolderWorkspaceCleanupGroupVeto } from './workspace-cleanup-folder-group'

const remove: WorkspaceCleanupEvaluation = { action: 'delete', reason: 'merged' }
const keepDirty: WorkspaceCleanupEvaluation = {
action: 'keep',
cause: 'uncommitted-changes'
}

describe('applyFolderWorkspaceCleanupGroupVeto', () => {
it('keeps every sibling when one folder member must keep', () => {
const evaluations = applyFolderWorkspaceCleanupGroupVeto([
{ folderParentKey: 'folder-1', evaluation: remove },
{ folderParentKey: 'folder-1', evaluation: keepDirty }
])
expect(evaluations).toEqual([
{ action: 'keep', cause: 'folder-mate-in-use' },
// The member that raised the veto keeps its own, more specific cause.
keepDirty
])
})

it('removes every member when all of them are removable', () => {
const evaluations = applyFolderWorkspaceCleanupGroupVeto([
{ folderParentKey: 'folder-1', evaluation: remove },
{ folderParentKey: 'folder-1', evaluation: { action: 'delete', reason: 'inactive' } }
])
expect(evaluations).toEqual([remove, { action: 'delete', reason: 'inactive' }])
})

it('leaves workspaces outside any folder workspace untouched', () => {
const evaluations = applyFolderWorkspaceCleanupGroupVeto([
{ evaluation: remove },
{ folderParentKey: 'folder-1', evaluation: keepDirty }
])
expect(evaluations).toEqual([remove, keepDirty])
})

it('does not cross groups', () => {
const evaluations = applyFolderWorkspaceCleanupGroupVeto([
{ folderParentKey: 'folder-1', evaluation: remove },
{ folderParentKey: 'folder-2', evaluation: keepDirty }
])
expect(evaluations).toEqual([remove, keepDirty])
})
})
30 changes: 30 additions & 0 deletions src/shared/workspace-cleanup/workspace-cleanup-folder-group.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import type { WorkspaceCleanupEvaluation } from './workspace-cleanup-evaluation'

/**
* A folder workspace is one unit of work: its attached checkouts (one per repo) clean up only when
* every member is removable. Any member that must keep vetoes its siblings, so cleanup never pulls
* one repo's checkout out from under another repo still being worked on (#44715).
*/
export function applyFolderWorkspaceCleanupGroupVeto(
rows: readonly {
readonly folderParentKey?: string
readonly evaluation: WorkspaceCleanupEvaluation
}[]
): WorkspaceCleanupEvaluation[] {
const vetoedGroups = new Set<string>()
for (const row of rows) {
if (row.folderParentKey !== undefined && row.evaluation.action === 'keep') {
vetoedGroups.add(row.folderParentKey)
}
}
if (vetoedGroups.size === 0) {
return rows.map((row) => row.evaluation)
}
return rows.map((row) =>
row.folderParentKey !== undefined &&
vetoedGroups.has(row.folderParentKey) &&
row.evaluation.action !== 'keep'
? { action: 'keep', cause: 'folder-mate-in-use' }
: row.evaluation
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ export const WORKSPACE_CLEANUP_KEEP_CAUSE_LABELS: Record<WorkspaceCleanupKeepCau
'git-unknown': 'Git status unknown',
'archive-unavailable': 'archive not available',
'archive-script': 'has an archive script',
removing: 'already being removed'
removing: 'already being removed',
'folder-mate-in-use': 'another repository in this workspace is still in use'
}

// A newer host can send a value this build has no label for; show it raw rather than nothing.
Expand Down