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, 23:30 UTC
fix(server): update branch labels after terminal checkouts (#23422)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Nov 11, 2026 at 11:56 UTC
0ceaa9a48ca6448caf5fb5b2e3d00bb1a92a1c60
3 files changed
+434
-30
apps/server/src/git/GitWorkflowService.ts
+15
@@ -60,6 +60,8 @@ export class GitWorkflowService extends Context.Service<
60
readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
61
readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
62
readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
63
+ /** The checkout's own HEAD file, inside a linked worktree's admin directory when there is one. */
64
+ readonly headPath: (cwd: string) => Effect.Effect<string | null, never>;
65
readonly pullCurrentBranch: (cwd: string) => Effect.Effect<VcsPullResult, GitCommandError>;
66
readonly runStackedAction: (
67
input: GitRunStackedActionInput,
@@ -370,6 +372,19 @@ export const make = Effect.gen(function* () {
372
invalidateLocalStatus: gitManager.invalidateLocalStatus,
373
invalidateRemoteStatus: gitManager.invalidateRemoteStatus,
374
invalidateStatus: gitManager.invalidateStatus,
375
+ headPath: Effect.fn("GitWorkflowService.headPath")(function (cwd) {
376
+ return git
377
+ .execute({
378
+ operation: "GitWorkflowService.headPath",
379
+ cwd,
380
+ args: ["rev-parse", "--path-format=absolute", "--git-path", "HEAD"],
381
+ allowNonZeroExit: true,
382
+ })
383
+ .pipe(
384
+ Effect.map((result) => (result.exitCode === 0 ? result.stdout.trim() || null : null)),
385
+ Effect.orElseSucceed(() => null),
386
+ );
387
+ }),
388
pullCurrentBranch: Effect.fn("GitWorkflowService.pullCurrentBranch")(function (cwd) {
389
return ensureGitCommand("GitWorkflowService.pullCurrentBranch", cwd).pipe(
390
Effect.andThen(git.pullCurrentBranch(cwd)),
apps/server/src/vcs/VcsStatusBroadcaster.test.ts
+274
-1
@@ -21,9 +21,11 @@ import type {
21
BackgroundScope,
22
VcsStatusLocalResult,
23
VcsStatusRemoteResult,
24
+ VcsStatusResult,
25
VcsStatusStreamEvent,
26
} from "@t3tools/contracts";
27
import { GitCommandError, GitManagerError } from "@t3tools/contracts";
28
+import { applyGitStatusStreamEvent } from "@t3tools/shared/git";
29
30
import * as VcsStatusBroadcaster from "./VcsStatusBroadcaster.ts";
31
import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
@@ -83,11 +85,15 @@ function layerTestFor(state: {
85
branchRead?: () => Effect.Effect<string | null>;
86
fileSystem?: FileSystem.FileSystem;
87
pullCurrentBranch?: GitWorkflowService.GitWorkflowService["Service"]["pullCurrentBranch"];
88
+ headPath?: string;
89
+ headPathCalls?: number;
90
+ failLocalStatus?: boolean;
91
+ onLocalStatusFailure?: Effect.Effect<void>;
92
}) {
93
return VcsStatusBroadcaster.layer.pipe(
94
Layer.provideMerge(
95
state.fileSystem
90
- ? Layer.succeed(FileSystem.FileSystem, state.fileSystem)
96
+ ? Layer.merge(Layer.succeed(FileSystem.FileSystem, state.fileSystem), Path.layer)
97
: NodeServices.layer,
98
),
99
Layer.provide(layerBackgroundPolicy(() => state.backgroundWorkEnabled !== false)),
@@ -102,6 +108,19 @@ function layerTestFor(state: {
108
localStatus: () =>
109
Effect.suspend(() => {
110
state.localStatusCalls += 1;
111
+ if (state.failLocalStatus) {
112
+ return (state.onLocalStatusFailure ?? Effect.void).pipe(
113
+ Effect.andThen(
114
+ Effect.fail(
115
+ new GitManagerError({
116
+ operation: "VcsStatusBroadcaster.test",
117
+ cwd: "/repo",
118
+ detail: "index.lock is held",
119
+ }),
120
+ ),
121
+ ),
122
+ );
123
+ }
124
return (state.beforeLocalStatus ?? Effect.void).pipe(
125
Effect.as(state.currentLocalStatus),
126
);
@@ -141,6 +160,11 @@ function layerTestFor(state: {
160
state.remoteInvalidationCalls += 1;
161
}),
162
...(state.pullCurrentBranch ? { pullCurrentBranch: state.pullCurrentBranch } : {}),
163
+ headPath: () =>
164
+ Effect.sync(() => {
165
+ state.headPathCalls = (state.headPathCalls ?? 0) + 1;
166
+ return state.headPath ?? null;
167
+ }),
168
}),
169
),
170
);
@@ -1249,6 +1273,255 @@ describe("VcsStatusBroadcaster", () => {
1273
}).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
1274
});
1275
1276
+ it.effect("a terminal checkout publishes the new branch without waiting for a poll", () =>
1277
+ Effect.gen(function* () {
1278
+ const fs = yield* FileSystem.FileSystem;
1279
+ const path = yield* Path.Path;
1280
+ const gitDir = yield* fs.makeTempDirectoryScoped({ prefix: "vcs-head-watch-" });
1281
+ const headPath = path.join(gitDir, "HEAD");
1282
+ yield* fs.writeFileString(headPath, "ref: refs/heads/main\n");
1283
+ const state = {
1284
+ currentLocalStatus: { ...baseLocalStatus, isDefaultRef: true, refName: "main" },
1285
+ currentRemoteStatus: remoteStatusWithPr as VcsStatusRemoteResult | null,
1286
+ localStatusCalls: 0,
1287
+ remoteStatusCalls: 0,
1288
+ localInvalidationCalls: 0,
1289
+ remoteInvalidationCalls: 0,
1290
+ remoteStatusRefreshUpstreamValues: [] as Array<boolean | undefined>,
1291
+ headPath,
1292
+ };
1293
+
1294
+ yield* Effect.gen(function* () {
1295
+ const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
1296
+ yield* broadcaster.getStatus({ cwd: "/repo" });
1297
+ const clientStates: Array<VcsStatusResult> = [];
1298
+ const subscribed = yield* Deferred.make<void>();
1299
+ const checkedOut = yield* Deferred.make<void>();
1300
+ yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) =>
1301
+ Effect.gen(function* () {
1302
+ const next = applyGitStatusStreamEvent(clientStates.at(-1) ?? null, event);
1303
+ clientStates.push(next);
1304
+ yield* Deferred.succeed(subscribed, undefined);
1305
+ if (next.refName === "repro") yield* Deferred.succeed(checkedOut, undefined);
1306
+ }),
1307
+ ).pipe(Effect.forkScoped);
1308
+ yield* Deferred.await(subscribed);
1309
+
1310
+ // What `git switch -c repro` does to HEAD, with the test clock never advanced.
1311
+ state.currentLocalStatus = { ...baseLocalStatus, isDefaultRef: false, refName: "repro" };
1312
+ state.currentRemoteStatus = { ...baseRemoteStatus, hasUpstream: false };
1313
+ const lockPath = path.join(gitDir, "HEAD.lock");
1314
+ yield* fs.writeFileString(lockPath, "ref: refs/heads/repro\n");
1315
+ yield* fs.rename(lockPath, headPath);
1316
+ yield* Deferred.await(checkedOut);
1317
+
1318
+ assert.deepStrictEqual(
1319
+ clientStates.filter((status) => status.refName === "repro").map((status) => status.pr),
1320
+ [null],
1321
+ );
1322
+ // A checkout must not trigger a network fetch.
1323
+ assert.deepStrictEqual(state.remoteStatusRefreshUpstreamValues.slice(1), [false]);
1324
+ }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
1325
+ }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
1326
+ );
1327
+
1328
+ it.effect("a terminal checkout updates branch-only subscribers without full status", () =>
1329
+ Effect.gen(function* () {
1330
+ const fs = yield* FileSystem.FileSystem;
1331
+ const path = yield* Path.Path;
1332
+ const gitDir = yield* fs.makeTempDirectoryScoped({ prefix: "vcs-head-watch-" });
1333
+ const headPath = path.join(gitDir, "HEAD");
1334
+ yield* fs.writeFileString(headPath, "ref: refs/heads/main\n");
1335
+ const state = {
1336
+ currentLocalStatus: { ...baseLocalStatus, refName: "main" },
1337
+ currentRemoteStatus: null,
1338
+ localStatusCalls: 0,
1339
+ remoteStatusCalls: 0,
1340
+ localInvalidationCalls: 0,
1341
+ remoteInvalidationCalls: 0,
1342
+ headPath,
1343
+ };
1344
+
1345
+ yield* Effect.gen(function* () {
1346
+ const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
1347
+ const branches = yield* Stream.toPull(broadcaster.streamBranchStatus({ cwd: "/repo" }));
1348
+ assert.deepEqual(yield* branches, [{ refName: "main" }]);
1349
+
1350
+ state.currentLocalStatus = { ...baseLocalStatus, refName: "repro" };
1351
+ const lockPath = path.join(gitDir, "HEAD.lock");
1352
+ yield* fs.writeFileString(lockPath, "ref: refs/heads/repro\n");
1353
+ yield* fs.rename(lockPath, headPath);
1354
+
1355
+ assert.deepEqual(yield* branches, [{ refName: "repro" }]);
1356
+ assert.equal(state.localStatusCalls, 0);
1357
+ }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
1358
+ }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
1359
+ );
1360
+
1361
+ it.effect("a checkout read that fails while index.lock is held retries until it succeeds", () =>
1362
+ Effect.gen(function* () {
1363
+ const fs = yield* FileSystem.FileSystem;
1364
+ const path = yield* Path.Path;
1365
+ const gitDir = yield* fs.makeTempDirectoryScoped({ prefix: "vcs-head-watch-" });
1366
+ const headPath = path.join(gitDir, "HEAD");
1367
+ yield* fs.writeFileString(headPath, "ref: refs/heads/main\n");
1368
+ const failed = yield* Deferred.make<void>();
1369
+ const state = {
1370
+ currentLocalStatus: { ...baseLocalStatus, isDefaultRef: true, refName: "main" },
1371
+ currentRemoteStatus: null,
1372
+ localStatusCalls: 0,
1373
+ remoteStatusCalls: 0,
1374
+ localInvalidationCalls: 0,
1375
+ remoteInvalidationCalls: 0,
1376
+ headPath,
1377
+ failLocalStatus: false,
1378
+ onLocalStatusFailure: Deferred.succeed(failed, undefined).pipe(Effect.asVoid),
1379
+ };
1380
+
1381
+ yield* Effect.gen(function* () {
1382
+ const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
1383
+ const subscribed = yield* Deferred.make<void>();
1384
+ const checkedOut = yield* Deferred.make<void>();
1385
+ let clientState: VcsStatusResult | null = null;
1386
+ yield* Stream.runForEach(
1387
+ broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }),
1388
+ (event) =>
1389
+ Effect.gen(function* () {
1390
+ clientState = applyGitStatusStreamEvent(clientState, event);
1391
+ yield* Deferred.succeed(subscribed, undefined);
1392
+ if (clientState.refName === "repro") yield* Deferred.succeed(checkedOut, undefined);
1393
+ }),
1394
+ ).pipe(Effect.forkScoped);
1395
+ yield* Deferred.await(subscribed);
1396
+
1397
+ // A terminal commit holds index.lock across the checkout, so the HEAD event's read fails.
1398
+ state.failLocalStatus = true;
1399
+ state.currentLocalStatus = { ...baseLocalStatus, isDefaultRef: false, refName: "repro" };
1400
+ const lockPath = path.join(gitDir, "HEAD.lock");
1401
+ yield* fs.writeFileString(lockPath, "ref: refs/heads/repro\n");
1402
+ yield* fs.rename(lockPath, headPath);
1403
+ yield* Deferred.await(failed);
1404
+ const failedCalls = state.localStatusCalls;
1405
+
1406
+ // Removing index.lock moves no HEAD, and no remote poll runs for this subscriber.
1407
+ state.failLocalStatus = false;
1408
+ yield* TestClock.adjust(Duration.seconds(30));
1409
+ yield* Deferred.await(checkedOut);
1410
+ assert.strictEqual(state.localStatusCalls, failedCalls + 1);
1411
+ }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
1412
+ }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
1413
+ );
1414
+
1415
+ it.effect("subscribers share one HEAD watch that ends with the last of them", () =>
1416
+ Effect.gen(function* () {
1417
+ const fs = yield* FileSystem.FileSystem;
1418
+ const path = yield* Path.Path;
1419
+ const gitDir = yield* fs.makeTempDirectoryScoped({ prefix: "vcs-head-watch-" });
1420
+ const headPath = path.join(gitDir, "HEAD");
1421
+ yield* fs.writeFileString(headPath, "ref: refs/heads/main\n");
1422
+ const state = {
1423
+ currentLocalStatus: baseLocalStatus,
1424
+ currentRemoteStatus: baseRemoteStatus as VcsStatusRemoteResult | null,
1425
+ localStatusCalls: 0,
1426
+ remoteStatusCalls: 0,
1427
+ localInvalidationCalls: 0,
1428
+ remoteInvalidationCalls: 0,
1429
+ headPath,
1430
+ headPathCalls: 0,
1431
+ };
1432
+
1433
+ yield* Effect.gen(function* () {
1434
+ const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
1435
+ const subscribe = Effect.gen(function* () {
1436
+ const received = yield* Deferred.make<void>();
1437
+ const fiber = yield* Stream.runForEach(
1438
+ broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }),
1439
+ () => Deferred.succeed(received, undefined),
1440
+ ).pipe(Effect.forkScoped);
1441
+ yield* Deferred.await(received);
1442
+ return fiber;
1443
+ });
1444
+
1445
+ const first = yield* subscribe;
1446
+ const second = yield* subscribe;
1447
+ assert.strictEqual(state.headPathCalls, 1);
1448
+
1449
+ yield* Fiber.interrupt(first);
1450
+ yield* Fiber.interrupt(second);
1451
+ yield* subscribe;
1452
+ assert.strictEqual(state.headPathCalls, 2);
1453
+ }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
1454
+ }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
1455
+ );
1456
+
1457
+ it.effect("a HEAD watch that ended restarts for the next subscriber and keeps earlier ones", () =>
1458
+ Effect.gen(function* () {
1459
+ const fs = yield* FileSystem.FileSystem;
1460
+ const path = yield* Path.Path;
1461
+ const gitDir = yield* fs.makeTempDirectoryScoped({ prefix: "vcs-head-watch-" });
1462
+ const headPath = path.join(gitDir, "HEAD");
1463
+ yield* fs.writeFileString(headPath, "ref: refs/heads/main\n");
1464
+ const state: Parameters<typeof layerTestFor>[0] = {
1465
+ currentLocalStatus: { ...baseLocalStatus, isDefaultRef: true, refName: "main" },
1466
+ currentRemoteStatus: null,
1467
+ localStatusCalls: 0,
1468
+ remoteStatusCalls: 0,
1469
+ localInvalidationCalls: 0,
1470
+ remoteInvalidationCalls: 0,
1471
+ headPathCalls: 0,
1472
+ };
1473
+
1474
+ yield* Effect.gen(function* () {
1475
+ const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
1476
+ const subscribe = Effect.gen(function* () {
1477
+ const subscribed = yield* Deferred.make<void>();
1478
+ const refs = new Map<string, Deferred.Deferred<void>>();
1479
+ const sawRef = (refName: string) => {
1480
+ const existing = refs.get(refName);
1481
+ if (existing) return existing;
1482
+ const created = Deferred.makeUnsafe<void>();
1483
+ refs.set(refName, created);
1484
+ return created;
1485
+ };
1486
+ let clientState: VcsStatusResult | null = null;
1487
+ const fiber = yield* Stream.runForEach(
1488
+ broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }),
1489
+ (event) =>
1490
+ Effect.gen(function* () {
1491
+ clientState = applyGitStatusStreamEvent(clientState, event);
1492
+ yield* Deferred.succeed(subscribed, undefined);
1493
+ yield* Deferred.succeed(sawRef(clientState.refName ?? ""), undefined);
1494
+ }),
1495
+ ).pipe(Effect.forkScoped);
1496
+ yield* Deferred.await(subscribed);
1497
+ return { fiber, sawRef };
1498
+ });
1499
+ const checkout = (refName: string) =>
1500
+ Effect.gen(function* () {
1501
+ state.currentLocalStatus = { ...baseLocalStatus, isDefaultRef: false, refName };
1502
+ const lockPath = path.join(gitDir, "HEAD.lock");
1503
+ yield* fs.writeFileString(lockPath, `ref: refs/heads/${refName}\n`);
1504
+ yield* fs.rename(lockPath, headPath);
1505
+ });
1506
+
1507
+ // The repository has no HEAD yet, so the first watch ends at once.
1508
+ const first = yield* subscribe;
1509
+ state.headPath = headPath;
1510
+ const second = yield* subscribe;
1511
+ assert.strictEqual(state.headPathCalls, 2);
1512
+
1513
+ yield* checkout("one");
1514
+ yield* Deferred.await(first.sawRef("one"));
1515
+ yield* Deferred.await(second.sawRef("one"));
1516
+
1517
+ // The replacement belongs to both subscribers, so the second leaving keeps it.
1518
+ yield* Fiber.interrupt(second.fiber);
1519
+ yield* checkout("two");
1520
+ yield* Deferred.await(first.sawRef("two"));
1521
+ }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
1522
+ }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
1523
+ );
1524
+
1525
it.effect("releases remote demand while passive observers remain", () => {
1526
const state = {
1527
currentLocalStatus: baseLocalStatus,
apps/server/src/vcs/VcsStatusBroadcaster.ts
+145
-29
@@ -1,11 +1,13 @@
1
import * as Cause from "effect/Cause";
2
import * as Context from "effect/Context";
3
+import * as Deferred from "effect/Deferred";
4
import * as Duration from "effect/Duration";
5
import * as Effect from "effect/Effect";
6
import * as Exit from "effect/Exit";
7
import * as Fiber from "effect/Fiber";
8
import * as FileSystem from "effect/FileSystem";
9
import * as Layer from "effect/Layer";
10
+import * as Path from "effect/Path";
11
import * as PubSub from "effect/PubSub";
12
import * as Ref from "effect/Ref";
13
import * as Schedule from "effect/Schedule";
@@ -36,6 +38,12 @@ import * as ServerSettings from "../serverSettings.ts";
38
const VCS_STATUS_REFRESH_FAILURE_BASE_DELAY = Duration.seconds(30);
39
const VCS_STATUS_REFRESH_FAILURE_MAX_DELAY = Duration.minutes(15);
40
const MAX_FAILURE_DIAGNOSTIC_VALUES = 8;
41
+// A held index.lock fails the read, and its removal moves no HEAD to trigger another.
42
+const CHECKOUT_REFRESH_RETRY = Schedule.exponential(Duration.seconds(1)).pipe(
43
+ Schedule.modifyDelay(({ duration }) =>
44
+ Effect.succeed(Duration.min(duration, Duration.seconds(30))),
45
+ ),
46
+);
47
const MAX_FAILURE_DIAGNOSTIC_VALUE_LENGTH = 128;
48
49
function boundedDiagnosticValue(value: string): string {
@@ -140,6 +148,12 @@ interface CachedVcsStatus {
148
readonly remote: CachedRemoteStatus | null;
149
}
150
151
+interface ActiveHeadWatcher {
152
+ readonly fiber: Fiber.Fiber<void, never>;
153
+ readonly ready: Deferred.Deferred<void>;
154
+ readonly subscriberCount: number;
155
+}
156
+
157
interface ActiveRemotePoller {
158
readonly fiber: Fiber.Fiber<void, never>;
159
readonly subscriberCount: number;
@@ -252,6 +266,7 @@ export const make = Effect.gen(function* () {
266
const workflow = yield* GitWorkflowService.GitWorkflowService;
267
const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
268
const fs = yield* FileSystem.FileSystem;
269
+ const path = yield* Path.Path;
270
const changesPubSub = yield* Effect.acquireRelease(
271
PubSub.unbounded<VcsStatusChange>(),
272
(pubsub) => PubSub.shutdown(pubsub),
@@ -291,6 +306,7 @@ export const make = Effect.gen(function* () {
306
const withRemoteWriteLock = <A, E, R>(cwd: string, effect: Effect.Effect<A, E, R>) =>
307
remoteWriteLocks.withLock(cwd, effect);
308
const pollersRef = yield* SynchronizedRef.make(new Map<string, ActiveRemotePoller>());
309
+ const headWatchersRef = yield* SynchronizedRef.make(new Map<string, ActiveHeadWatcher>());
310
311
const getCachedStatus = Effect.fn("VcsStatusBroadcaster.getCachedStatus")(function* (
312
cwd: string,
@@ -747,6 +763,132 @@ export const make = Effect.gen(function* () {
763
}
764
});
765
766
+ // Serialize branch publication and cache invalidation with detailed reads and refreshes.
767
+ const refreshBranchStatusCore = Effect.fn("VcsStatusBroadcaster.refreshBranchStatusCore")(
768
+ (cwd: string) =>
769
+ localRefreshLocks.withLock(
770
+ cwd,
771
+ Effect.gen(function* () {
772
+ if (detailedSubscribers.has(cwd)) {
773
+ const local = yield* getOrLoadLocalStatusUnlocked(cwd);
774
+ return { refName: local.refName, revision: branches.get(cwd)?.revision ?? 0 };
775
+ }
776
+ const refName = yield* workflow.currentBranch(cwd);
777
+ // HEAD cannot certify working-tree totals, even when it has not moved.
778
+ localRefreshResults.delete(cwd);
779
+ yield* workflow.invalidateLocalStatus(cwd);
780
+ yield* Ref.update(cacheRef, (cache) => {
781
+ const previous = cache.get(cwd);
782
+ return previous ? new Map(cache).set(cwd, { ...previous, local: null }) : cache;
783
+ });
784
+ if (detailedSubscribers.has(cwd)) {
785
+ const local = yield* workflow.localStatus({ cwd });
786
+ yield* updateCachedLocalStatus(cwd, local, { publish: true });
787
+ return { refName: local.refName, revision: branches.get(cwd)?.revision ?? 0 };
788
+ }
789
+ yield* publishBranch(cwd, refName);
790
+ return { refName, revision: branches.get(cwd)?.revision ?? 0 };
791
+ }),
792
+ ),
793
+ );
794
+
795
+ // A checkout outside T3 Code, such as `git switch` in the terminal, calls no refresh RPC.
796
+ // Rereading remote too, without a fetch, sends the new branch with its own PR and counts.
797
+ const refreshCheckedOutRef = Effect.fn("VcsStatusBroadcaster.refreshCheckedOutRef")(function* (
798
+ cwd: string,
799
+ ) {
800
+ if (!detailedSubscribers.has(cwd)) {
801
+ yield* refreshBranchStatusCore(cwd);
802
+ } else if ((yield* getCachedStatus(cwd))?.remote) {
803
+ yield* refreshRemoteStatus(cwd, { refreshUpstream: false });
804
+ } else {
805
+ yield* refreshLocalStatusCore(cwd);
806
+ }
807
+ });
808
+
809
+ // Runs for the subscription lifetime, so tracing would leave a span open indefinitely.
810
+ const watchHead = Effect.fnUntraced(function* (cwd: string, ready: Deferred.Deferred<void>) {
811
+ const headPath = yield* workflow.headPath(cwd);
812
+ if (headPath === null) return;
813
+ // Git replaces HEAD by renaming HEAD.lock, which a watch on the file itself would lose.
814
+ yield* fs
815
+ .watch(path.dirname(headPath), {
816
+ onReady: () => Deferred.doneUnsafe(ready, Exit.void),
817
+ })
818
+ .pipe(
819
+ Stream.filter((event) => path.basename(event.path) === "HEAD"),
820
+ // A rebase moves HEAD many times; refresh once for whatever arrived during a refresh.
821
+ Stream.buffer({ capacity: 1, strategy: "sliding" }),
822
+ Stream.runForEach(() =>
823
+ refreshCheckedOutRef(cwd).pipe(
824
+ Effect.retry(CHECKOUT_REFRESH_RETRY),
825
+ Effect.catchCause((cause) =>
826
+ Effect.logWarning("VCS checked-out ref refresh failed", {
827
+ cwdLength: cwd.length,
828
+ ...remoteRefreshFailureDiagnostics(cause),
829
+ }),
830
+ ),
831
+ ),
832
+ ),
833
+ );
834
+ });
835
+
836
+ const retainHeadWatcher = Effect.fn("VcsStatusBroadcaster.retainHeadWatcher")(function* (
837
+ cwd: string,
838
+ ) {
839
+ const ready = yield* SynchronizedRef.modifyEffect(headWatchersRef, (activeWatchers) => {
840
+ const existing = activeWatchers.get(cwd);
841
+ if (existing && existing.fiber.pollUnsafe() === undefined) {
842
+ const nextWatchers = new Map(activeWatchers).set(cwd, {
843
+ ...existing,
844
+ subscriberCount: existing.subscriberCount + 1,
845
+ });
846
+ return Effect.succeed([existing.ready, nextWatchers] as const);
847
+ }
848
+ // A watch that ended, say before the repository existed, restarts for everyone holding it.
849
+ return Effect.gen(function* () {
850
+ const ready = yield* Deferred.make<void>();
851
+ const fiber = yield* watchHead(cwd, ready).pipe(
852
+ Effect.catchCause((cause) =>
853
+ Effect.logWarning("VCS HEAD watch failed", {
854
+ cwdLength: cwd.length,
855
+ ...remoteRefreshFailureDiagnostics(cause),
856
+ }),
857
+ ),
858
+ // Subscribers wait for the watch, so one that cannot start must not hold them.
859
+ Effect.ensuring(Deferred.succeed(ready, undefined)),
860
+ Effect.forkIn(broadcasterScope),
861
+ );
862
+ const nextWatchers = new Map(activeWatchers).set(cwd, {
863
+ fiber,
864
+ ready,
865
+ subscriberCount: (existing?.subscriberCount ?? 0) + 1,
866
+ });
867
+ return [ready, nextWatchers] as const;
868
+ });
869
+ });
870
+ yield* Deferred.await(ready);
871
+ });
872
+
873
+ const releaseHeadWatcher = Effect.fn("VcsStatusBroadcaster.releaseHeadWatcher")(function* (
874
+ cwd: string,
875
+ ) {
876
+ const watcherToInterrupt = yield* SynchronizedRef.modify(headWatchersRef, (activeWatchers) => {
877
+ const existing = activeWatchers.get(cwd);
878
+ if (!existing) return [null, activeWatchers] as const;
879
+ const nextWatchers = new Map(activeWatchers);
880
+ if (existing.subscriberCount > 1) {
881
+ nextWatchers.set(cwd, { ...existing, subscriberCount: existing.subscriberCount - 1 });
882
+ return [null, nextWatchers] as const;
883
+ }
884
+ nextWatchers.delete(cwd);
885
+ return [existing.fiber, nextWatchers] as const;
886
+ });
887
+ if (watcherToInterrupt) {
888
+ yield* Fiber.interrupt(watcherToInterrupt).pipe(Effect.ignore);
889
+ }
890
+ });
891
+
892
const streamStatus: VcsStatusBroadcaster["Service"]["streamStatus"] = (input) =>
893
Stream.unwrap(
894
Effect.gen(function* () {
@@ -764,6 +906,8 @@ export const make = Effect.gen(function* () {
906
}),
907
);
908
const subscription = yield* PubSub.subscribe(changesPubSub);
909
+ // Watch before reading so a checkout in between still publishes.
910
+ yield* Effect.acquireRelease(retainHeadWatcher(cwd), () => releaseHeadWatcher(cwd));
911
const initialLocal = yield* getOrLoadLocalStatus(cwd);
912
const cachedStatus = yield* getCachedStatus(cwd);
913
const initialRemote = cachedStatus?.remote?.value ?? null;
@@ -793,35 +937,6 @@ export const make = Effect.gen(function* () {
937
}),
938
);
939
796
- // Serialize branch publication and cache invalidation with detailed reads and refreshes.
797
- const refreshBranchStatusCore = Effect.fn("VcsStatusBroadcaster.refreshBranchStatusCore")(
798
- (cwd: string) =>
799
- localRefreshLocks.withLock(
800
- cwd,
801
- Effect.gen(function* () {
802
- if (detailedSubscribers.has(cwd)) {
803
- const local = yield* getOrLoadLocalStatusUnlocked(cwd);
804
- return { refName: local.refName, revision: branches.get(cwd)?.revision ?? 0 };
805
- }
806
- const refName = yield* workflow.currentBranch(cwd);
807
- // HEAD cannot certify working-tree totals, even when it has not moved.
808
- localRefreshResults.delete(cwd);
809
- yield* workflow.invalidateLocalStatus(cwd);
810
- yield* Ref.update(cacheRef, (cache) => {
811
- const previous = cache.get(cwd);
812
- return previous ? new Map(cache).set(cwd, { ...previous, local: null }) : cache;
813
- });
814
- if (detailedSubscribers.has(cwd)) {
815
- const local = yield* workflow.localStatus({ cwd });
816
- yield* updateCachedLocalStatus(cwd, local, { publish: true });
817
- return { refName: local.refName, revision: branches.get(cwd)?.revision ?? 0 };
818
- }
819
- yield* publishBranch(cwd, refName);
820
- return { refName, revision: branches.get(cwd)?.revision ?? 0 };
821
- }),
822
- ),
823
- );
824
-
940
const refreshBranchStatus: VcsStatusBroadcaster["Service"]["refreshBranchStatus"] = Effect.fn(
941
"VcsStatusBroadcaster.refreshBranchStatus",
942
)(function* (input) {
@@ -836,6 +951,7 @@ export const make = Effect.gen(function* () {
951
Effect.gen(function* () {
952
const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
953
const subscription = yield* PubSub.subscribe(branchChangesPubSub);
954
+ yield* Effect.acquireRelease(retainHeadWatcher(cwd), () => releaseHeadWatcher(cwd));
955
const branch = yield* refreshBranchStatusCore(cwd);
956
return Stream.concat(
957
Stream.make({ refName: branch.refName }),