Open History to see the last commit
1import { SourceControlProviderKind } from "@t3tools/contracts";
2import { assert, it, describe } from "@effect/vitest";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import * as Deferred from "effect/Deferred";
5import * as DateTime from "effect/DateTime";
6import * as Duration from "effect/Duration";
7import * as Effect from "effect/Effect";
8import * as Fiber from "effect/Fiber";
9import * as Exit from "effect/Exit";
10import * as FileSystem from "effect/FileSystem";
11import * as Layer from "effect/Layer";
12import * as Option from "effect/Option";
13import * as Path from "effect/Path";
14import * as Queue from "effect/Queue";
15import * as Scope from "effect/Scope";
16import * as Scheduler from "effect/Scheduler";
17import * as Stream from "effect/Stream";
18import * as TestClock from "effect/testing/TestClock";
19import * as Tracer from "effect/Tracer";
20import type {
21 BackgroundScope,
22 VcsStatusLocalResult,
23 VcsStatusRemoteResult,
24 VcsStatusStreamEvent,
25} from "@t3tools/contracts";
26import { GitCommandError, GitManagerError } from "@t3tools/contracts";
27
28import * as VcsStatusBroadcaster from "./VcsStatusBroadcaster.ts";
29import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
30import * as GitWorkflowService from "../git/GitWorkflowService.ts";
31import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
32
33const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
34
35const baseLocalStatus: VcsStatusLocalResult = {
36 isRepo: true,
37 sourceControlProvider: {
38 kind: SourceControlProviderKind.make("github"),
39 name: "GitHub",
40 baseUrl: "https://github.com",
41 },
42 hasPrimaryRemote: true,
43 isDefaultRef: false,
44 refName: "feature/status-broadcast",
45 hasWorkingTreeChanges: false,
46 workingTree: { files: [], insertions: 0, deletions: 0 },
47};
48
49const baseRemoteStatus: VcsStatusRemoteResult = {
50 hasUpstream: true,
51 aheadCount: 0,
52 behindCount: 0,
53 pr: null,
54};
55
56const remoteStatusWithPr: VcsStatusRemoteResult = {
57 ...baseRemoteStatus,
58 pr: {
59 number: 2978,
60 title: "[codex] Rewrite client connection architecture",
61 url: "https://github.com/pingdotgg/t3code/pull/2978",
62 baseRef: "main",
63 headRef: "upstream-topic",
64 state: "open",
65 },
66};
67
68function layerTestFor(state: {
69 currentLocalStatus: VcsStatusLocalResult;
70 currentRemoteStatus: VcsStatusRemoteResult | null;
71 localStatusCalls: number;
72 remoteStatusCalls: number;
73 localInvalidationCalls: number;
74 remoteInvalidationCalls: number;
75 remoteStatusRefreshUpstreamValues?: Array<boolean | undefined>;
76 remoteStatusError?: GitManagerError;
77 backgroundWorkEnabled?: boolean;
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}) {
87 return VcsStatusBroadcaster.layer.pipe(
88 Layer.provideMerge(
89 state.fileSystem
90 ? Layer.succeed(FileSystem.FileSystem, state.fileSystem)
91 : NodeServices.layer,
92 ),
93 Layer.provide(layerBackgroundPolicy(() => state.backgroundWorkEnabled !== false)),
94 Layer.provide(
95 Layer.succeed(
96 VcsStatusBroadcaster.VcsAutomaticFetchInterval,
97 state.automaticFetchInterval ?? Effect.succeed(Duration.seconds(30)),
98 ),
99 ),
100 Layer.provide(
101 Layer.mock(GitWorkflowService.GitWorkflowService)({
102 localStatus: () =>
103 Effect.suspend(() => {
104 state.localStatusCalls += 1;
105 return (state.beforeLocalStatus ?? Effect.void).pipe(
106 Effect.as(state.currentLocalStatus),
107 );
108 }),
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(
118 Effect.andThen(
119 Effect.sync(() => {
120 state.remoteStatusCalls += 1;
121 state.remoteStatusRefreshUpstreamValues?.push(options?.refreshUpstream);
122 return state.currentRemoteStatus;
123 }),
124 ),
125 Effect.tap(() =>
126 state.remoteStatusError ? Effect.fail(state.remoteStatusError) : Effect.void,
127 ),
128 );
129 }),
130 invalidateLocalStatus: () =>
131 Effect.sync(() => {
132 state.localInvalidationCalls += 1;
133 }).pipe(Effect.andThen(state.beforeInvalidate ?? Effect.void)),
134 invalidateRemoteStatus: () =>
135 Effect.sync(() => {
136 state.remoteInvalidationCalls += 1;
137 }),
138 invalidateStatus: () =>
139 Effect.sync(() => {
140 state.localInvalidationCalls += 1;
141 state.remoteInvalidationCalls += 1;
142 }),
143 ...(state.pullCurrentBranch ? { pullCurrentBranch: state.pullCurrentBranch } : {}),
144 }),
145 ),
146 );
147}
148
149function layerBackgroundPolicy(shouldRunScopeWork: (scope: BackgroundScope) => boolean) {
150 return Layer.mock(BackgroundPolicy.BackgroundPolicy)({
151 reportClientActivity: () => Effect.void,
152 removeRpcClient: () => Effect.void,
153 snapshot: Effect.succeed({
154 hostPower: {
155 source: "unknown",
156 idle: "unknown",
157 idleSeconds: null,
158 locked: "unknown",
159 suspended: false,
160 onBattery: "unknown",
161 lowPowerMode: "unknown",
162 thermalState: "unknown",
163 stale: true,
164 updatedAt: TEST_EPOCH,
165 },
166 leases: [],
167 activeForegroundLeaseCount: 0,
168 activeScopeKeys: [],
169 shouldRunOpportunisticWork: false,
170 updatedAt: TEST_EPOCH,
171 }),
172 shouldRunScopeWork: (scope) => Effect.sync(() => shouldRunScopeWork(scope)),
173 shouldRunOpportunisticWork: Effect.succeed(true),
174 });
175}
176
177describe("VcsStatusBroadcaster", () => {
178 it.effect("refreshes queued behind a running one share the next git status read", () => {
179 const state: Parameters<typeof layerTestFor>[0] = {
180 currentLocalStatus: baseLocalStatus,
181 currentRemoteStatus: baseRemoteStatus,
182 localStatusCalls: 0,
183 remoteStatusCalls: 0,
184 localInvalidationCalls: 0,
185 remoteInvalidationCalls: 0,
186 fileSystem: FileSystem.makeNoop({ realPath: (cwd) => Effect.succeed(cwd) }),
187 };
188
189 return Effect.gen(function* () {
190 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
191 const started = yield* Deferred.make<void>();
192 const release = yield* Deferred.make<void>();
193 state.beforeLocalStatus = Deferred.succeed(started, undefined).pipe(
194 Effect.andThen(Deferred.await(release)),
195 );
196 const running = yield* broadcaster
197 .refreshLocalStatus("/repo")
198 .pipe(Effect.forkScoped({ startImmediately: true }));
199 yield* Deferred.await(started);
200 // Requested while the first read runs, so that read may predate their change.
201 state.currentLocalStatus = { ...baseLocalStatus, hasWorkingTreeChanges: true };
202 const queued = yield* Effect.all(
203 [broadcaster.refreshLocalStatus("/repo"), broadcaster.refreshLocalStatus("/repo")],
204 { concurrency: "unbounded" },
205 ).pipe(Effect.forkScoped({ startImmediately: true }));
206 yield* Deferred.succeed(release, undefined);
207
208 assert.isFalse((yield* Fiber.join(running)).hasWorkingTreeChanges);
209 const [second, third] = yield* Fiber.join(queued);
210 assert.isTrue(second.hasWorkingTreeChanges);
211 assert.isTrue(third.hasWorkingTreeChanges);
212 assert.strictEqual(state.localStatusCalls, 2);
213
214 yield* broadcaster.refreshLocalStatus("/repo");
215 assert.strictEqual(state.localStatusCalls, 3);
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,
351 currentRemoteStatus: remoteStatusWithPr,
352 localStatusCalls: 0,
353 remoteStatusCalls: 0,
354 localInvalidationCalls: 0,
355 remoteInvalidationCalls: 0,
356 };
357
358 return Effect.gen(function* () {
359 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
360 yield* broadcaster.getStatus({ cwd: "/repo" });
361 const branchEvents = yield* broadcaster.streamBranchChanges.pipe(
362 Stream.take(2),
363 Stream.runCollect,
364 Effect.forkScoped({ startImmediately: true }),
365 );
366 const subscribed = yield* Deferred.make<void>();
367 const events = yield* broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }).pipe(
368 Stream.tap((event) =>
369 event._tag === "snapshot" ? Deferred.succeed(subscribed, undefined) : Effect.void,
370 ),
371 Stream.take(3),
372 Stream.runCollect,
373 Effect.forkScoped,
374 );
375 yield* Deferred.await(subscribed);
376
377 state.currentLocalStatus = { ...baseLocalStatus, refName: "main" };
378 const refreshed = yield* broadcaster.refreshStatus("/repo", { localOnly: true });
379 assert.equal(refreshed.refName, "main");
380 assert.isNull(refreshed.pr);
381 assert.equal(state.localInvalidationCalls, 1);
382 assert.equal(state.remoteStatusCalls, 1);
383 assert.equal(state.remoteInvalidationCalls, 2);
384 assert.deepStrictEqual((yield* Fiber.join(events)).slice(1), [
385 { _tag: "remoteUpdated", remote: null },
386 { _tag: "localUpdated", local: state.currentLocalStatus },
387 ]);
388 assert.isNull((yield* broadcaster.getStatus({ cwd: "/repo" })).pr);
389 state.currentLocalStatus = { ...state.currentLocalStatus, hasWorkingTreeChanges: true };
390 yield* broadcaster.refreshLocalStatus("/repo");
391 state.currentLocalStatus = { ...baseLocalStatus, refName: "union" };
392 state.currentRemoteStatus = null;
393 const queried = yield* broadcaster.getStatus({ cwd: "/repo" });
394 assert.equal(queried.refName, "union");
395 assert.isNull(queried.pr);
396 const snapshot = yield* broadcaster
397 .streamStatus({ cwd: "/repo", includeRemote: false })
398 .pipe(Stream.take(1), Stream.runCollect);
399 assert.deepStrictEqual(snapshot[0], {
400 _tag: "snapshot",
401 local: state.currentLocalStatus,
402 remote: null,
403 });
404 assert.deepStrictEqual(yield* Fiber.join(branchEvents), [
405 { cwd: "/repo", refName: "main" },
406 { cwd: "/repo", refName: "union" },
407 ]);
408 }).pipe(Effect.provide(layerTestFor(state)));
409 });
410
411 it.effect(
412 "preserves cached remote status when a local-only refresh stays on the same branch",
413 () => {
414 const state = {
415 currentLocalStatus: baseLocalStatus,
416 currentRemoteStatus: { ...remoteStatusWithPr, aheadCount: 2, behindCount: 3 },
417 localStatusCalls: 0,
418 remoteStatusCalls: 0,
419 localInvalidationCalls: 0,
420 remoteInvalidationCalls: 0,
421 };
422
423 return Effect.gen(function* () {
424 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
425 const initial = yield* broadcaster.getStatus({ cwd: "/repo" });
426 const refreshed = yield* broadcaster.refreshStatus("/repo", { localOnly: true });
427 assert.deepStrictEqual(refreshed, initial);
428 assert.deepStrictEqual(yield* broadcaster.getStatus({ cwd: "/repo" }), refreshed);
429 assert.equal(state.localInvalidationCalls, 1);
430 assert.equal(state.remoteInvalidationCalls, 1);
431 assert.equal(state.remoteStatusCalls, 1);
432 }).pipe(Effect.provide(layerTestFor(state)));
433 },
434 );
435
436 it.effect("clears the previous branch's remote status after an in-flight PR refresh", () => {
437 const remoteReadStarted = Deferred.makeUnsafe<void>();
438 const releaseRemoteRead = Deferred.makeUnsafe<void>();
439 const state = {
440 currentLocalStatus: baseLocalStatus,
441 currentRemoteStatus: remoteStatusWithPr,
442 localStatusCalls: 0,
443 remoteStatusCalls: 0,
444 localInvalidationCalls: 0,
445 remoteInvalidationCalls: 0,
446 beforeRemoteStatus: Effect.void,
447 };
448
449 return Effect.gen(function* () {
450 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
451 yield* broadcaster.getStatus({ cwd: "/repo" });
452 state.beforeRemoteStatus = Deferred.succeed(remoteReadStarted, undefined).pipe(
453 Effect.andThen(Deferred.await(releaseRemoteRead)),
454 );
455 const remoteRefresh = yield* broadcaster
456 .refreshPullRequestStatus("/repo")
457 .pipe(Effect.forkScoped);
458 yield* Deferred.await(remoteReadStarted);
459 state.currentLocalStatus = { ...baseLocalStatus, refName: "main" };
460 const localRefresh = yield* broadcaster
461 .refreshStatus("/repo", { localOnly: true })
462 .pipe(Effect.forkScoped);
463 yield* Deferred.succeed(releaseRemoteRead, undefined);
464 yield* Fiber.join(remoteRefresh);
465 yield* Fiber.join(localRefresh);
466
467 const status = yield* broadcaster.getStatus({ cwd: "/repo" });
468 assert.equal(status.refName, "main");
469 assert.isNull(status.pr);
470 assert.equal(status.aheadCount, 0);
471 assert.equal(status.behindCount, 0);
472 assert.equal(state.remoteStatusCalls, 2);
473 }).pipe(Effect.provide(layerTestFor(state)));
474 });
475
476 it.effect.skipIf(!symlinksSupported)(
477 "automatically pulls an enabled clean default branch when status detects it is behind",
478 () => {
479 let remoteStatus: VcsStatusRemoteResult = { ...baseRemoteStatus, behindCount: 2 };
480 let pullCalls = 0;
481 let configuredWorkspaceRoot = "";
482 const localStatus: VcsStatusLocalResult = {
483 ...baseLocalStatus,
484 isDefaultRef: true,
485 refName: "main",
486 };
487 const layerTest = VcsStatusBroadcaster.layer.pipe(
488 Layer.provideMerge(NodeServices.layer),
489 Layer.provide(layerBackgroundPolicy(() => true)),
490 Layer.provide(
491 Layer.succeed(VcsStatusBroadcaster.VcsAutoPullPolicy, {
492 isEnabled: (cwd) => Effect.succeed(cwd === configuredWorkspaceRoot),
493 }),
494 ),
495 Layer.provide(
496 Layer.mock(GitWorkflowService.GitWorkflowService)({
497 localStatus: () => Effect.succeed(localStatus),
498 currentBranch: () => Effect.succeed(localStatus.refName),
499 remoteStatus: () => Effect.succeed(remoteStatus),
500 invalidateLocalStatus: () => Effect.void,
501 invalidateRemoteStatus: () => Effect.void,
502 invalidateStatus: () => Effect.void,
503 pullCurrentBranch: () =>
504 Effect.sync(() => {
505 pullCalls += 1;
506 remoteStatus = { ...remoteStatus, behindCount: 0 };
507 return {
508 status: "pulled" as const,
509 refName: "main",
510 upstreamRef: "origin/main",
511 };
512 }),
513 }),
514 ),
515 );
516
517 return Effect.gen(function* () {
518 const fileSystem = yield* FileSystem.FileSystem;
519 const path = yield* Path.Path;
520 const realDir = yield* fileSystem.makeTempDirectoryScoped({
521 prefix: "t3-vcs-auto-pull-real-",
522 });
523 const linkParent = yield* fileSystem.makeTempDirectoryScoped({
524 prefix: "t3-vcs-auto-pull-link-",
525 });
526 configuredWorkspaceRoot = path.join(linkParent, "repo-link");
527 yield* fileSystem.symlink(realDir, configuredWorkspaceRoot);
528
529 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
530 const status = yield* broadcaster.refreshStatus(configuredWorkspaceRoot);
531
532 assert.equal(pullCalls, 1);
533 assert.equal(status.behindCount, 0);
534 }).pipe(Effect.provide(layerTest));
535 },
536 );
537
538 it.effect("refreshes a loaded cwd without reusing a previous branch's PR", () => {
539 const state: Parameters<typeof layerTestFor>[0] = {
540 currentLocalStatus: baseLocalStatus,
541 currentRemoteStatus: { ...baseRemoteStatus, aheadCount: 3, behindCount: 5 },
542 localStatusCalls: 0,
543 remoteStatusCalls: 0,
544 localInvalidationCalls: 0,
545 remoteInvalidationCalls: 0,
546 remoteStatusRefreshUpstreamValues: [],
547 };
548
549 return Effect.gen(function* () {
550 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
551
552 assert.isNull(yield* broadcaster.refreshPullRequestStatus("/repo"));
553 assert.equal(state.remoteStatusCalls, 0);
554
555 yield* broadcaster.getStatus({ cwd: "/repo" });
556 assert.equal(state.remoteStatusCalls, 1);
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" });
564 assert.equal(merged.aheadCount, 7);
565 assert.equal(merged.behindCount, 0);
566 assert.equal(state.remoteStatusRefreshUpstreamValues?.at(-1), false);
567 assert.equal(state.remoteStatusCalls, 2);
568 assert.equal(state.remoteInvalidationCalls, 2);
569
570 state.currentLocalStatus = { ...baseLocalStatus, refName: "feature/next" };
571 state.currentRemoteStatus = baseRemoteStatus;
572 yield* broadcaster.refreshLocalStatus("/repo");
573 const refreshedBranch = yield* broadcaster.refreshPullRequestStatus("/repo");
574 assert.deepStrictEqual(refreshedBranch, baseRemoteStatus);
575 assert.equal(state.remoteStatusCalls, 3);
576 const refreshedStatus = yield* broadcaster.getStatus({ cwd: "/repo" });
577 assert.equal(refreshedStatus.refName, "feature/next");
578 assert.isNull(refreshedStatus.pr);
579 assert.equal(state.remoteStatusCalls, 3);
580 assert.equal(state.remoteInvalidationCalls, 3);
581 }).pipe(Effect.provide(layerTestFor(state)));
582 });
583
584 it.effect("a poll that started before the turn-end refresh cannot overwrite its PR", () => {
585 const releaseFirstPoll = Deferred.makeUnsafe<void>();
586 const firstPollStarted = Deferred.makeUnsafe<void>();
587 let remoteReads = 0;
588 const layer = VcsStatusBroadcaster.layer.pipe(
589 Layer.provideMerge(NodeServices.layer),
590 Layer.provide(layerBackgroundPolicy(() => true)),
591 Layer.provide(
592 Layer.mock(GitWorkflowService.GitWorkflowService)({
593 localStatus: () => Effect.succeed(baseLocalStatus),
594 currentBranch: () => Effect.succeed(baseLocalStatus.refName),
595 remoteStatus: () =>
596 Effect.gen(function* () {
597 remoteReads += 1;
598 if (remoteReads === 2) {
599 yield* Deferred.succeed(firstPollStarted, undefined);
600 yield* Deferred.await(releaseFirstPoll);
601 return baseRemoteStatus;
602 }
603 return remoteReads === 1 ? baseRemoteStatus : remoteStatusWithPr;
604 }),
605 invalidateLocalStatus: () => Effect.void,
606 invalidateRemoteStatus: () => Effect.void,
607 invalidateStatus: () => Effect.void,
608 }),
609 ),
610 );
611
612 return Effect.gen(function* () {
613 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
614 yield* broadcaster.getStatus({ cwd: "/repo" });
615
616 const poll = yield* broadcaster.refreshStatus("/repo").pipe(Effect.forkScoped);
617 yield* Deferred.await(firstPollStarted);
618 const refresh = yield* broadcaster.refreshPullRequestStatus("/repo").pipe(Effect.forkScoped);
619 yield* Deferred.succeed(releaseFirstPoll, undefined);
620 yield* Fiber.join(poll);
621 const refreshed = yield* Fiber.join(refresh);
622
623 assert.deepStrictEqual(refreshed, remoteStatusWithPr);
624 const final = yield* broadcaster.getStatus({ cwd: "/repo" });
625 assert.deepStrictEqual(final.pr, remoteStatusWithPr.pr);
626 }).pipe(Effect.provide(layer), Effect.scoped);
627 });
628
629 it.effect("an initial status read cannot overwrite an explicit refresh", () => {
630 const firstReadStarted = Deferred.makeUnsafe<void>();
631 const releaseFirstRead = Deferred.makeUnsafe<void>();
632 let remoteReads = 0;
633 const layer = VcsStatusBroadcaster.layer.pipe(
634 Layer.provide(FileSystem.layerNoop({ realPath: (path) => Effect.succeed(path) })),
635 Layer.provideMerge(NodeServices.layer),
636 Layer.provide(layerBackgroundPolicy(() => true)),
637 Layer.provide(
638 Layer.mock(GitWorkflowService.GitWorkflowService)({
639 localStatus: () => Effect.succeed(baseLocalStatus),
640 currentBranch: () => Effect.succeed(baseLocalStatus.refName),
641 remoteStatus: () =>
642 Effect.gen(function* () {
643 remoteReads += 1;
644 if (remoteReads === 1) {
645 yield* Deferred.succeed(firstReadStarted, undefined);
646 yield* Deferred.await(releaseFirstRead);
647 return baseRemoteStatus;
648 }
649 return remoteStatusWithPr;
650 }),
651 invalidateLocalStatus: () => Effect.void,
652 invalidateRemoteStatus: () => Effect.void,
653 invalidateStatus: () => Effect.void,
654 }),
655 ),
656 );
657 return Effect.gen(function* () {
658 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
659 const initial = yield* broadcaster.getStatus({ cwd: "/repo" }).pipe(Effect.forkScoped);
660 yield* Deferred.await(firstReadStarted);
661 const refresh = yield* broadcaster.refreshStatus("/repo").pipe(Effect.forkScoped);
662 yield* TestClock.adjust(Duration.zero);
663 yield* Deferred.succeed(releaseFirstRead, undefined);
664 yield* Fiber.join(initial);
665 yield* Fiber.join(refresh);
666 assert.deepStrictEqual(
667 (yield* broadcaster.getStatus({ cwd: "/repo" })).pr,
668 remoteStatusWithPr.pr,
669 );
670 }).pipe(Effect.provide(layer), Effect.scoped);
671 });
672
673 it.effect("keeps the published local snapshot when a refresh remote read fails", () => {
674 const state = {
675 currentLocalStatus: baseLocalStatus,
676 currentRemoteStatus: baseRemoteStatus,
677 localStatusCalls: 0,
678 remoteStatusCalls: 0,
679 localInvalidationCalls: 0,
680 remoteInvalidationCalls: 0,
681 failRemoteStatus: false,
682 };
683 const layerTest = VcsStatusBroadcaster.layer.pipe(
684 Layer.provideMerge(NodeServices.layer),
685 Layer.provide(layerBackgroundPolicy(() => true)),
686 Layer.provide(
687 Layer.mock(GitWorkflowService.GitWorkflowService)({
688 localStatus: () =>
689 Effect.sync(() => {
690 state.localStatusCalls += 1;
691 return state.currentLocalStatus;
692 }),
693 currentBranch: () => Effect.succeed(state.currentLocalStatus.refName),
694 remoteStatus: () =>
695 Effect.suspend(() => {
696 state.remoteStatusCalls += 1;
697 return state.failRemoteStatus
698 ? Effect.fail(
699 new GitManagerError({
700 operation: "VcsStatusBroadcaster.test",
701 cwd: "/repo",
702 detail: "remote status failed",
703 }),
704 )
705 : Effect.succeed(state.currentRemoteStatus);
706 }),
707 invalidateLocalStatus: () =>
708 Effect.sync(() => {
709 state.localInvalidationCalls += 1;
710 }),
711 invalidateRemoteStatus: () =>
712 Effect.sync(() => {
713 state.remoteInvalidationCalls += 1;
714 }),
715 invalidateStatus: () =>
716 Effect.sync(() => {
717 state.localInvalidationCalls += 1;
718 state.remoteInvalidationCalls += 1;
719 }),
720 }),
721 ),
722 );
723
724 return Effect.gen(function* () {
725 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
726 yield* broadcaster.getStatus({ cwd: "/repo" });
727
728 state.currentLocalStatus = {
729 ...baseLocalStatus,
730 refName: "feature/partial-refresh",
731 };
732 state.currentRemoteStatus = {
733 ...baseRemoteStatus,
734 aheadCount: 3,
735 };
736 state.failRemoteStatus = true;
737
738 const refreshExit = yield* broadcaster.refreshStatus("/repo").pipe(Effect.exit);
739 const snapshot = yield* Stream.runHead(
740 broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }),
741 );
742
743 assert.isTrue(Exit.isFailure(refreshExit));
744 assert.isTrue(Option.isSome(snapshot));
745 const event = Option.getOrThrow(snapshot);
746 assert.equal(event._tag, "snapshot");
747 if (event._tag === "snapshot") {
748 assert.equal(event.local.refName, "feature/partial-refresh");
749 assert.isNull(event.remote);
750 }
751 }).pipe(Effect.provide(layerTest));
752 });
753
754 it.effect.skipIf(!symlinksSupported)(
755 "normalizes symlinked CWDs before cache lookup and workflow calls",
756 () => {
757 const seenCwds: string[] = [];
758 const state = {
759 currentLocalStatus: baseLocalStatus,
760 currentRemoteStatus: baseRemoteStatus,
761 localStatusCalls: 0,
762 remoteStatusCalls: 0,
763 localInvalidationCalls: 0,
764 remoteInvalidationCalls: 0,
765 };
766 const layerTest = VcsStatusBroadcaster.layer.pipe(
767 Layer.provideMerge(NodeServices.layer),
768 Layer.provide(layerBackgroundPolicy(() => true)),
769 Layer.provide(
770 Layer.mock(GitWorkflowService.GitWorkflowService)({
771 localStatus: (input) =>
772 Effect.sync(() => {
773 seenCwds.push(input.cwd);
774 state.localStatusCalls += 1;
775 return state.currentLocalStatus;
776 }),
777 currentBranch: () => Effect.succeed(state.currentLocalStatus.refName),
778 remoteStatus: (input) =>
779 Effect.sync(() => {
780 seenCwds.push(input.cwd);
781 state.remoteStatusCalls += 1;
782 return state.currentRemoteStatus;
783 }),
784 invalidateLocalStatus: () =>
785 Effect.sync(() => {
786 state.localInvalidationCalls += 1;
787 }),
788 invalidateRemoteStatus: () =>
789 Effect.sync(() => {
790 state.remoteInvalidationCalls += 1;
791 }),
792 } satisfies Partial<GitWorkflowService.GitWorkflowService["Service"]>),
793 ),
794 );
795
796 return Effect.gen(function* () {
797 const fileSystem = yield* FileSystem.FileSystem;
798 const path = yield* Path.Path;
799 const realDir = yield* fileSystem.makeTempDirectoryScoped({
800 prefix: "t3-vcs-status-real-",
801 });
802 const linkParent = yield* fileSystem.makeTempDirectoryScoped({
803 prefix: "t3-vcs-status-link-",
804 });
805 const linkDir = path.join(linkParent, "repo-link");
806 yield* fileSystem.symlink(realDir, linkDir);
807 const realPath = yield* fileSystem.realPath(realDir);
808
809 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
810 yield* broadcaster.getStatus({ cwd: linkDir });
811 yield* broadcaster.getStatus({ cwd: realDir });
812
813 assert.deepStrictEqual(seenCwds, [realPath, realPath]);
814 assert.equal(state.localStatusCalls, 1);
815 assert.equal(state.remoteStatusCalls, 1);
816 }).pipe(Effect.provide(layerTest));
817 },
818 );
819
820 it.effect("a remote poll refreshes Changes totals when divergence counts stay the same", () => {
821 const state: Parameters<typeof layerTestFor>[0] = {
822 currentLocalStatus: {
823 ...baseLocalStatus,
824 branchChanges: { baseRef: "origin/main", insertions: 745, deletions: 24 },
825 },
826 currentRemoteStatus: baseRemoteStatus,
827 localStatusCalls: 0,
828 remoteStatusCalls: 0,
829 localInvalidationCalls: 0,
830 remoteInvalidationCalls: 0,
831 };
832
833 return Effect.gen(function* () {
834 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
835 yield* broadcaster.getStatus({ cwd: "/repo" });
836 const subscribed = yield* Deferred.make<void>();
837 const polled = yield* Deferred.make<void>();
838 yield* broadcaster.streamStatus({ cwd: "/repo" }).pipe(
839 Stream.runForEach((event) => {
840 if (event._tag === "snapshot") return Deferred.succeed(subscribed, undefined);
841 if (event._tag === "remoteUpdated") return Deferred.succeed(polled, undefined);
842 return Effect.void;
843 }),
844 Effect.forkScoped,
845 );
846 yield* Deferred.await(subscribed);
847 state.currentLocalStatus = {
848 ...baseLocalStatus,
849 branchChanges: { baseRef: "origin/main", insertions: 107, deletions: 4 },
850 };
851 state.currentRemoteStatus = remoteStatusWithPr;
852 yield* TestClock.adjust("30 seconds");
853 yield* Deferred.await(polled);
854 const status = yield* broadcaster.getStatus({ cwd: "/repo" });
855 assert.deepStrictEqual(status.branchChanges, state.currentLocalStatus.branchChanges);
856 }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
857 });
858
859 it.effect("an explicit refresh reads local totals after the fetch", () => {
860 return Effect.gen(function* () {
861 const fetchStarted = yield* Deferred.make<void>();
862 const finishFetch = yield* Deferred.make<void>();
863 let local: VcsStatusLocalResult = {
864 ...baseLocalStatus,
865 branchChanges: { baseRef: "origin/main", insertions: 745, deletions: 24 },
866 };
867 let cachedLocal: VcsStatusLocalResult | undefined;
868 const readLocalStatus = () => Effect.sync(() => (cachedLocal ??= local));
869 const layerTest = VcsStatusBroadcaster.layer.pipe(
870 Layer.provideMerge(NodeServices.layer),
871 Layer.provide(layerBackgroundPolicy(() => true)),
872 Layer.provide(
873 Layer.mock(GitWorkflowService.GitWorkflowService)({
874 localStatus: readLocalStatus,
875 invalidateStatus: () =>
876 Effect.sync(() => {
877 cachedLocal = undefined;
878 }),
879 invalidateLocalStatus: () =>
880 Effect.sync(() => {
881 cachedLocal = undefined;
882 }),
883 currentBranch: () => Effect.succeed(baseLocalStatus.refName),
884 invalidateRemoteStatus: () => Effect.void,
885 remoteStatus: () =>
886 Deferred.succeed(fetchStarted, undefined).pipe(
887 Effect.andThen(Deferred.await(finishFetch)),
888 Effect.as(baseRemoteStatus),
889 ),
890 }),
891 ),
892 );
893 yield* Effect.gen(function* () {
894 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
895 const refresh = yield* broadcaster.refreshStatus("/repo").pipe(Effect.forkScoped);
896 yield* Deferred.await(fetchStarted);
897 // Another reader can refill the local cache while fetch is still running.
898 yield* readLocalStatus();
899 local = {
900 ...baseLocalStatus,
901 branchChanges: { baseRef: "origin/main", insertions: 0, deletions: 0 },
902 };
903 yield* Deferred.succeed(finishFetch, undefined);
904 const status = yield* Fiber.join(refresh);
905 assert.deepStrictEqual(status.branchChanges, local.branchChanges);
906 }).pipe(Effect.provide(layerTest));
907 });
908 });
909
910 it.effect("publishes local status while an earlier lookup holds the remote lock", () => {
911 const state: Parameters<typeof layerTestFor>[0] = {
912 currentLocalStatus: baseLocalStatus,
913 currentRemoteStatus: baseRemoteStatus,
914 localStatusCalls: 0,
915 remoteStatusCalls: 0,
916 localInvalidationCalls: 0,
917 remoteInvalidationCalls: 0,
918 };
919
920 return Effect.gen(function* () {
921 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
922 yield* broadcaster.getStatus({ cwd: "/repo" });
923 const subscribed = yield* Deferred.make<void>();
924 const published = yield* Deferred.make<VcsStatusLocalResult>();
925 yield* broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }).pipe(
926 Stream.runForEach((event) => {
927 if (event._tag === "snapshot") return Deferred.succeed(subscribed, undefined);
928 if (event._tag === "localUpdated") return Deferred.succeed(published, event.local);
929 return Effect.void;
930 }),
931 Effect.forkScoped,
932 );
933 yield* Deferred.await(subscribed);
934 const started = yield* Deferred.make<void>();
935 const release = yield* Deferred.make<void>();
936 state.beforeRemoteStatus = Deferred.succeed(started, undefined).pipe(
937 Effect.andThen(Deferred.await(release)),
938 );
939 const earlier = yield* broadcaster.refreshPullRequestStatus("/repo").pipe(Effect.forkScoped);
940 yield* Deferred.await(started);
941 state.currentLocalStatus = { ...baseLocalStatus, hasWorkingTreeChanges: true };
942 const completed = yield* Deferred.make<void>();
943 const refresh = yield* broadcaster
944 .refreshStatus("/repo")
945 .pipe(Effect.ensuring(Deferred.succeed(completed, undefined)), Effect.forkScoped);
946
947 assert.deepStrictEqual(yield* Deferred.await(published), state.currentLocalStatus);
948 assert.isFalse(yield* Deferred.isDone(completed));
949 assert.isFalse(yield* Deferred.isDone(release));
950 state.currentRemoteStatus = remoteStatusWithPr;
951 yield* Deferred.succeed(release, undefined);
952 yield* Fiber.join(earlier);
953 const status = yield* Fiber.join(refresh);
954 assert.isTrue(status.hasWorkingTreeChanges);
955 assert.deepStrictEqual(status.pr, remoteStatusWithPr.pr);
956 }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
957 });
958
959 it.effect("publishes local changes before a remote error and propagates that error", () => {
960 const remoteError = new GitManagerError({
961 operation: "VcsStatusBroadcaster.remoteStatus",
962 cwd: "/repo",
963 detail: "The controlled remote lookup failed.",
964 });
965 const state: Parameters<typeof layerTestFor>[0] = {
966 currentLocalStatus: baseLocalStatus,
967 currentRemoteStatus: remoteStatusWithPr,
968 localStatusCalls: 0,
969 remoteStatusCalls: 0,
970 localInvalidationCalls: 0,
971 remoteInvalidationCalls: 0,
972 };
973
974 return Effect.gen(function* () {
975 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
976 yield* broadcaster.getStatus({ cwd: "/repo" });
977 const subscribed = yield* Deferred.make<void>();
978 const published = yield* Deferred.make<VcsStatusLocalResult>();
979 yield* broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }).pipe(
980 Stream.runForEach((event) => {
981 if (event._tag === "snapshot") return Deferred.succeed(subscribed, undefined);
982 if (event._tag === "localUpdated") return Deferred.succeed(published, event.local);
983 return Effect.void;
984 }),
985 Effect.forkScoped,
986 );
987 yield* Deferred.await(subscribed);
988 const started = yield* Deferred.make<void>();
989 const release = yield* Deferred.make<void>();
990 const completed = yield* Deferred.make<void>();
991 state.beforeRemoteStatus = Deferred.succeed(started, undefined).pipe(
992 Effect.andThen(Deferred.await(release)),
993 );
994 state.currentLocalStatus = { ...baseLocalStatus, hasWorkingTreeChanges: true };
995 state.remoteStatusError = remoteError;
996 const refresh = yield* broadcaster
997 .refreshStatus("/repo")
998 .pipe(
999 Effect.result,
1000 Effect.ensuring(Deferred.succeed(completed, undefined)),
1001 Effect.forkScoped,
1002 );
1003 yield* Deferred.await(started);
1004 assert.isFalse(yield* Deferred.isDone(completed));
1005 const pending = Option.getOrThrow(
1006 yield* Stream.runHead(broadcaster.streamStatus({ cwd: "/repo", includeRemote: false })),
1007 );
1008 assert.equal(pending._tag, "snapshot");
1009 if (pending._tag === "snapshot") assert.isTrue(pending.local.hasWorkingTreeChanges);
1010 yield* Deferred.succeed(release, undefined);
1011 const result = yield* Fiber.join(refresh);
1012 assert.equal(result._tag, "Failure");
1013 if (result._tag === "Failure") assert.strictEqual(result.failure, remoteError);
1014 const cached = yield* broadcaster.getStatus({ cwd: "/repo" });
1015 assert.isTrue(cached.hasWorkingTreeChanges);
1016 assert.deepStrictEqual(cached.pr, remoteStatusWithPr.pr);
1017 assert.deepStrictEqual(yield* Deferred.await(published), state.currentLocalStatus);
1018 }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
1019 });
1020
1021 it.effect.each(["getStatus", "refreshStatus", "autoPull", "autoPullFailure"] as const)(
1022 "%s keeps response parts consistent when local state changes after the remote cache write",
1023 (operation) => {
1024 const state: Parameters<typeof layerTestFor>[0] = {
1025 currentLocalStatus: baseLocalStatus,
1026 currentRemoteStatus: { ...remoteStatusWithPr, aheadCount: 3, behindCount: 5 },
1027 localStatusCalls: 0,
1028 remoteStatusCalls: 0,
1029 localInvalidationCalls: 0,
1030 remoteInvalidationCalls: 0,
1031 fileSystem: FileSystem.makeNoop({ realPath: (cwd) => Effect.succeed(cwd) }),
1032 };
1033 const autoPull = operation === "autoPull" || operation === "autoPullFailure";
1034 if (autoPull) {
1035 state.currentLocalStatus = { ...baseLocalStatus, isDefaultRef: true };
1036 state.currentRemoteStatus = { ...remoteStatusWithPr, aheadCount: 0, behindCount: 5 };
1037 state.pullCurrentBranch = () =>
1038 operation === "autoPullFailure"
1039 ? Effect.fail(
1040 new GitCommandError({
1041 operation: "test.pull",
1042 command: "pull",
1043 cwd: "/repo",
1044 detail: "Pull failed.",
1045 }),
1046 )
1047 : Effect.succeed({
1048 status: "pulled",
1049 refName: "feature/status-broadcast",
1050 upstreamRef: "origin/main",
1051 });
1052 }
1053 const layerTest = layerTestFor(state).pipe(
1054 Layer.provide(
1055 Layer.succeed(VcsStatusBroadcaster.VcsAutoPullPolicy, {
1056 isEnabled: () => Effect.succeed(autoPull),
1057 }),
1058 ),
1059 );
1060 return Effect.gen(function* () {
1061 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
1062 let switched = false;
1063 let remoteWritten = false;
1064 const writeCompleted = yield* Deferred.make<void>();
1065 const localRefresh = yield* Effect.gen(function* () {
1066 yield* Deferred.await(writeCompleted);
1067 state.currentLocalStatus = { ...baseLocalStatus, refName: "feature/next-status" };
1068 yield* broadcaster.refreshLocalStatus("/repo");
1069 switched = true;
1070 }).pipe(Effect.forkScoped);
1071 const scheduler = new Scheduler.MixedScheduler();
1072 const shouldYield = scheduler.shouldYield.bind(scheduler);
1073 scheduler.shouldYield = (fiber) => (remoteWritten && !switched) || shouldYield(fiber);
1074 const tracer = Tracer.make({
1075 span: (options) => {
1076 const span = new Tracer.NativeSpan(options);
1077 const end = span.end.bind(span);
1078 span.end = (time, exit) => {
1079 end(time, exit);
1080 if (
1081 options.name !== "VcsStatusBroadcaster.updateCachedRemoteStatus" ||
1082 remoteWritten
1083 ) {
1084 return;
1085 }
1086 // Yield this reader after its write until the local refresh finishes.
1087 remoteWritten = true;
1088 Deferred.doneUnsafe(writeCompleted, Effect.void);
1089 };
1090 return span;
1091 },
1092 });
1093 const status = yield* (
1094 operation === "getStatus"
1095 ? broadcaster.getStatus({ cwd: "/repo" })
1096 : broadcaster.refreshStatus("/repo")
1097 ).pipe(Effect.withTracer(tracer), Effect.provideService(Scheduler.Scheduler, scheduler));
1098 yield* Fiber.join(localRefresh);
1099 assert.isTrue(switched);
1100 assert.equal(status.refName, "feature/next-status");
1101 assert.isNull(status.pr);
1102 assert.equal(status.aheadCount, 0);
1103 assert.equal(status.behindCount, 0);
1104 }).pipe(Effect.provide(layerTest), Effect.scoped);
1105 },
1106 );
1107
1108 it.effect("recovers a discarded branch lookup on the next turn-end refresh", () => {
1109 const state: Parameters<typeof layerTestFor>[0] = {
1110 currentLocalStatus: baseLocalStatus,
1111 currentRemoteStatus: { ...remoteStatusWithPr, aheadCount: 3, behindCount: 5 },
1112 localStatusCalls: 0,
1113 remoteStatusCalls: 0,
1114 localInvalidationCalls: 0,
1115 remoteInvalidationCalls: 0,
1116 };
1117
1118 return Effect.gen(function* () {
1119 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
1120 const started = yield* Deferred.make<void>();
1121 const release = yield* Deferred.make<void>();
1122 state.beforeRemoteStatus = Deferred.succeed(started, undefined).pipe(
1123 Effect.andThen(Deferred.await(release)),
1124 );
1125 const lookup = yield* broadcaster.getStatus({ cwd: "/repo" }).pipe(Effect.forkScoped);
1126 yield* Deferred.await(started);
1127 state.currentLocalStatus = { ...baseLocalStatus, refName: "feature/next-status" };
1128 yield* Deferred.succeed(release, undefined);
1129 const discarded = yield* Fiber.join(lookup);
1130 assert.equal(discarded.refName, state.currentLocalStatus.refName);
1131 assert.isNull(discarded.pr);
1132 assert.equal(discarded.aheadCount, 0);
1133 assert.equal(discarded.behindCount, 0);
1134 const snapshot = Option.getOrThrow(
1135 yield* Stream.runHead(broadcaster.streamStatus({ cwd: "/repo", includeRemote: false })),
1136 );
1137 assert.equal(snapshot._tag, "snapshot");
1138 if (snapshot._tag === "snapshot") assert.isNull(snapshot.remote);
1139
1140 state.beforeRemoteStatus = Effect.void;
1141 state.currentRemoteStatus = {
1142 ...baseRemoteStatus,
1143 aheadCount: 2,
1144 pr: { ...remoteStatusWithPr.pr!, number: 2979, headRef: "feature/next-status" },
1145 };
1146 state.backgroundWorkEnabled = false;
1147 const recovered = yield* broadcaster.refreshPullRequestStatus("/repo");
1148 assert.deepStrictEqual(recovered, state.currentRemoteStatus);
1149 const cached = yield* broadcaster.getStatus({ cwd: "/repo" });
1150 assert.equal(cached.refName, state.currentLocalStatus.refName);
1151 assert.deepStrictEqual(cached.pr, state.currentRemoteStatus.pr);
1152 assert.equal(cached.aheadCount, 2);
1153 assert.equal(state.remoteStatusCalls, 2);
1154 }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
1155 });
1156
1157 it.effect("releases remote demand while passive observers remain", () => {
1158 const state = {
1159 currentLocalStatus: baseLocalStatus,
1160 currentRemoteStatus: baseRemoteStatus,
1161 localStatusCalls: 0,
1162 remoteStatusCalls: 0,
1163 localInvalidationCalls: 0,
1164 remoteInvalidationCalls: 0,
1165 };
1166 let remoteInterruptedDeferred: Deferred.Deferred<void, never> | null = null;
1167 let remoteStartedDeferred: Deferred.Deferred<void, never> | null = null;
1168 const layerTest = VcsStatusBroadcaster.layer.pipe(
1169 Layer.provideMerge(NodeServices.layer),
1170 Layer.provide(layerBackgroundPolicy(() => true)),
1171 Layer.provide(
1172 Layer.mock(GitWorkflowService.GitWorkflowService)({
1173 localStatus: () =>
1174 Effect.sync(() => {
1175 state.localStatusCalls += 1;
1176 return state.currentLocalStatus;
1177 }),
1178 currentBranch: () => Effect.succeed(state.currentLocalStatus.refName),
1179 remoteStatus: () =>
1180 Effect.sync(() => {
1181 state.remoteStatusCalls += 1;
1182 }).pipe(
1183 Effect.andThen(
1184 remoteStartedDeferred
1185 ? Deferred.succeed(remoteStartedDeferred, undefined).pipe(Effect.ignore)
1186 : Effect.void,
1187 ),
1188 Effect.andThen(Effect.never as Effect.Effect<VcsStatusRemoteResult | null, never>),
1189 Effect.onInterrupt(() =>
1190 remoteInterruptedDeferred
1191 ? Deferred.succeed(remoteInterruptedDeferred, undefined).pipe(Effect.ignore)
1192 : Effect.void,
1193 ),
1194 ),
1195 invalidateLocalStatus: () =>
1196 Effect.sync(() => {
1197 state.localInvalidationCalls += 1;
1198 }),
1199 invalidateRemoteStatus: () =>
1200 Effect.sync(() => {
1201 state.remoteInvalidationCalls += 1;
1202 }),
1203 } satisfies Partial<GitWorkflowService.GitWorkflowService["Service"]>),
1204 ),
1205 );
1206
1207 return Effect.gen(function* () {
1208 const remoteInterrupted = yield* Deferred.make<void>();
1209 const remoteStarted = yield* Deferred.make<void>();
1210 remoteInterruptedDeferred = remoteInterrupted;
1211 remoteStartedDeferred = remoteStarted;
1212
1213 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
1214 const firstSnapshot = yield* Deferred.make<VcsStatusStreamEvent>();
1215 const secondSnapshot = yield* Deferred.make<VcsStatusStreamEvent>();
1216 const firstScope = yield* Scope.make();
1217 const secondScope = yield* Scope.make();
1218 const passiveSnapshot = yield* Deferred.make<VcsStatusStreamEvent>();
1219 yield* Stream.runForEach(
1220 broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }),
1221 (event) =>
1222 event._tag === "snapshot"
1223 ? Deferred.succeed(passiveSnapshot, event).pipe(Effect.ignore)
1224 : Effect.void,
1225 ).pipe(Effect.forkScoped);
1226 yield* Deferred.await(passiveSnapshot);
1227 assert.equal(state.remoteStatusCalls, 0);
1228 yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) =>
1229 event._tag === "snapshot"
1230 ? Deferred.succeed(firstSnapshot, event).pipe(Effect.ignore)
1231 : Effect.void,
1232 ).pipe(Effect.forkIn(firstScope));
1233 yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) =>
1234 event._tag === "snapshot"
1235 ? Deferred.succeed(secondSnapshot, event).pipe(Effect.ignore)
1236 : Effect.void,
1237 ).pipe(Effect.forkIn(secondScope));
1238
1239 yield* Deferred.await(firstSnapshot);
1240 yield* Deferred.await(secondSnapshot);
1241 yield* Deferred.await(remoteStarted);
1242
1243 assert.equal(state.remoteStatusCalls, 1);
1244
1245 yield* Scope.close(firstScope, Exit.void);
1246 assert.isTrue(Option.isNone(yield* Deferred.poll(remoteInterrupted)));
1247
1248 yield* Scope.close(secondScope, Exit.void).pipe(Effect.forkScoped);
1249 yield* Deferred.await(remoteInterrupted);
1250 assert.isTrue(Option.isSome(yield* Deferred.poll(remoteInterrupted)));
1251 }).pipe(Effect.provide(layerTest));
1252 });
1253});
1254
1255const 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});
1264it.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});
1296it.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
1323it.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
1351it.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});