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

VcsStatusBroadcaster.test.ts

1,137 lines42.1 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 { 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 );
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 });
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("reuses the cached VCS status across repeated reads", () => {
216 const state = {
217 currentLocalStatus: baseLocalStatus,
218 currentRemoteStatus: baseRemoteStatus,
219 localStatusCalls: 0,
220 remoteStatusCalls: 0,
221 localInvalidationCalls: 0,
222 remoteInvalidationCalls: 0,
223 };
224​
225 return Effect.gen(function* () {
226 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
227​
228 const first = yield* broadcaster.getStatus({ cwd: "/repo" });
229 const second = yield* broadcaster.getStatus({ cwd: "/repo" });
230​
231 assert.deepStrictEqual(first, baseStatus);
232 assert.deepStrictEqual(second, baseStatus);
233 assert.equal(state.localStatusCalls, 1);
234 assert.equal(state.remoteStatusCalls, 1);
235 assert.equal(state.localInvalidationCalls, 0);
236 assert.equal(state.remoteInvalidationCalls, 0);
237 }).pipe(Effect.provide(layerTestFor(state)));
238 });
239​
240 it.effect("refreshes a loaded cwd without reusing a previous branch's PR", () => {
241 const state = {
242 currentLocalStatus: baseLocalStatus,
243 currentRemoteStatus: baseRemoteStatus,
244 localStatusCalls: 0,
245 remoteStatusCalls: 0,
246 localInvalidationCalls: 0,
247 remoteInvalidationCalls: 0,
248 };
249​
250 return Effect.gen(function* () {
251 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
252​
253 assert.isNull(yield* broadcaster.refreshPullRequestStatus("/repo"));
254 assert.equal(state.remoteStatusCalls, 0);
255​
256 yield* broadcaster.getStatus({ cwd: "/repo" });
257 assert.equal(state.remoteStatusCalls, 1);
258​
259 state.currentRemoteStatus = remoteStatusWithPr;
260 const refreshed = yield* broadcaster.refreshPullRequestStatus("/repo");
261 assert.deepStrictEqual(refreshed, remoteStatusWithPr);
262 assert.equal(state.remoteStatusCalls, 2);
263 assert.equal(state.remoteInvalidationCalls, 0);
264​
265 state.currentLocalStatus = { ...baseLocalStatus, refName: "feature/next" };
266 state.currentRemoteStatus = baseRemoteStatus;
267 yield* broadcaster.refreshLocalStatus("/repo");
268 const refreshedBranch = yield* broadcaster.refreshPullRequestStatus("/repo");
269 assert.deepStrictEqual(refreshedBranch, baseRemoteStatus);
270 assert.equal(state.remoteStatusCalls, 3);
271 }).pipe(Effect.provide(layerTestFor(state)));
272 });
273​
274 it.effect("a poll that started before the turn-end refresh cannot overwrite its PR", () => {
275 const releaseFirstPoll = Deferred.makeUnsafe<void>();
276 const firstPollStarted = Deferred.makeUnsafe<void>();
277 let remoteReads = 0;
278 const layer = VcsStatusBroadcaster.layer.pipe(
279 Layer.provideMerge(NodeServices.layer),
280 Layer.provide(layerBackgroundPolicy(() => true)),
281 Layer.provide(
282 Layer.mock(GitWorkflowService.GitWorkflowService)({
283 localStatus: () => Effect.succeed(baseLocalStatus),
284 remoteStatus: () =>
285 Effect.gen(function* () {
286 remoteReads += 1;
287 if (remoteReads === 2) {
288 yield* Deferred.succeed(firstPollStarted, undefined);
289 yield* Deferred.await(releaseFirstPoll);
290 return baseRemoteStatus;
291 }
292 return remoteReads === 1 ? baseRemoteStatus : remoteStatusWithPr;
293 }),
294 invalidateLocalStatus: () => Effect.void,
295 invalidateRemoteStatus: () => Effect.void,
296 invalidateStatus: () => Effect.void,
297 }),
298 ),
299 );
300​
301 return Effect.gen(function* () {
302 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
303 yield* broadcaster.getStatus({ cwd: "/repo" });
304​
305 const poll = yield* broadcaster.refreshStatus("/repo").pipe(Effect.forkScoped);
306 yield* Deferred.await(firstPollStarted);
307 const refresh = yield* broadcaster.refreshPullRequestStatus("/repo").pipe(Effect.forkScoped);
308 yield* Deferred.succeed(releaseFirstPoll, undefined);
309 yield* Fiber.join(poll);
310 const refreshed = yield* Fiber.join(refresh);
311​
312 assert.deepStrictEqual(refreshed, remoteStatusWithPr);
313 const final = yield* broadcaster.getStatus({ cwd: "/repo" });
314 assert.deepStrictEqual(final.pr, remoteStatusWithPr.pr);
315 }).pipe(Effect.provide(layer), Effect.scoped);
316 });
317​
318 it.effect("an initial status read cannot overwrite an explicit refresh", () => {
319 const firstReadStarted = Deferred.makeUnsafe<void>();
320 const releaseFirstRead = Deferred.makeUnsafe<void>();
321 let remoteReads = 0;
322 const layer = VcsStatusBroadcaster.layer.pipe(
323 Layer.provide(FileSystem.layerNoop({ realPath: (path) => Effect.succeed(path) })),
324 Layer.provideMerge(NodeServices.layer),
325 Layer.provide(layerBackgroundPolicy(() => true)),
326 Layer.provide(
327 Layer.mock(GitWorkflowService.GitWorkflowService)({
328 localStatus: () => Effect.succeed(baseLocalStatus),
329 remoteStatus: () =>
330 Effect.gen(function* () {
331 remoteReads += 1;
332 if (remoteReads === 1) {
333 yield* Deferred.succeed(firstReadStarted, undefined);
334 yield* Deferred.await(releaseFirstRead);
335 return baseRemoteStatus;
336 }
337 return remoteStatusWithPr;
338 }),
339 invalidateStatus: () => Effect.void,
340 }),
341 ),
342 );
343 return Effect.gen(function* () {
344 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
345 const initial = yield* broadcaster.getStatus({ cwd: "/repo" }).pipe(Effect.forkScoped);
346 yield* Deferred.await(firstReadStarted);
347 const refresh = yield* broadcaster.refreshStatus("/repo").pipe(Effect.forkScoped);
348 yield* TestClock.adjust(Duration.zero);
349 yield* Deferred.succeed(releaseFirstRead, undefined);
350 yield* Fiber.join(initial);
351 yield* Fiber.join(refresh);
352 assert.deepStrictEqual(
353 (yield* broadcaster.getStatus({ cwd: "/repo" })).pr,
354 remoteStatusWithPr.pr,
355 );
356 }).pipe(Effect.provide(layer), Effect.scoped);
357 });
358​
359 it.effect("turn-end refresh skips a loaded cwd when background policy pauses it", () => {
360 const state = {
361 currentLocalStatus: baseLocalStatus,
362 currentRemoteStatus: baseRemoteStatus,
363 localStatusCalls: 0,
364 remoteStatusCalls: 0,
365 localInvalidationCalls: 0,
366 remoteInvalidationCalls: 0,
367 backgroundWorkEnabled: false,
368 };
369 return Effect.gen(function* () {
370 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
371 yield* broadcaster.getStatus({ cwd: "/repo" });
372 yield* broadcaster.refreshPullRequestStatus("/repo");
373 assert.equal(state.remoteStatusCalls, 1);
374 assert.equal(state.remoteInvalidationCalls, 0);
375 }).pipe(Effect.provide(layerTestFor(state)));
376 });
377​
378 it.effect("refreshes the cached snapshot after explicit invalidation", () => {
379 const state = {
380 currentLocalStatus: baseLocalStatus,
381 currentRemoteStatus: baseRemoteStatus,
382 localStatusCalls: 0,
383 remoteStatusCalls: 0,
384 localInvalidationCalls: 0,
385 remoteInvalidationCalls: 0,
386 };
387​
388 return Effect.gen(function* () {
389 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
390 const initial = yield* broadcaster.getStatus({ cwd: "/repo" });
391​
392 state.currentLocalStatus = {
393 ...baseLocalStatus,
394 refName: "feature/updated-status",
395 };
396 state.currentRemoteStatus = {
397 ...baseRemoteStatus,
398 aheadCount: 2,
399 };
400 const refreshed = yield* broadcaster.refreshStatus("/repo");
401 const cached = yield* broadcaster.getStatus({ cwd: "/repo" });
402​
403 assert.deepStrictEqual(initial, baseStatus);
404 assert.deepStrictEqual(refreshed, {
405 ...state.currentLocalStatus,
406 ...state.currentRemoteStatus,
407 });
408 assert.deepStrictEqual(cached, {
409 ...state.currentLocalStatus,
410 ...state.currentRemoteStatus,
411 });
412 assert.equal(state.localStatusCalls, 2);
413 assert.equal(state.remoteStatusCalls, 2);
414 assert.equal(state.localInvalidationCalls, 1);
415 assert.equal(state.remoteInvalidationCalls, 1);
416 }).pipe(Effect.provide(layerTestFor(state)));
417 });
418​
419 it.effect("keeps the cached snapshot unchanged when a refresh branch fails", () => {
420 const state = {
421 currentLocalStatus: baseLocalStatus,
422 currentRemoteStatus: baseRemoteStatus,
423 localStatusCalls: 0,
424 remoteStatusCalls: 0,
425 localInvalidationCalls: 0,
426 remoteInvalidationCalls: 0,
427 failRemoteStatus: false,
428 };
429 const layerTest = VcsStatusBroadcaster.layer.pipe(
430 Layer.provideMerge(NodeServices.layer),
431 Layer.provide(layerBackgroundPolicy(() => true)),
432 Layer.provide(
433 Layer.mock(GitWorkflowService.GitWorkflowService)({
434 localStatus: () =>
435 Effect.sync(() => {
436 state.localStatusCalls += 1;
437 return state.currentLocalStatus;
438 }),
439 remoteStatus: () =>
440 Effect.suspend(() => {
441 state.remoteStatusCalls += 1;
442 return state.failRemoteStatus
443 ? Effect.fail(
444 new GitManagerError({
445 operation: "VcsStatusBroadcaster.test",
446 cwd: "/repo",
447 detail: "remote status failed",
448 }),
449 )
450 : Effect.succeed(state.currentRemoteStatus);
451 }),
452 invalidateLocalStatus: () =>
453 Effect.sync(() => {
454 state.localInvalidationCalls += 1;
455 }),
456 invalidateRemoteStatus: () =>
457 Effect.sync(() => {
458 state.remoteInvalidationCalls += 1;
459 }),
460 invalidateStatus: () =>
461 Effect.sync(() => {
462 state.localInvalidationCalls += 1;
463 state.remoteInvalidationCalls += 1;
464 }),
465 }),
466 ),
467 );
468​
469 return Effect.gen(function* () {
470 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
471 yield* broadcaster.getStatus({ cwd: "/repo" });
472​
473 state.currentLocalStatus = {
474 ...baseLocalStatus,
475 refName: "feature/partial-refresh",
476 };
477 state.currentRemoteStatus = {
478 ...baseRemoteStatus,
479 aheadCount: 3,
480 };
481 state.failRemoteStatus = true;
482​
483 const refreshExit = yield* broadcaster.refreshStatus("/repo").pipe(Effect.exit);
484 const cached = yield* broadcaster.getStatus({ cwd: "/repo" });
485​
486 assert.isTrue(Exit.isFailure(refreshExit));
487 assert.deepStrictEqual(cached, baseStatus);
488 }).pipe(Effect.provide(layerTest));
489 });
490​
491 it.effect("refreshes only the cached local snapshot when requested", () => {
492 const state = {
493 currentLocalStatus: baseLocalStatus,
494 currentRemoteStatus: baseRemoteStatus,
495 localStatusCalls: 0,
496 remoteStatusCalls: 0,
497 localInvalidationCalls: 0,
498 remoteInvalidationCalls: 0,
499 };
500​
501 return Effect.gen(function* () {
502 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
503 const initial = yield* broadcaster.getStatus({ cwd: "/repo" });
504​
505 state.currentLocalStatus = {
506 ...baseLocalStatus,
507 refName: "feature/local-only-refresh",
508 hasWorkingTreeChanges: true,
509 };
510​
511 const refreshedLocal = yield* broadcaster.refreshLocalStatus("/repo");
512 const cached = yield* broadcaster.getStatus({ cwd: "/repo" });
513​
514 assert.deepStrictEqual(initial, baseStatus);
515 assert.deepStrictEqual(refreshedLocal, state.currentLocalStatus);
516 assert.deepStrictEqual(cached, {
517 ...state.currentLocalStatus,
518 ...baseRemoteStatus,
519 });
520 assert.equal(state.localStatusCalls, 2);
521 assert.equal(state.remoteStatusCalls, 1);
522 assert.equal(state.localInvalidationCalls, 1);
523 assert.equal(state.remoteInvalidationCalls, 0);
524 }).pipe(Effect.provide(layerTestFor(state)));
525 });
526​
527 it.effect.skipIf(!symlinksSupported)(
528 "normalizes symlinked CWDs before cache lookup and workflow calls",
529 () => {
530 const seenCwds: string[] = [];
531 const state = {
532 currentLocalStatus: baseLocalStatus,
533 currentRemoteStatus: baseRemoteStatus,
534 localStatusCalls: 0,
535 remoteStatusCalls: 0,
536 localInvalidationCalls: 0,
537 remoteInvalidationCalls: 0,
538 };
539 const layerTest = VcsStatusBroadcaster.layer.pipe(
540 Layer.provideMerge(NodeServices.layer),
541 Layer.provide(layerBackgroundPolicy(() => true)),
542 Layer.provide(
543 Layer.mock(GitWorkflowService.GitWorkflowService)({
544 localStatus: (input) =>
545 Effect.sync(() => {
546 seenCwds.push(input.cwd);
547 state.localStatusCalls += 1;
548 return state.currentLocalStatus;
549 }),
550 remoteStatus: (input) =>
551 Effect.sync(() => {
552 seenCwds.push(input.cwd);
553 state.remoteStatusCalls += 1;
554 return state.currentRemoteStatus;
555 }),
556 invalidateLocalStatus: () =>
557 Effect.sync(() => {
558 state.localInvalidationCalls += 1;
559 }),
560 invalidateRemoteStatus: () =>
561 Effect.sync(() => {
562 state.remoteInvalidationCalls += 1;
563 }),
564 } satisfies Partial<GitWorkflowService.GitWorkflowService["Service"]>),
565 ),
566 );
567​
568 return Effect.gen(function* () {
569 const fileSystem = yield* FileSystem.FileSystem;
570 const path = yield* Path.Path;
571 const realDir = yield* fileSystem.makeTempDirectoryScoped({
572 prefix: "t3-vcs-status-real-",
573 });
574 const linkParent = yield* fileSystem.makeTempDirectoryScoped({
575 prefix: "t3-vcs-status-link-",
576 });
577 const linkDir = path.join(linkParent, "repo-link");
578 yield* fileSystem.symlink(realDir, linkDir);
579 const realPath = yield* fileSystem.realPath(realDir);
580​
581 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
582 yield* broadcaster.getStatus({ cwd: linkDir });
583 yield* broadcaster.getStatus({ cwd: realDir });
584​
585 assert.deepStrictEqual(seenCwds, [realPath, realPath]);
586 assert.equal(state.localStatusCalls, 1);
587 assert.equal(state.remoteStatusCalls, 1);
588 }).pipe(Effect.provide(layerTest));
589 },
590 );
591​
592 it.effect("passive streams retain cached remote status", () => {
593 const state = {
594 currentLocalStatus: baseLocalStatus,
595 currentRemoteStatus: baseRemoteStatus,
596 localStatusCalls: 0,
597 remoteStatusCalls: 0,
598 localInvalidationCalls: 0,
599 remoteInvalidationCalls: 0,
600 };
601​
602 return Effect.gen(function* () {
603 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
604 const snapshotDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
605 const remoteUpdatedDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
606 yield* Stream.runForEach(
607 broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }),
608 (event) => {
609 if (event._tag === "snapshot") {
610 return Deferred.succeed(snapshotDeferred, event).pipe(Effect.ignore);
611 }
612 if (event._tag === "remoteUpdated") {
613 return Deferred.succeed(remoteUpdatedDeferred, event).pipe(Effect.ignore);
614 }
615 return Effect.void;
616 },
617 ).pipe(Effect.forkScoped);
618​
619 const snapshot = yield* Deferred.await(snapshotDeferred);
620 yield* TestClock.adjust("1 minute");
621 assert.equal(state.remoteStatusCalls, 0);
622 yield* broadcaster.getStatus({ cwd: "/repo" });
623 state.currentRemoteStatus = remoteStatusWithPr;
624 yield* broadcaster.refreshPullRequestStatus("/repo");
625 const remoteUpdated = yield* Deferred.await(remoteUpdatedDeferred);
626​
627 assert.deepStrictEqual(snapshot, {
628 _tag: "snapshot",
629 local: baseLocalStatus,
630 remote: null,
631 } satisfies VcsStatusStreamEvent);
632 assert.deepStrictEqual(remoteUpdated, {
633 _tag: "remoteUpdated",
634 remote: remoteStatusWithPr,
635 } satisfies VcsStatusStreamEvent);
636 const cachedSnapshot = yield* Stream.runHead(
637 broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }),
638 );
639 assert.deepStrictEqual(Option.getOrThrow(cachedSnapshot), {
640 _tag: "snapshot",
641 local: baseLocalStatus,
642 remote: remoteStatusWithPr,
643 });
644 }).pipe(Effect.provide(layerTestFor(state)));
645 });
646​
647 it.effect("loads remote status once when periodic refreshes are disabled", () => {
648 const state = {
649 currentLocalStatus: baseLocalStatus,
650 currentRemoteStatus: remoteStatusWithPr,
651 localStatusCalls: 0,
652 remoteStatusCalls: 0,
653 localInvalidationCalls: 0,
654 remoteInvalidationCalls: 0,
655 remoteStatusRefreshUpstreamValues: [] as Array<boolean | undefined>,
656 };
657​
658 return Effect.gen(function* () {
659 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
660 const scope = yield* Scope.make();
661 const snapshotDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
662 const remoteUpdatedDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
663 yield* Stream.runForEach(
664 broadcaster.streamStatus(
665 { cwd: "/repo" },
666 { automaticRemoteRefreshInterval: Effect.succeed(Duration.zero) },
667 ),
668 (event) => {
669 if (event._tag === "snapshot") {
670 return Deferred.succeed(snapshotDeferred, event).pipe(Effect.ignore);
671 }
672 if (event._tag === "remoteUpdated") {
673 return Deferred.succeed(remoteUpdatedDeferred, event).pipe(Effect.ignore);
674 }
675 return Effect.void;
676 },
677 ).pipe(Effect.forkIn(scope));
678​
679 const snapshot = yield* Deferred.await(snapshotDeferred);
680 const remoteUpdated = yield* Deferred.await(remoteUpdatedDeferred);
681​
682 assert.deepStrictEqual(snapshot, {
683 _tag: "snapshot",
684 local: baseLocalStatus,
685 remote: null,
686 } satisfies VcsStatusStreamEvent);
687 assert.deepStrictEqual(remoteUpdated, {
688 _tag: "remoteUpdated",
689 remote: remoteStatusWithPr,
690 } satisfies VcsStatusStreamEvent);
691 assert.equal(state.remoteStatusCalls, 1);
692 assert.equal(state.remoteInvalidationCalls, 0);
693 assert.deepStrictEqual(state.remoteStatusRefreshUpstreamValues, [false]);
694​
695 yield* TestClock.adjust(Duration.minutes(2));
696 assert.equal(state.remoteStatusCalls, 1);
697 assert.equal(state.remoteInvalidationCalls, 0);
698​
699 yield* Scope.close(scope, Exit.void);
700 }).pipe(Effect.provide(Layer.merge(layerTestFor(state), TestClock.layer())));
701 });
702​
703 it.effect("retries the initial remote load when periodic refreshes are disabled", () => {
704 const state = {
705 currentLocalStatus: baseLocalStatus,
706 localStatusCalls: 0,
707 remoteStatusCalls: 0,
708 localInvalidationCalls: 0,
709 remoteInvalidationCalls: 0,
710 remoteStatusRefreshUpstreamValues: [] as Array<boolean | undefined>,
711 };
712 const privateCwd = "/private/user/workspace/repo";
713 const nestedCause = new Error("private nested VCS failure");
714 const messages: Array<ReadonlyArray<unknown>> = [];
715 const logger = Logger.make<unknown, void>(({ message }) => {
716 messages.push(message as ReadonlyArray<unknown>);
717 });
718 let firstRemoteAttemptDeferred: Deferred.Deferred<void> | null = null;
719 const layerTest = VcsStatusBroadcaster.layer.pipe(
720 Layer.provideMerge(NodeServices.layer),
721 Layer.provide(layerBackgroundPolicy(() => true)),
722 Layer.provide(
723 Layer.mock(GitWorkflowService.GitWorkflowService)({
724 localStatus: () =>
725 Effect.sync(() => {
726 state.localStatusCalls += 1;
727 return state.currentLocalStatus;
728 }),
729 remoteStatus: (_input, options) =>
730 Effect.suspend(() => {
731 state.remoteStatusCalls += 1;
732 state.remoteStatusRefreshUpstreamValues.push(options?.refreshUpstream);
733 if (state.remoteStatusCalls === 1) {
734 return Effect.fail(
735 new GitManagerError({
736 operation: "VcsStatusBroadcaster.test",
737 cwd: privateCwd,
738 detail: "private initial remote status failure",
739 cause: nestedCause,
740 }),
741 ).pipe(
742 Effect.ensuring(
743 firstRemoteAttemptDeferred
744 ? Deferred.succeed(firstRemoteAttemptDeferred, undefined).pipe(Effect.ignore)
745 : Effect.void,
746 ),
747 );
748 }
749 return Effect.succeed(remoteStatusWithPr);
750 }),
751 invalidateLocalStatus: () =>
752 Effect.sync(() => {
753 state.localInvalidationCalls += 1;
754 }),
755 invalidateRemoteStatus: () =>
756 Effect.sync(() => {
757 state.remoteInvalidationCalls += 1;
758 }),
759 }),
760 ),
761 );
762​
763 return Effect.gen(function* () {
764 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
765 const scope = yield* Scope.make();
766 firstRemoteAttemptDeferred = yield* Deferred.make<void>();
767 const remoteUpdatedDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
768 yield* Stream.runForEach(
769 broadcaster.streamStatus(
770 { cwd: privateCwd },
771 { automaticRemoteRefreshInterval: Effect.succeed(Duration.zero) },
772 ),
773 (event) =>
774 event._tag === "remoteUpdated"
775 ? Deferred.succeed(remoteUpdatedDeferred, event).pipe(Effect.ignore)
776 : Effect.void,
777 ).pipe(Effect.forkIn(scope));
778​
779 yield* Deferred.await(firstRemoteAttemptDeferred);
780 yield* Effect.yieldNow;
781 assert.equal(state.remoteStatusCalls, 1);
782 assert.deepStrictEqual(
783 messages.find((message) => message[0] === "VCS remote status refresh failed"),
784 [
785 "VCS remote status refresh failed",
786 {
787 cwdLength: privateCwd.length,
788 reasonCount: 1,
789 failureCount: 1,
790 failureTags: ["GitManagerError"],
791 failureOperations: ["VcsStatusBroadcaster.test"],
792 defectCount: 0,
793 defectTags: [],
794 interruptionCount: 0,
795 consecutiveFailures: 1,
796 nextDelayMs: 30_000,
797 },
798 ],
799 );
800​
801 yield* TestClock.adjust(Duration.seconds(30));
802 const remoteUpdated = yield* Deferred.await(remoteUpdatedDeferred);
803​
804 assert.deepStrictEqual(remoteUpdated, {
805 _tag: "remoteUpdated",
806 remote: remoteStatusWithPr,
807 } satisfies VcsStatusStreamEvent);
808 assert.equal(state.remoteStatusCalls, 2);
809 assert.equal(state.remoteInvalidationCalls, 0);
810 assert.deepStrictEqual(state.remoteStatusRefreshUpstreamValues, [false, false]);
811​
812 yield* Scope.close(scope, Exit.void);
813 }).pipe(
814 Effect.provide(
815 Layer.mergeAll(
816 layerTest,
817 TestClock.layer(),
818 Logger.layer([logger], { mergeWithExisting: false }),
819 ),
820 ),
821 );
822 });
823​
824 it.effect("delays automatic refresh when a cached remote snapshot is available", () => {
825 const state = {
826 currentLocalStatus: baseLocalStatus,
827 currentRemoteStatus: baseRemoteStatus,
828 localStatusCalls: 0,
829 remoteStatusCalls: 0,
830 localInvalidationCalls: 0,
831 remoteInvalidationCalls: 0,
832 };
833​
834 return Effect.gen(function* () {
835 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
836 yield* broadcaster.getStatus({ cwd: "/repo" });
837 const scope = yield* Scope.make();
838 const snapshotDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
839 yield* Stream.runForEach(
840 broadcaster.streamStatus(
841 { cwd: "/repo" },
842 { automaticRemoteRefreshInterval: Effect.succeed(Duration.minutes(1)) },
843 ),
844 (event) =>
845 event._tag === "snapshot"
846 ? Deferred.succeed(snapshotDeferred, event).pipe(Effect.ignore)
847 : Effect.void,
848 ).pipe(Effect.forkIn(scope));
849​
850 yield* Deferred.await(snapshotDeferred);
851 assert.equal(state.remoteStatusCalls, 1);
852 assert.equal(state.remoteInvalidationCalls, 0);
853​
854 yield* TestClock.adjust(Duration.seconds(59));
855 assert.equal(state.remoteStatusCalls, 1);
856​
857 yield* TestClock.adjust(Duration.seconds(1));
858 yield* Effect.yieldNow;
859 assert.equal(state.remoteStatusCalls, 2);
860 assert.equal(state.remoteInvalidationCalls, 1);
861​
862 yield* Scope.close(scope, Exit.void);
863 }).pipe(Effect.provide(Layer.merge(layerTestFor(state), TestClock.layer())));
864 });
865​
866 it.effect.each([
867 ["a push", { ...baseRemoteStatus, aheadCount: 1, aheadOfDefaultCount: 0 }],
868 ["a merged pull request", { ...baseRemoteStatus, aheadOfDefaultCount: 2 }],
869 ] as const)("re-reads local status when a fetch reflects %s", ([, initialRemote]) => {
870 const state = {
871 currentLocalStatus: baseLocalStatus,
872 currentRemoteStatus: initialRemote as VcsStatusRemoteResult | null,
873 localStatusCalls: 0,
874 remoteStatusCalls: 0,
875 localInvalidationCalls: 0,
876 remoteInvalidationCalls: 0,
877 };
878​
879 return Effect.gen(function* () {
880 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
881 yield* broadcaster.getStatus({ cwd: "/repo" });
882 const scope = yield* Scope.make();
883 const snapshotDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
884 const localUpdatedDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
885 yield* Stream.runForEach(
886 broadcaster.streamStatus(
887 { cwd: "/repo" },
888 { automaticRemoteRefreshInterval: Effect.succeed(Duration.minutes(1)) },
889 ),
890 (event) =>
891 event._tag === "snapshot"
892 ? Deferred.succeed(snapshotDeferred, event).pipe(Effect.ignore)
893 : event._tag === "localUpdated"
894 ? Deferred.succeed(localUpdatedDeferred, event).pipe(Effect.ignore)
895 : Effect.void,
896 ).pipe(Effect.forkIn(scope));
897 yield* Deferred.await(snapshotDeferred);
898​
899 const pushedLocal: VcsStatusLocalResult = {
900 ...baseLocalStatus,
901 branchChanges: { baseRef: "origin/main", insertions: 0, deletions: 0 },
902 };
903 state.currentLocalStatus = pushedLocal;
904 state.currentRemoteStatus = { ...baseRemoteStatus, aheadOfDefaultCount: 0 };
905 yield* TestClock.adjust(Duration.minutes(1));
906​
907 assert.deepStrictEqual(yield* Deferred.await(localUpdatedDeferred), {
908 _tag: "localUpdated",
909 local: pushedLocal,
910 } satisfies VcsStatusStreamEvent);
911 yield* Scope.close(scope, Exit.void);
912 }).pipe(Effect.provide(Layer.merge(layerTestFor(state), TestClock.layer())));
913 });
914​
915 it.effect("an explicit refresh reads local totals after the fetch", () => {
916 const state: Parameters<typeof layerTestFor>[0] = {
917 currentLocalStatus: baseLocalStatus,
918 currentRemoteStatus: baseRemoteStatus,
919 localStatusCalls: 0,
920 remoteStatusCalls: 0,
921 localInvalidationCalls: 0,
922 remoteInvalidationCalls: 0,
923 };
924​
925 return Effect.gen(function* () {
926 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
927 const fetchStarted = yield* Deferred.make<void>();
928 const finishFetch = yield* Deferred.make<void>();
929 state.beforeRemoteStatus = Deferred.succeed(fetchStarted, undefined).pipe(
930 Effect.andThen(Deferred.await(finishFetch)),
931 );
932 const refresh = yield* broadcaster.refreshStatus("/repo").pipe(Effect.forkScoped);
933 yield* Deferred.await(fetchStarted);
934​
935 const fetchedLocal: VcsStatusLocalResult = {
936 ...baseLocalStatus,
937 branchChanges: { baseRef: "origin/main", insertions: 0, deletions: 0 },
938 };
939 state.currentLocalStatus = fetchedLocal;
940 yield* Deferred.succeed(finishFetch, undefined);
941​
942 const status = yield* Fiber.join(refresh);
943 assert.deepStrictEqual(status.branchChanges, fetchedLocal.branchChanges);
944 }).pipe(Effect.provide(layerTestFor(state)));
945 });
946​
947 it("backs off remote refresh failures exponentially and honors larger configured intervals", () => {
948 assert.equal(
949 Duration.toMillis(VcsStatusBroadcaster.remoteRefreshFailureDelay(1, Duration.seconds(1))),
950 30_000,
951 );
952 assert.equal(
953 Duration.toMillis(VcsStatusBroadcaster.remoteRefreshFailureDelay(2, Duration.seconds(1))),
954 60_000,
955 );
956 assert.equal(
957 Duration.toMillis(VcsStatusBroadcaster.remoteRefreshFailureDelay(3, Duration.seconds(1))),
958 120_000,
959 );
960 assert.equal(
961 Duration.toMillis(VcsStatusBroadcaster.remoteRefreshFailureDelay(1, Duration.minutes(5))),
962 300_000,
963 );
964 assert.equal(
965 Duration.toMillis(VcsStatusBroadcaster.remoteRefreshFailureDelay(20, Duration.seconds(1))),
966 900_000,
967 );
968 });
969​
970 it("summarizes refresh causes without exposing nested failure details", () => {
971 const nestedCause = new Error("private nested failure detail");
972 const failure = new GitManagerError({
973 operation: "VcsStatusBroadcaster.remoteStatus",
974 cwd: "/private/user/workspace/repo",
975 detail: "private Git failure detail",
976 cause: nestedCause,
977 });
978 const cause = Cause.combine(Cause.fail(failure), Cause.die(new TypeError("private defect")));
979​
980 assert.deepStrictEqual(VcsStatusBroadcaster.remoteRefreshFailureDiagnostics(cause), {
981 reasonCount: 2,
982 failureCount: 1,
983 failureTags: ["GitManagerError"],
984 failureOperations: ["VcsStatusBroadcaster.remoteStatus"],
985 defectCount: 1,
986 defectTags: ["TypeError"],
987 interruptionCount: 0,
988 });
989 });
990​
991 it.effect("does not start automatic remote refreshes without foreground client demand", () => {
992 const state = {
993 currentLocalStatus: baseLocalStatus,
994 currentRemoteStatus: baseRemoteStatus,
995 localStatusCalls: 0,
996 remoteStatusCalls: 0,
997 localInvalidationCalls: 0,
998 remoteInvalidationCalls: 0,
999 };
1000 const layerTest = VcsStatusBroadcaster.layer.pipe(
1001 Layer.provideMerge(NodeServices.layer),
1002 Layer.provide(layerBackgroundPolicy(() => false)),
1003 Layer.provide(
1004 Layer.mock(GitWorkflowService.GitWorkflowService)({
1005 localStatus: () =>
1006 Effect.sync(() => {
1007 state.localStatusCalls += 1;
1008 return state.currentLocalStatus;
1009 }),
1010 remoteStatus: () =>
1011 Effect.sync(() => {
1012 state.remoteStatusCalls += 1;
1013 return state.currentRemoteStatus;
1014 }),
1015 invalidateLocalStatus: () =>
1016 Effect.sync(() => {
1017 state.localInvalidationCalls += 1;
1018 }),
1019 invalidateRemoteStatus: () =>
1020 Effect.sync(() => {
1021 state.remoteInvalidationCalls += 1;
1022 }),
1023 } satisfies Partial<GitWorkflowService.GitWorkflowService["Service"]>),
1024 ),
1025 );
1026​
1027 return Effect.gen(function* () {
1028 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
1029 const snapshot = yield* Stream.runHead(
1030 broadcaster.streamStatus(
1031 { cwd: "/repo" },
1032 { automaticRemoteRefreshInterval: Effect.succeed(Duration.seconds(1)) },
1033 ),
1034 );
1035​
1036 assert.isTrue(Option.isSome(snapshot));
1037 assert.equal(state.remoteStatusCalls, 0);
1038 assert.equal(state.remoteInvalidationCalls, 0);
1039 }).pipe(Effect.provide(layerTest));
1040 });
1041​
1042 it.effect("releases remote demand while passive observers remain", () => {
1043 const state = {
1044 currentLocalStatus: baseLocalStatus,
1045 currentRemoteStatus: baseRemoteStatus,
1046 localStatusCalls: 0,
1047 remoteStatusCalls: 0,
1048 localInvalidationCalls: 0,
1049 remoteInvalidationCalls: 0,
1050 };
1051 let remoteInterruptedDeferred: Deferred.Deferred<void, never> | null = null;
1052 let remoteStartedDeferred: Deferred.Deferred<void, never> | null = null;
1053 const layerTest = VcsStatusBroadcaster.layer.pipe(
1054 Layer.provideMerge(NodeServices.layer),
1055 Layer.provide(layerBackgroundPolicy(() => true)),
1056 Layer.provide(
1057 Layer.mock(GitWorkflowService.GitWorkflowService)({
1058 localStatus: () =>
1059 Effect.sync(() => {
1060 state.localStatusCalls += 1;
1061 return state.currentLocalStatus;
1062 }),
1063 remoteStatus: () =>
1064 Effect.sync(() => {
1065 state.remoteStatusCalls += 1;
1066 }).pipe(
1067 Effect.andThen(
1068 remoteStartedDeferred
1069 ? Deferred.succeed(remoteStartedDeferred, undefined).pipe(Effect.ignore)
1070 : Effect.void,
1071 ),
1072 Effect.andThen(Effect.never as Effect.Effect<VcsStatusRemoteResult | null, never>),
1073 Effect.onInterrupt(() =>
1074 remoteInterruptedDeferred
1075 ? Deferred.succeed(remoteInterruptedDeferred, undefined).pipe(Effect.ignore)
1076 : Effect.void,
1077 ),
1078 ),
1079 invalidateLocalStatus: () =>
1080 Effect.sync(() => {
1081 state.localInvalidationCalls += 1;
1082 }),
1083 invalidateRemoteStatus: () =>
1084 Effect.sync(() => {
1085 state.remoteInvalidationCalls += 1;
1086 }),
1087 } satisfies Partial<GitWorkflowService.GitWorkflowService["Service"]>),
1088 ),
1089 );
1090​
1091 return Effect.gen(function* () {
1092 const remoteInterrupted = yield* Deferred.make<void>();
1093 const remoteStarted = yield* Deferred.make<void>();
1094 remoteInterruptedDeferred = remoteInterrupted;
1095 remoteStartedDeferred = remoteStarted;
1096​
1097 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
1098 const firstSnapshot = yield* Deferred.make<VcsStatusStreamEvent>();
1099 const secondSnapshot = yield* Deferred.make<VcsStatusStreamEvent>();
1100 const firstScope = yield* Scope.make();
1101 const secondScope = yield* Scope.make();
1102 const passiveSnapshot = yield* Deferred.make<VcsStatusStreamEvent>();
1103 yield* Stream.runForEach(
1104 broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }),
1105 (event) =>
1106 event._tag === "snapshot"
1107 ? Deferred.succeed(passiveSnapshot, event).pipe(Effect.ignore)
1108 : Effect.void,
1109 ).pipe(Effect.forkScoped);
1110 yield* Deferred.await(passiveSnapshot);
1111 assert.equal(state.remoteStatusCalls, 0);
1112 yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) =>
1113 event._tag === "snapshot"
1114 ? Deferred.succeed(firstSnapshot, event).pipe(Effect.ignore)
1115 : Effect.void,
1116 ).pipe(Effect.forkIn(firstScope));
1117 yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) =>
1118 event._tag === "snapshot"
1119 ? Deferred.succeed(secondSnapshot, event).pipe(Effect.ignore)
1120 : Effect.void,
1121 ).pipe(Effect.forkIn(secondScope));
1122​
1123 yield* Deferred.await(firstSnapshot);
1124 yield* Deferred.await(secondSnapshot);
1125 yield* Deferred.await(remoteStarted);
1126​
1127 assert.equal(state.remoteStatusCalls, 1);
1128​
1129 yield* Scope.close(firstScope, Exit.void);
1130 assert.isTrue(Option.isNone(yield* Deferred.poll(remoteInterrupted)));
1131​
1132 yield* Scope.close(secondScope, Exit.void).pipe(Effect.forkScoped);
1133 yield* Deferred.await(remoteInterrupted);
1134 assert.isTrue(Option.isSome(yield* Deferred.poll(remoteInterrupted)));
1135 }).pipe(Effect.provide(layerTest));
1136 });
1137});