Skip to content

Commit 02cb2fc

Browse files
authored
fix(server): threads follow their worktree's branch changes (pingdotgg#31599)
1 parent 725cfc9 commit 02cb2fc

5 files changed

Lines changed: 239 additions & 6 deletions

File tree

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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+
);
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import * as WorktreeBranchSync from "./WorktreeBranchSync.ts";
12
import * as GuestShareService from "../guest/GuestShareService.ts";
23
import * as UsageLimitRecoveryWorker from "./UsageLimitRecoveryWorker.ts";
34
import * as Scheduler from "../scheduling/Scheduler.ts";
@@ -368,6 +369,9 @@ export const layer = Layer.mergeAll(
368369
);
369370

370371
export const layerProduction = Layer.mergeAll(
372+
WorktreeBranchSync.layer.pipe(
373+
Layer.provide(Layer.merge(layerThreadManagementProvided, ProjectionStore.layer)),
374+
),
371375
layer.pipe(Layer.provide(layerProjectService)),
372376
layerProjectService,
373377
layerManagedProjectFoldersProvided,

‎apps/server/src/vcs/VcsStatusBroadcaster.test.ts‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -207,8 +207,8 @@ describe("VcsStatusBroadcaster", () => {
207207
}).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
208208
});
209209

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] = {
212212
currentLocalStatus: baseLocalStatus,
213213
currentRemoteStatus: remoteStatusWithPr,
214214
localStatusCalls: 0,
@@ -220,6 +220,11 @@ describe("VcsStatusBroadcaster", () => {
220220
return Effect.gen(function* () {
221221
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
222222
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+
);
223228
const subscribed = yield* Deferred.make<void>();
224229
const events = yield* broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }).pipe(
225230
Stream.tap((event) =>
@@ -243,6 +248,13 @@ describe("VcsStatusBroadcaster", () => {
243248
{ _tag: "localUpdated", local: state.currentLocalStatus },
244249
]);
245250
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);
246258
const snapshot = yield* broadcaster
247259
.streamStatus({ cwd: "/repo", includeRemote: false })
248260
.pipe(Stream.take(1), Stream.runCollect);
@@ -251,6 +263,10 @@ describe("VcsStatusBroadcaster", () => {
251263
local: state.currentLocalStatus,
252264
remote: null,
253265
});
266+
assert.deepStrictEqual(yield* Fiber.join(branchEvents), [
267+
{ cwd: "/repo", refName: "main" },
268+
{ cwd: "/repo", refName: "union" },
269+
]);
254270
}).pipe(Effect.provide(layerTestFor(state)));
255271
});
256272

‎apps/server/src/vcs/VcsStatusBroadcaster.ts‎

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,10 @@ function remoteRefreshFailureDelay(
205205
export class VcsStatusBroadcaster extends Context.Service<
206206
VcsStatusBroadcaster,
207207
{
208+
readonly streamBranchChanges: Stream.Stream<{
209+
readonly cwd: string;
210+
readonly refName: string | null;
211+
}>;
208212
readonly getStatus: (
209213
input: VcsStatusInput,
210214
) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
@@ -245,6 +249,10 @@ export const make = Effect.gen(function* () {
245249
PubSub.unbounded<VcsStatusChange>(),
246250
(pubsub) => PubSub.shutdown(pubsub),
247251
);
252+
const branchChangesPubSub = yield* Effect.acquireRelease(
253+
PubSub.unbounded<{ readonly cwd: string; readonly refName: string | null }>(),
254+
(pubsub) => PubSub.shutdown(pubsub),
255+
);
248256
const broadcasterScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
249257
Scope.close(scope, Exit.void),
250258
);
@@ -266,14 +274,21 @@ export const make = Effect.gen(function* () {
266274
const updateCachedLocalStatus = Effect.fn("VcsStatusBroadcaster.updateCachedLocalStatus")(
267275
function* (cwd: string, local: VcsStatusLocalResult, options?: { publish?: boolean }) {
268276
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) => {
270278
const previous = cache.get(cwd) ?? { local: null, remote: null };
271279
const remote = previous.remote?.branch === local.refName ? previous.remote : null;
272280
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+
],
274286
new Map(cache).set(cwd, { local: nextLocal, remote }),
275287
] as const;
276288
});
289+
if (branchChanged && local.isRepo) {
290+
yield* PubSub.publish(branchChangesPubSub, { cwd, refName: local.refName });
291+
}
277292
if (options?.publish && remoteCleared) {
278293
yield* PubSub.publish(changesPubSub, {
279294
cwd,
@@ -322,7 +337,9 @@ export const make = Effect.gen(function* () {
322337
) {
323338
const cached = yield* getCachedStatus(cwd);
324339
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);
326343
}
327344
return yield* loadLocalStatus(cwd);
328345
});
@@ -341,11 +358,11 @@ export const make = Effect.gen(function* () {
341358
"VcsStatusBroadcaster.getStatus",
342359
)(function* (input) {
343360
const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
361+
yield* getOrLoadLocalStatus(cwd);
344362
const cached = yield* getCachedStatus(cwd);
345363
if (cached?.local && cached.remote) {
346364
return mergeGitStatusParts(cached.local.value, cached.remote.value);
347365
}
348-
yield* getOrLoadLocalStatus(cwd);
349366
return yield* withRemoteWriteLock(
350367
cwd,
351368
Effect.gen(function* () {
@@ -752,6 +769,7 @@ export const make = Effect.gen(function* () {
752769
);
753770

754771
return VcsStatusBroadcaster.of({
772+
streamBranchChanges: Stream.fromPubSub(branchChangesPubSub),
755773
getStatus,
756774
refreshLocalStatus,
757775
refreshStatus,

0 commit comments

Comments
 (0)