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

VcsStatusBroadcaster.test.ts

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