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 22, 02:00 UTC
perf(sidebar): avoid full git status for branch labels (#32947)
Co-authored-by: GPT 6.1 Sol <codex@openai.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Grok 4.7 <noreply@x.ai>
Wout Stiens committed
Nov 8, 2026 at 20:13 UTC
0d809db501817356882ed4a2d79b3f2d52f515f1
19 files changed
+751
-49
apps/mobile/src/features/threads/git/GitBranchesSheet.occupancy.test.tsx
+1
-1
@@ -51,7 +51,7 @@ vi.mock("../../../state/use-selected-thread-git-actions", () => ({
51
useSelectedThreadGitActions: () => ({ canChangeThreadBranch: true }),
52
}));
53
vi.mock("../../../state/query", () => ({ useEnvironmentQuery: () => ({ data: null }) }));
54
-vi.mock("../../../state/vcs", () => ({ vcsEnvironment: { status: () => null } }));
54
+vi.mock("../../../state/vcs", () => ({ vcsEnvironment: { branch: () => null } }));
55
56
import { GitBranchesSheet } from "./GitBranchesSheet";
57
apps/mobile/src/features/threads/git/GitBranchesSheet.test.tsx
+1
-1
@@ -71,7 +71,7 @@ vi.mock("../../../state/use-selected-thread-git-actions", () => ({
71
},
72
}),
73
}));
74
-vi.mock("../../../state/vcs", () => ({ vcsEnvironment: { status: () => null } }));
74
+vi.mock("../../../state/vcs", () => ({ vcsEnvironment: { branch: () => null } }));
75
vi.mock("./gitSheetComponents", () => ({
76
SheetActionButton: (props: ActionProps) => {
77
state.actions.set(props.label, props);
apps/mobile/src/features/threads/git/GitBranchesSheet.tsx
+1
-1
@@ -33,7 +33,7 @@ export function GitBranchesSheet(_props: GitBranchesSheetProps) {
33
34
const gitStatus = useEnvironmentQuery(
35
selectedThread !== null && selectedThreadCwd !== null
36
- ? vcsEnvironment.status({
36
+ ? vcsEnvironment.branch({
37
environmentId: selectedThread.environmentId,
38
input: { cwd: selectedThreadCwd },
39
})
apps/server/src/auth/RpcAuthorization.test.ts
+61
@@ -68,6 +68,12 @@ describe("RPC authorization scopes", () => {
68
}
69
});
70
71
+ it("lets thread readers observe and refresh checkout branches", () => {
72
+ for (const method of [WS_METHODS.subscribeVcsBranch, WS_METHODS.vcsRefreshBranch]) {
73
+ expect(requiredScopeForRpcMethod(method)).toBe(AuthOrchestrationReadScope);
74
+ }
75
+ });
76
+
77
it("rejects unknown RPC method names", () => {
78
for (const method of ["server.notRegistered", "toString", "constructor"]) {
79
expect(() => requiredScopeForRpcMethod(method)).toThrow(
@@ -133,6 +139,61 @@ describe("RPC scope middleware", () => {
139
);
140
});
141
142
+it.effect.each([WS_METHODS.subscribeVcsBranch, WS_METHODS.subscribeVcsStatus] as const)(
143
+ "enforces read permission on stream %s",
144
+ (method) =>
145
+ Effect.gen(function* () {
146
+ const group = WsRpcGroup.omit(
147
+ ...[...WsRpcGroup.requests.keys()].filter(
148
+ (
149
+ tag,
150
+ ): tag is Exclude<
151
+ keyof typeof RPC_REQUIRED_SCOPES,
152
+ typeof WS_METHODS.subscribeVcsBranch | typeof WS_METHODS.subscribeVcsStatus
153
+ > => tag !== WS_METHODS.subscribeVcsBranch && tag !== WS_METHODS.subscribeVcsStatus,
154
+ ),
155
+ );
156
+ let handled = 0;
157
+ const handlers = Layer.mergeAll(
158
+ group.toLayerHandler(WS_METHODS.subscribeVcsBranch, () =>
159
+ Stream.fromEffect(
160
+ Effect.sync(() => {
161
+ handled++;
162
+ return { refName: "main" };
163
+ }),
164
+ ),
165
+ ),
166
+ group.toLayerHandler(WS_METHODS.subscribeVcsStatus, () =>
167
+ Stream.fromEffect(
168
+ Effect.sync(() => {
169
+ handled++;
170
+ }),
171
+ ).pipe(Stream.drain),
172
+ ),
173
+ );
174
+ const denied = yield* RpcTest.makeClient(group).pipe(
175
+ Effect.provide(Layer.merge(handlers, RpcAuthorization.layer([]))),
176
+ );
177
+ expect(
178
+ yield* Stream.runDrain(
179
+ method === WS_METHODS.subscribeVcsBranch
180
+ ? denied[method]({ cwd: "/repo" }).pipe(Stream.drain)
181
+ : denied[method]({ cwd: "/repo" }).pipe(Stream.drain),
182
+ ).pipe(Effect.flip),
183
+ ).toMatchObject({ requiredPermission: AuthOrchestrationReadScope });
184
+ expect(handled).toBe(0);
185
+ const granted = yield* RpcTest.makeClient(group).pipe(
186
+ Effect.provide(Layer.merge(handlers, RpcAuthorization.layer([AuthOrchestrationReadScope]))),
187
+ );
188
+ yield* Stream.runDrain(
189
+ method === WS_METHODS.subscribeVcsBranch
190
+ ? granted[method]({ cwd: "/repo" }).pipe(Stream.drain)
191
+ : granted[method]({ cwd: "/repo" }).pipe(Stream.drain),
192
+ );
193
+ expect(handled).toBe(1);
194
+ }).pipe(Effect.scoped),
195
+);
196
+
197
describe("settings mutation authorization", () => {
198
const group = WsRpcGroup.omit(
199
...[...WsRpcGroup.requests.keys()].filter(
apps/server/src/auth/RpcAuthorization.ts
+2
@@ -169,6 +169,8 @@ export const RPC_REQUIRED_SCOPES = {
169
[WS_METHODS.mcpAppsReadResource]: AuthOrchestrationReadScope,
170
[WS_METHODS.mcpAppsUpdateModelContext]: AuthOrchestrationOperateScope,
171
[WS_METHODS.subscribeVcsStatus]: AuthOrchestrationReadScope,
172
+ [WS_METHODS.subscribeVcsBranch]: AuthOrchestrationReadScope,
173
+ [WS_METHODS.vcsRefreshBranch]: AuthOrchestrationReadScope,
174
[WS_METHODS.subscribeWorktreeSetup]: AuthOrchestrationReadScope,
175
[WS_METHODS.worktreeSetupCancel]: AuthOrchestrationOperateScope,
176
[WS_METHODS.subscribeResourceTelemetry]: AuthDiagnosticsReadScope,
apps/server/src/environment/ServerEnvironment.ts
+1
@@ -227,6 +227,7 @@ export const make = Effect.gen(function* () {
227
pullRequests: true,
228
pullRequestChecks: true,
229
sideChats: true,
230
+ vcsBranchStatus: true,
231
inlineMessageContext: true,
232
requiredWorktreeBootstrap: true,
233
threadSettlement: true,
apps/server/src/observability/RpcInstrumentation.ts
+2
@@ -173,6 +173,8 @@ const RPC_AGGREGATES = {
173
[WS_METHODS.mcpAppsUpdateModelContext]: "provider",
174
[WS_METHODS.mcpAppsReadResource]: "provider",
175
[WS_METHODS.subscribeVcsStatus]: "vcs",
176
+ [WS_METHODS.subscribeVcsBranch]: "vcs",
177
+ [WS_METHODS.vcsRefreshBranch]: "vcs",
178
[WS_METHODS.subscribeWorktreeSetup]: "vcs",
179
[WS_METHODS.worktreeSetupCancel]: "vcs",
180
[WS_METHODS.subscribeResourceTelemetry]: "server",
apps/server/src/vcs/VcsStatusBroadcaster.test.ts
+270
-2
@@ -11,6 +11,7 @@ import * as FileSystem from "effect/FileSystem";
11
import * as Layer from "effect/Layer";
12
import * as Option from "effect/Option";
13
import * as Path from "effect/Path";
14
+import * as Queue from "effect/Queue";
15
import * as Scope from "effect/Scope";
16
import * as Scheduler from "effect/Scheduler";
17
import * as Stream from "effect/Stream";
@@ -77,6 +78,9 @@ function layerTestFor(state: {
78
automaticFetchInterval?: Effect.Effect<Duration.Duration>;
79
beforeRemoteStatus?: Effect.Effect<void>;
80
beforeLocalStatus?: Effect.Effect<void>;
81
+ beforeCurrentBranch?: Effect.Effect<void>;
82
+ beforeInvalidate?: Effect.Effect<void>;
83
+ branchRead?: () => Effect.Effect<string | null>;
84
fileSystem?: FileSystem.FileSystem;
85
pullCurrentBranch?: GitWorkflowService.GitWorkflowService["Service"]["pullCurrentBranch"];
86
}) {
@@ -102,7 +106,12 @@ function layerTestFor(state: {
106
Effect.as(state.currentLocalStatus),
107
);
108
}),
105
- currentBranch: () => Effect.sync(() => state.currentLocalStatus.refName),
109
+ currentBranch: () =>
110
+ state.branchRead
111
+ ? state.branchRead()
112
+ : (state.beforeCurrentBranch ?? Effect.void).pipe(
113
+ Effect.andThen(Effect.sync(() => state.currentLocalStatus.refName)),
114
+ ),
115
remoteStatus: (_input, options) =>
116
Effect.suspend(() => {
117
return (state.beforeRemoteStatus ?? Effect.void).pipe(
@@ -121,7 +130,7 @@ function layerTestFor(state: {
130
invalidateLocalStatus: () =>
131
Effect.sync(() => {
132
state.localInvalidationCalls += 1;
124
- }),
133
+ }).pipe(Effect.andThen(state.beforeInvalidate ?? Effect.void)),
134
invalidateRemoteStatus: () =>
135
Effect.sync(() => {
136
state.remoteInvalidationCalls += 1;
@@ -207,6 +216,135 @@ describe("VcsStatusBroadcaster", () => {
216
}).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
217
});
218
219
+ it.effect(
220
+ "streams fresh branch-only reads, detached HEAD, non-repositories, and detailed demand without mixing results",
221
+ () => {
222
+ const state: Parameters<typeof layerTestFor>[0] = {
223
+ currentLocalStatus: baseLocalStatus,
224
+ currentRemoteStatus: null,
225
+ localStatusCalls: 0,
226
+ remoteStatusCalls: 0,
227
+ localInvalidationCalls: 0,
228
+ remoteInvalidationCalls: 0,
229
+ fileSystem: FileSystem.makeNoop({
230
+ realPath: (cwd) => Effect.succeed(cwd === "/alias" ? "/repo" : cwd),
231
+ }),
232
+ };
233
+ return Effect.gen(function* () {
234
+ const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
235
+ const branches = yield* Stream.toPull(broadcaster.streamBranchStatus({ cwd: "/repo" }));
236
+ assert.deepEqual(yield* branches, [{ refName: baseLocalStatus.refName }]);
237
+ assert.equal(state.localStatusCalls, 0);
238
+ state.currentLocalStatus = { ...baseLocalStatus, refName: "external" };
239
+ yield* broadcaster.refreshBranchStatus({ cwd: "/repo" });
240
+ assert.deepEqual(yield* branches, [{ refName: "external" }]);
241
+ state.currentLocalStatus = { ...baseLocalStatus, refName: null };
242
+ yield* broadcaster.refreshBranchStatus({ cwd: "/repo" });
243
+ assert.deepEqual(yield* branches, [{ refName: null }]);
244
+ assert.equal(state.localStatusCalls, 0);
245
+ const detailScope = yield* Scope.make();
246
+ const details = yield* Stream.toPull(
247
+ broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }),
248
+ ).pipe(Scope.provide(detailScope));
249
+ assert.deepEqual(yield* details, [
250
+ { _tag: "snapshot", local: state.currentLocalStatus, remote: null },
251
+ ]);
252
+ const callsWithDetail = state.localStatusCalls;
253
+ const extraBranches = yield* Stream.toPull(
254
+ broadcaster.streamBranchStatus({ cwd: "/repo" }),
255
+ );
256
+ yield* extraBranches;
257
+ yield* broadcaster.refreshBranchStatus({ cwd: "/repo" });
258
+ assert.equal(state.localStatusCalls, callsWithDetail);
259
+ state.currentLocalStatus = {
260
+ ...baseLocalStatus,
261
+ refName: "changed",
262
+ workingTree: { files: [], insertions: 12, deletions: 3 },
263
+ };
264
+ yield* broadcaster.refreshBranchStatus({ cwd: "/repo" });
265
+ assert.deepEqual(yield* details, [
266
+ { _tag: "localUpdated", local: state.currentLocalStatus },
267
+ ]);
268
+ assert.deepEqual(yield* branches, [{ refName: "changed" }]);
269
+ const secondScope = yield* Scope.make();
270
+ const secondDetails = yield* Stream.toPull(
271
+ broadcaster.streamStatus({ cwd: "/alias", includeRemote: false }),
272
+ ).pipe(Scope.provide(secondScope));
273
+ yield* secondDetails;
274
+ yield* Scope.close(detailScope, Exit.void);
275
+ state.currentLocalStatus = {
276
+ ...state.currentLocalStatus,
277
+ workingTree: { files: [], insertions: 20, deletions: 4 },
278
+ };
279
+ yield* broadcaster.refreshLocalStatus("/repo");
280
+ assert.deepEqual(yield* secondDetails, [
281
+ { _tag: "localUpdated", local: state.currentLocalStatus },
282
+ ]);
283
+ yield* Scope.close(secondScope, Exit.void);
284
+ const callsAfterRelease = state.localStatusCalls;
285
+ state.currentLocalStatus = {
286
+ ...state.currentLocalStatus,
287
+ workingTree: { files: [], insertions: 30, deletions: 5 },
288
+ };
289
+ yield* broadcaster.refreshBranchStatus({ cwd: "/repo" });
290
+ assert.equal(state.localStatusCalls, callsAfterRelease);
291
+ const reopened = yield* Stream.toPull(
292
+ broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }),
293
+ );
294
+ assert.deepEqual(yield* reopened, [
295
+ { _tag: "snapshot", local: state.currentLocalStatus, remote: null },
296
+ ]);
297
+ state.currentLocalStatus = {
298
+ ...baseLocalStatus,
299
+ isRepo: false,
300
+ refName: null,
301
+ };
302
+ yield* broadcaster.refreshBranchStatus({ cwd: "/repo" });
303
+ assert.deepEqual(yield* reopened, [
304
+ { _tag: "localUpdated", local: state.currentLocalStatus },
305
+ ]);
306
+ assert.deepEqual(yield* branches, [{ refName: null }]);
307
+ assert.equal(state.remoteStatusCalls, 0);
308
+ }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
309
+ },
310
+ );
311
+
312
+ it.effect("upgrades an in-flight branch refresh when detailed demand arrives", () => {
313
+ const state: Parameters<typeof layerTestFor>[0] = {
314
+ currentLocalStatus: baseLocalStatus,
315
+ currentRemoteStatus: null,
316
+ localStatusCalls: 0,
317
+ remoteStatusCalls: 0,
318
+ localInvalidationCalls: 0,
319
+ remoteInvalidationCalls: 0,
320
+ };
321
+ return Effect.gen(function* () {
322
+ const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
323
+ const reading = yield* Deferred.make<void>();
324
+ const resume = yield* Deferred.make<void>();
325
+ state.beforeCurrentBranch = Deferred.succeed(reading, undefined).pipe(
326
+ Effect.andThen(Deferred.await(resume)),
327
+ );
328
+ const refresh = yield* broadcaster
329
+ .refreshBranchStatus({ cwd: "/repo" })
330
+ .pipe(Effect.forkScoped);
331
+ yield* Deferred.await(reading);
332
+ const detailsFiber = yield* Stream.runHead(
333
+ broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }),
334
+ ).pipe(Effect.forkScoped);
335
+ state.currentLocalStatus = {
336
+ ...baseLocalStatus,
337
+ workingTree: { files: [], insertions: 8, deletions: 2 },
338
+ };
339
+ yield* Deferred.succeed(resume, undefined);
340
+ yield* Fiber.join(refresh);
341
+ assert.deepEqual(
342
+ yield* Fiber.join(detailsFiber),
343
+ Option.some({ _tag: "snapshot" as const, local: state.currentLocalStatus, remote: null }),
344
+ );
345
+ }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
346
+ });
347
+
348
it.effect("publishes terminal branch switches and validates cached status reads", () => {
349
const state: Parameters<typeof layerTestFor>[0] = {
350
currentLocalStatus: baseLocalStatus,
@@ -419,6 +557,7 @@ describe("VcsStatusBroadcaster", () => {
557
558
state.backgroundWorkEnabled = false;
559
state.currentRemoteStatus = { ...remoteStatusWithPr, aheadCount: 7 };
560
+ yield* broadcaster.refreshBranchStatus({ cwd: "/repo" });
561
const refreshed = yield* broadcaster.refreshPullRequestStatus("/repo");
562
assert.deepStrictEqual(refreshed, state.currentRemoteStatus);
563
const merged = yield* broadcaster.getStatus({ cwd: "/repo" });
@@ -1112,3 +1251,132 @@ describe("VcsStatusBroadcaster", () => {
1251
}).pipe(Effect.provide(layerTest));
1252
});
1253
});
1254
+
1255
+const newState = (): Parameters<typeof layerTestFor>[0] => ({
1256
+ fileSystem: FileSystem.makeNoop({ realPath: (cwd) => Effect.succeed(cwd) }),
1257
+ currentLocalStatus: baseLocalStatus,
1258
+ currentRemoteStatus: null,
1259
+ localStatusCalls: 0,
1260
+ remoteStatusCalls: 0,
1261
+ localInvalidationCalls: 0,
1262
+ remoteInvalidationCalls: 0,
1263
+});
1264
+it.effect("detail join during invalidation must get fresh totals", () => {
1265
+ const state = newState();
1266
+ return Effect.gen(function* () {
1267
+ const b = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
1268
+ const oldScope = yield* Scope.make();
1269
+ const old = yield* Stream.toPull(b.streamStatus({ cwd: "/repo", includeRemote: false })).pipe(
1270
+ Scope.provide(oldScope),
1271
+ );
1272
+ yield* old;
1273
+ yield* Scope.close(oldScope, Exit.void);
1274
+ state.currentLocalStatus = {
1275
+ ...baseLocalStatus,
1276
+ workingTree: { files: [], insertions: 42, deletions: 0 },
1277
+ };
1278
+ const entered = yield* Deferred.make<void>();
1279
+ const resume = yield* Deferred.make<void>();
1280
+ state.beforeInvalidate = Deferred.succeed(entered, undefined).pipe(
1281
+ Effect.andThen(Deferred.await(resume)),
1282
+ );
1283
+ const refresh = yield* b.refreshBranchStatus({ cwd: "/repo" }).pipe(Effect.forkScoped);
1284
+ yield* Deferred.await(entered);
1285
+ const snapshotFiber = yield* Stream.runHead(
1286
+ b.streamStatus({ cwd: "/repo", includeRemote: false }),
1287
+ ).pipe(Effect.forkScoped({ startImmediately: true }));
1288
+ yield* Deferred.succeed(resume, undefined);
1289
+ yield* Fiber.join(refresh);
1290
+ assert.deepEqual(
1291
+ yield* Fiber.join(snapshotFiber),
1292
+ Option.some({ _tag: "snapshot" as const, local: state.currentLocalStatus, remote: null }),
1293
+ );
1294
+ }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
1295
+});
1296
+it.effect("serializes branch reads with detailed refresh publication", () => {
1297
+ const state = newState();
1298
+ return Effect.gen(function* () {
1299
+ const b = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
1300
+ const entered = yield* Deferred.make<void>();
1301
+ const resume = yield* Deferred.make<void>();
1302
+ state.branchRead = () =>
1303
+ Deferred.succeed(entered, undefined).pipe(
1304
+ Effect.andThen(Deferred.await(resume)),
1305
+ Effect.as("old"),
1306
+ );
1307
+ const older = yield* b.refreshBranchStatus({ cwd: "/repo" }).pipe(Effect.forkScoped);
1308
+ yield* Deferred.await(entered);
1309
+ state.currentLocalStatus = { ...baseLocalStatus, refName: "new" };
1310
+ const newer = yield* b
1311
+ .refreshLocalStatus("/repo")
1312
+ .pipe(Effect.forkScoped({ startImmediately: true }));
1313
+ yield* Deferred.succeed(resume, undefined);
1314
+ yield* Fiber.join(older);
1315
+ yield* Fiber.join(newer);
1316
+ state.branchRead = () => Effect.succeed("new");
1317
+ const result = yield* b.getStatus({ cwd: "/repo" });
1318
+ assert.equal(result.refName, "new");
1319
+ assert.equal(state.localStatusCalls, 1);
1320
+ }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
1321
+});
1322
+
1323
+it.effect("publishes overlapping branch reads in checkout order", () => {
1324
+ const state = newState();
1325
+ return Effect.gen(function* () {
1326
+ const b = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
1327
+ const branches = yield* Stream.toPull(b.streamBranchStatus({ cwd: "/repo" }));
1328
+ yield* branches;
1329
+ const entered = yield* Deferred.make<void>();
1330
+ const resume = yield* Deferred.make<void>();
1331
+ let reads = 0;
1332
+ state.branchRead = () =>
1333
+ ++reads === 1
1334
+ ? Deferred.succeed(entered, undefined).pipe(
1335
+ Effect.andThen(Deferred.await(resume)),
1336
+ Effect.as("old"),
1337
+ )
1338
+ : Effect.succeed("new");
1339
+ const older = yield* b.refreshBranchStatus({ cwd: "/repo" }).pipe(Effect.forkScoped);
1340
+ yield* Deferred.await(entered);
1341
+ const newer = yield* b
1342
+ .refreshBranchStatus({ cwd: "/repo" })
1343
+ .pipe(Effect.forkScoped({ startImmediately: true }));
1344
+ yield* Deferred.succeed(resume, undefined);
1345
+ yield* Fiber.join(older);
1346
+ yield* Fiber.join(newer);
1347
+ assert.deepEqual(yield* branches, [{ refName: "old" }, { refName: "new" }]);
1348
+ }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
1349
+});
1350
+
1351
+it.effect("does not replay older queued branches after a new subscriber snapshot", () => {
1352
+ const state = newState();
1353
+ return Effect.gen(function* () {
1354
+ const b = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
1355
+ const entered = yield* Deferred.make<void>();
1356
+ const resume = yield* Deferred.make<void>();
1357
+ const values = yield* Queue.unbounded<{ readonly refName: string | null }>();
1358
+ let reads = 0;
1359
+ state.branchRead = () =>
1360
+ ++reads === 1
1361
+ ? Deferred.succeed(entered, undefined).pipe(
1362
+ Effect.andThen(Deferred.await(resume)),
1363
+ Effect.as("old"),
1364
+ )
1365
+ : Effect.succeed("new");
1366
+ const older = yield* b.refreshBranchStatus({ cwd: "/repo" }).pipe(Effect.forkScoped);
1367
+ yield* Deferred.await(entered);
1368
+ const subscriber = yield* b.streamBranchStatus({ cwd: "/repo" }).pipe(
1369
+ Stream.tap((value) => Queue.offer(values, value)),
1370
+ Stream.take(2),
1371
+ Stream.runDrain,
1372
+ Effect.forkScoped({ startImmediately: true }),
1373
+ );
1374
+ yield* Deferred.succeed(resume, undefined);
1375
+ yield* Fiber.join(older);
1376
+ assert.deepEqual(yield* Queue.take(values), { refName: "new" });
1377
+ state.branchRead = () => Effect.succeed("latest");
1378
+ yield* b.refreshBranchStatus({ cwd: "/repo" });
1379
+ assert.deepEqual(yield* Queue.take(values), { refName: "latest" });
1380
+ yield* Fiber.join(subscriber);
1381
+ }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
1382
+});
apps/server/src/vcs/VcsStatusBroadcaster.ts
+121
-25
@@ -15,6 +15,7 @@ import * as SynchronizedRef from "effect/SynchronizedRef";
15
import type {
16
GitManagerServiceError,
17
VcsStatusInput,
18
+ VcsBranchStatus,
19
VcsStatusLocalResult,
20
VcsStatusRemoteResult,
21
VcsStatusResult,
@@ -205,6 +206,12 @@ function remoteRefreshFailureDelay(
206
export class VcsStatusBroadcaster extends Context.Service<
207
VcsStatusBroadcaster,
208
{
209
+ readonly streamBranchStatus: (
210
+ input: VcsStatusInput,
211
+ ) => Stream.Stream<VcsBranchStatus, GitManagerServiceError>;
212
+ readonly refreshBranchStatus: (
213
+ input: VcsStatusInput,
214
+ ) => Effect.Effect<VcsBranchStatus, GitManagerServiceError>;
215
readonly streamBranchChanges: Stream.Stream<{
216
readonly cwd: string;
217
readonly refName: string | null;
@@ -250,12 +257,32 @@ export const make = Effect.gen(function* () {
257
(pubsub) => PubSub.shutdown(pubsub),
258
);
259
const branchChangesPubSub = yield* Effect.acquireRelease(
253
- PubSub.unbounded<{ readonly cwd: string; readonly refName: string | null }>(),
260
+ PubSub.unbounded<{
261
+ readonly cwd: string;
262
+ readonly refName: string | null;
263
+ readonly revision: number;
264
+ }>(),
265
(pubsub) => PubSub.shutdown(pubsub),
266
);
267
const broadcasterScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
268
Scope.close(scope, Exit.void),
269
);
270
+ const detailedSubscribers = new Map<string, number>();
271
+ const branches = new Map<
272
+ string,
273
+ { readonly refName: string | null; readonly revision: number }
274
+ >();
275
+ let branchRevision = 0;
276
+ const publishBranch = Effect.fn("VcsStatusBroadcaster.publishBranch")(function* (
277
+ cwd: string,
278
+ refName: string | null,
279
+ ) {
280
+ if (branches.get(cwd)?.refName === refName) return;
281
+ const revision = ++branchRevision;
282
+ branches.set(cwd, { refName, revision });
283
+ yield* PubSub.publish(branchChangesPubSub, { cwd, refName, revision });
284
+ });
285
+ const localRefreshLocks = yield* KeyedLock.make<string>();
286
const cacheRef = yield* Ref.make(new Map<string, CachedVcsStatus>());
287
// One permit per cwd for remote reads that write the cache. Without it a
288
// periodic poll that started before an agent creates a PR can finish after the
@@ -274,21 +301,15 @@ export const make = Effect.gen(function* () {
301
const updateCachedLocalStatus = Effect.fn("VcsStatusBroadcaster.updateCachedLocalStatus")(
302
function* (cwd: string, local: VcsStatusLocalResult, options?: { publish?: boolean }) {
303
const nextLocal = { fingerprint: fingerprintStatusPart(local), value: local };
277
- const [localChanged, branchChanged, remoteCleared] = yield* Ref.modify(cacheRef, (cache) => {
304
+ const [localChanged, remoteCleared] = yield* Ref.modify(cacheRef, (cache) => {
305
const previous = cache.get(cwd) ?? { local: null, remote: null };
306
const remote = previous.remote?.branch === local.refName ? previous.remote : null;
307
return [
281
- [
282
- previous.local?.fingerprint !== nextLocal.fingerprint,
283
- previous.local?.value.refName !== local.refName,
284
- previous.remote !== remote,
285
- ],
308
+ [previous.local?.fingerprint !== nextLocal.fingerprint, previous.remote !== remote],
309
new Map(cache).set(cwd, { local: nextLocal, remote }),
310
] as const;
311
});
289
- if (branchChanged && local.isRepo) {
290
- yield* PubSub.publish(branchChangesPubSub, { cwd, refName: local.refName });
291
- }
312
+ yield* publishBranch(cwd, local.refName);
313
if (options?.publish && remoteCleared) {
314
yield* PubSub.publish(changesPubSub, {
315
cwd,
@@ -332,24 +353,30 @@ export const make = Effect.gen(function* () {
353
return yield* updateCachedLocalStatus(cwd, local);
354
});
355
335
- const getOrLoadLocalStatus = Effect.fn("VcsStatusBroadcaster.getOrLoadLocalStatus")(function* (
336
- cwd: string,
337
- ) {
338
- const cached = yield* getCachedStatus(cwd);
339
- if (cached?.local) {
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
- });
356
+ const getOrLoadLocalStatusUnlocked = Effect.fn("VcsStatusBroadcaster.getOrLoadLocalStatus")(
357
+ function* (cwd: string) {
358
+ const cached = yield* getCachedStatus(cwd);
359
+ if (cached?.local) {
360
+ const branch = yield* workflow.currentBranch(cwd);
361
+ if (branch === cached.local.value.refName) return cached.local.value;
362
+ yield* workflow.invalidateLocalStatus(cwd);
363
+ return yield* updateCachedLocalStatus(cwd, yield* workflow.localStatus({ cwd }), {
364
+ publish: true,
365
+ });
366
+ }
367
+ return yield* loadLocalStatus(cwd);
368
+ },
369
+ );
370
+
371
+ const getOrLoadLocalStatus = (cwd: string) =>
372
+ localRefreshLocks.withLock(cwd, getOrLoadLocalStatusUnlocked(cwd));
373
374
const getStatusParts = Effect.fn("VcsStatusBroadcaster.getStatusParts")(function* (cwd: string) {
375
const cached = yield* getCachedStatus(cwd);
376
if (cached?.local) {
377
return { local: cached.local.value, remote: cached.remote?.value ?? null };
378
}
352
- return { local: yield* loadLocalStatus(cwd), remote: null };
379
+ return { local: yield* getOrLoadLocalStatus(cwd), remote: null };
380
});
381
382
const withFileSystem = Effect.provideService(FileSystem.FileSystem, fs);
@@ -378,7 +405,6 @@ export const make = Effect.gen(function* () {
405
406
// A refresh that started after a request saw every change that request could mean, so queued
407
// callers share it instead of each running git status again.
381
- const localRefreshLocks = yield* KeyedLock.make<string>();
408
const localRefreshRequests = new Map<string, number>();
409
const localRefreshResults = new Map<
410
string,
@@ -556,7 +582,7 @@ export const make = Effect.gen(function* () {
582
cwd,
583
Effect.gen(function* () {
584
const cached = yield* getCachedStatus(cwd);
559
- if (!cached?.local || cached.remote?.value === null) return null;
585
+ if (!cached || cached.remote?.value === null) return null;
586
// Turn completion must update divergence even when background polling is paused.
587
const remoteRead = yield* readRemoteStatus(cwd, {
588
refreshUpstream: false,
@@ -738,6 +764,18 @@ export const make = Effect.gen(function* () {
764
Stream.unwrap(
765
Effect.gen(function* () {
766
const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
767
+ yield* Effect.acquireRelease(
768
+ Effect.sync(() => {
769
+ const previous = detailedSubscribers.get(cwd) ?? 0;
770
+ detailedSubscribers.set(cwd, previous + 1);
771
+ }),
772
+ () =>
773
+ Effect.sync(() => {
774
+ const remaining = (detailedSubscribers.get(cwd) ?? 1) - 1;
775
+ if (remaining === 0) detailedSubscribers.delete(cwd);
776
+ else detailedSubscribers.set(cwd, remaining);
777
+ }),
778
+ );
779
const subscription = yield* PubSub.subscribe(changesPubSub);
780
const initialLocal = yield* getOrLoadLocalStatus(cwd);
781
const cachedStatus = yield* getCachedStatus(cwd);
@@ -768,8 +806,66 @@ export const make = Effect.gen(function* () {
806
}),
807
);
808
809
+ // Serialize branch publication and cache invalidation with detailed reads and refreshes.
810
+ const refreshBranchStatusCore = Effect.fn("VcsStatusBroadcaster.refreshBranchStatusCore")(
811
+ (cwd: string) =>
812
+ localRefreshLocks.withLock(
813
+ cwd,
814
+ Effect.gen(function* () {
815
+ if (detailedSubscribers.has(cwd)) {
816
+ const local = yield* getOrLoadLocalStatusUnlocked(cwd);
817
+ return { refName: local.refName, revision: branches.get(cwd)?.revision ?? 0 };
818
+ }
819
+ const refName = yield* workflow.currentBranch(cwd);
820
+ // HEAD cannot certify working-tree totals, even when it has not moved.
821
+ localRefreshResults.delete(cwd);
822
+ yield* workflow.invalidateLocalStatus(cwd);
823
+ yield* Ref.update(cacheRef, (cache) => {
824
+ const previous = cache.get(cwd);
825
+ return previous ? new Map(cache).set(cwd, { ...previous, local: null }) : cache;
826
+ });
827
+ if (detailedSubscribers.has(cwd)) {
828
+ const local = yield* workflow.localStatus({ cwd });
829
+ yield* updateCachedLocalStatus(cwd, local, { publish: true });
830
+ return { refName: local.refName, revision: branches.get(cwd)?.revision ?? 0 };
831
+ }
832
+ yield* publishBranch(cwd, refName);
833
+ return { refName, revision: branches.get(cwd)?.revision ?? 0 };
834
+ }),
835
+ ),
836
+ );
837
+
838
+ const refreshBranchStatus: VcsStatusBroadcaster["Service"]["refreshBranchStatus"] = Effect.fn(
839
+ "VcsStatusBroadcaster.refreshBranchStatus",
840
+ )(function* (input) {
841
+ const { refName } = yield* refreshBranchStatusCore(
842
+ yield* withFileSystem(normalizeCwd(input.cwd)),
843
+ );
844
+ return { refName };
845
+ });
846
+
847
+ const streamBranchStatus: VcsStatusBroadcaster["Service"]["streamBranchStatus"] = (input) =>
848
+ Stream.unwrap(
849
+ Effect.gen(function* () {
850
+ const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
851
+ const subscription = yield* PubSub.subscribe(branchChangesPubSub);
852
+ const branch = yield* refreshBranchStatusCore(cwd);
853
+ return Stream.concat(
854
+ Stream.make({ refName: branch.refName }),
855
+ Stream.fromSubscription(subscription).pipe(
856
+ Stream.filter((event) => event.cwd === cwd && event.revision > branch.revision),
857
+ Stream.map(({ refName }) => ({ refName })),
858
+ ),
859
+ ).pipe(Stream.changesWith((left, right) => left.refName === right.refName));
860
+ }),
861
+ );
862
+
863
return VcsStatusBroadcaster.of({
772
- streamBranchChanges: Stream.fromPubSub(branchChangesPubSub),
864
+ streamBranchStatus,
865
+ refreshBranchStatus,
866
+ streamBranchChanges: Stream.fromPubSub(branchChangesPubSub).pipe(
867
+ Stream.map(({ cwd, refName }) => ({ cwd, refName })),
868
+ ),
869
getStatus,
870
refreshLocalStatus,
871
refreshStatus,
apps/server/src/ws.ts
+3
@@ -3112,6 +3112,9 @@ export const layerWsRpc = (
3112
}),
3113
[WS_METHODS.assetsPersistChatAttachments]: (input) =>
3114
persistChatAttachments(input).pipe(Effect.map((attachments) => ({ attachments }))),
3115
+ [WS_METHODS.subscribeVcsBranch]: (input) => vcsStatusBroadcaster.streamBranchStatus(input),
3116
+ [WS_METHODS.vcsRefreshBranch]: (input) =>
3117
+ vcsStatusBroadcaster.refreshBranchStatus(input).pipe(Effect.asVoid),
3118
[WS_METHODS.subscribeVcsStatus]: (input) => vcsStatusBroadcaster.streamStatus(input),
3119
[WS_METHODS.subscribeWorktreeSetup]: (input) => worktreeSetupTracker.stream(input.threadId),
3120
[WS_METHODS.worktreeSetupCancel]: (input) =>
apps/web/src/components/sidebar/SidebarThreadRow.tsx
+24
-13
@@ -1,3 +1,4 @@
1
+import { useAtomMount } from "@effect/atom-react";
2
import { ThreadHoverCard, ThreadHoverCardPopup } from "../ThreadHoverCard";
3
import { ThreadTerminalStatusButton } from "../ThreadStatusIndicators";
4
import { discardComposerDraft } from "../../lib/discardComposerDraft";
@@ -68,7 +69,7 @@ import { useUiStateStore } from "../../uiStateStore";
69
import { useThreadSelectionStore } from "../../threadSelectionStore";
70
import { useNowMinute } from "../../hooks/useNowMinute";
71
import { useNowSecond } from "../../hooks/useNowSecond";
71
-import { vcsEnvironment } from "../../state/vcs";
72
+import { vcsEnvironment, vcsBranchRevalidation } from "../../state/vcs";
73
import { useEnvironmentQuery } from "../../state/query";
74
import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
75
import { formatRelativeTimeLabel, parseTimestampDate } from "../../timestampFormat";
@@ -687,14 +688,19 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
688
thread.pullRequests,
689
thread.branchPullRequest,
690
);
690
- const gitStatus = useEnvironmentQuery(
691
+ const branchTarget =
692
leaseLiveStatus && (thread.branch != null || thread.worktreePath !== null) && gitCwd !== null
692
- ? vcsEnvironment.status({
693
- environmentId: thread.environmentId,
694
- input: { cwd: gitCwd, includeRemote: false },
695
- })
696
- : null,
693
+ ? { environmentId: thread.environmentId, cwd: gitCwd }
694
+ : null;
695
+ const gitStatus = useEnvironmentQuery(
696
+ branchTarget === null
697
+ ? null
698
+ : vcsEnvironment.branch({
699
+ environmentId: branchTarget.environmentId,
700
+ input: { cwd: branchTarget.cwd },
701
+ }),
702
);
703
+ useAtomMount(vcsBranchRevalidation(branchTarget));
704
const visibleGitStatus = useRetainedValue(
705
JSON.stringify([thread.environmentId, gitCwd]),
706
gitStatus.data,
@@ -1640,14 +1646,19 @@ export const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props
1646
props.isHighlighted || props.isRouteActive,
1647
);
1648
const gitCwd = thread.worktreePath ?? props.project?.workspaceRoot ?? null;
1643
- const gitStatus = useEnvironmentQuery(
1649
+ const branchTarget =
1650
leaseLiveStatus && (thread.branch != null || thread.worktreePath !== null) && gitCwd !== null
1645
- ? vcsEnvironment.status({
1646
- environmentId: thread.environmentId,
1647
- input: { cwd: gitCwd, includeRemote: false },
1648
- })
1649
- : null,
1651
+ ? { environmentId: thread.environmentId, cwd: gitCwd }
1652
+ : null;
1653
+ const gitStatus = useEnvironmentQuery(
1654
+ branchTarget === null
1655
+ ? null
1656
+ : vcsEnvironment.branch({
1657
+ environmentId: branchTarget.environmentId,
1658
+ input: { cwd: branchTarget.cwd },
1659
+ }),
1660
);
1661
+ useAtomMount(vcsBranchRevalidation(branchTarget));
1662
const visibleGitStatus = useRetainedValue(
1663
JSON.stringify([thread.environmentId, gitCwd]),
1664
gitStatus.data,
apps/web/src/state/vcs.ts
+6
@@ -19,3 +19,9 @@ export const vcsStatusRevalidation = createVcsStatusRevalidationAtomFamily({
19
subscribeWake: subscribeDocumentReturn,
20
wakeDebounceMs: 250,
21
});
22
+
23
+export const vcsBranchRevalidation = createVcsStatusRevalidationAtomFamily({
24
+ refreshStatus: vcsEnvironment.refreshBranch,
25
+ subscribeWake: subscribeDocumentReturn,
26
+ wakeDebounceMs: 250,
27
+});
packages/client-runtime/src/rpc/client.test.ts
+70
-1
@@ -1,6 +1,7 @@
1
import {
2
EnvironmentId,
3
type RelayClientInstallProgressEvent,
4
+ type ServerConfig,
5
type ServerLifecycleStreamEvent,
6
WS_METHODS,
7
} from "@t3tools/contracts";
@@ -26,7 +27,7 @@ import {
27
import * as EnvironmentSupervisor from "../connection/supervisor.ts";
28
import * as RpcSession from "../rpc/session.ts";
29
import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
29
-import { runStream, subscribe, subscribeDynamicWithSession } from "./client.ts";
30
+import { runStream, subscribe, subscribeDynamicWithSession, refreshVcsBranch } from "./client.ts";
31
32
const TARGET = new PrimaryConnectionTarget({
33
environmentId: EnvironmentId.make("environment-1"),
@@ -414,3 +415,71 @@ describe("environment RPC", () => {
415
}),
416
);
417
});
418
+
419
+it.effect.each([true, false])(
420
+ "refreshes branches using the connected server capability (%s)",
421
+ (supported) =>
422
+ Effect.gen(function* () {
423
+ const { activeSession, supervisor } = yield* makeHarness();
424
+ const inputs: unknown[] = [];
425
+ const client = {
426
+ [supported ? WS_METHODS.vcsRefreshBranch : WS_METHODS.vcsRefreshStatus]: (
427
+ input: unknown,
428
+ ) => {
429
+ inputs.push(input);
430
+ return Effect.void;
431
+ },
432
+ } as unknown as WsRpcProtocolClient;
433
+ yield* SubscriptionRef.set(
434
+ activeSession,
435
+ Option.some({
436
+ ...session(client),
437
+ initialConfig: Effect.succeed({
438
+ environment: { capabilities: supported ? { vcsBranchStatus: true } : {} },
439
+ } as ServerConfig),
440
+ }),
441
+ );
442
+ expect(
443
+ yield* refreshVcsBranch({ cwd: "/repo" }).pipe(
444
+ Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
445
+ ),
446
+ ).toBeUndefined();
447
+ expect(inputs).toEqual(supported ? [{ cwd: "/repo" }] : []);
448
+ }).pipe(Effect.scoped),
449
+);
450
+
451
+it.effect("binds branch capability selection and execution to one session", () =>
452
+ Effect.gen(function* () {
453
+ const { activeSession, supervisor } = yield* makeHarness();
454
+ const configRequested = yield* Deferred.make<void>();
455
+ const config = yield* Deferred.make<ServerConfig>();
456
+ const executed = yield* Deferred.make<void>();
457
+ const original = {
458
+ [WS_METHODS.vcsRefreshBranch]: () =>
459
+ Deferred.succeed(executed, undefined).pipe(Effect.asVoid),
460
+ } as unknown as WsRpcProtocolClient;
461
+ const replacement = {
462
+ [WS_METHODS.vcsRefreshStatus]: () => Effect.succeed({ refName: "replacement" }),
463
+ } as unknown as WsRpcProtocolClient;
464
+ yield* SubscriptionRef.set(
465
+ activeSession,
466
+ Option.some({
467
+ ...session(original),
468
+ initialConfig: Deferred.succeed(configRequested, undefined).pipe(
469
+ Effect.andThen(Deferred.await(config)),
470
+ ),
471
+ }),
472
+ );
473
+ const refresh = yield* refreshVcsBranch({ cwd: "/repo" }).pipe(
474
+ Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
475
+ Effect.forkChild,
476
+ );
477
+ yield* Deferred.await(configRequested);
478
+ yield* SubscriptionRef.set(activeSession, Option.some(session(replacement)));
479
+ yield* Deferred.succeed(config, {
480
+ environment: { capabilities: { vcsBranchStatus: true } },
481
+ } as ServerConfig);
482
+ expect(yield* Fiber.join(refresh)).toBeUndefined();
483
+ yield* Deferred.await(executed);
484
+ }).pipe(Effect.scoped),
485
+);
packages/client-runtime/src/rpc/client.ts
+68
-4
@@ -68,6 +68,7 @@ export type EnvironmentSubscriptionRpcTag =
68
| typeof WS_METHODS.subscribeResourceTelemetry
69
| typeof WS_METHODS.pullRequestsSubscribeRefreshes
70
| typeof WS_METHODS.subscribeVcsStatus
71
+ | typeof WS_METHODS.subscribeVcsBranch
72
| typeof WS_METHODS.subscribeWorktreeSetup
73
| typeof WS_METHODS.subscribeProjectClones
74
| typeof WS_METHODS.terminalAttach
@@ -186,15 +187,14 @@ const authorizeRequest = Effect.fn("EnvironmentRpc.authorize")(function* (
187
yield* guard.authorize(supervisor.target.environmentId, method, input);
188
});
189
189
-export const requestGuarded = Effect.fn("EnvironmentRpc.request")(function* <
190
+const requestInSession = Effect.fn("EnvironmentRpc.request")(function* <
191
TTag extends EnvironmentUnaryRpcTag,
191
->(tag: TTag, input: EnvironmentRpcInput<TTag>) {
192
+>(session: RpcSession, tag: TTag, input: EnvironmentRpcInput<TTag>) {
193
const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
194
yield* Effect.annotateCurrentSpan({
195
"environment.id": supervisor.target.environmentId,
196
"rpc.method": tag,
197
});
197
- const session = yield* currentSession();
198
yield* authorizeRequest(tag, input);
199
const observer = yield* EnvironmentRpcRequestObserver;
200
const method = session.client[tag] as (
@@ -208,6 +208,14 @@ export const requestGuarded = Effect.fn("EnvironmentRpc.request")(function* <
208
return yield* method(input).pipe(Effect.ensuring(completeObservation));
209
});
210
211
+// The session-bound request owns the existing EnvironmentRpc.request span.
212
+export const requestGuarded = Effect.fnUntraced(function* <TTag extends EnvironmentUnaryRpcTag>(
213
+ tag: TTag,
214
+ input: EnvironmentRpcInput<TTag>,
215
+) {
216
+ return yield* requestInSession(yield* currentSession(), tag, input);
217
+});
218
+
219
export function runStreamGuarded<TTag extends EnvironmentStreamCommandRpcTag>(
220
tag: TTag,
221
input: EnvironmentRpcInput<TTag>,
@@ -300,7 +308,10 @@ function subscribeDynamicMapped<TTag extends EnvironmentSubscriptionRpcTag, A>(
308
method: tag,
309
input,
310
});
303
- const stream = mapStream(session, method(input)).pipe(
311
+ const stream = mapStream(
312
+ session,
313
+ Stream.suspend(() => method(input)),
314
+ ).pipe(
315
Stream.onFirst(() =>
316
Effect.sync(() => {
317
expectedFailureRetries = 0;
@@ -436,6 +447,59 @@ export function subscribe<TTag extends EnvironmentSubscriptionRpcTag>(
447
return subscribeDynamic(tag, () => Effect.succeed(input), options);
448
}
449
450
+export const subscribeVcsBranch = (
451
+ input: EnvironmentRpcInput<typeof WS_METHODS.subscribeVcsBranch>,
452
+) =>
453
+ subscribeDynamicMapped(
454
+ WS_METHODS.subscribeVcsBranch,
455
+ () => Effect.succeed(input),
456
+ (session, stream) =>
457
+ Stream.unwrap(
458
+ session.initialConfig.pipe(
459
+ Effect.mapError(
460
+ (error) =>
461
+ new RpcClientError.RpcClientError({
462
+ reason: new RpcClientError.RpcClientDefect({
463
+ message: error.message,
464
+ cause: error,
465
+ }),
466
+ }),
467
+ ),
468
+ Effect.map((config) =>
469
+ config.environment.capabilities.vcsBranchStatus === true
470
+ ? stream
471
+ : session.client[WS_METHODS.subscribeVcsStatus]({
472
+ ...input,
473
+ includeRemote: false,
474
+ }).pipe(
475
+ Stream.filter((event) => event._tag !== "remoteUpdated"),
476
+ Stream.map((event) => ({ refName: event.local.refName })),
477
+ ),
478
+ ),
479
+ ),
480
+ ),
481
+ );
482
+
483
+export const refreshVcsBranch = Effect.fn("EnvironmentRpc.refreshVcsBranch")(function* (
484
+ input: EnvironmentRpcInput<typeof WS_METHODS.vcsRefreshBranch>,
485
+) {
486
+ const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
487
+ const session = yield* currentSession();
488
+ const config = yield* session.initialConfig.pipe(
489
+ Effect.mapError(
490
+ (error) =>
491
+ new EnvironmentRpcUnavailableError({
492
+ environmentId: supervisor.target.environmentId,
493
+ message: error.message,
494
+ }),
495
+ ),
496
+ );
497
+ if (config.environment.capabilities.vcsBranchStatus === true) {
498
+ return yield* requestInSession(session, WS_METHODS.vcsRefreshBranch, input);
499
+ }
500
+ // Older hosts retain their existing status stream without adding per-row wake scans.
501
+});
502
+
503
export const request = <TTag extends Exclude<EnvironmentUnaryRpcTag, ClientGuardedRpcTag>>(
504
tag: TTag,
505
input: EnvironmentRpcInput<TTag>,
packages/client-runtime/src/state/vcs.test.ts
+78
@@ -7,6 +7,7 @@ import {
7
type VcsListRefsInput,
8
type VcsListRefsResult,
9
type VcsStatusResult,
10
+ type ServerConfig,
11
} from "@t3tools/contracts";
12
import { describe, expect, it } from "@effect/vitest";
13
import * as Deferred from "effect/Deferred";
@@ -124,6 +125,83 @@ function cacheWithRefs(
125
});
126
}
127
128
+describe("branch subscriptions", () => {
129
+ it.effect.each([true, false])(
130
+ "shares and releases branch streams across session replacement (capability %s)",
131
+ (supported) =>
132
+ Effect.gen(function* () {
133
+ const released = yield* Queue.unbounded<string>();
134
+ let subscriptions = 0;
135
+ const clientFor = (refName: string, branchSupported: boolean) =>
136
+ ({
137
+ [branchSupported ? WS_METHODS.subscribeVcsBranch : WS_METHODS.subscribeVcsStatus]:
138
+ () => {
139
+ subscriptions += 1;
140
+ return Stream.concat(
141
+ Stream.make(
142
+ branchSupported
143
+ ? { refName }
144
+ : { _tag: "snapshot", local: status({ refName }), remote: null },
145
+ ),
146
+ Stream.never,
147
+ ).pipe(Stream.ensuring(Queue.offer(released, refName)));
148
+ },
149
+ }) as unknown as WsRpcProtocolClient;
150
+ const branchSession = (refName: string, branchSupported: boolean): RpcSession => ({
151
+ ...session(clientFor(refName, branchSupported)),
152
+ initialConfig: Effect.succeed({
153
+ environment: { capabilities: branchSupported ? { vcsBranchStatus: true } : {} },
154
+ } as ServerConfig),
155
+ });
156
+ const activeSession = yield* SubscriptionRef.make(
157
+ Option.some(branchSession("main", supported)),
158
+ );
159
+ const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
160
+ target: TARGET,
161
+ state: yield* SubscriptionRef.make(CONNECTED_CONNECTION_STATE),
162
+ session: activeSession,
163
+ prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
164
+ connect: Effect.void,
165
+ disconnect: Effect.void,
166
+ retryNow: Effect.void,
167
+ });
168
+ const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({
169
+ followStream: (_environmentId, stream) =>
170
+ Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
171
+ } as EnvironmentRegistry.EnvironmentRegistry["Service"]);
172
+ const runtime = Atom.runtime(
173
+ Layer.merge(
174
+ Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
175
+ Layer.succeed(Persistence.EnvironmentCacheStore, cacheWithRefs(Option.none())),
176
+ ),
177
+ );
178
+ const atoms = createVcsEnvironmentAtoms(runtime);
179
+ const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (value) =>
180
+ Effect.sync(() => value.dispose()),
181
+ );
182
+ const target = { environmentId: TARGET.environmentId, input: { cwd: "/repo" } };
183
+ const first = yield* Stream.toPull(
184
+ AtomRegistry.toStreamResult(registry, atoms.branch(target)),
185
+ );
186
+ expect(yield* first).toEqual([{ refName: "main" }]);
187
+ const second = yield* Stream.toPull(
188
+ AtomRegistry.toStreamResult(registry, atoms.branch(target)),
189
+ );
190
+ expect(yield* second).toEqual([{ refName: "main" }]);
191
+ expect(subscriptions).toBe(1);
192
+ yield* SubscriptionRef.set(
193
+ activeSession,
194
+ Option.some(branchSession("external", !supported)),
195
+ );
196
+ expect(yield* Queue.take(released)).toBe("main");
197
+ expect(yield* first).toEqual([{ refName: "external" }]);
198
+ expect(yield* second).toEqual([{ refName: "external" }]);
199
+ registry.dispose();
200
+ expect(yield* Queue.take(released)).toBe("external");
201
+ }).pipe(Effect.scoped),
202
+ );
203
+});
204
+
205
describe("cached VCS refs", () => {
206
it("invalidates all ref streams in the mutated environment", () => {
207
const registry = AtomRegistry.make();
packages/client-runtime/src/state/vcs.ts
+20
-1
@@ -24,7 +24,13 @@ import type { EnvironmentRegistry } from "../connection/registry.ts";
24
import * as EnvironmentSupervisor from "../connection/supervisor.ts";
25
import { safeErrorLogAttributes } from "../errors/safeLog.ts";
26
import * as Persistence from "../platform/persistence.ts";
27
-import { request, subscribe, type EnvironmentRpcInput } from "../rpc/client.ts";
27
+import {
28
+ request,
29
+ subscribe,
30
+ subscribeVcsBranch,
31
+ refreshVcsBranch,
32
+ type EnvironmentRpcInput,
33
+} from "../rpc/client.ts";
34
import { followStreamInEnvironment } from "./runtime.ts";
35
import { vcsCommandConcurrency, vcsCommandScheduler } from "./vcsCommandScheduler.ts";
36
import {
@@ -294,6 +300,19 @@ export function createVcsEnvironmentAtoms<R, E>(
300
label: "environment-data:vcs:read-refs",
301
tag: WS_METHODS.vcsListRefs,
302
}),
303
+ branch: createEnvironmentSubscriptionAtomFamily(runtime, {
304
+ label: "environment-data:vcs:branch",
305
+ idleTtlMs: VCS_STATUS_IDLE_TTL_MS,
306
+ subscribe: (input: EnvironmentRpcInput<typeof WS_METHODS.subscribeVcsBranch>) =>
307
+ subscribeVcsBranch(input),
308
+ }),
309
+ refreshBranch: createEnvironmentRpcCommand(runtime, {
310
+ label: "environment-data:vcs:refresh-branch",
311
+ tag: WS_METHODS.vcsRefreshBranch,
312
+ execute: refreshVcsBranch,
313
+ scheduler: vcsCommandScheduler,
314
+ concurrency: vcsCommandConcurrency,
315
+ }),
316
status: createEnvironmentSubscriptionAtomFamily(runtime, {
317
label: "environment-data:vcs:status",
318
idleTtlMs: VCS_STATUS_IDLE_TTL_MS,
packages/contracts/src/environment.ts
+1
@@ -88,6 +88,7 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
88
pullRequestChecks: Schema.optionalKey(Schema.Boolean),
89
/** Side chats: hidden `lineage.sideChat` forks. Older servers ignore the fork flag. */
90
sideChats: Schema.optionalKey(Schema.Boolean),
91
+ vcsBranchStatus: Schema.optionalKey(Schema.Boolean),
92
/** Every protocol-2 server sends this; older mobile builds still read it. */
93
inlineMessageContext: Schema.optionalKey(Schema.Boolean),
94
requiredWorktreeBootstrap: Schema.optionalKey(Schema.Boolean),
packages/contracts/src/git.ts
+3
@@ -111,6 +111,9 @@ export const VcsStatusInput = Schema.Struct({
111
});
112
export type VcsStatusInput = typeof VcsStatusInput.Type;
113
114
+export const VcsBranchStatus = Schema.Struct({ refName: Schema.NullOr(Schema.String) });
115
+export type VcsBranchStatus = typeof VcsBranchStatus.Type;
116
+
117
export const VcsStatusSubscriptionInput = Schema.Struct({
118
...VcsStatusInput.fields,
119
/** Passive observers receive cached remote status without retaining its refresh loop. */
packages/contracts/src/rpc.ts
+18
@@ -145,6 +145,7 @@ import {
145
GitResolvePullRequestResult,
146
GitRunStackedActionInput,
147
VcsStatusInput,
148
+ VcsBranchStatus,
149
VcsStatusSubscriptionInput,
150
VcsStatusResult,
151
VcsStatusStreamEvent,
@@ -605,6 +606,8 @@ export const WS_METHODS = {
606
subscribeProjectClones: "subscribeProjectClones",
607
608
subscribeVcsStatus: "subscribeVcsStatus",
609
+ subscribeVcsBranch: "subscribeVcsBranch",
610
+ vcsRefreshBranch: "vcs.refreshBranch",
611
subscribeWorktreeSetup: "subscribeWorktreeSetup",
612
worktreeSetupCancel: "worktreeSetup.cancel",
613
subscribeTerminalMetadata: "subscribeTerminalMetadata",
@@ -1454,6 +1457,19 @@ const WsProviderUploadFeedbackRpc = Rpc.make(WS_METHODS.providerUploadFeedback,
1457
error: Schema.Union([ProviderUploadFeedbackError, EnvironmentAuthorizationError]),
1458
});
1459
1460
+const WsSubscribeVcsBranchRpc = Rpc.make(WS_METHODS.subscribeVcsBranch, {
1461
+ payload: VcsStatusInput,
1462
+ success: VcsBranchStatus,
1463
+ error: Schema.Union([GitManagerServiceError, EnvironmentAuthorizationError]),
1464
+ stream: true,
1465
+});
1466
+
1467
+const WsVcsRefreshBranchRpc = Rpc.make(WS_METHODS.vcsRefreshBranch, {
1468
+ payload: VcsStatusInput,
1469
+ success: Schema.Void,
1470
+ error: Schema.Union([GitManagerServiceError, EnvironmentAuthorizationError]),
1471
+});
1472
+
1473
const WsSubscribeVcsStatusRpc = Rpc.make(WS_METHODS.subscribeVcsStatus, {
1474
payload: VcsStatusSubscriptionInput,
1475
success: VcsStatusStreamEvent,
@@ -2149,6 +2165,8 @@ export const WsRpcGroup = RpcGroup.make(
2165
WsMcpAppsUpdateModelContextRpc,
2166
WsProviderUploadFeedbackRpc,
2167
WsSubscribeVcsStatusRpc,
2168
+ WsSubscribeVcsBranchRpc,
2169
+ WsVcsRefreshBranchRpc,
2170
WsSubscribeWorktreeSetupRpc,
2171
WsWorktreeSetupCancelRpc,
2172
WsVcsPullRpc,