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

VcsStatusBroadcaster.test.ts

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