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