Add safe worktree inventory, pruning, and revival #4742
Closedjuliusmarmingewants to merge 1 commit into
main fromt3code/plan-worktree-managementopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- @@ -495,3 +497,6 @@495497 thread,496498 projects: project ? [project] : [],497499 });500+ // A pruned (or manually deleted) worktree is recreated from the thread's501+ // branch before the provider session starts in it.502+ if (thread.worktreePath !== null && thread.branch !== null && project) {@@ -0,0 +511,21 @@511+ "worktree",512+ "prune",513+ ]).pipe(Effect.ignore({ log: true })),514+ { concurrency: 1 },515+ );516+517+ if (removed.length > 0) {518+ yield* Effect.logInfo("worktrees.pruned", {519+ removedCount: removed.length,520+ skippedCount: skipped.length,521+ removedPaths: removed.map((entry) => entry.path),522+ });523+ }524+525+ return { removed, skipped };526+ });527+528+ const reviveWorktree: WorktreeService["Service"]["reviveWorktree"] = Effect.fn(529+ "WorktreeService.reviveWorktree",530+ )(function* (input) {531+ const exists = yield* fs.exists(input.worktreePath).pipe(Effect.orElseSucceed(() => false));@@ -0,0 +366,21 @@366+ const lastActivityAt = anyThreadActivity ?? (yield* worktreeDirMtime(entry.path));367+368+ const blockers: WorktreePruneBlocker[] = [];369+ if (threadRefs.some((thread) => thread.status === "active")) {370+ blockers.push("active_thread");371+ }372+ if (dirty === true) {373+ blockers.push("dirty");374+ } else if (dirty === null) {375+ blockers.push("status_unavailable");376+ }377+ if (branchName === null) {378+ // Detached HEAD: no branch retains this worktree's commits.379+ blockers.push("status_unavailable");380+ } else if (sync !== undefined && sync.upstream !== null && !sync.upstreamGone) {381+ if (aheadOfUpstreamCount === null) {382+ blockers.push("status_unavailable");383+ } else if (aheadOfUpstreamCount > 0) {384+ blockers.push("unpushed");385+ }386+ } else if (sync !== undefined && sync.upstreamGone) {@@ -200,3 +204,17 @@200204 scheduler: vcsCommandScheduler,201205 concurrency: vcsCommandConcurrency,202206 }),207+ listWorktrees: createEnvironmentRpcQueryAtomFamily(runtime, {208+ label: "environment-data:vcs:list-worktrees",209+ tag: WS_METHODS.vcsListWorktrees,210+ staleTimeMs: 10_000,211+ }),212+ pruneWorktrees: createEnvironmentRpcCommand(runtime, {213+ label: "environment-data:vcs:prune-worktrees",214+ tag: WS_METHODS.vcsPruneWorktrees,215+ scheduler: vcsCommandScheduler,216+ // Prune spans repositories, so serialize per environment instead of217+ // per-cwd like the other vcs commands.218+ concurrency: {219+ mode: "serial",220+ key: ({ environmentId }) => JSON.stringify([environmentId, "worktrees.prune"]),@@ -0,0 +435,21 @@435+ const selectedProjects = projects.filter(436+ (project) =>437+ project.deletedAt === null &&438+ (input.projectId === undefined || project.projectId === input.projectId),439+ );440+441+ const perProject = yield* Effect.forEach(442+ selectedProjects,443+ (project) => listProjectWorktrees(project),444+ { concurrency: PROJECT_SCAN_CONCURRENCY },445+ );446+447+ // Two projects can point at the same repository; keep the first record448+ // per worktree path.449+ const seen = new Set<string>();450+ const worktrees: WorktreeInfo[] = [];451+ for (const record of perProject.flat()) {452+ if (seen.has(record.path)) continue;453+ seen.add(record.path);454+ worktrees.push(record);455+ }@@ -55,3 +64,15 @@5564 threadId,5665 });576667+ const pruneOrphanedWorktree = (threadId: ThreadDeletedEvent["payload"]["threadId"]) =>68+ logCleanupCauseUnlessInterrupted({69+ effect: Effect.gen(function* () {70+ const settings = yield* serverSettings.getSettings;71+ if (!settings.worktrees.deleteOrphanedImmediately) {72+ return;73+ }74+ const thread = Option.getOrNull(yield* threadRepository.getById({ threadId }));75+ if (thread === null || thread.worktreePath === null) {76+ return;77+ }78+ const worktreePath = pathService.resolve(thread.worktreePath);
- @@ -55,3 +64,19 @@5564 threadId,5665 });576667+ const pruneOrphanedWorktree = (threadId: ThreadDeletedEvent["payload"]["threadId"]) =>68+ logCleanupCauseUnlessInterrupted({69+ effect: Effect.gen(function* () {70+ const settings = yield* serverSettings.getSettings;71+ if (!settings.worktrees.deleteOrphanedImmediately) {72+ return;73+ }74+ const thread = Option.getOrNull(yield* threadRepository.getById({ threadId }));75+ if (thread === null || thread.worktreePath === null) {76+ return;77+ }78+ const worktreePath = pathService.resolve(thread.worktreePath);79+ const { worktrees } = yield* worktreeService.listWorktrees({80+ projectId: thread.projectId,81+ });82+ const record = worktrees.find((worktree) => worktree.path === worktreePath);@@ -0,0 +374,21 @@374+ } else if (dirty === null) {375+ blockers.push("status_unavailable");376+ }377+ if (branchName === null) {378+ // Detached HEAD: no branch retains this worktree's commits.379+ blockers.push("status_unavailable");380+ } else if (sync !== undefined && sync.upstream !== null && !sync.upstreamGone) {381+ if (aheadOfUpstreamCount === null) {382+ blockers.push("status_unavailable");383+ } else if (aheadOfUpstreamCount > 0) {384+ blockers.push("unpushed");385+ }386+ } else if (sync !== undefined && sync.upstreamGone) {387+ // The branch was pushed and its remote ref was deleted — the usual388+ // post-merge state. The local branch keeps the commits, so this is389+ // not "unpushed".390+ } else if (aheadOfDefaultCount === null) {391+ blockers.push("status_unavailable");392+ } else if (aheadOfDefaultCount > 0) {393+ blockers.push("unpushed");394+ }@@ -258,6 +263,11 @@258263 ? formatWorktreePathForDisplay(orphanedWorktreePath)259264 : null;260265 const canDeleteWorktree = orphanedWorktreePath !== null && threadProject !== null;266+ // When the server is configured to remove orphaned worktrees on its267+ // own, skip the dialog and the client-side removal — the server's268+ // thread-deletion reactor prunes the worktree (safely, never forced).269+ const serverPrunesOrphan =270+ deleteOrphanedWorktreesImmediately && threadRef.environmentId === primaryEnvironmentId;261271 const localApi = readLocalApi();262272 let shouldDeleteWorktree = false;263- if (canDeleteWorktree && localApi) {273+ if (canDeleteWorktree && localApi && !serverPrunesOrphan) {
- @@ -495,3 +497,20 @@495497 thread,496498 projects: project ? [project] : [],497499 });500+ // A pruned (or manually deleted) worktree is recreated from the thread's501+ // branch before the provider session starts in it.502+ if (thread.worktreePath !== null && thread.branch !== null && project) {503+ yield* worktreeService504+ .reviveWorktree({505+ workspaceRoot: project.workspaceRoot,506+ worktreePath: thread.worktreePath,507+ branch: thread.branch,508+ })509+ .pipe(510+ Effect.mapError(511+ (error) =>512+ new ProviderAdapterRequestError({513+ provider: providerErrorLabel(preferredProvider),514+ method: "thread.turn.start",515+ detail: `Could not restore the thread's worktree: ${error.message}`,516+ }),@@ -0,0 +175,21 @@175+ const fs = yield* FileSystem.FileSystem;176+ const pathService = yield* Path.Path;177+ const git = yield* GitVcsDriver.GitVcsDriver;178+ const gitWorkflow = yield* GitWorkflowService;179+ const projectRepository = yield* ProjectionProjectRepository;180+ const threadRepository = yield* ProjectionThreadRepository;181+182+ // Canonicalize through symlinks (macOS /var → /private/var) so paths from183+ // `git worktree list` compare equal to configured and stored paths.184+ const canonicalizePath = (value: string) =>185+ fs.realPath(value).pipe(Effect.orElseSucceed(() => pathService.resolve(value)));186+187+ const managedWorktreesRoot = yield* canonicalizePath(worktreesDir);188+189+ const isManagedWorktreePath = (worktreePath: string): boolean => {190+ const relative = pathService.relative(managedWorktreesRoot, worktreePath);191+ return relative.length > 0 && !relative.startsWith("..") && !pathService.isAbsolute(relative);192+ };193+194+ const toGitManagerError = (operation: string, cwd: string, detail: string) => (cause: unknown) =>195+ new GitManagerError({ operation, cwd, detail, cause });
juliusmarminge closed this
juliusmarminge reopened this
- @@ -126,3 +127,7 @@126127 });127128 const sidebarThreadSortOrder = useClientSettings((settings) => settings.sidebarThreadSortOrder);128129 const confirmThreadDelete = useClientSettings((settings) => settings.confirmThreadDelete);130+ const primaryEnvironmentId = usePrimaryEnvironmentId();131+ const deleteOrphanedWorktreesImmediately = usePrimarySettings(132+ (settings) => settings.worktrees.deleteOrphanedImmediately,133+ );
juliusmarminge closed this
Sign in to join this conversation.


Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID:
5c02353a-5db8-4289-8a06-09d0b5c74a96You can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
✨ Finishing Touches
🧪 Generate unit tests (beta)
Comment `@coderabbitai help` to get the list of available commands.