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

VcsStatusBroadcaster.test.ts

881 lines31.4 KB

1import { assert, it, describe } from "@effect/vitest";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import * as Cause from "effect/Cause";
4import * as Deferred from "effect/Deferred";
5import * as DateTime from "effect/DateTime";
6import * as Duration from "effect/Duration";
7import * as Effect from "effect/Effect";
8import * as Exit from "effect/Exit";
9import * as FileSystem from "effect/FileSystem";
10import * as Layer from "effect/Layer";
11import * as Logger from "effect/Logger";
12import * as Option from "effect/Option";
13import * as Path from "effect/Path";
14import * as Scope from "effect/Scope";
15import * as Stream from "effect/Stream";
16import * as TestClock from "effect/testing/TestClock";
17import type {
18 BackgroundScope,
19 VcsStatusLocalResult,
20 VcsStatusRemoteResult,
21 VcsStatusResult,
22 VcsStatusStreamEvent,
23} from "@t3tools/contracts";
24import { GitManagerError } from "@t3tools/contracts";
25​
26import * as VcsStatusBroadcaster from "./VcsStatusBroadcaster.ts";
27import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
28import * as GitWorkflowService from "../git/GitWorkflowService.ts";
29​
30const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
31​
32const baseLocalStatus: VcsStatusLocalResult = {
33 isRepo: true,
34 sourceControlProvider: {
35 kind: "github",
36 name: "GitHub",
37 baseUrl: "https://github.com",
38 },
39 hasPrimaryRemote: true,
40 isDefaultRef: false,
41 refName: "feature/status-broadcast",
42 hasWorkingTreeChanges: false,
43 workingTree: { files: [], insertions: 0, deletions: 0 },
44};
45​
46const baseRemoteStatus: VcsStatusRemoteResult = {
47 hasUpstream: true,
48 aheadCount: 0,
49 behindCount: 0,
50 pr: null,
51};
52​
53const remoteStatusWithPr: VcsStatusRemoteResult = {
54 ...baseRemoteStatus,
55 pr: {
56 number: 2978,
57 title: "[codex] Rewrite client connection architecture",
58 url: "https://github.com/pingdotgg/t3code/pull/2978",
59 baseRef: "main",
60 headRef: "codex/connection-state-audit",
61 state: "open",
62 },
63};
64​
65const baseStatus: VcsStatusResult = {
66 ...baseLocalStatus,
67 ...baseRemoteStatus,
68};
69​
70function makeTestLayer(state: {
71 currentLocalStatus: VcsStatusLocalResult;
72 currentRemoteStatus: VcsStatusRemoteResult | null;
73 localStatusCalls: number;
74 remoteStatusCalls: number;
75 localInvalidationCalls: number;
76 remoteInvalidationCalls: number;
77 remoteStatusRefreshUpstreamValues?: Array<boolean | undefined>;
78}) {
79 return VcsStatusBroadcaster.layer.pipe(
80 Layer.provideMerge(NodeServices.layer),
81 Layer.provide(makeBackgroundPolicyLayer(() => true)),
82 Layer.provide(
83 Layer.mock(GitWorkflowService.GitWorkflowService)({
84 localStatus: () =>
85 Effect.sync(() => {
86 state.localStatusCalls += 1;
87 return state.currentLocalStatus;
88 }),
89 remoteStatus: (_input, options) =>
90 Effect.sync(() => {
91 state.remoteStatusCalls += 1;
92 state.remoteStatusRefreshUpstreamValues?.push(options?.refreshUpstream);
93 return state.currentRemoteStatus;
94 }),
95 invalidateLocalStatus: () =>
96 Effect.sync(() => {
97 state.localInvalidationCalls += 1;
98 }),
99 invalidateRemoteStatus: () =>
100 Effect.sync(() => {
101 state.remoteInvalidationCalls += 1;
102 }),
103 invalidateStatus: () =>
104 Effect.sync(() => {
105 state.localInvalidationCalls += 1;
106 state.remoteInvalidationCalls += 1;
107 }),
108 }),
109 ),
110 );
112​
113function makeBackgroundPolicyLayer(shouldRunScopeWork: (scope: BackgroundScope) => boolean) {
114 return Layer.mock(BackgroundPolicy.BackgroundPolicy)({
115 reportClientActivity: () => Effect.void,
116 removeRpcClient: () => Effect.void,
117 reportHostPowerState: () => Effect.void,
118 snapshot: Effect.succeed({
119 hostPower: {
120 source: "unknown",
121 idle: "unknown",
122 idleSeconds: null,
123 locked: "unknown",
124 suspended: false,
125 onBattery: "unknown",
126 lowPowerMode: "unknown",
127 thermalState: "unknown",
128 stale: true,
129 updatedAt: TEST_EPOCH,
130 },
131 leases: [],
132 activeForegroundLeaseCount: 0,
133 activeScopeKeys: [],
134 shouldRunOpportunisticWork: false,
135 updatedAt: TEST_EPOCH,
136 }),
137 streamChanges: Stream.empty,
138 hasDemand: () => Effect.succeed(true),
139 shouldRunScopeWork: (scope) => Effect.sync(() => shouldRunScopeWork(scope)),
140 shouldRunOpportunisticWork: Effect.succeed(true),
141 });
143​
144describe("VcsStatusBroadcaster", () => {
145 it.effect(
146 "automatically pulls an enabled clean default branch when status detects it is behind",
147 () => {
148 let remoteStatus: VcsStatusRemoteResult = { ...baseRemoteStatus, behindCount: 2 };
149 let pullCalls = 0;
150 let configuredWorkspaceRoot = "";
151 const localStatus: VcsStatusLocalResult = {
152 ...baseLocalStatus,
153 isDefaultRef: true,
154 refName: "main",
155 };
156 const testLayer = VcsStatusBroadcaster.layer.pipe(
157 Layer.provideMerge(NodeServices.layer),
158 Layer.provide(makeBackgroundPolicyLayer(() => true)),
159 Layer.provide(
160 Layer.succeed(VcsStatusBroadcaster.VcsAutoPullPolicy, {
161 isEnabled: (cwd) => Effect.succeed(cwd === configuredWorkspaceRoot),
162 }),
163 ),
164 Layer.provide(
165 Layer.mock(GitWorkflowService.GitWorkflowService)({
166 localStatus: () => Effect.succeed(localStatus),
167 remoteStatus: () => Effect.succeed(remoteStatus),
168 invalidateLocalStatus: () => Effect.void,
169 invalidateRemoteStatus: () => Effect.void,
170 invalidateStatus: () => Effect.void,
171 pullCurrentBranch: () =>
172 Effect.sync(() => {
173 pullCalls += 1;
174 remoteStatus = { ...remoteStatus, behindCount: 0 };
175 return {
176 status: "pulled" as const,
177 refName: "main",
178 upstreamRef: "origin/main",
179 };
180 }),
181 }),
182 ),
183 );
184​
185 return Effect.gen(function* () {
186 const fileSystem = yield* FileSystem.FileSystem;
187 const path = yield* Path.Path;
188 const realDir = yield* fileSystem.makeTempDirectoryScoped({
189 prefix: "t3-vcs-auto-pull-real-",
190 });
191 const linkParent = yield* fileSystem.makeTempDirectoryScoped({
192 prefix: "t3-vcs-auto-pull-link-",
193 });
194 configuredWorkspaceRoot = path.join(linkParent, "repo-link");
195 yield* fileSystem.symlink(realDir, configuredWorkspaceRoot);
196​
197 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
198 const status = yield* broadcaster.refreshStatus(configuredWorkspaceRoot);
199​
200 assert.equal(pullCalls, 1);
201 assert.equal(status.behindCount, 0);
202 }).pipe(Effect.provide(testLayer));
203 },
204 );
205​
206 it.effect("reuses the cached VCS status across repeated reads", () => {
207 const state = {
208 currentLocalStatus: baseLocalStatus,
209 currentRemoteStatus: baseRemoteStatus,
210 localStatusCalls: 0,
211 remoteStatusCalls: 0,
212 localInvalidationCalls: 0,
213 remoteInvalidationCalls: 0,
214 };
215​
216 return Effect.gen(function* () {
217 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
218​
219 const first = yield* broadcaster.getStatus({ cwd: "/repo" });
220 const second = yield* broadcaster.getStatus({ cwd: "/repo" });
221​
222 assert.deepStrictEqual(first, baseStatus);
223 assert.deepStrictEqual(second, baseStatus);
224 assert.equal(state.localStatusCalls, 1);
225 assert.equal(state.remoteStatusCalls, 1);
226 assert.equal(state.localInvalidationCalls, 0);
227 assert.equal(state.remoteInvalidationCalls, 0);
228 }).pipe(Effect.provide(makeTestLayer(state)));
229 });
230​
231 it.effect("refreshes the cached snapshot after explicit invalidation", () => {
232 const state = {
233 currentLocalStatus: baseLocalStatus,
234 currentRemoteStatus: baseRemoteStatus,
235 localStatusCalls: 0,
236 remoteStatusCalls: 0,
237 localInvalidationCalls: 0,
238 remoteInvalidationCalls: 0,
239 };
240​
241 return Effect.gen(function* () {
242 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
243 const initial = yield* broadcaster.getStatus({ cwd: "/repo" });
244​
245 state.currentLocalStatus = {
246 ...baseLocalStatus,
247 refName: "feature/updated-status",
248 };
249 state.currentRemoteStatus = {
250 ...baseRemoteStatus,
251 aheadCount: 2,
252 };
253 const refreshed = yield* broadcaster.refreshStatus("/repo");
254 const cached = yield* broadcaster.getStatus({ cwd: "/repo" });
255​
256 assert.deepStrictEqual(initial, baseStatus);
257 assert.deepStrictEqual(refreshed, {
258 ...state.currentLocalStatus,
259 ...state.currentRemoteStatus,
260 });
261 assert.deepStrictEqual(cached, {
262 ...state.currentLocalStatus,
263 ...state.currentRemoteStatus,
264 });
265 assert.equal(state.localStatusCalls, 2);
266 assert.equal(state.remoteStatusCalls, 2);
267 assert.equal(state.localInvalidationCalls, 1);
268 assert.equal(state.remoteInvalidationCalls, 1);
269 }).pipe(Effect.provide(makeTestLayer(state)));
270 });
271​
272 it.effect("keeps the cached snapshot unchanged when a refresh branch fails", () => {
273 const state = {
274 currentLocalStatus: baseLocalStatus,
275 currentRemoteStatus: baseRemoteStatus,
276 localStatusCalls: 0,
277 remoteStatusCalls: 0,
278 localInvalidationCalls: 0,
279 remoteInvalidationCalls: 0,
280 failRemoteStatus: false,
281 };
282 const testLayer = VcsStatusBroadcaster.layer.pipe(
283 Layer.provideMerge(NodeServices.layer),
284 Layer.provide(makeBackgroundPolicyLayer(() => true)),
285 Layer.provide(
286 Layer.mock(GitWorkflowService.GitWorkflowService)({
287 localStatus: () =>
288 Effect.sync(() => {
289 state.localStatusCalls += 1;
290 return state.currentLocalStatus;
291 }),
292 remoteStatus: () =>
293 Effect.suspend(() => {
294 state.remoteStatusCalls += 1;
295 return state.failRemoteStatus
296 ? Effect.fail(
297 new GitManagerError({
298 operation: "VcsStatusBroadcaster.test",
299 cwd: "/repo",
300 detail: "remote status failed",
301 }),
302 )
303 : Effect.succeed(state.currentRemoteStatus);
304 }),
305 invalidateLocalStatus: () =>
306 Effect.sync(() => {
307 state.localInvalidationCalls += 1;
308 }),
309 invalidateRemoteStatus: () =>
310 Effect.sync(() => {
311 state.remoteInvalidationCalls += 1;
312 }),
313 invalidateStatus: () =>
314 Effect.sync(() => {
315 state.localInvalidationCalls += 1;
316 state.remoteInvalidationCalls += 1;
317 }),
318 }),
319 ),
320 );
321​
322 return Effect.gen(function* () {
323 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
324 yield* broadcaster.getStatus({ cwd: "/repo" });
325​
326 state.currentLocalStatus = {
327 ...baseLocalStatus,
328 refName: "feature/partial-refresh",
329 };
330 state.currentRemoteStatus = {
331 ...baseRemoteStatus,
332 aheadCount: 3,
333 };
334 state.failRemoteStatus = true;
335​
336 const refreshExit = yield* broadcaster.refreshStatus("/repo").pipe(Effect.exit);
337 const cached = yield* broadcaster.getStatus({ cwd: "/repo" });
338​
339 assert.isTrue(Exit.isFailure(refreshExit));
340 assert.deepStrictEqual(cached, baseStatus);
341 }).pipe(Effect.provide(testLayer));
342 });
343​
344 it.effect("refreshes only the cached local snapshot when requested", () => {
345 const state = {
346 currentLocalStatus: baseLocalStatus,
347 currentRemoteStatus: baseRemoteStatus,
348 localStatusCalls: 0,
349 remoteStatusCalls: 0,
350 localInvalidationCalls: 0,
351 remoteInvalidationCalls: 0,
352 };
353​
354 return Effect.gen(function* () {
355 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
356 const initial = yield* broadcaster.getStatus({ cwd: "/repo" });
357​
358 state.currentLocalStatus = {
359 ...baseLocalStatus,
360 refName: "feature/local-only-refresh",
361 hasWorkingTreeChanges: true,
362 };
363​
364 const refreshedLocal = yield* broadcaster.refreshLocalStatus("/repo");
365 const cached = yield* broadcaster.getStatus({ cwd: "/repo" });
366​
367 assert.deepStrictEqual(initial, baseStatus);
368 assert.deepStrictEqual(refreshedLocal, state.currentLocalStatus);
369 assert.deepStrictEqual(cached, {
370 ...state.currentLocalStatus,
371 ...baseRemoteStatus,
372 });
373 assert.equal(state.localStatusCalls, 2);
374 assert.equal(state.remoteStatusCalls, 1);
375 assert.equal(state.localInvalidationCalls, 1);
376 assert.equal(state.remoteInvalidationCalls, 0);
377 }).pipe(Effect.provide(makeTestLayer(state)));
378 });
379​
380 it.effect("normalizes symlinked CWDs before cache lookup and workflow calls", () => {
381 const seenCwds: string[] = [];
382 const state = {
383 currentLocalStatus: baseLocalStatus,
384 currentRemoteStatus: baseRemoteStatus,
385 localStatusCalls: 0,
386 remoteStatusCalls: 0,
387 localInvalidationCalls: 0,
388 remoteInvalidationCalls: 0,
389 };
390 const testLayer = VcsStatusBroadcaster.layer.pipe(
391 Layer.provideMerge(NodeServices.layer),
392 Layer.provide(makeBackgroundPolicyLayer(() => true)),
393 Layer.provide(
394 Layer.mock(GitWorkflowService.GitWorkflowService)({
395 localStatus: (input) =>
396 Effect.sync(() => {
397 seenCwds.push(input.cwd);
398 state.localStatusCalls += 1;
399 return state.currentLocalStatus;
400 }),
401 remoteStatus: (input) =>
402 Effect.sync(() => {
403 seenCwds.push(input.cwd);
404 state.remoteStatusCalls += 1;
405 return state.currentRemoteStatus;
406 }),
407 invalidateLocalStatus: () =>
408 Effect.sync(() => {
409 state.localInvalidationCalls += 1;
410 }),
411 invalidateRemoteStatus: () =>
412 Effect.sync(() => {
413 state.remoteInvalidationCalls += 1;
414 }),
415 } satisfies Partial<GitWorkflowService.GitWorkflowService["Service"]>),
416 ),
417 );
418​
419 return Effect.gen(function* () {
420 const fileSystem = yield* FileSystem.FileSystem;
421 const path = yield* Path.Path;
422 const realDir = yield* fileSystem.makeTempDirectoryScoped({
423 prefix: "t3-vcs-status-real-",
424 });
425 const linkParent = yield* fileSystem.makeTempDirectoryScoped({
426 prefix: "t3-vcs-status-link-",
427 });
428 const linkDir = path.join(linkParent, "repo-link");
429 yield* fileSystem.symlink(realDir, linkDir);
430 const realPath = yield* fileSystem.realPath(realDir);
431​
432 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
433 yield* broadcaster.getStatus({ cwd: linkDir });
434 yield* broadcaster.getStatus({ cwd: realDir });
435​
436 assert.deepStrictEqual(seenCwds, [realPath, realPath]);
437 assert.equal(state.localStatusCalls, 1);
438 assert.equal(state.remoteStatusCalls, 1);
439 }).pipe(Effect.provide(testLayer));
440 });
441​
442 it.effect("streams a local snapshot first and remote updates later", () => {
443 const state = {
444 currentLocalStatus: baseLocalStatus,
445 currentRemoteStatus: baseRemoteStatus,
446 localStatusCalls: 0,
447 remoteStatusCalls: 0,
448 localInvalidationCalls: 0,
449 remoteInvalidationCalls: 0,
450 };
451​
452 return Effect.gen(function* () {
453 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
454 const snapshotDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
455 const remoteUpdatedDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
456 yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) => {
457 if (event._tag === "snapshot") {
458 return Deferred.succeed(snapshotDeferred, event).pipe(Effect.ignore);
459 }
460 if (event._tag === "remoteUpdated") {
461 return Deferred.succeed(remoteUpdatedDeferred, event).pipe(Effect.ignore);
462 }
463 return Effect.void;
464 }).pipe(Effect.forkScoped);
465​
466 const snapshot = yield* Deferred.await(snapshotDeferred);
467 yield* broadcaster.refreshStatus("/repo");
468 const remoteUpdated = yield* Deferred.await(remoteUpdatedDeferred);
469​
470 assert.deepStrictEqual(snapshot, {
471 _tag: "snapshot",
472 local: baseLocalStatus,
473 remote: null,
474 } satisfies VcsStatusStreamEvent);
475 assert.deepStrictEqual(remoteUpdated, {
476 _tag: "remoteUpdated",
477 remote: baseRemoteStatus,
478 } satisfies VcsStatusStreamEvent);
479 }).pipe(Effect.provide(makeTestLayer(state)));
480 });
481​
482 it.effect("loads remote status once when periodic refreshes are disabled", () => {
483 const state = {
484 currentLocalStatus: baseLocalStatus,
485 currentRemoteStatus: remoteStatusWithPr,
486 localStatusCalls: 0,
487 remoteStatusCalls: 0,
488 localInvalidationCalls: 0,
489 remoteInvalidationCalls: 0,
490 remoteStatusRefreshUpstreamValues: [] as Array<boolean | undefined>,
491 };
492​
493 return Effect.gen(function* () {
494 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
495 const scope = yield* Scope.make();
496 const snapshotDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
497 const remoteUpdatedDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
498 yield* Stream.runForEach(
499 broadcaster.streamStatus(
500 { cwd: "/repo" },
501 { automaticRemoteRefreshInterval: Effect.succeed(Duration.zero) },
502 ),
503 (event) => {
504 if (event._tag === "snapshot") {
505 return Deferred.succeed(snapshotDeferred, event).pipe(Effect.ignore);
506 }
507 if (event._tag === "remoteUpdated") {
508 return Deferred.succeed(remoteUpdatedDeferred, event).pipe(Effect.ignore);
509 }
510 return Effect.void;
511 },
512 ).pipe(Effect.forkIn(scope));
513​
514 const snapshot = yield* Deferred.await(snapshotDeferred);
515 const remoteUpdated = yield* Deferred.await(remoteUpdatedDeferred);
516​
517 assert.deepStrictEqual(snapshot, {
518 _tag: "snapshot",
519 local: baseLocalStatus,
520 remote: null,
521 } satisfies VcsStatusStreamEvent);
522 assert.deepStrictEqual(remoteUpdated, {
523 _tag: "remoteUpdated",
524 remote: remoteStatusWithPr,
525 } satisfies VcsStatusStreamEvent);
526 assert.equal(state.remoteStatusCalls, 1);
527 assert.equal(state.remoteInvalidationCalls, 0);
528 assert.deepStrictEqual(state.remoteStatusRefreshUpstreamValues, [false]);
529​
530 yield* TestClock.adjust(Duration.minutes(2));
531 assert.equal(state.remoteStatusCalls, 1);
532 assert.equal(state.remoteInvalidationCalls, 0);
533​
534 yield* Scope.close(scope, Exit.void);
535 }).pipe(Effect.provide(Layer.merge(makeTestLayer(state), TestClock.layer())));
536 });
537​
538 it.effect("retries the initial remote load when periodic refreshes are disabled", () => {
539 const state = {
540 currentLocalStatus: baseLocalStatus,
541 localStatusCalls: 0,
542 remoteStatusCalls: 0,
543 localInvalidationCalls: 0,
544 remoteInvalidationCalls: 0,
545 remoteStatusRefreshUpstreamValues: [] as Array<boolean | undefined>,
546 };
547 const privateCwd = "/private/user/workspace/repo";
548 const nestedCause = new Error("private nested VCS failure");
549 const messages: Array<ReadonlyArray<unknown>> = [];
550 const logger = Logger.make<unknown, void>(({ message }) => {
551 messages.push(message as ReadonlyArray<unknown>);
552 });
553 let firstRemoteAttemptDeferred: Deferred.Deferred<void> | null = null;
554 const testLayer = VcsStatusBroadcaster.layer.pipe(
555 Layer.provideMerge(NodeServices.layer),
556 Layer.provide(makeBackgroundPolicyLayer(() => true)),
557 Layer.provide(
558 Layer.mock(GitWorkflowService.GitWorkflowService)({
559 localStatus: () =>
560 Effect.sync(() => {
561 state.localStatusCalls += 1;
562 return state.currentLocalStatus;
563 }),
564 remoteStatus: (_input, options) =>
565 Effect.suspend(() => {
566 state.remoteStatusCalls += 1;
567 state.remoteStatusRefreshUpstreamValues.push(options?.refreshUpstream);
568 if (state.remoteStatusCalls === 1) {
569 return Effect.fail(
570 new GitManagerError({
571 operation: "VcsStatusBroadcaster.test",
572 cwd: privateCwd,
573 detail: "private initial remote status failure",
574 cause: nestedCause,
575 }),
576 ).pipe(
577 Effect.ensuring(
578 firstRemoteAttemptDeferred
579 ? Deferred.succeed(firstRemoteAttemptDeferred, undefined).pipe(Effect.ignore)
580 : Effect.void,
581 ),
582 );
583 }
584 return Effect.succeed(remoteStatusWithPr);
585 }),
586 invalidateLocalStatus: () =>
587 Effect.sync(() => {
588 state.localInvalidationCalls += 1;
589 }),
590 invalidateRemoteStatus: () =>
591 Effect.sync(() => {
592 state.remoteInvalidationCalls += 1;
593 }),
594 }),
595 ),
596 );
597​
598 return Effect.gen(function* () {
599 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
600 const scope = yield* Scope.make();
601 firstRemoteAttemptDeferred = yield* Deferred.make<void>();
602 const remoteUpdatedDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
603 yield* Stream.runForEach(
604 broadcaster.streamStatus(
605 { cwd: privateCwd },
606 { automaticRemoteRefreshInterval: Effect.succeed(Duration.zero) },
607 ),
608 (event) =>
609 event._tag === "remoteUpdated"
610 ? Deferred.succeed(remoteUpdatedDeferred, event).pipe(Effect.ignore)
611 : Effect.void,
612 ).pipe(Effect.forkIn(scope));
613​
614 yield* Deferred.await(firstRemoteAttemptDeferred);
615 yield* Effect.yieldNow;
616 assert.equal(state.remoteStatusCalls, 1);
617 assert.deepStrictEqual(
618 messages.find((message) => message[0] === "VCS remote status refresh failed"),
619 [
620 "VCS remote status refresh failed",
621 {
622 cwdLength: privateCwd.length,
623 reasonCount: 1,
624 failureCount: 1,
625 failureTags: ["GitManagerError"],
626 failureOperations: ["VcsStatusBroadcaster.test"],
627 defectCount: 0,
628 defectTags: [],
629 interruptionCount: 0,
630 consecutiveFailures: 1,
631 nextDelayMs: 30_000,
632 },
633 ],
634 );
635​
636 yield* TestClock.adjust(Duration.seconds(30));
637 const remoteUpdated = yield* Deferred.await(remoteUpdatedDeferred);
638​
639 assert.deepStrictEqual(remoteUpdated, {
640 _tag: "remoteUpdated",
641 remote: remoteStatusWithPr,
642 } satisfies VcsStatusStreamEvent);
643 assert.equal(state.remoteStatusCalls, 2);
644 assert.equal(state.remoteInvalidationCalls, 0);
645 assert.deepStrictEqual(state.remoteStatusRefreshUpstreamValues, [false, false]);
646​
647 yield* Scope.close(scope, Exit.void);
648 }).pipe(
649 Effect.provide(
650 Layer.mergeAll(
651 testLayer,
652 TestClock.layer(),
653 Logger.layer([logger], { mergeWithExisting: false }),
654 ),
655 ),
656 );
657 });
658​
659 it.effect("delays automatic refresh when a cached remote snapshot is available", () => {
660 const state = {
661 currentLocalStatus: baseLocalStatus,
662 currentRemoteStatus: baseRemoteStatus,
663 localStatusCalls: 0,
664 remoteStatusCalls: 0,
665 localInvalidationCalls: 0,
666 remoteInvalidationCalls: 0,
667 };
668​
669 return Effect.gen(function* () {
670 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
671 yield* broadcaster.getStatus({ cwd: "/repo" });
672 const scope = yield* Scope.make();
673 const snapshotDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
674 yield* Stream.runForEach(
675 broadcaster.streamStatus(
676 { cwd: "/repo" },
677 { automaticRemoteRefreshInterval: Effect.succeed(Duration.minutes(1)) },
678 ),
679 (event) =>
680 event._tag === "snapshot"
681 ? Deferred.succeed(snapshotDeferred, event).pipe(Effect.ignore)
682 : Effect.void,
683 ).pipe(Effect.forkIn(scope));
684​
685 yield* Deferred.await(snapshotDeferred);
686 assert.equal(state.remoteStatusCalls, 1);
687 assert.equal(state.remoteInvalidationCalls, 0);
688​
689 yield* TestClock.adjust(Duration.seconds(59));
690 assert.equal(state.remoteStatusCalls, 1);
691​
692 yield* TestClock.adjust(Duration.seconds(1));
693 yield* Effect.yieldNow;
694 assert.equal(state.remoteStatusCalls, 2);
695 assert.equal(state.remoteInvalidationCalls, 1);
696​
697 yield* Scope.close(scope, Exit.void);
698 }).pipe(Effect.provide(Layer.merge(makeTestLayer(state), TestClock.layer())));
699 });
700​
701 it("backs off remote refresh failures exponentially and honors larger configured intervals", () => {
702 assert.equal(
703 Duration.toMillis(VcsStatusBroadcaster.remoteRefreshFailureDelay(1, Duration.seconds(1))),
704 30_000,
705 );
706 assert.equal(
707 Duration.toMillis(VcsStatusBroadcaster.remoteRefreshFailureDelay(2, Duration.seconds(1))),
708 60_000,
709 );
710 assert.equal(
711 Duration.toMillis(VcsStatusBroadcaster.remoteRefreshFailureDelay(3, Duration.seconds(1))),
712 120_000,
713 );
714 assert.equal(
715 Duration.toMillis(VcsStatusBroadcaster.remoteRefreshFailureDelay(1, Duration.minutes(5))),
716 300_000,
717 );
718 assert.equal(
719 Duration.toMillis(VcsStatusBroadcaster.remoteRefreshFailureDelay(20, Duration.seconds(1))),
720 900_000,
721 );
722 });
723​
724 it("summarizes refresh causes without exposing nested failure details", () => {
725 const nestedCause = new Error("private nested failure detail");
726 const failure = new GitManagerError({
727 operation: "VcsStatusBroadcaster.remoteStatus",
728 cwd: "/private/user/workspace/repo",
729 detail: "private Git failure detail",
730 cause: nestedCause,
731 });
732 const cause = Cause.combine(Cause.fail(failure), Cause.die(new TypeError("private defect")));
733​
734 assert.deepStrictEqual(VcsStatusBroadcaster.remoteRefreshFailureDiagnostics(cause), {
735 reasonCount: 2,
736 failureCount: 1,
737 failureTags: ["GitManagerError"],
738 failureOperations: ["VcsStatusBroadcaster.remoteStatus"],
739 defectCount: 1,
740 defectTags: ["TypeError"],
741 interruptionCount: 0,
742 });
743 });
744​
745 it.effect("does not start automatic remote refreshes without foreground client demand", () => {
746 const state = {
747 currentLocalStatus: baseLocalStatus,
748 currentRemoteStatus: baseRemoteStatus,
749 localStatusCalls: 0,
750 remoteStatusCalls: 0,
751 localInvalidationCalls: 0,
752 remoteInvalidationCalls: 0,
753 };
754 const testLayer = VcsStatusBroadcaster.layer.pipe(
755 Layer.provideMerge(NodeServices.layer),
756 Layer.provide(makeBackgroundPolicyLayer(() => false)),
757 Layer.provide(
758 Layer.mock(GitWorkflowService.GitWorkflowService)({
759 localStatus: () =>
760 Effect.sync(() => {
761 state.localStatusCalls += 1;
762 return state.currentLocalStatus;
763 }),
764 remoteStatus: () =>
765 Effect.sync(() => {
766 state.remoteStatusCalls += 1;
767 return state.currentRemoteStatus;
768 }),
769 invalidateLocalStatus: () =>
770 Effect.sync(() => {
771 state.localInvalidationCalls += 1;
772 }),
773 invalidateRemoteStatus: () =>
774 Effect.sync(() => {
775 state.remoteInvalidationCalls += 1;
776 }),
777 } satisfies Partial<GitWorkflowService.GitWorkflowService["Service"]>),
778 ),
779 );
780​
781 return Effect.gen(function* () {
782 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
783 const snapshot = yield* Stream.runHead(
784 broadcaster.streamStatus(
785 { cwd: "/repo" },
786 { automaticRemoteRefreshInterval: Effect.succeed(Duration.seconds(1)) },
787 ),
788 );
789​
790 assert.isTrue(Option.isSome(snapshot));
791 assert.equal(state.remoteStatusCalls, 0);
792 assert.equal(state.remoteInvalidationCalls, 0);
793 }).pipe(Effect.provide(testLayer));
794 });
795​
796 it.effect("stops the remote poller after the last stream subscriber disconnects", () => {
797 const state = {
798 currentLocalStatus: baseLocalStatus,
799 currentRemoteStatus: baseRemoteStatus,
800 localStatusCalls: 0,
801 remoteStatusCalls: 0,
802 localInvalidationCalls: 0,
803 remoteInvalidationCalls: 0,
804 };
805 let remoteInterruptedDeferred: Deferred.Deferred<void, never> | null = null;
806 let remoteStartedDeferred: Deferred.Deferred<void, never> | null = null;
807 const testLayer = VcsStatusBroadcaster.layer.pipe(
808 Layer.provideMerge(NodeServices.layer),
809 Layer.provide(makeBackgroundPolicyLayer(() => true)),
810 Layer.provide(
811 Layer.mock(GitWorkflowService.GitWorkflowService)({
812 localStatus: () =>
813 Effect.sync(() => {
814 state.localStatusCalls += 1;
815 return state.currentLocalStatus;
816 }),
817 remoteStatus: () =>
818 Effect.sync(() => {
819 state.remoteStatusCalls += 1;
820 }).pipe(
821 Effect.andThen(
822 remoteStartedDeferred
823 ? Deferred.succeed(remoteStartedDeferred, undefined).pipe(Effect.ignore)
824 : Effect.void,
825 ),
826 Effect.andThen(Effect.never as Effect.Effect<VcsStatusRemoteResult | null, never>),
827 Effect.onInterrupt(() =>
828 remoteInterruptedDeferred
829 ? Deferred.succeed(remoteInterruptedDeferred, undefined).pipe(Effect.ignore)
830 : Effect.void,
831 ),
832 ),
833 invalidateLocalStatus: () =>
834 Effect.sync(() => {
835 state.localInvalidationCalls += 1;
836 }),
837 invalidateRemoteStatus: () =>
838 Effect.sync(() => {
839 state.remoteInvalidationCalls += 1;
840 }),
841 } satisfies Partial<GitWorkflowService.GitWorkflowService["Service"]>),
842 ),
843 );
844​
845 return Effect.gen(function* () {
846 const remoteInterrupted = yield* Deferred.make<void>();
847 const remoteStarted = yield* Deferred.make<void>();
848 remoteInterruptedDeferred = remoteInterrupted;
849 remoteStartedDeferred = remoteStarted;
850​
851 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
852 const firstSnapshot = yield* Deferred.make<VcsStatusStreamEvent>();
853 const secondSnapshot = yield* Deferred.make<VcsStatusStreamEvent>();
854 const firstScope = yield* Scope.make();
855 const secondScope = yield* Scope.make();
856 yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) =>
857 event._tag === "snapshot"
858 ? Deferred.succeed(firstSnapshot, event).pipe(Effect.ignore)
859 : Effect.void,
860 ).pipe(Effect.forkIn(firstScope));
861 yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) =>
862 event._tag === "snapshot"
863 ? Deferred.succeed(secondSnapshot, event).pipe(Effect.ignore)
864 : Effect.void,
865 ).pipe(Effect.forkIn(secondScope));
866​
867 yield* Deferred.await(firstSnapshot);
868 yield* Deferred.await(secondSnapshot);
869 yield* Deferred.await(remoteStarted);
870​
871 assert.equal(state.remoteStatusCalls, 1);
872​
873 yield* Scope.close(firstScope, Exit.void);
874 assert.isTrue(Option.isNone(yield* Deferred.poll(remoteInterrupted)));
875​
876 yield* Scope.close(secondScope, Exit.void).pipe(Effect.forkScoped);
877 yield* Deferred.await(remoteInterrupted);
878 assert.isTrue(Option.isSome(yield* Deferred.poll(remoteInterrupted)));
879 }).pipe(Effect.provide(testLayer));
880 });
881});