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

VcsStatusBroadcaster.test.ts

1,348 lines50.5 KB

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