The best way to control Claude Code, Codex and more from any computer or phone
fix(server): threads follow their worktree's branch changes (#31599)
Yash Singh committed
Nov 5, 2026 at 11:59 UTC
02cb2fc4653f8aadd2733ec505858aa3d5dc5e08
5 files changed
+239
-6
apps/server/src/orchestration-v2/WorktreeBranchSync.test.ts
new
+111
@@ -0,0 +1,111 @@
1
+import { assert, it } from "@effect/vitest";
2
+import {
3
+ ThreadId,
4
+ type OrchestrationV2ThreadShell,
5
+ type OrchestrationV2ServerCommand,
6
+} from "@t3tools/contracts";
7
+import * as Deferred from "effect/Deferred";
8
+import * as Stream from "effect/Stream";
9
+import * as Effect from "effect/Effect";
10
+import * as FileSystem from "effect/FileSystem";
11
+import * as Layer from "effect/Layer";
12
+
13
+import * as GitWorkflowService from "../git/GitWorkflowService.ts";
14
+import * as VcsStatusBroadcaster from "../vcs/VcsStatusBroadcaster.ts";
15
+import * as ProjectionStore from "./ProjectionStore.ts";
16
+import * as Orchestrator from "./Orchestrator.ts";
17
+import * as ThreadManagement from "./ThreadManagementService.ts";
18
+import * as WorktreeBranchSync from "./WorktreeBranchSync.ts";
19
+
20
+it.effect.each([false, true])(
21
+ "reconciles shared worktree branches without changing root checkouts or detached HEADs, conflict=%s",
22
+ (conflict) => {
23
+ const reconciled = Deferred.makeUnsafe<void>();
24
+ const commands: OrchestrationV2ServerCommand[] = [];
25
+ const thread = (id: string, branch: string, worktreePath: string | null) =>
26
+ ({ id: ThreadId.make(id), branch, worktreePath }) as OrchestrationV2ThreadShell;
27
+ const snapshot = {
28
+ schemaVersion: 2,
29
+ snapshotSequence: 0,
30
+ threads: [
31
+ thread("generated", "t3/unify-converter-branches", "/worktree"),
32
+ thread("shared", "t3/bfc349ae", "/link/worktree"),
33
+ thread("current", "union", "/worktree"),
34
+ thread("root", "main", null),
35
+ thread("other", "feature", "/other"),
36
+ ],
37
+ archivedThreads: [thread("archived", "t3/bfc349ae", "/worktree")],
38
+ };
39
+ return Effect.gen(function* () {
40
+ yield* Layer.build(WorktreeBranchSync.layer);
41
+ yield* Deferred.await(reconciled);
42
+ assert.deepEqual(
43
+ commands.map((command) => {
44
+ assert.equal(command.type, "thread.metadata.update");
45
+ if (command.type !== "thread.metadata.update") throw new Error("Unexpected command");
46
+ return [
47
+ command.threadId,
48
+ command.branch,
49
+ command.expectedBranch,
50
+ command.expectedWorktreePath,
51
+ ];
52
+ }),
53
+ [
54
+ ["generated", "union", "t3/unify-converter-branches", "/worktree"],
55
+ ["shared", "union", "t3/bfc349ae", "/link/worktree"],
56
+ ["archived", "union", "t3/bfc349ae", "/worktree"],
57
+ ],
58
+ );
59
+ }).pipe(
60
+ Effect.provide(
61
+ Layer.mergeAll(
62
+ FileSystem.layerNoop({
63
+ realPath: (path) => Effect.succeed(path === "/link/worktree" ? "/worktree" : path),
64
+ }),
65
+ Layer.mock(ProjectionStore.ProjectionStoreV2)({
66
+ getThreadWorktreePaths: () =>
67
+ Effect.succeed(
68
+ [...snapshot.threads, ...snapshot.archivedThreads].flatMap((thread) =>
69
+ thread.worktreePath === null
70
+ ? []
71
+ : [{ threadId: thread.id, worktreePath: thread.worktreePath }],
72
+ ),
73
+ ),
74
+ }),
75
+ Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({
76
+ streamBranchChanges: Stream.fromIterable([null, "t3/bfc349ae", "union"]).pipe(
77
+ Stream.map((refName) => ({
78
+ cwd: "/worktree",
79
+ refName,
80
+ })),
81
+ Stream.ensuring(Deferred.succeed(reconciled, undefined)),
82
+ ),
83
+ }),
84
+ Layer.mock(GitWorkflowService.GitWorkflowService)({
85
+ currentBranch: () => Effect.succeed("union"),
86
+ }),
87
+ Layer.mock(ThreadManagement.ThreadManagementService)({
88
+ getShellSnapshot: () => Effect.succeed(snapshot),
89
+ dispatch: (command) =>
90
+ Effect.gen(function* () {
91
+ commands.push(command);
92
+ if (
93
+ command.type === "thread.metadata.update" &&
94
+ command.threadId === ThreadId.make("generated") &&
95
+ conflict
96
+ ) {
97
+ return yield* new Orchestrator.OrchestratorDispatchError({
98
+ commandId: command.commandId,
99
+ commandType: command.type,
100
+ cause: "Thread moved before branch metadata could be applied.",
101
+ });
102
+ }
103
+ return { sequence: commands.length, storedEvents: [] };
104
+ }),
105
+ }),
106
+ ),
107
+ ),
108
+ Effect.scoped,
109
+ );
110
+ },
111
+);
apps/server/src/orchestration-v2/WorktreeBranchSync.ts
new
+84
@@ -0,0 +1,84 @@
1
+import { CommandId } from "@t3tools/contracts";
2
+import { randomUuidV4 } from "@t3tools/provider-core/server/randomUuid";
3
+import * as Effect from "effect/Effect";
4
+import * as FileSystem from "effect/FileSystem";
5
+import * as Layer from "effect/Layer";
6
+import * as Stream from "effect/Stream";
7
+
8
+import * as GitWorkflowService from "../git/GitWorkflowService.ts";
9
+import { forkParked } from "../serverActivation.ts";
10
+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* () {
15
+ const threads = yield* ThreadManagement.ThreadManagementService;
16
+ const git = yield* GitWorkflowService.GitWorkflowService;
17
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
18
+ const fs = yield* FileSystem.FileSystem;
19
+ return Effect.fn("WorktreeBranchSync.reconcile")(function* (input: {
20
+ readonly cwd: string;
21
+ readonly refName: string | null;
22
+ }) {
23
+ if (input.refName === null) return;
24
+ const paths = yield* projections.getThreadWorktreePaths({ includeArchived: true });
25
+ const matchingPaths = new Set<string>();
26
+ for (const worktreePath of new Set(paths.map((thread) => thread.worktreePath))) {
27
+ const realPath =
28
+ worktreePath === input.cwd
29
+ ? worktreePath
30
+ : yield* fs.realPath(worktreePath).pipe(Effect.orElseSucceed(() => null));
31
+ if (realPath === input.cwd) matchingPaths.add(worktreePath);
32
+ }
33
+ const matchingThreads = new Map(
34
+ paths
35
+ .filter((thread) => matchingPaths.has(thread.worktreePath))
36
+ .map((thread) => [thread.threadId, thread.worktreePath]),
37
+ );
38
+ if (matchingThreads.size === 0) return;
39
+ const snapshot = yield* threads.getShellSnapshot({ threadIds: [...matchingThreads.keys()] });
40
+ const sharing = [...snapshot.threads, ...snapshot.archivedThreads].filter(
41
+ (thread) =>
42
+ thread.worktreePath === matchingThreads.get(thread.id) && thread.branch !== input.refName,
43
+ );
44
+ if (sharing.length === 0) return;
45
+ // Status events may queue behind a generated rename or another checkout.
46
+ if ((yield* git.currentBranch(input.cwd)) !== input.refName) return;
47
+ for (const thread of sharing) {
48
+ yield* threads
49
+ .dispatch({
50
+ type: "thread.metadata.update",
51
+ commandId: CommandId.make(yield* randomUuidV4),
52
+ threadId: thread.id,
53
+ branch: input.refName,
54
+ expectedBranch: thread.branch,
55
+ expectedWorktreePath: thread.worktreePath,
56
+ })
57
+ .pipe(
58
+ Effect.catchTags({
59
+ OrchestratorDispatchError: (cause) =>
60
+ Effect.logWarning("Worktree branch update was rejected", {
61
+ threadId: thread.id,
62
+ cause,
63
+ }),
64
+ }),
65
+ );
66
+ }
67
+ });
68
+});
69
+
70
+export const layer = Layer.effectDiscard(
71
+ Effect.gen(function* () {
72
+ const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
73
+ const reconcile = yield* make;
74
+ yield* forkParked(
75
+ Stream.runForEach(broadcaster.streamBranchChanges, (input) =>
76
+ reconcile(input).pipe(
77
+ Effect.catchCause((cause) =>
78
+ Effect.logWarning("Failed to reconcile worktree branch", { cwd: input.cwd, cause }),
79
+ ),
80
+ ),
81
+ ),
82
+ );
83
+ }),
84
+);
apps/server/src/orchestration-v2/runtimeLayer.ts
+4
@@ -1,3 +1,4 @@
1
+import * as WorktreeBranchSync from "./WorktreeBranchSync.ts";
2
import * as GuestShareService from "../guest/GuestShareService.ts";
3
import * as UsageLimitRecoveryWorker from "./UsageLimitRecoveryWorker.ts";
4
import * as Scheduler from "../scheduling/Scheduler.ts";
@@ -368,6 +369,9 @@ export const layer = Layer.mergeAll(
369
);
370
371
export const layerProduction = Layer.mergeAll(
372
+ WorktreeBranchSync.layer.pipe(
373
+ Layer.provide(Layer.merge(layerThreadManagementProvided, ProjectionStore.layer)),
374
+ ),
375
layer.pipe(Layer.provide(layerProjectService)),
376
layerProjectService,
377
layerManagedProjectFoldersProvided,
apps/server/src/vcs/VcsStatusBroadcaster.test.ts
+18
-2
@@ -207,8 +207,8 @@ describe("VcsStatusBroadcaster", () => {
207
}).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
208
});
209
210
- it.effect("publishes a terminal branch switch without reading remote status", () => {
211
- const state = {
210
+ it.effect("publishes terminal branch switches and validates cached status reads", () => {
211
+ const state: Parameters<typeof layerTestFor>[0] = {
212
currentLocalStatus: baseLocalStatus,
213
currentRemoteStatus: remoteStatusWithPr,
214
localStatusCalls: 0,
@@ -220,6 +220,11 @@ describe("VcsStatusBroadcaster", () => {
220
return Effect.gen(function* () {
221
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
222
yield* broadcaster.getStatus({ cwd: "/repo" });
223
+ const branchEvents = yield* broadcaster.streamBranchChanges.pipe(
224
+ Stream.take(2),
225
+ Stream.runCollect,
226
+ Effect.forkScoped({ startImmediately: true }),
227
+ );
228
const subscribed = yield* Deferred.make<void>();
229
const events = yield* broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }).pipe(
230
Stream.tap((event) =>
@@ -243,6 +248,13 @@ describe("VcsStatusBroadcaster", () => {
248
{ _tag: "localUpdated", local: state.currentLocalStatus },
249
]);
250
assert.isNull((yield* broadcaster.getStatus({ cwd: "/repo" })).pr);
251
+ state.currentLocalStatus = { ...state.currentLocalStatus, hasWorkingTreeChanges: true };
252
+ yield* broadcaster.refreshLocalStatus("/repo");
253
+ state.currentLocalStatus = { ...baseLocalStatus, refName: "union" };
254
+ state.currentRemoteStatus = null;
255
+ const queried = yield* broadcaster.getStatus({ cwd: "/repo" });
256
+ assert.equal(queried.refName, "union");
257
+ assert.isNull(queried.pr);
258
const snapshot = yield* broadcaster
259
.streamStatus({ cwd: "/repo", includeRemote: false })
260
.pipe(Stream.take(1), Stream.runCollect);
@@ -251,6 +263,10 @@ describe("VcsStatusBroadcaster", () => {
263
local: state.currentLocalStatus,
264
remote: null,
265
});
266
+ assert.deepStrictEqual(yield* Fiber.join(branchEvents), [
267
+ { cwd: "/repo", refName: "main" },
268
+ { cwd: "/repo", refName: "union" },
269
+ ]);
270
}).pipe(Effect.provide(layerTestFor(state)));
271
});
272
apps/server/src/vcs/VcsStatusBroadcaster.ts
+22
-4
@@ -205,6 +205,10 @@ function remoteRefreshFailureDelay(
205
export class VcsStatusBroadcaster extends Context.Service<
206
VcsStatusBroadcaster,
207
{
208
+ readonly streamBranchChanges: Stream.Stream<{
209
+ readonly cwd: string;
210
+ readonly refName: string | null;
211
+ }>;
212
readonly getStatus: (
213
input: VcsStatusInput,
214
) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
@@ -245,6 +249,10 @@ export const make = Effect.gen(function* () {
249
PubSub.unbounded<VcsStatusChange>(),
250
(pubsub) => PubSub.shutdown(pubsub),
251
);
252
+ const branchChangesPubSub = yield* Effect.acquireRelease(
253
+ PubSub.unbounded<{ readonly cwd: string; readonly refName: string | null }>(),
254
+ (pubsub) => PubSub.shutdown(pubsub),
255
+ );
256
const broadcasterScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
257
Scope.close(scope, Exit.void),
258
);
@@ -266,14 +274,21 @@ export const make = Effect.gen(function* () {
274
const updateCachedLocalStatus = Effect.fn("VcsStatusBroadcaster.updateCachedLocalStatus")(
275
function* (cwd: string, local: VcsStatusLocalResult, options?: { publish?: boolean }) {
276
const nextLocal = { fingerprint: fingerprintStatusPart(local), value: local };
269
- const [localChanged, remoteCleared] = yield* Ref.modify(cacheRef, (cache) => {
277
+ const [localChanged, branchChanged, remoteCleared] = yield* Ref.modify(cacheRef, (cache) => {
278
const previous = cache.get(cwd) ?? { local: null, remote: null };
279
const remote = previous.remote?.branch === local.refName ? previous.remote : null;
280
return [
273
- [previous.local?.fingerprint !== nextLocal.fingerprint, previous.remote !== remote],
281
+ [
282
+ previous.local?.fingerprint !== nextLocal.fingerprint,
283
+ previous.local?.value.refName !== local.refName,
284
+ previous.remote !== remote,
285
+ ],
286
new Map(cache).set(cwd, { local: nextLocal, remote }),
287
] as const;
288
});
289
+ if (branchChanged && local.isRepo) {
290
+ yield* PubSub.publish(branchChangesPubSub, { cwd, refName: local.refName });
291
+ }
292
if (options?.publish && remoteCleared) {
293
yield* PubSub.publish(changesPubSub, {
294
cwd,
@@ -322,7 +337,9 @@ export const make = Effect.gen(function* () {
337
) {
338
const cached = yield* getCachedStatus(cwd);
339
if (cached?.local) {
325
- return cached.local.value;
340
+ const branch = yield* workflow.currentBranch(cwd);
341
+ if (branch === cached.local.value.refName) return cached.local.value;
342
+ return yield* refreshLocalStatusCore(cwd);
343
}
344
return yield* loadLocalStatus(cwd);
345
});
@@ -341,11 +358,11 @@ export const make = Effect.gen(function* () {
358
"VcsStatusBroadcaster.getStatus",
359
)(function* (input) {
360
const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
361
+ yield* getOrLoadLocalStatus(cwd);
362
const cached = yield* getCachedStatus(cwd);
363
if (cached?.local && cached.remote) {
364
return mergeGitStatusParts(cached.local.value, cached.remote.value);
365
}
348
- yield* getOrLoadLocalStatus(cwd);
366
return yield* withRemoteWriteLock(
367
cwd,
368
Effect.gen(function* () {
@@ -752,6 +769,7 @@ export const make = Effect.gen(function* () {
769
);
770
771
return VcsStatusBroadcaster.of({
772
+ streamBranchChanges: Stream.fromPubSub(branchChangesPubSub),
773
getStatus,
774
refreshLocalStatus,
775
refreshStatus,