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 Cause from "effect/Cause";
5import * as Deferred from "effect/Deferred";
6import * as DateTime from "effect/DateTime";
7import * as Duration from "effect/Duration";
8import * as Effect from "effect/Effect";
9import * as Fiber from "effect/Fiber";
10import * as Exit from "effect/Exit";
11import * as FileSystem from "effect/FileSystem";
12import * as Layer from "effect/Layer";
13import * as Logger from "effect/Logger";
14import * as Option from "effect/Option";
15import * as Path from "effect/Path";
16import * as Scope from "effect/Scope";
17import * as Stream from "effect/Stream";
18import * as TestClock from "effect/testing/TestClock";
19import type {
20 BackgroundScope,
21 VcsStatusLocalResult,
22 VcsStatusRemoteResult,
23 VcsStatusResult,
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: "codex/connection-state-audit",
64 state: "open",
65 },
66};
67
68const baseStatus: VcsStatusResult = {
69 ...baseLocalStatus,
70 ...baseRemoteStatus,
71};
72
73function layerTestFor(state: {
74 currentLocalStatus: VcsStatusLocalResult;
75 currentRemoteStatus: VcsStatusRemoteResult | null;
76 localStatusCalls: number;
77 remoteStatusCalls: number;
78 localInvalidationCalls: number;
79 remoteInvalidationCalls: number;
80 remoteStatusRefreshUpstreamValues?: Array<boolean | undefined>;
81 backgroundWorkEnabled?: boolean;
82 beforeRemoteStatus?: Effect.Effect<void>;
83}) {
84 return VcsStatusBroadcaster.layer.pipe(
85 Layer.provideMerge(NodeServices.layer),
86 Layer.provide(layerBackgroundPolicy(() => state.backgroundWorkEnabled !== false)),
87 Layer.provide(
88 Layer.mock(GitWorkflowService.GitWorkflowService)({
89 localStatus: () =>
90 Effect.sync(() => {
91 state.localStatusCalls += 1;
92 return state.currentLocalStatus;
93 }),
94 remoteStatus: (_input, options) =>
95 Effect.suspend(() => state.beforeRemoteStatus ?? Effect.void).pipe(
96 Effect.andThen(
97 Effect.sync(() => {
98 state.remoteStatusCalls += 1;
99 state.remoteStatusRefreshUpstreamValues?.push(options?.refreshUpstream);
100 return state.currentRemoteStatus;
101 }),
102 ),
103 ),
104 invalidateLocalStatus: () =>
105 Effect.sync(() => {
106 state.localInvalidationCalls += 1;
107 }),
108 invalidateRemoteStatus: () =>
109 Effect.sync(() => {
110 state.remoteInvalidationCalls += 1;
111 }),
112 invalidateStatus: () =>
113 Effect.sync(() => {
114 state.localInvalidationCalls += 1;
115 state.remoteInvalidationCalls += 1;
116 }),
117 }),
118 ),
119 );
120}
121
122function layerBackgroundPolicy(shouldRunScopeWork: (scope: BackgroundScope) => boolean) {
123 return Layer.mock(BackgroundPolicy.BackgroundPolicy)({
124 reportClientActivity: () => Effect.void,
125 removeRpcClient: () => Effect.void,
126 reportHostPowerState: () => Effect.void,
127 snapshot: Effect.succeed({
128 hostPower: {
129 source: "unknown",
130 idle: "unknown",
131 idleSeconds: null,
132 locked: "unknown",
133 suspended: false,
134 onBattery: "unknown",
135 lowPowerMode: "unknown",
136 thermalState: "unknown",
137 stale: true,
138 updatedAt: TEST_EPOCH,
139 },
140 leases: [],
141 activeForegroundLeaseCount: 0,
142 activeScopeKeys: [],
143 shouldRunOpportunisticWork: false,
144 updatedAt: TEST_EPOCH,
145 }),
146 streamChanges: Stream.empty,
147 hasDemand: () => Effect.succeed(true),
148 shouldRunScopeWork: (scope) => Effect.sync(() => shouldRunScopeWork(scope)),
149 shouldRunOpportunisticWork: Effect.succeed(true),
150 });
151}
152
153describe("VcsStatusBroadcaster", () => {
154 it.effect.skipIf(!symlinksSupported)(
155 "automatically pulls an enabled clean default branch when status detects it is behind",
156 () => {
157 let remoteStatus: VcsStatusRemoteResult = { ...baseRemoteStatus, behindCount: 2 };
158 let pullCalls = 0;
159 let configuredWorkspaceRoot = "";
160 const localStatus: VcsStatusLocalResult = {
161 ...baseLocalStatus,
162 isDefaultRef: true,
163 refName: "main",
164 };
165 const layerTest = VcsStatusBroadcaster.layer.pipe(
166 Layer.provideMerge(NodeServices.layer),
167 Layer.provide(layerBackgroundPolicy(() => true)),
168 Layer.provide(
169 Layer.succeed(VcsStatusBroadcaster.VcsAutoPullPolicy, {
170 isEnabled: (cwd) => Effect.succeed(cwd === configuredWorkspaceRoot),
171 }),
172 ),
173 Layer.provide(
174 Layer.mock(GitWorkflowService.GitWorkflowService)({
175 localStatus: () => Effect.succeed(localStatus),
176 remoteStatus: () => Effect.succeed(remoteStatus),
177 invalidateLocalStatus: () => Effect.void,
178 invalidateRemoteStatus: () => Effect.void,
179 invalidateStatus: () => Effect.void,
180 pullCurrentBranch: () =>
181 Effect.sync(() => {
182 pullCalls += 1;
183 remoteStatus = { ...remoteStatus, behindCount: 0 };
184 return {
185 status: "pulled" as const,
186 refName: "main",
187 upstreamRef: "origin/main",
188 };
189 }),
190 }),
191 ),
192 );
193
194 return Effect.gen(function* () {
195 const fileSystem = yield* FileSystem.FileSystem;
196 const path = yield* Path.Path;
197 const realDir = yield* fileSystem.makeTempDirectoryScoped({
198 prefix: "t3-vcs-auto-pull-real-",
199 });
200 const linkParent = yield* fileSystem.makeTempDirectoryScoped({
201 prefix: "t3-vcs-auto-pull-link-",
202 });
203 configuredWorkspaceRoot = path.join(linkParent, "repo-link");
204 yield* fileSystem.symlink(realDir, configuredWorkspaceRoot);
205
206 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
207 const status = yield* broadcaster.refreshStatus(configuredWorkspaceRoot);
208
209 assert.equal(pullCalls, 1);
210 assert.equal(status.behindCount, 0);
211 }).pipe(Effect.provide(layerTest));
212 },
213 );
214
215 it.effect.each([
216 { refresh: "explicit", failure: "pull" },
217 { refresh: "explicit", failure: "post-pull remote read" },
218 { refresh: "explicit", failure: "recovery scan" },
219 { refresh: "background", failure: "pull" },
220 { refresh: "background", failure: "post-pull remote read" },
221 { refresh: "background", failure: "recovery scan" },
222 ] as const)(
223 "$refresh refresh reconciles local status after failure at $failure",
224 ({ refresh, failure }) => {
225 let local = { ...baseLocalStatus, isDefaultRef: true, refName: "main" };
226 const afterPull = { ...local, hasWorkingTreeChanges: true };
227 let pullCalls = 0;
228 let seeded = false;
229 const subscribed = Deferred.makeUnsafe<void>();
230 const outcome = Deferred.makeUnsafe<"updated" | "failed">();
231 const recoveryError = new GitManagerError({
232 operation: "test",
233 cwd: "/repo",
234 detail: "recovery scan failed",
235 });
236 const logger = Logger.make(({ message }) => {
237 if (Array.isArray(message) && message[0] === "VCS remote status refresh failed") {
238 Deferred.doneUnsafe(outcome, Effect.succeed("failed"));
239 }
240 });
241 const layerTest = VcsStatusBroadcaster.layer.pipe(
242 Layer.provideMerge(NodeServices.layer),
243 Layer.provide(layerBackgroundPolicy(() => true)),
244 Layer.provide(
245 Layer.succeed(VcsStatusBroadcaster.VcsAutoPullPolicy, {
246 isEnabled: () => Effect.succeed(true),
247 }),
248 ),
249 Layer.provide(
250 Layer.mock(GitWorkflowService.GitWorkflowService)({
251 localStatus: () =>
252 Effect.suspend(() =>
253 failure === "recovery scan" && pullCalls > 0
254 ? Effect.fail(recoveryError)
255 : Effect.succeed(local),
256 ),
257 remoteStatus: () =>
258 Effect.suspend(() =>
259 failure === "post-pull remote read" && pullCalls > 0
260 ? Effect.fail(
261 new GitManagerError({
262 operation: "test",
263 cwd: "/repo",
264 detail: "post-pull read failed",
265 }),
266 )
267 : Effect.succeed({
268 ...baseRemoteStatus,
269 behindCount: 2,
270 pr: seeded ? remoteStatusWithPr.pr : null,
271 }),
272 ),
273 invalidateLocalStatus: () => Effect.void,
274 invalidateRemoteStatus: () => Effect.void,
275 invalidateStatus: () => Effect.void,
276 pullCurrentBranch: () =>
277 Effect.suspend(() => {
278 pullCalls += 1;
279 local = afterPull;
280 return failure !== "post-pull remote read"
281 ? Effect.fail(
282 new GitCommandError({
283 operation: "test",
284 command: "pull",
285 cwd: "/repo",
286 detail: "pull failed",
287 }),
288 )
289 : Effect.succeed({
290 status: "pulled" as const,
291 refName: "main",
292 upstreamRef: "origin/main",
293 });
294 }),
295 }),
296 ),
297 );
298 return Effect.gen(function* () {
299 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
300 // Seed the same divergence so background recovery cannot rely on a moved remote ref.
301 yield* broadcaster.getStatus({ cwd: "/repo" });
302 seeded = true;
303 if (refresh === "explicit") {
304 const result = yield* Effect.result(broadcaster.refreshStatus("/repo"));
305 if (failure === "recovery scan") {
306 assert.isTrue(result._tag === "Failure");
307 if (result._tag === "Failure") assert.strictEqual(result.failure, recoveryError);
308 return;
309 }
310 assert.isTrue(result._tag === "Success");
311 if (result._tag === "Success") assert.isTrue(result.success.hasWorkingTreeChanges);
312 } else {
313 yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) => {
314 if (event._tag === "snapshot" && !event.local.hasWorkingTreeChanges) {
315 return Deferred.succeed(subscribed, undefined).pipe(Effect.asVoid);
316 }
317 return Deferred.succeed(outcome, "updated").pipe(Effect.asVoid);
318 }).pipe(Effect.forkScoped);
319 yield* Deferred.await(subscribed);
320 yield* TestClock.adjust(Duration.seconds(30));
321 assert.equal(
322 yield* Deferred.await(outcome),
323 failure === "recovery scan" ? "failed" : "updated",
324 );
325 }
326 assert.equal(pullCalls, 1);
327 if (failure !== "recovery scan") {
328 assert.isTrue((yield* broadcaster.getStatus({ cwd: "/repo" })).hasWorkingTreeChanges);
329 }
330 }).pipe(
331 Effect.scoped,
332 Effect.provide(
333 Layer.mergeAll(
334 layerTest,
335 TestClock.layer(),
336 Logger.layer([logger], { mergeWithExisting: true }),
337 ),
338 ),
339 );
340 },
341 );
342
343 it.effect("reuses the cached VCS status across repeated reads", () => {
344 const state = {
345 currentLocalStatus: baseLocalStatus,
346 currentRemoteStatus: baseRemoteStatus,
347 localStatusCalls: 0,
348 remoteStatusCalls: 0,
349 localInvalidationCalls: 0,
350 remoteInvalidationCalls: 0,
351 };
352
353 return Effect.gen(function* () {
354 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
355
356 const first = yield* broadcaster.getStatus({ cwd: "/repo" });
357 const second = yield* broadcaster.getStatus({ cwd: "/repo" });
358
359 assert.deepStrictEqual(first, baseStatus);
360 assert.deepStrictEqual(second, baseStatus);
361 assert.equal(state.localStatusCalls, 1);
362 assert.equal(state.remoteStatusCalls, 1);
363 assert.equal(state.localInvalidationCalls, 0);
364 assert.equal(state.remoteInvalidationCalls, 0);
365 }).pipe(Effect.provide(layerTestFor(state)));
366 });
367
368 it.effect("refreshes a loaded cwd without reusing a previous branch's PR", () => {
369 const state = {
370 currentLocalStatus: baseLocalStatus,
371 currentRemoteStatus: baseRemoteStatus,
372 localStatusCalls: 0,
373 remoteStatusCalls: 0,
374 localInvalidationCalls: 0,
375 remoteInvalidationCalls: 0,
376 };
377
378 return Effect.gen(function* () {
379 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
380
381 assert.isNull(yield* broadcaster.refreshPullRequestStatus("/repo"));
382 assert.equal(state.remoteStatusCalls, 0);
383
384 yield* broadcaster.getStatus({ cwd: "/repo" });
385 assert.equal(state.remoteStatusCalls, 1);
386
387 state.currentRemoteStatus = remoteStatusWithPr;
388 const refreshed = yield* broadcaster.refreshPullRequestStatus("/repo");
389 assert.deepStrictEqual(refreshed, remoteStatusWithPr);
390 assert.equal(state.remoteStatusCalls, 2);
391 assert.equal(state.remoteInvalidationCalls, 0);
392
393 state.currentLocalStatus = { ...baseLocalStatus, refName: "feature/next" };
394 state.currentRemoteStatus = baseRemoteStatus;
395 yield* broadcaster.refreshLocalStatus("/repo");
396 const refreshedBranch = yield* broadcaster.refreshPullRequestStatus("/repo");
397 assert.deepStrictEqual(refreshedBranch, baseRemoteStatus);
398 assert.equal(state.remoteStatusCalls, 3);
399 }).pipe(Effect.provide(layerTestFor(state)));
400 });
401
402 it.effect("a poll that started before the turn-end refresh cannot overwrite its PR", () => {
403 const releaseFirstPoll = Deferred.makeUnsafe<void>();
404 const firstPollStarted = Deferred.makeUnsafe<void>();
405 let remoteReads = 0;
406 const layer = VcsStatusBroadcaster.layer.pipe(
407 Layer.provideMerge(NodeServices.layer),
408 Layer.provide(layerBackgroundPolicy(() => true)),
409 Layer.provide(
410 Layer.mock(GitWorkflowService.GitWorkflowService)({
411 localStatus: () => Effect.succeed(baseLocalStatus),
412 remoteStatus: () =>
413 Effect.gen(function* () {
414 remoteReads += 1;
415 if (remoteReads === 2) {
416 yield* Deferred.succeed(firstPollStarted, undefined);
417 yield* Deferred.await(releaseFirstPoll);
418 return baseRemoteStatus;
419 }
420 return remoteReads === 1 ? baseRemoteStatus : remoteStatusWithPr;
421 }),
422 invalidateLocalStatus: () => Effect.void,
423 invalidateRemoteStatus: () => Effect.void,
424 invalidateStatus: () => Effect.void,
425 }),
426 ),
427 );
428
429 return Effect.gen(function* () {
430 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
431 yield* broadcaster.getStatus({ cwd: "/repo" });
432
433 const poll = yield* broadcaster.refreshStatus("/repo").pipe(Effect.forkScoped);
434 yield* Deferred.await(firstPollStarted);
435 const refresh = yield* broadcaster.refreshPullRequestStatus("/repo").pipe(Effect.forkScoped);
436 yield* Deferred.succeed(releaseFirstPoll, undefined);
437 yield* Fiber.join(poll);
438 const refreshed = yield* Fiber.join(refresh);
439
440 assert.deepStrictEqual(refreshed, remoteStatusWithPr);
441 const final = yield* broadcaster.getStatus({ cwd: "/repo" });
442 assert.deepStrictEqual(final.pr, remoteStatusWithPr.pr);
443 }).pipe(Effect.provide(layer), Effect.scoped);
444 });
445
446 it.effect("an initial status read cannot overwrite an explicit refresh", () => {
447 const firstReadStarted = Deferred.makeUnsafe<void>();
448 const releaseFirstRead = Deferred.makeUnsafe<void>();
449 let remoteReads = 0;
450 const layer = VcsStatusBroadcaster.layer.pipe(
451 Layer.provide(FileSystem.layerNoop({ realPath: (path) => Effect.succeed(path) })),
452 Layer.provideMerge(NodeServices.layer),
453 Layer.provide(layerBackgroundPolicy(() => true)),
454 Layer.provide(
455 Layer.mock(GitWorkflowService.GitWorkflowService)({
456 localStatus: () => Effect.succeed(baseLocalStatus),
457 remoteStatus: () =>
458 Effect.gen(function* () {
459 remoteReads += 1;
460 if (remoteReads === 1) {
461 yield* Deferred.succeed(firstReadStarted, undefined);
462 yield* Deferred.await(releaseFirstRead);
463 return baseRemoteStatus;
464 }
465 return remoteStatusWithPr;
466 }),
467 invalidateStatus: () => Effect.void,
468 }),
469 ),
470 );
471 return Effect.gen(function* () {
472 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
473 const initial = yield* broadcaster.getStatus({ cwd: "/repo" }).pipe(Effect.forkScoped);
474 yield* Deferred.await(firstReadStarted);
475 const refresh = yield* broadcaster.refreshStatus("/repo").pipe(Effect.forkScoped);
476 yield* TestClock.adjust(Duration.zero);
477 yield* Deferred.succeed(releaseFirstRead, undefined);
478 yield* Fiber.join(initial);
479 yield* Fiber.join(refresh);
480 assert.deepStrictEqual(
481 (yield* broadcaster.getStatus({ cwd: "/repo" })).pr,
482 remoteStatusWithPr.pr,
483 );
484 }).pipe(Effect.provide(layer), Effect.scoped);
485 });
486
487 it.effect("turn-end refresh skips a loaded cwd when background policy pauses it", () => {
488 const state = {
489 currentLocalStatus: baseLocalStatus,
490 currentRemoteStatus: baseRemoteStatus,
491 localStatusCalls: 0,
492 remoteStatusCalls: 0,
493 localInvalidationCalls: 0,
494 remoteInvalidationCalls: 0,
495 backgroundWorkEnabled: false,
496 };
497 return Effect.gen(function* () {
498 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
499 yield* broadcaster.getStatus({ cwd: "/repo" });
500 yield* broadcaster.refreshPullRequestStatus("/repo");
501 assert.equal(state.remoteStatusCalls, 1);
502 assert.equal(state.remoteInvalidationCalls, 0);
503 }).pipe(Effect.provide(layerTestFor(state)));
504 });
505
506 it.effect("refreshes the cached snapshot after explicit invalidation", () => {
507 const state = {
508 currentLocalStatus: baseLocalStatus,
509 currentRemoteStatus: baseRemoteStatus,
510 localStatusCalls: 0,
511 remoteStatusCalls: 0,
512 localInvalidationCalls: 0,
513 remoteInvalidationCalls: 0,
514 };
515
516 return Effect.gen(function* () {
517 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
518 const initial = yield* broadcaster.getStatus({ cwd: "/repo" });
519
520 state.currentLocalStatus = {
521 ...baseLocalStatus,
522 refName: "feature/updated-status",
523 };
524 state.currentRemoteStatus = {
525 ...baseRemoteStatus,
526 aheadCount: 2,
527 };
528 const refreshed = yield* broadcaster.refreshStatus("/repo");
529 const cached = yield* broadcaster.getStatus({ cwd: "/repo" });
530
531 assert.deepStrictEqual(initial, baseStatus);
532 assert.deepStrictEqual(refreshed, {
533 ...state.currentLocalStatus,
534 ...state.currentRemoteStatus,
535 });
536 assert.deepStrictEqual(cached, {
537 ...state.currentLocalStatus,
538 ...state.currentRemoteStatus,
539 });
540 assert.equal(state.localStatusCalls, 2);
541 assert.equal(state.remoteStatusCalls, 2);
542 assert.equal(state.localInvalidationCalls, 1);
543 assert.equal(state.remoteInvalidationCalls, 1);
544 }).pipe(Effect.provide(layerTestFor(state)));
545 });
546
547 it.effect("keeps the cached snapshot unchanged when a refresh branch fails", () => {
548 const state = {
549 currentLocalStatus: baseLocalStatus,
550 currentRemoteStatus: baseRemoteStatus,
551 localStatusCalls: 0,
552 remoteStatusCalls: 0,
553 localInvalidationCalls: 0,
554 remoteInvalidationCalls: 0,
555 failRemoteStatus: false,
556 };
557 const layerTest = VcsStatusBroadcaster.layer.pipe(
558 Layer.provideMerge(NodeServices.layer),
559 Layer.provide(layerBackgroundPolicy(() => true)),
560 Layer.provide(
561 Layer.mock(GitWorkflowService.GitWorkflowService)({
562 localStatus: () =>
563 Effect.sync(() => {
564 state.localStatusCalls += 1;
565 return state.currentLocalStatus;
566 }),
567 remoteStatus: () =>
568 Effect.suspend(() => {
569 state.remoteStatusCalls += 1;
570 return state.failRemoteStatus
571 ? Effect.fail(
572 new GitManagerError({
573 operation: "VcsStatusBroadcaster.test",
574 cwd: "/repo",
575 detail: "remote status failed",
576 }),
577 )
578 : Effect.succeed(state.currentRemoteStatus);
579 }),
580 invalidateLocalStatus: () =>
581 Effect.sync(() => {
582 state.localInvalidationCalls += 1;
583 }),
584 invalidateRemoteStatus: () =>
585 Effect.sync(() => {
586 state.remoteInvalidationCalls += 1;
587 }),
588 invalidateStatus: () =>
589 Effect.sync(() => {
590 state.localInvalidationCalls += 1;
591 state.remoteInvalidationCalls += 1;
592 }),
593 }),
594 ),
595 );
596
597 return Effect.gen(function* () {
598 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
599 yield* broadcaster.getStatus({ cwd: "/repo" });
600
601 state.currentLocalStatus = {
602 ...baseLocalStatus,
603 refName: "feature/partial-refresh",
604 };
605 state.currentRemoteStatus = {
606 ...baseRemoteStatus,
607 aheadCount: 3,
608 };
609 state.failRemoteStatus = true;
610
611 const refreshExit = yield* broadcaster.refreshStatus("/repo").pipe(Effect.exit);
612 const cached = yield* broadcaster.getStatus({ cwd: "/repo" });
613
614 assert.isTrue(Exit.isFailure(refreshExit));
615 assert.deepStrictEqual(cached, baseStatus);
616 }).pipe(Effect.provide(layerTest));
617 });
618
619 it.effect("refreshes only the cached local snapshot when requested", () => {
620 const state = {
621 currentLocalStatus: baseLocalStatus,
622 currentRemoteStatus: baseRemoteStatus,
623 localStatusCalls: 0,
624 remoteStatusCalls: 0,
625 localInvalidationCalls: 0,
626 remoteInvalidationCalls: 0,
627 };
628
629 return Effect.gen(function* () {
630 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
631 const initial = yield* broadcaster.getStatus({ cwd: "/repo" });
632
633 state.currentLocalStatus = {
634 ...baseLocalStatus,
635 refName: "feature/local-only-refresh",
636 hasWorkingTreeChanges: true,
637 };
638
639 const refreshedLocal = yield* broadcaster.refreshLocalStatus("/repo");
640 const cached = yield* broadcaster.getStatus({ cwd: "/repo" });
641
642 assert.deepStrictEqual(initial, baseStatus);
643 assert.deepStrictEqual(refreshedLocal, state.currentLocalStatus);
644 assert.deepStrictEqual(cached, {
645 ...state.currentLocalStatus,
646 ...baseRemoteStatus,
647 });
648 assert.equal(state.localStatusCalls, 2);
649 assert.equal(state.remoteStatusCalls, 1);
650 assert.equal(state.localInvalidationCalls, 1);
651 assert.equal(state.remoteInvalidationCalls, 0);
652 }).pipe(Effect.provide(layerTestFor(state)));
653 });
654
655 it.effect.skipIf(!symlinksSupported)(
656 "normalizes symlinked CWDs before cache lookup and workflow calls",
657 () => {
658 const seenCwds: string[] = [];
659 const state = {
660 currentLocalStatus: baseLocalStatus,
661 currentRemoteStatus: baseRemoteStatus,
662 localStatusCalls: 0,
663 remoteStatusCalls: 0,
664 localInvalidationCalls: 0,
665 remoteInvalidationCalls: 0,
666 };
667 const layerTest = VcsStatusBroadcaster.layer.pipe(
668 Layer.provideMerge(NodeServices.layer),
669 Layer.provide(layerBackgroundPolicy(() => true)),
670 Layer.provide(
671 Layer.mock(GitWorkflowService.GitWorkflowService)({
672 localStatus: (input) =>
673 Effect.sync(() => {
674 seenCwds.push(input.cwd);
675 state.localStatusCalls += 1;
676 return state.currentLocalStatus;
677 }),
678 remoteStatus: (input) =>
679 Effect.sync(() => {
680 seenCwds.push(input.cwd);
681 state.remoteStatusCalls += 1;
682 return state.currentRemoteStatus;
683 }),
684 invalidateLocalStatus: () =>
685 Effect.sync(() => {
686 state.localInvalidationCalls += 1;
687 }),
688 invalidateRemoteStatus: () =>
689 Effect.sync(() => {
690 state.remoteInvalidationCalls += 1;
691 }),
692 } satisfies Partial<GitWorkflowService.GitWorkflowService["Service"]>),
693 ),
694 );
695
696 return Effect.gen(function* () {
697 const fileSystem = yield* FileSystem.FileSystem;
698 const path = yield* Path.Path;
699 const realDir = yield* fileSystem.makeTempDirectoryScoped({
700 prefix: "t3-vcs-status-real-",
701 });
702 const linkParent = yield* fileSystem.makeTempDirectoryScoped({
703 prefix: "t3-vcs-status-link-",
704 });
705 const linkDir = path.join(linkParent, "repo-link");
706 yield* fileSystem.symlink(realDir, linkDir);
707 const realPath = yield* fileSystem.realPath(realDir);
708
709 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
710 yield* broadcaster.getStatus({ cwd: linkDir });
711 yield* broadcaster.getStatus({ cwd: realDir });
712
713 assert.deepStrictEqual(seenCwds, [realPath, realPath]);
714 assert.equal(state.localStatusCalls, 1);
715 assert.equal(state.remoteStatusCalls, 1);
716 }).pipe(Effect.provide(layerTest));
717 },
718 );
719
720 it.effect("passive streams retain cached remote status", () => {
721 const state = {
722 currentLocalStatus: baseLocalStatus,
723 currentRemoteStatus: baseRemoteStatus,
724 localStatusCalls: 0,
725 remoteStatusCalls: 0,
726 localInvalidationCalls: 0,
727 remoteInvalidationCalls: 0,
728 };
729
730 return Effect.gen(function* () {
731 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
732 const snapshotDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
733 const remoteUpdatedDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
734 yield* Stream.runForEach(
735 broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }),
736 (event) => {
737 if (event._tag === "snapshot") {
738 return Deferred.succeed(snapshotDeferred, event).pipe(Effect.ignore);
739 }
740 if (event._tag === "remoteUpdated") {
741 return Deferred.succeed(remoteUpdatedDeferred, event).pipe(Effect.ignore);
742 }
743 return Effect.void;
744 },
745 ).pipe(Effect.forkScoped);
746
747 const snapshot = yield* Deferred.await(snapshotDeferred);
748 yield* TestClock.adjust("1 minute");
749 assert.equal(state.remoteStatusCalls, 0);
750 yield* broadcaster.getStatus({ cwd: "/repo" });
751 state.currentRemoteStatus = remoteStatusWithPr;
752 yield* broadcaster.refreshPullRequestStatus("/repo");
753 const remoteUpdated = yield* Deferred.await(remoteUpdatedDeferred);
754
755 assert.deepStrictEqual(snapshot, {
756 _tag: "snapshot",
757 local: baseLocalStatus,
758 remote: null,
759 } satisfies VcsStatusStreamEvent);
760 assert.deepStrictEqual(remoteUpdated, {
761 _tag: "remoteUpdated",
762 remote: remoteStatusWithPr,
763 } satisfies VcsStatusStreamEvent);
764 const cachedSnapshot = yield* Stream.runHead(
765 broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }),
766 );
767 assert.deepStrictEqual(Option.getOrThrow(cachedSnapshot), {
768 _tag: "snapshot",
769 local: baseLocalStatus,
770 remote: remoteStatusWithPr,
771 });
772 }).pipe(Effect.provide(layerTestFor(state)));
773 });
774
775 it.effect("loads remote status once when periodic refreshes are disabled", () => {
776 const state = {
777 currentLocalStatus: baseLocalStatus,
778 currentRemoteStatus: remoteStatusWithPr,
779 localStatusCalls: 0,
780 remoteStatusCalls: 0,
781 localInvalidationCalls: 0,
782 remoteInvalidationCalls: 0,
783 remoteStatusRefreshUpstreamValues: [] as Array<boolean | undefined>,
784 };
785
786 return Effect.gen(function* () {
787 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
788 const scope = yield* Scope.make();
789 const snapshotDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
790 const remoteUpdatedDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
791 yield* Stream.runForEach(
792 broadcaster.streamStatus(
793 { cwd: "/repo" },
794 { automaticRemoteRefreshInterval: Effect.succeed(Duration.zero) },
795 ),
796 (event) => {
797 if (event._tag === "snapshot") {
798 return Deferred.succeed(snapshotDeferred, event).pipe(Effect.ignore);
799 }
800 if (event._tag === "remoteUpdated") {
801 return Deferred.succeed(remoteUpdatedDeferred, event).pipe(Effect.ignore);
802 }
803 return Effect.void;
804 },
805 ).pipe(Effect.forkIn(scope));
806
807 const snapshot = yield* Deferred.await(snapshotDeferred);
808 const remoteUpdated = yield* Deferred.await(remoteUpdatedDeferred);
809
810 assert.deepStrictEqual(snapshot, {
811 _tag: "snapshot",
812 local: baseLocalStatus,
813 remote: null,
814 } satisfies VcsStatusStreamEvent);
815 assert.deepStrictEqual(remoteUpdated, {
816 _tag: "remoteUpdated",
817 remote: remoteStatusWithPr,
818 } satisfies VcsStatusStreamEvent);
819 assert.equal(state.remoteStatusCalls, 1);
820 assert.equal(state.remoteInvalidationCalls, 0);
821 assert.deepStrictEqual(state.remoteStatusRefreshUpstreamValues, [false]);
822
823 yield* TestClock.adjust(Duration.minutes(2));
824 assert.equal(state.remoteStatusCalls, 1);
825 assert.equal(state.remoteInvalidationCalls, 0);
826
827 yield* Scope.close(scope, Exit.void);
828 }).pipe(Effect.provide(Layer.merge(layerTestFor(state), TestClock.layer())));
829 });
830
831 it.effect("retries the initial remote load when periodic refreshes are disabled", () => {
832 const state = {
833 currentLocalStatus: baseLocalStatus,
834 localStatusCalls: 0,
835 remoteStatusCalls: 0,
836 localInvalidationCalls: 0,
837 remoteInvalidationCalls: 0,
838 remoteStatusRefreshUpstreamValues: [] as Array<boolean | undefined>,
839 };
840 const privateCwd = "/private/user/workspace/repo";
841 const nestedCause = new Error("private nested VCS failure");
842 const messages: Array<ReadonlyArray<unknown>> = [];
843 const logger = Logger.make<unknown, void>(({ message }) => {
844 messages.push(message as ReadonlyArray<unknown>);
845 });
846 let firstRemoteAttemptDeferred: Deferred.Deferred<void> | null = null;
847 const layerTest = VcsStatusBroadcaster.layer.pipe(
848 Layer.provideMerge(NodeServices.layer),
849 Layer.provide(layerBackgroundPolicy(() => true)),
850 Layer.provide(
851 Layer.mock(GitWorkflowService.GitWorkflowService)({
852 localStatus: () =>
853 Effect.sync(() => {
854 state.localStatusCalls += 1;
855 return state.currentLocalStatus;
856 }),
857 remoteStatus: (_input, options) =>
858 Effect.suspend(() => {
859 state.remoteStatusCalls += 1;
860 state.remoteStatusRefreshUpstreamValues.push(options?.refreshUpstream);
861 if (state.remoteStatusCalls === 1) {
862 return Effect.fail(
863 new GitManagerError({
864 operation: "VcsStatusBroadcaster.test",
865 cwd: privateCwd,
866 detail: "private initial remote status failure",
867 cause: nestedCause,
868 }),
869 ).pipe(
870 Effect.ensuring(
871 firstRemoteAttemptDeferred
872 ? Deferred.succeed(firstRemoteAttemptDeferred, undefined).pipe(Effect.ignore)
873 : Effect.void,
874 ),
875 );
876 }
877 return Effect.succeed(remoteStatusWithPr);
878 }),
879 invalidateLocalStatus: () =>
880 Effect.sync(() => {
881 state.localInvalidationCalls += 1;
882 }),
883 invalidateRemoteStatus: () =>
884 Effect.sync(() => {
885 state.remoteInvalidationCalls += 1;
886 }),
887 }),
888 ),
889 );
890
891 return Effect.gen(function* () {
892 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
893 const scope = yield* Scope.make();
894 firstRemoteAttemptDeferred = yield* Deferred.make<void>();
895 const remoteUpdatedDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
896 yield* Stream.runForEach(
897 broadcaster.streamStatus(
898 { cwd: privateCwd },
899 { automaticRemoteRefreshInterval: Effect.succeed(Duration.zero) },
900 ),
901 (event) =>
902 event._tag === "remoteUpdated"
903 ? Deferred.succeed(remoteUpdatedDeferred, event).pipe(Effect.ignore)
904 : Effect.void,
905 ).pipe(Effect.forkIn(scope));
906
907 yield* Deferred.await(firstRemoteAttemptDeferred);
908 yield* Effect.yieldNow;
909 assert.equal(state.remoteStatusCalls, 1);
910 assert.deepStrictEqual(
911 messages.find((message) => message[0] === "VCS remote status refresh failed"),
912 [
913 "VCS remote status refresh failed",
914 {
915 cwdLength: privateCwd.length,
916 reasonCount: 1,
917 failureCount: 1,
918 failureTags: ["GitManagerError"],
919 failureOperations: ["VcsStatusBroadcaster.test"],
920 defectCount: 0,
921 defectTags: [],
922 interruptionCount: 0,
923 consecutiveFailures: 1,
924 nextDelayMs: 30_000,
925 },
926 ],
927 );
928
929 yield* TestClock.adjust(Duration.seconds(30));
930 const remoteUpdated = yield* Deferred.await(remoteUpdatedDeferred);
931
932 assert.deepStrictEqual(remoteUpdated, {
933 _tag: "remoteUpdated",
934 remote: remoteStatusWithPr,
935 } satisfies VcsStatusStreamEvent);
936 assert.equal(state.remoteStatusCalls, 2);
937 assert.equal(state.remoteInvalidationCalls, 0);
938 assert.deepStrictEqual(state.remoteStatusRefreshUpstreamValues, [false, false]);
939
940 yield* Scope.close(scope, Exit.void);
941 }).pipe(
942 Effect.provide(
943 Layer.mergeAll(
944 layerTest,
945 TestClock.layer(),
946 Logger.layer([logger], { mergeWithExisting: false }),
947 ),
948 ),
949 );
950 });
951
952 it.effect("delays automatic refresh when a cached remote snapshot is available", () => {
953 const state = {
954 currentLocalStatus: baseLocalStatus,
955 currentRemoteStatus: baseRemoteStatus,
956 localStatusCalls: 0,
957 remoteStatusCalls: 0,
958 localInvalidationCalls: 0,
959 remoteInvalidationCalls: 0,
960 };
961
962 return Effect.gen(function* () {
963 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
964 yield* broadcaster.getStatus({ cwd: "/repo" });
965 const scope = yield* Scope.make();
966 const snapshotDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
967 yield* Stream.runForEach(
968 broadcaster.streamStatus(
969 { cwd: "/repo" },
970 { automaticRemoteRefreshInterval: Effect.succeed(Duration.minutes(1)) },
971 ),
972 (event) =>
973 event._tag === "snapshot"
974 ? Deferred.succeed(snapshotDeferred, event).pipe(Effect.ignore)
975 : Effect.void,
976 ).pipe(Effect.forkIn(scope));
977
978 yield* Deferred.await(snapshotDeferred);
979 assert.equal(state.remoteStatusCalls, 1);
980 assert.equal(state.remoteInvalidationCalls, 0);
981
982 yield* TestClock.adjust(Duration.seconds(59));
983 assert.equal(state.remoteStatusCalls, 1);
984
985 yield* TestClock.adjust(Duration.seconds(1));
986 yield* Effect.yieldNow;
987 assert.equal(state.remoteStatusCalls, 2);
988 assert.equal(state.remoteInvalidationCalls, 1);
989
990 yield* Scope.close(scope, Exit.void);
991 }).pipe(Effect.provide(Layer.merge(layerTestFor(state), TestClock.layer())));
992 });
993
994 it.effect.each([
995 ["a push", { ...baseRemoteStatus, aheadCount: 1, aheadOfDefaultCount: 0 }],
996 ["a merged pull request", { ...baseRemoteStatus, aheadOfDefaultCount: 2 }],
997 ] as const)("re-reads local status when a fetch reflects %s", ([, initialRemote]) => {
998 const state = {
999 currentLocalStatus: baseLocalStatus,
1000 currentRemoteStatus: initialRemote as VcsStatusRemoteResult | null,
1001 localStatusCalls: 0,
1002 remoteStatusCalls: 0,
1003 localInvalidationCalls: 0,
1004 remoteInvalidationCalls: 0,
1005 };
1006
1007 return Effect.gen(function* () {
1008 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
1009 yield* broadcaster.getStatus({ cwd: "/repo" });
1010 const scope = yield* Scope.make();
1011 const snapshotDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
1012 const localUpdatedDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
1013 yield* Stream.runForEach(
1014 broadcaster.streamStatus(
1015 { cwd: "/repo" },
1016 { automaticRemoteRefreshInterval: Effect.succeed(Duration.minutes(1)) },
1017 ),
1018 (event) =>
1019 event._tag === "snapshot"
1020 ? Deferred.succeed(snapshotDeferred, event).pipe(Effect.ignore)
1021 : event._tag === "localUpdated"
1022 ? Deferred.succeed(localUpdatedDeferred, event).pipe(Effect.ignore)
1023 : Effect.void,
1024 ).pipe(Effect.forkIn(scope));
1025 yield* Deferred.await(snapshotDeferred);
1026
1027 const pushedLocal: VcsStatusLocalResult = {
1028 ...baseLocalStatus,
1029 branchChanges: { baseRef: "origin/main", insertions: 0, deletions: 0 },
1030 };
1031 state.currentLocalStatus = pushedLocal;
1032 state.currentRemoteStatus = { ...baseRemoteStatus, aheadOfDefaultCount: 0 };
1033 yield* TestClock.adjust(Duration.minutes(1));
1034
1035 assert.deepStrictEqual(yield* Deferred.await(localUpdatedDeferred), {
1036 _tag: "localUpdated",
1037 local: pushedLocal,
1038 } satisfies VcsStatusStreamEvent);
1039 yield* Scope.close(scope, Exit.void);
1040 }).pipe(Effect.provide(Layer.merge(layerTestFor(state), TestClock.layer())));
1041 });
1042
1043 it.effect("an explicit refresh reads local totals after the fetch", () => {
1044 const state: Parameters<typeof layerTestFor>[0] = {
1045 currentLocalStatus: baseLocalStatus,
1046 currentRemoteStatus: baseRemoteStatus,
1047 localStatusCalls: 0,
1048 remoteStatusCalls: 0,
1049 localInvalidationCalls: 0,
1050 remoteInvalidationCalls: 0,
1051 };
1052
1053 return Effect.gen(function* () {
1054 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
1055 const fetchStarted = yield* Deferred.make<void>();
1056 const finishFetch = yield* Deferred.make<void>();
1057 state.beforeRemoteStatus = Deferred.succeed(fetchStarted, undefined).pipe(
1058 Effect.andThen(Deferred.await(finishFetch)),
1059 );
1060 const refresh = yield* broadcaster.refreshStatus("/repo").pipe(Effect.forkScoped);
1061 yield* Deferred.await(fetchStarted);
1062
1063 const fetchedLocal: VcsStatusLocalResult = {
1064 ...baseLocalStatus,
1065 branchChanges: { baseRef: "origin/main", insertions: 0, deletions: 0 },
1066 };
1067 state.currentLocalStatus = fetchedLocal;
1068 yield* Deferred.succeed(finishFetch, undefined);
1069
1070 const status = yield* Fiber.join(refresh);
1071 assert.deepStrictEqual(status.branchChanges, fetchedLocal.branchChanges);
1072 }).pipe(Effect.provide(layerTestFor(state)));
1073 });
1074
1075 it("backs off remote refresh failures exponentially and honors larger configured intervals", () => {
1076 assert.equal(
1077 Duration.toMillis(VcsStatusBroadcaster.remoteRefreshFailureDelay(1, Duration.seconds(1))),
1078 30_000,
1079 );
1080 assert.equal(
1081 Duration.toMillis(VcsStatusBroadcaster.remoteRefreshFailureDelay(2, Duration.seconds(1))),
1082 60_000,
1083 );
1084 assert.equal(
1085 Duration.toMillis(VcsStatusBroadcaster.remoteRefreshFailureDelay(3, Duration.seconds(1))),
1086 120_000,
1087 );
1088 assert.equal(
1089 Duration.toMillis(VcsStatusBroadcaster.remoteRefreshFailureDelay(1, Duration.minutes(5))),
1090 300_000,
1091 );
1092 assert.equal(
1093 Duration.toMillis(VcsStatusBroadcaster.remoteRefreshFailureDelay(20, Duration.seconds(1))),
1094 900_000,
1095 );
1096 });
1097
1098 it("summarizes refresh causes without exposing nested failure details", () => {
1099 const nestedCause = new Error("private nested failure detail");
1100 const failure = new GitManagerError({
1101 operation: "VcsStatusBroadcaster.remoteStatus",
1102 cwd: "/private/user/workspace/repo",
1103 detail: "private Git failure detail",
1104 cause: nestedCause,
1105 });
1106 const cause = Cause.combine(Cause.fail(failure), Cause.die(new TypeError("private defect")));
1107
1108 assert.deepStrictEqual(VcsStatusBroadcaster.remoteRefreshFailureDiagnostics(cause), {
1109 reasonCount: 2,
1110 failureCount: 1,
1111 failureTags: ["GitManagerError"],
1112 failureOperations: ["VcsStatusBroadcaster.remoteStatus"],
1113 defectCount: 1,
1114 defectTags: ["TypeError"],
1115 interruptionCount: 0,
1116 });
1117 });
1118
1119 it.effect("does not start automatic remote refreshes without foreground client demand", () => {
1120 const state = {
1121 currentLocalStatus: baseLocalStatus,
1122 currentRemoteStatus: baseRemoteStatus,
1123 localStatusCalls: 0,
1124 remoteStatusCalls: 0,
1125 localInvalidationCalls: 0,
1126 remoteInvalidationCalls: 0,
1127 };
1128 const layerTest = VcsStatusBroadcaster.layer.pipe(
1129 Layer.provideMerge(NodeServices.layer),
1130 Layer.provide(layerBackgroundPolicy(() => false)),
1131 Layer.provide(
1132 Layer.mock(GitWorkflowService.GitWorkflowService)({
1133 localStatus: () =>
1134 Effect.sync(() => {
1135 state.localStatusCalls += 1;
1136 return state.currentLocalStatus;
1137 }),
1138 remoteStatus: () =>
1139 Effect.sync(() => {
1140 state.remoteStatusCalls += 1;
1141 return state.currentRemoteStatus;
1142 }),
1143 invalidateLocalStatus: () =>
1144 Effect.sync(() => {
1145 state.localInvalidationCalls += 1;
1146 }),
1147 invalidateRemoteStatus: () =>
1148 Effect.sync(() => {
1149 state.remoteInvalidationCalls += 1;
1150 }),
1151 } satisfies Partial<GitWorkflowService.GitWorkflowService["Service"]>),
1152 ),
1153 );
1154
1155 return Effect.gen(function* () {
1156 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
1157 const snapshot = yield* Stream.runHead(
1158 broadcaster.streamStatus(
1159 { cwd: "/repo" },
1160 { automaticRemoteRefreshInterval: Effect.succeed(Duration.seconds(1)) },
1161 ),
1162 );
1163
1164 assert.isTrue(Option.isSome(snapshot));
1165 assert.equal(state.remoteStatusCalls, 0);
1166 assert.equal(state.remoteInvalidationCalls, 0);
1167 }).pipe(Effect.provide(layerTest));
1168 });
1169
1170 it.effect("releases remote demand while passive observers remain", () => {
1171 const state = {
1172 currentLocalStatus: baseLocalStatus,
1173 currentRemoteStatus: baseRemoteStatus,
1174 localStatusCalls: 0,
1175 remoteStatusCalls: 0,
1176 localInvalidationCalls: 0,
1177 remoteInvalidationCalls: 0,
1178 };
1179 let remoteInterruptedDeferred: Deferred.Deferred<void, never> | null = null;
1180 let remoteStartedDeferred: Deferred.Deferred<void, never> | null = null;
1181 const layerTest = VcsStatusBroadcaster.layer.pipe(
1182 Layer.provideMerge(NodeServices.layer),
1183 Layer.provide(layerBackgroundPolicy(() => true)),
1184 Layer.provide(
1185 Layer.mock(GitWorkflowService.GitWorkflowService)({
1186 localStatus: () =>
1187 Effect.sync(() => {
1188 state.localStatusCalls += 1;
1189 return state.currentLocalStatus;
1190 }),
1191 remoteStatus: () =>
1192 Effect.sync(() => {
1193 state.remoteStatusCalls += 1;
1194 }).pipe(
1195 Effect.andThen(
1196 remoteStartedDeferred
1197 ? Deferred.succeed(remoteStartedDeferred, undefined).pipe(Effect.ignore)
1198 : Effect.void,
1199 ),
1200 Effect.andThen(Effect.never as Effect.Effect<VcsStatusRemoteResult | null, never>),
1201 Effect.onInterrupt(() =>
1202 remoteInterruptedDeferred
1203 ? Deferred.succeed(remoteInterruptedDeferred, undefined).pipe(Effect.ignore)
1204 : Effect.void,
1205 ),
1206 ),
1207 invalidateLocalStatus: () =>
1208 Effect.sync(() => {
1209 state.localInvalidationCalls += 1;
1210 }),
1211 invalidateRemoteStatus: () =>
1212 Effect.sync(() => {
1213 state.remoteInvalidationCalls += 1;
1214 }),
1215 } satisfies Partial<GitWorkflowService.GitWorkflowService["Service"]>),
1216 ),
1217 );
1218
1219 return Effect.gen(function* () {
1220 const remoteInterrupted = yield* Deferred.make<void>();
1221 const remoteStarted = yield* Deferred.make<void>();
1222 remoteInterruptedDeferred = remoteInterrupted;
1223 remoteStartedDeferred = remoteStarted;
1224
1225 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
1226 const firstSnapshot = yield* Deferred.make<VcsStatusStreamEvent>();
1227 const secondSnapshot = yield* Deferred.make<VcsStatusStreamEvent>();
1228 const firstScope = yield* Scope.make();
1229 const secondScope = yield* Scope.make();
1230 const passiveSnapshot = yield* Deferred.make<VcsStatusStreamEvent>();
1231 yield* Stream.runForEach(
1232 broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }),
1233 (event) =>
1234 event._tag === "snapshot"
1235 ? Deferred.succeed(passiveSnapshot, event).pipe(Effect.ignore)
1236 : Effect.void,
1237 ).pipe(Effect.forkScoped);
1238 yield* Deferred.await(passiveSnapshot);
1239 assert.equal(state.remoteStatusCalls, 0);
1240 yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) =>
1241 event._tag === "snapshot"
1242 ? Deferred.succeed(firstSnapshot, event).pipe(Effect.ignore)
1243 : Effect.void,
1244 ).pipe(Effect.forkIn(firstScope));
1245 yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) =>
1246 event._tag === "snapshot"
1247 ? Deferred.succeed(secondSnapshot, event).pipe(Effect.ignore)
1248 : Effect.void,
1249 ).pipe(Effect.forkIn(secondScope));
1250
1251 yield* Deferred.await(firstSnapshot);
1252 yield* Deferred.await(secondSnapshot);
1253 yield* Deferred.await(remoteStarted);
1254
1255 assert.equal(state.remoteStatusCalls, 1);
1256
1257 yield* Scope.close(firstScope, Exit.void);
1258 assert.isTrue(Option.isNone(yield* Deferred.poll(remoteInterrupted)));
1259
1260 yield* Scope.close(secondScope, Exit.void).pipe(Effect.forkScoped);
1261 yield* Deferred.await(remoteInterrupted);
1262 assert.isTrue(Option.isSome(yield* Deferred.poll(remoteInterrupted)));
1263 }).pipe(Effect.provide(layerTest));
1264 });
1265});