Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

VcsStatusBroadcaster.test.ts

1,477 lines60.5 KB

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 );
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 });
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 state.currentRemoteStatus = baseRemoteStatus;
379 const refreshed = yield* broadcaster.refreshStatus("/repo", { localOnly: true });
380 assert.equal(refreshed.refName, "main");
381 assert.isNull(refreshed.pr);
382 assert.equal(state.localInvalidationCalls, 1);
383 assert.equal(state.remoteStatusCalls, 1);
384 assert.equal(state.remoteInvalidationCalls, 1);
385 assert.deepStrictEqual((yield* Fiber.join(events)).slice(1), [
386 { _tag: "remoteUpdated", remote: null },
387 { _tag: "localUpdated", local: state.currentLocalStatus },
388 ]);
389 assert.isNull((yield* broadcaster.getStatus({ cwd: "/repo" })).pr);
390 assert.equal(state.remoteStatusCalls, 2);
391 state.currentLocalStatus = { ...state.currentLocalStatus, hasWorkingTreeChanges: true };
392 yield* broadcaster.refreshLocalStatus("/repo");
393 state.currentLocalStatus = { ...baseLocalStatus, refName: "union" };
394 state.currentRemoteStatus = null;
395 const queried = yield* broadcaster.getStatus({ cwd: "/repo" });
396 assert.equal(queried.refName, "union");
397 assert.isNull(queried.pr);
398 const snapshot = yield* broadcaster
399 .streamStatus({ cwd: "/repo", includeRemote: false })
400 .pipe(Stream.take(1), Stream.runCollect);
401 assert.deepStrictEqual(snapshot[0], {
402 _tag: "snapshot",
403 local: state.currentLocalStatus,
404 remote: null,
405 });
406 assert.deepStrictEqual(yield* Fiber.join(branchEvents), [
407 { cwd: "/repo", refName: "main" },
408 { cwd: "/repo", refName: "union" },
409 ]);
410 }).pipe(Effect.provide(layerTestFor(state)));
411 });
412​
413 it.effect(
414 "preserves cached remote status when a local-only refresh stays on the same branch",
415 () => {
416 const state = {
417 currentLocalStatus: baseLocalStatus,
418 currentRemoteStatus: { ...remoteStatusWithPr, aheadCount: 2, behindCount: 3 },
419 localStatusCalls: 0,
420 remoteStatusCalls: 0,
421 localInvalidationCalls: 0,
422 remoteInvalidationCalls: 0,
423 };
424​
425 return Effect.gen(function* () {
426 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
427 const initial = yield* broadcaster.getStatus({ cwd: "/repo" });
428 const refreshed = yield* broadcaster.refreshStatus("/repo", { localOnly: true });
429 assert.deepStrictEqual(refreshed, initial);
430 assert.deepStrictEqual(yield* broadcaster.getStatus({ cwd: "/repo" }), refreshed);
431 assert.equal(state.localInvalidationCalls, 1);
432 assert.equal(state.remoteInvalidationCalls, 1);
433 assert.equal(state.remoteStatusCalls, 1);
434 }).pipe(Effect.provide(layerTestFor(state)));
435 },
436 );
437​
438 it.effect("a local-only refresh that overlaps the first remote poll keeps its PR", () => {
439 const state: Parameters<typeof layerTestFor>[0] = {
440 currentLocalStatus: baseLocalStatus,
441 currentRemoteStatus: remoteStatusWithPr,
442 localStatusCalls: 0,
443 remoteStatusCalls: 0,
444 localInvalidationCalls: 0,
445 remoteInvalidationCalls: 0,
446 };
447​
448 return Effect.gen(function* () {
449 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
450 const pollStarted = yield* Deferred.make<void>();
451 const releasePoll = yield* Deferred.make<void>();
452 state.beforeRemoteStatus = Deferred.succeed(pollStarted, undefined).pipe(
453 Effect.andThen(Deferred.await(releasePoll)),
454 );
455 const localSeen = yield* Deferred.make<void>();
456 yield* broadcaster.streamStatus({ cwd: "/repo" }).pipe(
457 Stream.runForEach((event) =>
458 event._tag === "localUpdated" ? Deferred.succeed(localSeen, undefined) : Effect.void,
459 ),
460 Effect.forkScoped,
461 );
462 yield* Deferred.await(pollStarted);
463 state.beforeRemoteStatus = Effect.void;
464​
465 state.currentLocalStatus = { ...baseLocalStatus, hasWorkingTreeChanges: true };
466 const refresh = yield* broadcaster
467 .refreshStatus("/repo", { localOnly: true })
468 .pipe(Effect.forkScoped);
469 yield* Deferred.await(localSeen);
470 yield* Deferred.succeed(releasePoll, undefined);
471 yield* Fiber.join(refresh);
472​
473 const status = yield* broadcaster.getStatus({ cwd: "/repo" });
474 assert.deepStrictEqual(status.pr, remoteStatusWithPr.pr);
475 assert.equal(state.remoteStatusCalls, 1);
476 }).pipe(Effect.provide(layerTestFor(state)));
477 });
478​
479 it.effect(
480 "a local-only refresh before any remote read leaves the PR refresh able to read",
481 () => {
482 const state: Parameters<typeof layerTestFor>[0] = {
483 currentLocalStatus: baseLocalStatus,
484 currentRemoteStatus: remoteStatusWithPr,
485 localStatusCalls: 0,
486 remoteStatusCalls: 0,
487 localInvalidationCalls: 0,
488 remoteInvalidationCalls: 0,
489 };
490​
491 return Effect.gen(function* () {
492 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
493 yield* broadcaster.refreshStatus("/repo", { localOnly: true });
494​
495 const remote = yield* broadcaster.refreshPullRequestStatus("/repo");
496 assert.deepStrictEqual(remote?.pr, remoteStatusWithPr.pr);
497 assert.equal(state.remoteStatusCalls, 1);
498 }).pipe(Effect.provide(layerTestFor(state)));
499 },
500 );
501​
502 it.effect("a local-only refresh after a branch switch leaves the PR refresh able to read", () => {
503 const state: Parameters<typeof layerTestFor>[0] = {
504 currentLocalStatus: baseLocalStatus,
505 currentRemoteStatus: remoteStatusWithPr,
506 localStatusCalls: 0,
507 remoteStatusCalls: 0,
508 localInvalidationCalls: 0,
509 remoteInvalidationCalls: 0,
510 };
511​
512 return Effect.gen(function* () {
513 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
514 yield* broadcaster.getStatus({ cwd: "/repo" });
515​
516 state.currentLocalStatus = { ...baseLocalStatus, refName: "feature/next" };
517 const nextBranchRemote: VcsStatusRemoteResult = {
518 ...baseRemoteStatus,
519 pr: { ...remoteStatusWithPr.pr!, number: 3001, headRef: "feature/next" },
520 };
521 state.currentRemoteStatus = nextBranchRemote;
522 yield* broadcaster.refreshStatus("/repo", { localOnly: true });
523​
524 const remote = yield* broadcaster.refreshPullRequestStatus("/repo");
525 assert.deepStrictEqual(remote?.pr, nextBranchRemote.pr);
526 assert.equal(state.remoteStatusCalls, 2);
527 }).pipe(Effect.provide(layerTestFor(state)));
528 });
529​
530 it.effect("clears the previous branch's remote status after an in-flight PR refresh", () => {
531 const remoteReadStarted = Deferred.makeUnsafe<void>();
532 const releaseRemoteRead = Deferred.makeUnsafe<void>();
533 const state = {
534 currentLocalStatus: baseLocalStatus,
535 currentRemoteStatus: remoteStatusWithPr,
536 localStatusCalls: 0,
537 remoteStatusCalls: 0,
538 localInvalidationCalls: 0,
539 remoteInvalidationCalls: 0,
540 beforeRemoteStatus: Effect.void,
541 };
542​
543 return Effect.gen(function* () {
544 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
545 yield* broadcaster.getStatus({ cwd: "/repo" });
546 state.beforeRemoteStatus = Deferred.succeed(remoteReadStarted, undefined).pipe(
547 Effect.andThen(Deferred.await(releaseRemoteRead)),
548 );
549 const remoteRefresh = yield* broadcaster
550 .refreshPullRequestStatus("/repo")
551 .pipe(Effect.forkScoped);
552 yield* Deferred.await(remoteReadStarted);
553 state.currentLocalStatus = { ...baseLocalStatus, refName: "main" };
554 const localRefresh = yield* broadcaster
555 .refreshStatus("/repo", { localOnly: true })
556 .pipe(Effect.forkScoped);
557 yield* Deferred.succeed(releaseRemoteRead, undefined);
558 yield* Fiber.join(remoteRefresh);
559 yield* Fiber.join(localRefresh);
560 state.currentRemoteStatus = baseRemoteStatus;
561​
562 const status = yield* broadcaster.getStatus({ cwd: "/repo" });
563 assert.equal(status.refName, "main");
564 assert.isNull(status.pr);
565 assert.equal(status.aheadCount, 0);
566 assert.equal(status.behindCount, 0);
567 assert.equal(state.remoteStatusCalls, 3);
568 }).pipe(Effect.provide(layerTestFor(state)));
569 });
570​
571 it.effect.skipIf(!symlinksSupported)(
572 "automatically pulls an enabled clean default branch when status detects it is behind",
573 () => {
574 let remoteStatus: VcsStatusRemoteResult = { ...baseRemoteStatus, behindCount: 2 };
575 let pullCalls = 0;
576 let configuredWorkspaceRoot = "";
577 const localStatus: VcsStatusLocalResult = {
578 ...baseLocalStatus,
579 isDefaultRef: true,
580 refName: "main",
581 };
582 const layerTest = VcsStatusBroadcaster.layer.pipe(
583 Layer.provideMerge(NodeServices.layer),
584 Layer.provide(layerBackgroundPolicy(() => true)),
585 Layer.provide(
586 Layer.succeed(VcsStatusBroadcaster.VcsAutoPullPolicy, {
587 isEnabled: (cwd) => Effect.succeed(cwd === configuredWorkspaceRoot),
588 }),
589 ),
590 Layer.provide(
591 Layer.mock(GitWorkflowService.GitWorkflowService)({
592 localStatus: () => Effect.succeed(localStatus),
593 currentBranch: () => Effect.succeed(localStatus.refName),
594 remoteStatus: () => Effect.succeed(remoteStatus),
595 invalidateLocalStatus: () => Effect.void,
596 invalidateRemoteStatus: () => Effect.void,
597 invalidateStatus: () => Effect.void,
598 pullCurrentBranch: () =>
599 Effect.sync(() => {
600 pullCalls += 1;
601 remoteStatus = { ...remoteStatus, behindCount: 0 };
602 return {
603 status: "pulled" as const,
604 refName: "main",
605 upstreamRef: "origin/main",
606 };
607 }),
608 }),
609 ),
610 );
611​
612 return Effect.gen(function* () {
613 const fileSystem = yield* FileSystem.FileSystem;
614 const path = yield* Path.Path;
615 const realDir = yield* fileSystem.makeTempDirectoryScoped({
616 prefix: "t3-vcs-auto-pull-real-",
617 });
618 const linkParent = yield* fileSystem.makeTempDirectoryScoped({
619 prefix: "t3-vcs-auto-pull-link-",
620 });
621 configuredWorkspaceRoot = path.join(linkParent, "repo-link");
622 yield* fileSystem.symlink(realDir, configuredWorkspaceRoot);
623​
624 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
625 const status = yield* broadcaster.refreshStatus(configuredWorkspaceRoot);
626​
627 assert.equal(pullCalls, 1);
628 assert.equal(status.behindCount, 0);
629 }).pipe(Effect.provide(layerTest));
630 },
631 );
632​
633 it.effect("refreshes a loaded cwd without reusing a previous branch's PR", () => {
634 const state: Parameters<typeof layerTestFor>[0] = {
635 currentLocalStatus: baseLocalStatus,
636 currentRemoteStatus: { ...baseRemoteStatus, aheadCount: 3, behindCount: 5 },
637 localStatusCalls: 0,
638 remoteStatusCalls: 0,
639 localInvalidationCalls: 0,
640 remoteInvalidationCalls: 0,
641 remoteStatusRefreshUpstreamValues: [],
642 };
643​
644 return Effect.gen(function* () {
645 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
646​
647 assert.isNull(yield* broadcaster.refreshPullRequestStatus("/repo"));
648 assert.equal(state.remoteStatusCalls, 0);
649​
650 yield* broadcaster.getStatus({ cwd: "/repo" });
651 assert.equal(state.remoteStatusCalls, 1);
652​
653 state.backgroundWorkEnabled = false;
654 state.currentRemoteStatus = { ...remoteStatusWithPr, aheadCount: 7 };
655 yield* broadcaster.refreshBranchStatus({ cwd: "/repo" });
656 const refreshed = yield* broadcaster.refreshPullRequestStatus("/repo");
657 assert.deepStrictEqual(refreshed, state.currentRemoteStatus);
658 const merged = yield* broadcaster.getStatus({ cwd: "/repo" });
659 assert.equal(merged.aheadCount, 7);
660 assert.equal(merged.behindCount, 0);
661 assert.equal(state.remoteStatusRefreshUpstreamValues?.at(-1), false);
662 assert.equal(state.remoteStatusCalls, 2);
663 assert.equal(state.remoteInvalidationCalls, 2);
664​
665 state.currentLocalStatus = { ...baseLocalStatus, refName: "feature/next" };
666 state.currentRemoteStatus = baseRemoteStatus;
667 yield* broadcaster.refreshLocalStatus("/repo");
668 const refreshedBranch = yield* broadcaster.refreshPullRequestStatus("/repo");
669 assert.deepStrictEqual(refreshedBranch, baseRemoteStatus);
670 assert.equal(state.remoteStatusCalls, 3);
671 const refreshedStatus = yield* broadcaster.getStatus({ cwd: "/repo" });
672 assert.equal(refreshedStatus.refName, "feature/next");
673 assert.isNull(refreshedStatus.pr);
674 assert.equal(state.remoteStatusCalls, 3);
675 assert.equal(state.remoteInvalidationCalls, 3);
676 }).pipe(Effect.provide(layerTestFor(state)));
677 });
678​
679 it.effect("a poll that started before the turn-end refresh cannot overwrite its PR", () => {
680 const releaseFirstPoll = Deferred.makeUnsafe<void>();
681 const firstPollStarted = Deferred.makeUnsafe<void>();
682 let remoteReads = 0;
683 const layer = VcsStatusBroadcaster.layer.pipe(
684 Layer.provideMerge(NodeServices.layer),
685 Layer.provide(layerBackgroundPolicy(() => true)),
686 Layer.provide(
687 Layer.mock(GitWorkflowService.GitWorkflowService)({
688 localStatus: () => Effect.succeed(baseLocalStatus),
689 currentBranch: () => Effect.succeed(baseLocalStatus.refName),
690 remoteStatus: () =>
691 Effect.gen(function* () {
692 remoteReads += 1;
693 if (remoteReads === 2) {
694 yield* Deferred.succeed(firstPollStarted, undefined);
695 yield* Deferred.await(releaseFirstPoll);
696 return baseRemoteStatus;
697 }
698 return remoteReads === 1 ? baseRemoteStatus : remoteStatusWithPr;
699 }),
700 invalidateLocalStatus: () => Effect.void,
701 invalidateRemoteStatus: () => Effect.void,
702 invalidateStatus: () => Effect.void,
703 }),
704 ),
705 );
706​
707 return Effect.gen(function* () {
708 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
709 yield* broadcaster.getStatus({ cwd: "/repo" });
710​
711 const poll = yield* broadcaster.refreshStatus("/repo").pipe(Effect.forkScoped);
712 yield* Deferred.await(firstPollStarted);
713 const refresh = yield* broadcaster.refreshPullRequestStatus("/repo").pipe(Effect.forkScoped);
714 yield* Deferred.succeed(releaseFirstPoll, undefined);
715 yield* Fiber.join(poll);
716 const refreshed = yield* Fiber.join(refresh);
717​
718 assert.deepStrictEqual(refreshed, remoteStatusWithPr);
719 const final = yield* broadcaster.getStatus({ cwd: "/repo" });
720 assert.deepStrictEqual(final.pr, remoteStatusWithPr.pr);
721 }).pipe(Effect.provide(layer), Effect.scoped);
722 });
723​
724 it.effect("an initial status read cannot overwrite an explicit refresh", () => {
725 const firstReadStarted = Deferred.makeUnsafe<void>();
726 const releaseFirstRead = Deferred.makeUnsafe<void>();
727 let remoteReads = 0;
728 const layer = VcsStatusBroadcaster.layer.pipe(
729 Layer.provide(FileSystem.layerNoop({ realPath: (path) => Effect.succeed(path) })),
730 Layer.provideMerge(NodeServices.layer),
731 Layer.provide(layerBackgroundPolicy(() => true)),
732 Layer.provide(
733 Layer.mock(GitWorkflowService.GitWorkflowService)({
734 localStatus: () => Effect.succeed(baseLocalStatus),
735 currentBranch: () => Effect.succeed(baseLocalStatus.refName),
736 remoteStatus: () =>
737 Effect.gen(function* () {
738 remoteReads += 1;
739 if (remoteReads === 1) {
740 yield* Deferred.succeed(firstReadStarted, undefined);
741 yield* Deferred.await(releaseFirstRead);
742 return baseRemoteStatus;
743 }
744 return remoteStatusWithPr;
745 }),
746 invalidateLocalStatus: () => Effect.void,
747 invalidateRemoteStatus: () => Effect.void,
748 invalidateStatus: () => Effect.void,
749 }),
750 ),
751 );
752 return Effect.gen(function* () {
753 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
754 const initial = yield* broadcaster.getStatus({ cwd: "/repo" }).pipe(Effect.forkScoped);
755 yield* Deferred.await(firstReadStarted);
756 const refresh = yield* broadcaster.refreshStatus("/repo").pipe(Effect.forkScoped);
757 yield* TestClock.adjust(Duration.zero);
758 yield* Deferred.succeed(releaseFirstRead, undefined);
759 yield* Fiber.join(initial);
760 yield* Fiber.join(refresh);
761 assert.deepStrictEqual(
762 (yield* broadcaster.getStatus({ cwd: "/repo" })).pr,
763 remoteStatusWithPr.pr,
764 );
765 }).pipe(Effect.provide(layer), Effect.scoped);
766 });
767​
768 it.effect("keeps the published local snapshot when a refresh remote read fails", () => {
769 const state = {
770 currentLocalStatus: baseLocalStatus,
771 currentRemoteStatus: baseRemoteStatus,
772 localStatusCalls: 0,
773 remoteStatusCalls: 0,
774 localInvalidationCalls: 0,
775 remoteInvalidationCalls: 0,
776 failRemoteStatus: false,
777 };
778 const layerTest = VcsStatusBroadcaster.layer.pipe(
779 Layer.provideMerge(NodeServices.layer),
780 Layer.provide(layerBackgroundPolicy(() => true)),
781 Layer.provide(
782 Layer.mock(GitWorkflowService.GitWorkflowService)({
783 localStatus: () =>
784 Effect.sync(() => {
785 state.localStatusCalls += 1;
786 return state.currentLocalStatus;
787 }),
788 currentBranch: () => Effect.succeed(state.currentLocalStatus.refName),
789 remoteStatus: () =>
790 Effect.suspend(() => {
791 state.remoteStatusCalls += 1;
792 return state.failRemoteStatus
793 ? Effect.fail(
794 new GitManagerError({
795 operation: "VcsStatusBroadcaster.test",
796 cwd: "/repo",
797 detail: "remote status failed",
798 }),
799 )
800 : Effect.succeed(state.currentRemoteStatus);
801 }),
802 invalidateLocalStatus: () =>
803 Effect.sync(() => {
804 state.localInvalidationCalls += 1;
805 }),
806 invalidateRemoteStatus: () =>
807 Effect.sync(() => {
808 state.remoteInvalidationCalls += 1;
809 }),
810 invalidateStatus: () =>
811 Effect.sync(() => {
812 state.localInvalidationCalls += 1;
813 state.remoteInvalidationCalls += 1;
814 }),
815 }),
816 ),
817 );
818​
819 return Effect.gen(function* () {
820 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
821 yield* broadcaster.getStatus({ cwd: "/repo" });
822​
823 state.currentLocalStatus = {
824 ...baseLocalStatus,
825 refName: "feature/partial-refresh",
826 };
827 state.currentRemoteStatus = {
828 ...baseRemoteStatus,
829 aheadCount: 3,
830 };
831 state.failRemoteStatus = true;
832​
833 const refreshExit = yield* broadcaster.refreshStatus("/repo").pipe(Effect.exit);
834 const snapshot = yield* Stream.runHead(
835 broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }),
836 );
837​
838 assert.isTrue(Exit.isFailure(refreshExit));
839 assert.isTrue(Option.isSome(snapshot));
840 const event = Option.getOrThrow(snapshot);
841 assert.equal(event._tag, "snapshot");
842 if (event._tag === "snapshot") {
843 assert.equal(event.local.refName, "feature/partial-refresh");
844 assert.isNull(event.remote);
845 }
846 }).pipe(Effect.provide(layerTest));
847 });
848​
849 it.effect.skipIf(!symlinksSupported)(
850 "normalizes symlinked CWDs before cache lookup and workflow calls",
851 () => {
852 const seenCwds: string[] = [];
853 const state = {
854 currentLocalStatus: baseLocalStatus,
855 currentRemoteStatus: baseRemoteStatus,
856 localStatusCalls: 0,
857 remoteStatusCalls: 0,
858 localInvalidationCalls: 0,
859 remoteInvalidationCalls: 0,
860 };
861 const layerTest = VcsStatusBroadcaster.layer.pipe(
862 Layer.provideMerge(NodeServices.layer),
863 Layer.provide(layerBackgroundPolicy(() => true)),
864 Layer.provide(
865 Layer.mock(GitWorkflowService.GitWorkflowService)({
866 localStatus: (input) =>
867 Effect.sync(() => {
868 seenCwds.push(input.cwd);
869 state.localStatusCalls += 1;
870 return state.currentLocalStatus;
871 }),
872 currentBranch: () => Effect.succeed(state.currentLocalStatus.refName),
873 remoteStatus: (input) =>
874 Effect.sync(() => {
875 seenCwds.push(input.cwd);
876 state.remoteStatusCalls += 1;
877 return state.currentRemoteStatus;
878 }),
879 invalidateLocalStatus: () =>
880 Effect.sync(() => {
881 state.localInvalidationCalls += 1;
882 }),
883 invalidateRemoteStatus: () =>
884 Effect.sync(() => {
885 state.remoteInvalidationCalls += 1;
886 }),
887 } satisfies Partial<GitWorkflowService.GitWorkflowService["Service"]>),
888 ),
889 );
890​
891 return Effect.gen(function* () {
892 const fileSystem = yield* FileSystem.FileSystem;
893 const path = yield* Path.Path;
894 const realDir = yield* fileSystem.makeTempDirectoryScoped({
895 prefix: "t3-vcs-status-real-",
896 });
897 const linkParent = yield* fileSystem.makeTempDirectoryScoped({
898 prefix: "t3-vcs-status-link-",
899 });
900 const linkDir = path.join(linkParent, "repo-link");
901 yield* fileSystem.symlink(realDir, linkDir);
902 const realPath = yield* fileSystem.realPath(realDir);
903​
904 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
905 yield* broadcaster.getStatus({ cwd: linkDir });
906 yield* broadcaster.getStatus({ cwd: realDir });
907​
908 assert.deepStrictEqual(seenCwds, [realPath, realPath]);
909 assert.equal(state.localStatusCalls, 1);
910 assert.equal(state.remoteStatusCalls, 1);
911 }).pipe(Effect.provide(layerTest));
912 },
913 );
914​
915 it.effect("a remote poll refreshes Changes totals when divergence counts stay the same", () => {
916 const state: Parameters<typeof layerTestFor>[0] = {
917 currentLocalStatus: {
918 ...baseLocalStatus,
919 branchChanges: { baseRef: "origin/main", insertions: 745, deletions: 24 },
920 },
921 currentRemoteStatus: baseRemoteStatus,
922 localStatusCalls: 0,
923 remoteStatusCalls: 0,
924 localInvalidationCalls: 0,
925 remoteInvalidationCalls: 0,
926 };
927​
928 return Effect.gen(function* () {
929 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
930 yield* broadcaster.getStatus({ cwd: "/repo" });
931 const subscribed = yield* Deferred.make<void>();
932 const polled = yield* Deferred.make<void>();
933 yield* broadcaster.streamStatus({ cwd: "/repo" }).pipe(
934 Stream.runForEach((event) => {
935 if (event._tag === "snapshot") return Deferred.succeed(subscribed, undefined);
936 if (event._tag === "remoteUpdated") return Deferred.succeed(polled, undefined);
937 return Effect.void;
938 }),
939 Effect.forkScoped,
940 );
941 yield* Deferred.await(subscribed);
942 state.currentLocalStatus = {
943 ...baseLocalStatus,
944 branchChanges: { baseRef: "origin/main", insertions: 107, deletions: 4 },
945 };
946 state.currentRemoteStatus = remoteStatusWithPr;
947 yield* TestClock.adjust("30 seconds");
948 yield* Deferred.await(polled);
949 const status = yield* broadcaster.getStatus({ cwd: "/repo" });
950 assert.deepStrictEqual(status.branchChanges, state.currentLocalStatus.branchChanges);
951 }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
952 });
953​
954 it.effect("an explicit refresh reads local totals after the fetch", () => {
955 return Effect.gen(function* () {
956 const fetchStarted = yield* Deferred.make<void>();
957 const finishFetch = yield* Deferred.make<void>();
958 let local: VcsStatusLocalResult = {
959 ...baseLocalStatus,
960 branchChanges: { baseRef: "origin/main", insertions: 745, deletions: 24 },
961 };
962 let cachedLocal: VcsStatusLocalResult | undefined;
963 const readLocalStatus = () => Effect.sync(() => (cachedLocal ??= local));
964 const layerTest = VcsStatusBroadcaster.layer.pipe(
965 Layer.provideMerge(NodeServices.layer),
966 Layer.provide(layerBackgroundPolicy(() => true)),
967 Layer.provide(
968 Layer.mock(GitWorkflowService.GitWorkflowService)({
969 localStatus: readLocalStatus,
970 invalidateStatus: () =>
971 Effect.sync(() => {
972 cachedLocal = undefined;
973 }),
974 invalidateLocalStatus: () =>
975 Effect.sync(() => {
976 cachedLocal = undefined;
977 }),
978 currentBranch: () => Effect.succeed(baseLocalStatus.refName),
979 invalidateRemoteStatus: () => Effect.void,
980 remoteStatus: () =>
981 Deferred.succeed(fetchStarted, undefined).pipe(
982 Effect.andThen(Deferred.await(finishFetch)),
983 Effect.as(baseRemoteStatus),
984 ),
985 }),
986 ),
987 );
988 yield* Effect.gen(function* () {
989 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
990 const refresh = yield* broadcaster.refreshStatus("/repo").pipe(Effect.forkScoped);
991 yield* Deferred.await(fetchStarted);
992 // Another reader can refill the local cache while fetch is still running.
993 yield* readLocalStatus();
994 local = {
995 ...baseLocalStatus,
996 branchChanges: { baseRef: "origin/main", insertions: 0, deletions: 0 },
997 };
998 yield* Deferred.succeed(finishFetch, undefined);
999 const status = yield* Fiber.join(refresh);
1000 assert.deepStrictEqual(status.branchChanges, local.branchChanges);
1001 }).pipe(Effect.provide(layerTest));
1002 });
1003 });
1004​
1005 it.effect("publishes local status while an earlier lookup holds the remote lock", () => {
1006 const state: Parameters<typeof layerTestFor>[0] = {
1007 currentLocalStatus: baseLocalStatus,
1008 currentRemoteStatus: baseRemoteStatus,
1009 localStatusCalls: 0,
1010 remoteStatusCalls: 0,
1011 localInvalidationCalls: 0,
1012 remoteInvalidationCalls: 0,
1013 };
1014​
1015 return Effect.gen(function* () {
1016 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
1017 yield* broadcaster.getStatus({ cwd: "/repo" });
1018 const subscribed = yield* Deferred.make<void>();
1019 const published = yield* Deferred.make<VcsStatusLocalResult>();
1020 yield* broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }).pipe(
1021 Stream.runForEach((event) => {
1022 if (event._tag === "snapshot") return Deferred.succeed(subscribed, undefined);
1023 if (event._tag === "localUpdated") return Deferred.succeed(published, event.local);
1024 return Effect.void;
1025 }),
1026 Effect.forkScoped,
1027 );
1028 yield* Deferred.await(subscribed);
1029 const started = yield* Deferred.make<void>();
1030 const release = yield* Deferred.make<void>();
1031 state.beforeRemoteStatus = Deferred.succeed(started, undefined).pipe(
1032 Effect.andThen(Deferred.await(release)),
1033 );
1034 const earlier = yield* broadcaster.refreshPullRequestStatus("/repo").pipe(Effect.forkScoped);
1035 yield* Deferred.await(started);
1036 state.currentLocalStatus = { ...baseLocalStatus, hasWorkingTreeChanges: true };
1037 const completed = yield* Deferred.make<void>();
1038 const refresh = yield* broadcaster
1039 .refreshStatus("/repo")
1040 .pipe(Effect.ensuring(Deferred.succeed(completed, undefined)), Effect.forkScoped);
1041​
1042 assert.deepStrictEqual(yield* Deferred.await(published), state.currentLocalStatus);
1043 assert.isFalse(yield* Deferred.isDone(completed));
1044 assert.isFalse(yield* Deferred.isDone(release));
1045 state.currentRemoteStatus = remoteStatusWithPr;
1046 yield* Deferred.succeed(release, undefined);
1047 yield* Fiber.join(earlier);
1048 const status = yield* Fiber.join(refresh);
1049 assert.isTrue(status.hasWorkingTreeChanges);
1050 assert.deepStrictEqual(status.pr, remoteStatusWithPr.pr);
1051 }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
1052 });
1053​
1054 it.effect("publishes local changes before a remote error and propagates that error", () => {
1055 const remoteError = new GitManagerError({
1056 operation: "VcsStatusBroadcaster.remoteStatus",
1057 cwd: "/repo",
1058 detail: "The controlled remote lookup failed.",
1059 });
1060 const state: Parameters<typeof layerTestFor>[0] = {
1061 currentLocalStatus: baseLocalStatus,
1062 currentRemoteStatus: remoteStatusWithPr,
1063 localStatusCalls: 0,
1064 remoteStatusCalls: 0,
1065 localInvalidationCalls: 0,
1066 remoteInvalidationCalls: 0,
1067 };
1068​
1069 return Effect.gen(function* () {
1070 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
1071 yield* broadcaster.getStatus({ cwd: "/repo" });
1072 const subscribed = yield* Deferred.make<void>();
1073 const published = yield* Deferred.make<VcsStatusLocalResult>();
1074 yield* broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }).pipe(
1075 Stream.runForEach((event) => {
1076 if (event._tag === "snapshot") return Deferred.succeed(subscribed, undefined);
1077 if (event._tag === "localUpdated") return Deferred.succeed(published, event.local);
1078 return Effect.void;
1079 }),
1080 Effect.forkScoped,
1081 );
1082 yield* Deferred.await(subscribed);
1083 const started = yield* Deferred.make<void>();
1084 const release = yield* Deferred.make<void>();
1085 const completed = yield* Deferred.make<void>();
1086 state.beforeRemoteStatus = Deferred.succeed(started, undefined).pipe(
1087 Effect.andThen(Deferred.await(release)),
1088 );
1089 state.currentLocalStatus = { ...baseLocalStatus, hasWorkingTreeChanges: true };
1090 state.remoteStatusError = remoteError;
1091 const refresh = yield* broadcaster
1092 .refreshStatus("/repo")
1093 .pipe(
1094 Effect.result,
1095 Effect.ensuring(Deferred.succeed(completed, undefined)),
1096 Effect.forkScoped,
1097 );
1098 yield* Deferred.await(started);
1099 assert.isFalse(yield* Deferred.isDone(completed));
1100 const pending = Option.getOrThrow(
1101 yield* Stream.runHead(broadcaster.streamStatus({ cwd: "/repo", includeRemote: false })),
1102 );
1103 assert.equal(pending._tag, "snapshot");
1104 if (pending._tag === "snapshot") assert.isTrue(pending.local.hasWorkingTreeChanges);
1105 yield* Deferred.succeed(release, undefined);
1106 const result = yield* Fiber.join(refresh);
1107 assert.equal(result._tag, "Failure");
1108 if (result._tag === "Failure") assert.strictEqual(result.failure, remoteError);
1109 const cached = yield* broadcaster.getStatus({ cwd: "/repo" });
1110 assert.isTrue(cached.hasWorkingTreeChanges);
1111 assert.deepStrictEqual(cached.pr, remoteStatusWithPr.pr);
1112 assert.deepStrictEqual(yield* Deferred.await(published), state.currentLocalStatus);
1113 }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
1114 });
1115​
1116 it.effect.each(["getStatus", "refreshStatus", "autoPull", "autoPullFailure"] as const)(
1117 "%s keeps response parts consistent when local state changes after the remote cache write",
1118 (operation) => {
1119 const state: Parameters<typeof layerTestFor>[0] = {
1120 currentLocalStatus: baseLocalStatus,
1121 currentRemoteStatus: { ...remoteStatusWithPr, aheadCount: 3, behindCount: 5 },
1122 localStatusCalls: 0,
1123 remoteStatusCalls: 0,
1124 localInvalidationCalls: 0,
1125 remoteInvalidationCalls: 0,
1126 fileSystem: FileSystem.makeNoop({ realPath: (cwd) => Effect.succeed(cwd) }),
1127 };
1128 const autoPull = operation === "autoPull" || operation === "autoPullFailure";
1129 if (autoPull) {
1130 state.currentLocalStatus = { ...baseLocalStatus, isDefaultRef: true };
1131 state.currentRemoteStatus = { ...remoteStatusWithPr, aheadCount: 0, behindCount: 5 };
1132 state.pullCurrentBranch = () =>
1133 operation === "autoPullFailure"
1134 ? Effect.fail(
1135 new GitCommandError({
1136 operation: "test.pull",
1137 command: "pull",
1138 cwd: "/repo",
1139 detail: "Pull failed.",
1140 }),
1142 : Effect.succeed({
1143 status: "pulled",
1144 refName: "feature/status-broadcast",
1145 upstreamRef: "origin/main",
1146 });
1148 const layerTest = layerTestFor(state).pipe(
1149 Layer.provide(
1150 Layer.succeed(VcsStatusBroadcaster.VcsAutoPullPolicy, {
1151 isEnabled: () => Effect.succeed(autoPull),
1152 }),
1153 ),
1154 );
1155 return Effect.gen(function* () {
1156 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
1157 let switched = false;
1158 let remoteWritten = false;
1159 const writeCompleted = yield* Deferred.make<void>();
1160 const localRefresh = yield* Effect.gen(function* () {
1161 yield* Deferred.await(writeCompleted);
1162 state.currentLocalStatus = { ...baseLocalStatus, refName: "feature/next-status" };
1163 yield* broadcaster.refreshLocalStatus("/repo");
1164 switched = true;
1165 }).pipe(Effect.forkScoped);
1166 const scheduler = new Scheduler.MixedScheduler();
1167 const shouldYield = scheduler.shouldYield.bind(scheduler);
1168 scheduler.shouldYield = (fiber) => (remoteWritten && !switched) || shouldYield(fiber);
1169 const tracer = Tracer.make({
1170 span: (options) => {
1171 const span = new Tracer.NativeSpan(options);
1172 const end = span.end.bind(span);
1173 span.end = (time, exit) => {
1174 end(time, exit);
1175 if (
1176 options.name !== "VcsStatusBroadcaster.updateCachedRemoteStatus" ||
1177 remoteWritten
1178 ) {
1179 return;
1181 // Yield this reader after its write until the local refresh finishes.
1182 remoteWritten = true;
1183 Deferred.doneUnsafe(writeCompleted, Effect.void);
1184 };
1185 return span;
1186 },
1187 });
1188 const status = yield* (
1189 operation === "getStatus"
1190 ? broadcaster.getStatus({ cwd: "/repo" })
1191 : broadcaster.refreshStatus("/repo")
1192 ).pipe(Effect.withTracer(tracer), Effect.provideService(Scheduler.Scheduler, scheduler));
1193 yield* Fiber.join(localRefresh);
1194 assert.isTrue(switched);
1195 assert.equal(status.refName, "feature/next-status");
1196 assert.isNull(status.pr);
1197 assert.equal(status.aheadCount, 0);
1198 assert.equal(status.behindCount, 0);
1199 }).pipe(Effect.provide(layerTest), Effect.scoped);
1200 },
1201 );
1202​
1203 it.effect("recovers a discarded branch lookup on the next turn-end refresh", () => {
1204 const state: Parameters<typeof layerTestFor>[0] = {
1205 currentLocalStatus: baseLocalStatus,
1206 currentRemoteStatus: { ...remoteStatusWithPr, aheadCount: 3, behindCount: 5 },
1207 localStatusCalls: 0,
1208 remoteStatusCalls: 0,
1209 localInvalidationCalls: 0,
1210 remoteInvalidationCalls: 0,
1211 };
1212​
1213 return Effect.gen(function* () {
1214 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
1215 const started = yield* Deferred.make<void>();
1216 const release = yield* Deferred.make<void>();
1217 state.beforeRemoteStatus = Deferred.succeed(started, undefined).pipe(
1218 Effect.andThen(Deferred.await(release)),
1219 );
1220 const lookup = yield* broadcaster.getStatus({ cwd: "/repo" }).pipe(Effect.forkScoped);
1221 yield* Deferred.await(started);
1222 state.currentLocalStatus = { ...baseLocalStatus, refName: "feature/next-status" };
1223 yield* Deferred.succeed(release, undefined);
1224 const discarded = yield* Fiber.join(lookup);
1225 assert.equal(discarded.refName, state.currentLocalStatus.refName);
1226 assert.isNull(discarded.pr);
1227 assert.equal(discarded.aheadCount, 0);
1228 assert.equal(discarded.behindCount, 0);
1229 const snapshot = Option.getOrThrow(
1230 yield* Stream.runHead(broadcaster.streamStatus({ cwd: "/repo", includeRemote: false })),
1231 );
1232 assert.equal(snapshot._tag, "snapshot");
1233 if (snapshot._tag === "snapshot") assert.isNull(snapshot.remote);
1234​
1235 state.beforeRemoteStatus = Effect.void;
1236 state.currentRemoteStatus = {
1237 ...baseRemoteStatus,
1238 aheadCount: 2,
1239 pr: { ...remoteStatusWithPr.pr!, number: 2979, headRef: "feature/next-status" },
1240 };
1241 state.backgroundWorkEnabled = false;
1242 const recovered = yield* broadcaster.refreshPullRequestStatus("/repo");
1243 assert.deepStrictEqual(recovered, state.currentRemoteStatus);
1244 const cached = yield* broadcaster.getStatus({ cwd: "/repo" });
1245 assert.equal(cached.refName, state.currentLocalStatus.refName);
1246 assert.deepStrictEqual(cached.pr, state.currentRemoteStatus.pr);
1247 assert.equal(cached.aheadCount, 2);
1248 assert.equal(state.remoteStatusCalls, 2);
1249 }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
1250 });
1251​
1252 it.effect("releases remote demand while passive observers remain", () => {
1253 const state = {
1254 currentLocalStatus: baseLocalStatus,
1255 currentRemoteStatus: baseRemoteStatus,
1256 localStatusCalls: 0,
1257 remoteStatusCalls: 0,
1258 localInvalidationCalls: 0,
1259 remoteInvalidationCalls: 0,
1260 };
1261 let remoteInterruptedDeferred: Deferred.Deferred<void, never> | null = null;
1262 let remoteStartedDeferred: Deferred.Deferred<void, never> | null = null;
1263 const layerTest = VcsStatusBroadcaster.layer.pipe(
1264 Layer.provideMerge(NodeServices.layer),
1265 Layer.provide(layerBackgroundPolicy(() => true)),
1266 Layer.provide(
1267 Layer.mock(GitWorkflowService.GitWorkflowService)({
1268 localStatus: () =>
1269 Effect.sync(() => {
1270 state.localStatusCalls += 1;
1271 return state.currentLocalStatus;
1272 }),
1273 currentBranch: () => Effect.succeed(state.currentLocalStatus.refName),
1274 remoteStatus: () =>
1275 Effect.sync(() => {
1276 state.remoteStatusCalls += 1;
1277 }).pipe(
1278 Effect.andThen(
1279 remoteStartedDeferred
1280 ? Deferred.succeed(remoteStartedDeferred, undefined).pipe(Effect.ignore)
1281 : Effect.void,
1282 ),
1283 Effect.andThen(Effect.never as Effect.Effect<VcsStatusRemoteResult | null, never>),
1284 Effect.onInterrupt(() =>
1285 remoteInterruptedDeferred
1286 ? Deferred.succeed(remoteInterruptedDeferred, undefined).pipe(Effect.ignore)
1287 : Effect.void,
1288 ),
1289 ),
1290 invalidateLocalStatus: () =>
1291 Effect.sync(() => {
1292 state.localInvalidationCalls += 1;
1293 }),
1294 invalidateRemoteStatus: () =>
1295 Effect.sync(() => {
1296 state.remoteInvalidationCalls += 1;
1297 }),
1298 } satisfies Partial<GitWorkflowService.GitWorkflowService["Service"]>),
1299 ),
1300 );
1301​
1302 return Effect.gen(function* () {
1303 const remoteInterrupted = yield* Deferred.make<void>();
1304 const remoteStarted = yield* Deferred.make<void>();
1305 remoteInterruptedDeferred = remoteInterrupted;
1306 remoteStartedDeferred = remoteStarted;
1307​
1308 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
1309 const firstSnapshot = yield* Deferred.make<VcsStatusStreamEvent>();
1310 const secondSnapshot = yield* Deferred.make<VcsStatusStreamEvent>();
1311 const firstScope = yield* Scope.make();
1312 const secondScope = yield* Scope.make();
1313 const passiveSnapshot = yield* Deferred.make<VcsStatusStreamEvent>();
1314 yield* Stream.runForEach(
1315 broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }),
1316 (event) =>
1317 event._tag === "snapshot"
1318 ? Deferred.succeed(passiveSnapshot, event).pipe(Effect.ignore)
1319 : Effect.void,
1320 ).pipe(Effect.forkScoped);
1321 yield* Deferred.await(passiveSnapshot);
1322 assert.equal(state.remoteStatusCalls, 0);
1323 yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) =>
1324 event._tag === "snapshot"
1325 ? Deferred.succeed(firstSnapshot, event).pipe(Effect.ignore)
1326 : Effect.void,
1327 ).pipe(Effect.forkIn(firstScope));
1328 yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) =>
1329 event._tag === "snapshot"
1330 ? Deferred.succeed(secondSnapshot, event).pipe(Effect.ignore)
1331 : Effect.void,
1332 ).pipe(Effect.forkIn(secondScope));
1333​
1334 yield* Deferred.await(firstSnapshot);
1335 yield* Deferred.await(secondSnapshot);
1336 yield* Deferred.await(remoteStarted);
1337​
1338 assert.equal(state.remoteStatusCalls, 1);
1339​
1340 yield* Scope.close(firstScope, Exit.void);
1341 assert.isTrue(Option.isNone(yield* Deferred.poll(remoteInterrupted)));
1342​
1343 yield* Scope.close(secondScope, Exit.void).pipe(Effect.forkScoped);
1344 yield* Deferred.await(remoteInterrupted);
1345 assert.isTrue(Option.isSome(yield* Deferred.poll(remoteInterrupted)));
1346 }).pipe(Effect.provide(layerTest));
1347 });
1348});
1349​
1350const newState = (): Parameters<typeof layerTestFor>[0] => ({
1351 fileSystem: FileSystem.makeNoop({ realPath: (cwd) => Effect.succeed(cwd) }),
1352 currentLocalStatus: baseLocalStatus,
1353 currentRemoteStatus: null,
1354 localStatusCalls: 0,
1355 remoteStatusCalls: 0,
1356 localInvalidationCalls: 0,
1357 remoteInvalidationCalls: 0,
1358});
1359it.effect("detail join during invalidation must get fresh totals", () => {
1360 const state = newState();
1361 return Effect.gen(function* () {
1362 const b = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
1363 const oldScope = yield* Scope.make();
1364 const old = yield* Stream.toPull(b.streamStatus({ cwd: "/repo", includeRemote: false })).pipe(
1365 Scope.provide(oldScope),
1366 );
1367 yield* old;
1368 yield* Scope.close(oldScope, Exit.void);
1369 state.currentLocalStatus = {
1370 ...baseLocalStatus,
1371 workingTree: { files: [], insertions: 42, deletions: 0 },
1372 };
1373 const entered = yield* Deferred.make<void>();
1374 const resume = yield* Deferred.make<void>();
1375 state.beforeInvalidate = Deferred.succeed(entered, undefined).pipe(
1376 Effect.andThen(Deferred.await(resume)),
1377 );
1378 const refresh = yield* b.refreshBranchStatus({ cwd: "/repo" }).pipe(Effect.forkScoped);
1379 yield* Deferred.await(entered);
1380 const snapshotFiber = yield* Stream.runHead(
1381 b.streamStatus({ cwd: "/repo", includeRemote: false }),
1382 ).pipe(Effect.forkScoped({ startImmediately: true }));
1383 yield* Deferred.succeed(resume, undefined);
1384 yield* Fiber.join(refresh);
1385 assert.deepEqual(
1386 yield* Fiber.join(snapshotFiber),
1387 Option.some({ _tag: "snapshot" as const, local: state.currentLocalStatus, remote: null }),
1388 );
1389 }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
1390});
1391it.effect("serializes branch reads with detailed refresh publication", () => {
1392 const state = newState();
1393 return Effect.gen(function* () {
1394 const b = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
1395 const entered = yield* Deferred.make<void>();
1396 const resume = yield* Deferred.make<void>();
1397 state.branchRead = () =>
1398 Deferred.succeed(entered, undefined).pipe(
1399 Effect.andThen(Deferred.await(resume)),
1400 Effect.as("old"),
1401 );
1402 const older = yield* b.refreshBranchStatus({ cwd: "/repo" }).pipe(Effect.forkScoped);
1403 yield* Deferred.await(entered);
1404 state.currentLocalStatus = { ...baseLocalStatus, refName: "new" };
1405 const newer = yield* b
1406 .refreshLocalStatus("/repo")
1407 .pipe(Effect.forkScoped({ startImmediately: true }));
1408 yield* Deferred.succeed(resume, undefined);
1409 yield* Fiber.join(older);
1410 yield* Fiber.join(newer);
1411 state.branchRead = () => Effect.succeed("new");
1412 const result = yield* b.getStatus({ cwd: "/repo" });
1413 assert.equal(result.refName, "new");
1414 assert.equal(state.localStatusCalls, 1);
1415 }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
1416});
1417​
1418it.effect("publishes overlapping branch reads in checkout order", () => {
1419 const state = newState();
1420 return Effect.gen(function* () {
1421 const b = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
1422 const branches = yield* Stream.toPull(b.streamBranchStatus({ cwd: "/repo" }));
1423 yield* branches;
1424 const entered = yield* Deferred.make<void>();
1425 const resume = yield* Deferred.make<void>();
1426 let reads = 0;
1427 state.branchRead = () =>
1428 ++reads === 1
1429 ? Deferred.succeed(entered, undefined).pipe(
1430 Effect.andThen(Deferred.await(resume)),
1431 Effect.as("old"),
1433 : Effect.succeed("new");
1434 const older = yield* b.refreshBranchStatus({ cwd: "/repo" }).pipe(Effect.forkScoped);
1435 yield* Deferred.await(entered);
1436 const newer = yield* b
1437 .refreshBranchStatus({ cwd: "/repo" })
1438 .pipe(Effect.forkScoped({ startImmediately: true }));
1439 yield* Deferred.succeed(resume, undefined);
1440 yield* Fiber.join(older);
1441 yield* Fiber.join(newer);
1442 assert.deepEqual(yield* branches, [{ refName: "old" }, { refName: "new" }]);
1443 }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
1444});
1445​
1446it.effect("does not replay older queued branches after a new subscriber snapshot", () => {
1447 const state = newState();
1448 return Effect.gen(function* () {
1449 const b = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
1450 const entered = yield* Deferred.make<void>();
1451 const resume = yield* Deferred.make<void>();
1452 const values = yield* Queue.unbounded<{ readonly refName: string | null }>();
1453 let reads = 0;
1454 state.branchRead = () =>
1455 ++reads === 1
1456 ? Deferred.succeed(entered, undefined).pipe(
1457 Effect.andThen(Deferred.await(resume)),
1458 Effect.as("old"),
1460 : Effect.succeed("new");
1461 const older = yield* b.refreshBranchStatus({ cwd: "/repo" }).pipe(Effect.forkScoped);
1462 yield* Deferred.await(entered);
1463 const subscriber = yield* b.streamBranchStatus({ cwd: "/repo" }).pipe(
1464 Stream.tap((value) => Queue.offer(values, value)),
1465 Stream.take(2),
1466 Stream.runDrain,
1467 Effect.forkScoped({ startImmediately: true }),
1468 );
1469 yield* Deferred.succeed(resume, undefined);
1470 yield* Fiber.join(older);
1471 assert.deepEqual(yield* Queue.take(values), { refName: "new" });
1472 state.branchRead = () => Effect.succeed("latest");
1473 yield* b.refreshBranchStatus({ cwd: "/repo" });
1474 assert.deepEqual(yield* Queue.take(values), { refName: "latest" });
1475 yield* Fiber.join(subscriber);
1476 }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
1477});