@devries-cameron20 / t3code Mirror · read-only / commits / 0cb9328ea0
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 13:30 UTC

fix(server): storage cleanup removes idle worktrees whose branch was renamed or switched (#34984)

Co-authored-by: Julius Marminge <julius0216@outlook.com>

Alex Hatzenbuhler committed Nov 14, 2026 at 12:31 UTC 0cb9328ea002065f0a1d2a5d89b8e0f97ea9e5e6
3 files changed +94 -4
apps/server/src/orchestration-v2/WorktreeBranchSync.ts
+2 -2
@@ -11,7 +11,7 @@ import * as VcsStatusBroadcaster from "../vcs/VcsStatusBroadcaster.ts";
11 import * as ProjectionStore from "./ProjectionStore.ts";
12 import * as ThreadManagement from "./ThreadManagementService.ts";
13
14 -const make = Effect.gen(function* () {
14 +export const makeReconcile = Effect.gen(function* () {
15 const threads = yield* ThreadManagement.ThreadManagementService;
16 const git = yield* GitWorkflowService.GitWorkflowService;
17 const projections = yield* ProjectionStore.ProjectionStoreV2;
@@ -70,7 +70,7 @@ const make = Effect.gen(function* () {
70 export const layer = Layer.effectDiscard(
71 Effect.gen(function* () {
72 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
73 - const reconcile = yield* make;
73 + const reconcile = yield* makeReconcile;
74 yield* forkParked(
75 Stream.runForEach(broadcaster.streamBranchChanges, (input) =>
76 reconcile(input).pipe(
apps/server/src/storageCleanup.test.ts
+69 -1
@@ -26,11 +26,13 @@ import * as ServerConfig from "./config.ts";
26 import * as StorageCleanup from "./storageCleanup.ts";
27 import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
28 import * as GitManager from "./git/GitManager.ts";
29 +import * as GitWorkflowService from "./git/GitWorkflowService.ts";
30 import * as Settings from "./serverSettings.ts";
31 import * as ProjectionStore from "./orchestration-v2/ProjectionStore.ts";
32 import * as ProviderSessionManager from "./orchestration-v2/ProviderSessionManager.ts";
33 import * as ProjectStore from "./orchestration-v2/ProjectStore.ts";
34 import * as Orchestrator from "./orchestration-v2/Orchestrator.ts";
35 +import * as ThreadManagement from "./orchestration-v2/ThreadManagementService.ts";
36 import * as TerminalManager from "./terminal/Manager.ts";
37 import { CodexProviderCapabilitiesV2 } from "./orchestration-v2/Adapters/CodexAdapterV2.ts";
38 import { ServerActivation } from "./serverActivation.ts";
@@ -46,6 +48,7 @@ import {
48 RuntimeRequestId,
49 ThreadId,
50 type OrchestrationV2DomainEvent,
51 + type OrchestrationV2ServerCommand,
52 type OrchestrationV2ThreadShell,
53 } from "@t3tools/contracts";
54 import * as DateTime from "effect/DateTime";
@@ -427,6 +430,31 @@ const cleanupFixture = (
430 getThreadShell: (threadId: ThreadId) =>
431 Effect.sync(() => threads.find((thread) => thread.id === threadId) ?? null),
432 } as unknown as ProjectionStore.ProjectionStoreV2["Service"]),
433 + Effect.provideService(ThreadManagement.ThreadManagementService, {
434 + getShellSnapshot: (input?: { threadIds?: ReadonlyArray<ThreadId> }) =>
435 + Effect.sync(() => ({
436 + threads: threads.filter((thread) => input?.threadIds?.includes(thread.id) ?? true),
437 + archivedThreads: [],
438 + })),
439 + dispatch: (command: OrchestrationV2ServerCommand) =>
440 + Effect.sync(() => {
441 + if (command.type === "thread.metadata.update" && command.branch != null) {
442 + const branch = command.branch;
443 + threads = threads.map((thread) =>
444 + thread.id === command.threadId && thread.branch === command.expectedBranch
445 + ? { ...thread, branch }
446 + : thread,
447 + );
448 + }
449 + return { sequence: 0, storedEvents: [] };
450 + }),
451 + } as unknown as ThreadManagement.ThreadManagementService["Service"]),
452 + Effect.provideService(GitWorkflowService.GitWorkflowService, {
453 + currentBranch: (cwd: string) =>
454 + command(cwd, ["branch", "--show-current"]).pipe(
455 + Effect.map((result) => result.stdout.trim() || null),
456 + ),
457 + } as unknown as GitWorkflowService.GitWorkflowService["Service"]),
458 Effect.provideService(ProviderSessionManager.ProviderSessionManagerV2, {
459 isLive: () =>
460 Effect.sync(() => {
@@ -530,6 +558,7 @@ const cleanupFixture = (
558 setThreads: (next: typeof threads) => {
559 threads = next;
560 },
561 + threadBranches: () => threads.map((thread) => thread.branch),
562 setOnLiveCheck: (hook: Effect.Effect<void>) => {
563 onLiveCheck = hook;
564 },
@@ -1374,6 +1403,28 @@ describe("deleted thread worktrees", () => {
1403 }).pipe(Effect.provide(cleanupTestLayer)),
1404 );
1405
1406 + it.effect("leaves a deleted owner's subagent on the owner's saved branch", () =>
1407 + Effect.gen(function* () {
1408 + yield* TestClock.setTime(NOW_MS);
1409 + const fixture = yield* cleanupFixture({
1410 + ...DEFAULT_SERVER_SETTINGS.storageCleanup,
1411 + worktreeAfterDays: null,
1412 + worktreeOnDelete: true,
1413 + });
1414 + const owner = parent(fixture.worktree);
1415 + fixture.setDeletedThreads([owner]);
1416 + fixture.setThreads([subagent(owner)]);
1417 + yield* fixture.command(fixture.worktree, ["switch", "-c", "renamed"]);
1418 + expect((yield* fixture.service.runNow).entries[0]).toMatchObject({
1419 + threadId: owner.id,
1420 + outcome: "kept",
1421 + reason: "Repository or branch changed",
1422 + });
1423 + // The deleted owner cannot follow, so moving its subagent would split their records.
1424 + expect(fixture.threadBranches()).toEqual(["feature"]);
1425 + }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped),
1426 + );
1427 +
1428 it.effect("applies the remaining subagent's rules when deletion cleanup is off", () =>
1429 Effect.gen(function* () {
1430 yield* TestClock.setTime(NOW_MS);
@@ -2792,6 +2843,20 @@ describe("storage cleanup reports and local file policies", () => {
2843 }),
2844 ),
2845 );
2846 + it.live("follows a branch switched while nothing watched the worktree", () =>
2847 + runCleanupTest(
2848 + Effect.gen(function* () {
2849 + const { service, worktree, command, threadBranches } = yield* cleanupFixture();
2850 + yield* command(worktree, ["switch", "-c", "renamed"]);
2851 + expect((yield* service.runNow).entries[0]).toMatchObject({
2852 + outcome: "kept",
2853 + reason: "Repository or branch changed",
2854 + });
2855 + expect(threadBranches()).toEqual(["renamed"]);
2856 + expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "removed" });
2857 + }),
2858 + ),
2859 + );
2860 it.live("does not measure a worktree kept for an open provider session", () =>
2861 runCleanupTest(
2862 Effect.gen(function* () {
@@ -2843,7 +2908,8 @@ describe("storage cleanup reports and local file policies", () => {
2908 it.live("compares the checked-out branch without a full status", () =>
2909 runCleanupTest(
2910 Effect.gen(function* () {
2846 - const { service, fs, repo, worktree, command, fullStatusCalls } = yield* cleanupFixture();
2911 + const { service, fs, repo, worktree, command, fullStatusCalls, threadBranches } =
2912 + yield* cleanupFixture();
2913 const changed = { outcome: "kept", reason: "Repository or branch changed" };
2914 yield* command(worktree, ["checkout", "--detach"]);
2915 expect((yield* service.runNow).entries[0]).toMatchObject(changed);
@@ -2853,6 +2919,8 @@ describe("storage cleanup reports and local file policies", () => {
2919 // Newer Git refuses to create a tag named HEAD, but still reads one.
2920 yield* command(worktree, ["update-ref", "refs/tags/HEAD", "refs/heads/feature"]);
2921 yield* command(worktree, ["switch", "feature"]);
2922 + expect((yield* service.runNow).entries[0]).toMatchObject(changed);
2923 + expect(threadBranches()).toEqual(["feature"]);
2924 const index = (yield* command(worktree, ["rev-parse", "--git-path", "index"])).stdout;
2925 yield* fs.writeFileString(`${index.trim()}.lock`, "");
2926 const locked = (yield* service.runNow).entries[0];
apps/server/src/storageCleanup.ts
+23 -1
@@ -40,6 +40,7 @@ import { parse as parseYaml } from "yaml";
40
41 import * as ServerConfig from "./config.ts";
42 import * as GitManager from "./git/GitManager.ts";
43 +import * as GitWorkflowService from "./git/GitWorkflowService.ts";
44 import * as ProjectStore from "./orchestration-v2/ProjectStore.ts";
45 import { scratchFolderRoot } from "./project/ManagedProjectFolders.ts";
46 import * as Orchestrator from "./orchestration-v2/Orchestrator.ts";
@@ -47,6 +48,7 @@ import * as ProjectionStore from "./orchestration-v2/ProjectionStore.ts";
48 import * as ProviderSessionManager from "./orchestration-v2/ProviderSessionManager.ts";
49 import { threadHasQueuedTurnStart } from "./orchestration-v2/ThreadSettlementService.ts";
50 import { MAX_OVERDUE_ARM_MS } from "./orchestration-v2/UsageLimitRecoveryWorker.ts";
51 +import * as WorktreeBranchSync from "./orchestration-v2/WorktreeBranchSync.ts";
52 import { forkParked } from "./serverActivation.ts";
53 import * as Settings from "./serverSettings.ts";
54 import * as TerminalManager from "./terminal/Manager.ts";
@@ -321,6 +323,8 @@ const make = Effect.gen(function* () {
323 const sql = yield* SqlClient.SqlClient;
324 const git = yield* GitVcsDriver.GitVcsDriver;
325 const gitManager = yield* GitManager.GitManager;
326 + const gitWorkflow = yield* GitWorkflowService.GitWorkflowService;
327 + const reconcileBranch = yield* WorktreeBranchSync.makeReconcile;
328 const terminals = yield* TerminalManager.TerminalManager;
329 const fs = yield* FileSystem.FileSystem;
330 const path = yield* Path.Path;
@@ -707,6 +711,21 @@ const make = Effect.gen(function* () {
711 return name !== branch;
712 });
713
714 + // Nothing watches an idle worktree, so its threads still record the branch it left.
715 + // Record the checked-out one so the next sweep can apply the rules to it.
716 + const followBranch = Effect.fn("StorageCleanup.followBranch")(
717 + function* (worktreePath: string) {
718 + const cwd = yield* fs.realPath(worktreePath);
719 + yield* reconcileBranch({ cwd, refName: yield* gitWorkflow.currentBranch(cwd) });
720 + },
721 + (effect, worktreePath) =>
722 + effect.pipe(
723 + Effect.catchCause((cause) =>
724 + Effect.logWarning("Failed to reconcile worktree branch", { cwd: worktreePath, cause }),
725 + ),
726 + ),
727 + );
728 +
729 // Git status and non-forced worktree removal both skip assume-unchanged and skip-worktree files.
730 const hiddenTrackedChange = Effect.fn("StorageCleanup.hiddenTrackedChange")(function* (
731 cwd: string,
@@ -1403,8 +1422,11 @@ const make = Effect.gen(function* () {
1422 if (pathReason !== null) return keep(pathReason);
1423 if (yield* containsProjectRoot(worktreePaths, [project, ...snapshot.projects]))
1424 return keep("contains a project checkout");
1406 - if (yield* branchChanged(worktreePath, thread.branch))
1425 + if (yield* branchChanged(worktreePath, thread.branch)) {
1426 + // A deleted owner cannot follow, so its remaining subagents stay on its branch.
1427 + if (!deleted) yield* followBranch(worktreePath);
1428 return keep("repository or branch changed");
1429 + }
1430 const changes = yield* localChangesReason(worktreePath, settings);
1431 if (changes !== null) return keep(changes);
1432 const head = yield* git.resolveCommit({ cwd: worktreePath, revision: "HEAD" });