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

VcsStatusBroadcaster.test.ts

1,145 lines42.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("passive streams retain cached remote status", () => {
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(
612 broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }),
613 (event) => {
614 if (event._tag === "snapshot") {
615 return Deferred.succeed(snapshotDeferred, event).pipe(Effect.ignore);
616 }
617 if (event._tag === "remoteUpdated") {
618 return Deferred.succeed(remoteUpdatedDeferred, event).pipe(Effect.ignore);
619 }
620 return Effect.void;
621 },
622 ).pipe(Effect.forkScoped);
623​
624 const snapshot = yield* Deferred.await(snapshotDeferred);
625 yield* TestClock.adjust("1 minute");
626 assert.equal(state.remoteStatusCalls, 0);
627 yield* broadcaster.getStatus({ cwd: "/repo" });
628 state.currentRemoteStatus = remoteStatusWithPr;
629 yield* broadcaster.refreshPullRequestStatus("/repo");
630 const remoteUpdated = yield* Deferred.await(remoteUpdatedDeferred);
631​
632 assert.deepStrictEqual(snapshot, {
633 _tag: "snapshot",
634 local: baseLocalStatus,
635 remote: null,
636 } satisfies VcsStatusStreamEvent);
637 assert.deepStrictEqual(remoteUpdated, {
638 _tag: "remoteUpdated",
639 remote: remoteStatusWithPr,
640 } satisfies VcsStatusStreamEvent);
641 const cachedSnapshot = yield* Stream.runHead(
642 broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }),
643 );
644 assert.deepStrictEqual(Option.getOrThrow(cachedSnapshot), {
645 _tag: "snapshot",
646 local: baseLocalStatus,
647 remote: remoteStatusWithPr,
648 });
649 }).pipe(Effect.provide(layerTestFor(state)));
650 });
651​
652 it.effect("loads remote status once when periodic refreshes are disabled", () => {
653 const state = {
654 currentLocalStatus: baseLocalStatus,
655 currentRemoteStatus: remoteStatusWithPr,
656 localStatusCalls: 0,
657 remoteStatusCalls: 0,
658 localInvalidationCalls: 0,
659 remoteInvalidationCalls: 0,
660 remoteStatusRefreshUpstreamValues: [] as Array<boolean | undefined>,
661 };
662​
663 return Effect.gen(function* () {
664 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
665 const scope = yield* Scope.make();
666 const snapshotDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
667 const remoteUpdatedDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
668 yield* Stream.runForEach(
669 broadcaster.streamStatus(
670 { cwd: "/repo" },
671 { automaticRemoteRefreshInterval: Effect.succeed(Duration.zero) },
672 ),
673 (event) => {
674 if (event._tag === "snapshot") {
675 return Deferred.succeed(snapshotDeferred, event).pipe(Effect.ignore);
676 }
677 if (event._tag === "remoteUpdated") {
678 return Deferred.succeed(remoteUpdatedDeferred, event).pipe(Effect.ignore);
679 }
680 return Effect.void;
681 },
682 ).pipe(Effect.forkIn(scope));
683​
684 const snapshot = yield* Deferred.await(snapshotDeferred);
685 const remoteUpdated = yield* Deferred.await(remoteUpdatedDeferred);
686​
687 assert.deepStrictEqual(snapshot, {
688 _tag: "snapshot",
689 local: baseLocalStatus,
690 remote: null,
691 } satisfies VcsStatusStreamEvent);
692 assert.deepStrictEqual(remoteUpdated, {
693 _tag: "remoteUpdated",
694 remote: remoteStatusWithPr,
695 } satisfies VcsStatusStreamEvent);
696 assert.equal(state.remoteStatusCalls, 1);
697 assert.equal(state.remoteInvalidationCalls, 0);
698 assert.deepStrictEqual(state.remoteStatusRefreshUpstreamValues, [false]);
699​
700 yield* TestClock.adjust(Duration.minutes(2));
701 assert.equal(state.remoteStatusCalls, 1);
702 assert.equal(state.remoteInvalidationCalls, 0);
703​
704 yield* Scope.close(scope, Exit.void);
705 }).pipe(Effect.provide(Layer.merge(layerTestFor(state), TestClock.layer())));
706 });
707​
708 it.effect("retries the initial remote load when periodic refreshes are disabled", () => {
709 const state = {
710 currentLocalStatus: baseLocalStatus,
711 localStatusCalls: 0,
712 remoteStatusCalls: 0,
713 localInvalidationCalls: 0,
714 remoteInvalidationCalls: 0,
715 remoteStatusRefreshUpstreamValues: [] as Array<boolean | undefined>,
716 };
717 const privateCwd = "/private/user/workspace/repo";
718 const nestedCause = new Error("private nested VCS failure");
719 const messages: Array<ReadonlyArray<unknown>> = [];
720 const logger = Logger.make<unknown, void>(({ message }) => {
721 messages.push(message as ReadonlyArray<unknown>);
722 });
723 let firstRemoteAttemptDeferred: Deferred.Deferred<void> | null = null;
724 const layerTest = VcsStatusBroadcaster.layer.pipe(
725 Layer.provideMerge(NodeServices.layer),
726 Layer.provide(layerBackgroundPolicy(() => true)),
727 Layer.provide(
728 Layer.mock(GitWorkflowService.GitWorkflowService)({
729 localStatus: () =>
730 Effect.sync(() => {
731 state.localStatusCalls += 1;
732 return state.currentLocalStatus;
733 }),
734 remoteStatus: (_input, options) =>
735 Effect.suspend(() => {
736 state.remoteStatusCalls += 1;
737 state.remoteStatusRefreshUpstreamValues.push(options?.refreshUpstream);
738 if (state.remoteStatusCalls === 1) {
739 return Effect.fail(
740 new GitManagerError({
741 operation: "VcsStatusBroadcaster.test",
742 cwd: privateCwd,
743 detail: "private initial remote status failure",
744 cause: nestedCause,
745 }),
746 ).pipe(
747 Effect.ensuring(
748 firstRemoteAttemptDeferred
749 ? Deferred.succeed(firstRemoteAttemptDeferred, undefined).pipe(Effect.ignore)
750 : Effect.void,
751 ),
752 );
753 }
754 return Effect.succeed(remoteStatusWithPr);
755 }),
756 invalidateLocalStatus: () =>
757 Effect.sync(() => {
758 state.localInvalidationCalls += 1;
759 }),
760 invalidateRemoteStatus: () =>
761 Effect.sync(() => {
762 state.remoteInvalidationCalls += 1;
763 }),
764 }),
765 ),
766 );
767​
768 return Effect.gen(function* () {
769 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
770 const scope = yield* Scope.make();
771 firstRemoteAttemptDeferred = yield* Deferred.make<void>();
772 const remoteUpdatedDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
773 yield* Stream.runForEach(
774 broadcaster.streamStatus(
775 { cwd: privateCwd },
776 { automaticRemoteRefreshInterval: Effect.succeed(Duration.zero) },
777 ),
778 (event) =>
779 event._tag === "remoteUpdated"
780 ? Deferred.succeed(remoteUpdatedDeferred, event).pipe(Effect.ignore)
781 : Effect.void,
782 ).pipe(Effect.forkIn(scope));
783​
784 yield* Deferred.await(firstRemoteAttemptDeferred);
785 yield* Effect.yieldNow;
786 assert.equal(state.remoteStatusCalls, 1);
787 assert.deepStrictEqual(
788 messages.find((message) => message[0] === "VCS remote status refresh failed"),
789 [
790 "VCS remote status refresh failed",
791 {
792 cwdLength: privateCwd.length,
793 reasonCount: 1,
794 failureCount: 1,
795 failureTags: ["GitManagerError"],
796 failureOperations: ["VcsStatusBroadcaster.test"],
797 defectCount: 0,
798 defectTags: [],
799 interruptionCount: 0,
800 consecutiveFailures: 1,
801 nextDelayMs: 30_000,
802 },
803 ],
804 );
805​
806 yield* TestClock.adjust(Duration.seconds(30));
807 const remoteUpdated = yield* Deferred.await(remoteUpdatedDeferred);
808​
809 assert.deepStrictEqual(remoteUpdated, {
810 _tag: "remoteUpdated",
811 remote: remoteStatusWithPr,
812 } satisfies VcsStatusStreamEvent);
813 assert.equal(state.remoteStatusCalls, 2);
814 assert.equal(state.remoteInvalidationCalls, 0);
815 assert.deepStrictEqual(state.remoteStatusRefreshUpstreamValues, [false, false]);
816​
817 yield* Scope.close(scope, Exit.void);
818 }).pipe(
819 Effect.provide(
820 Layer.mergeAll(
821 layerTest,
822 TestClock.layer(),
823 Logger.layer([logger], { mergeWithExisting: false }),
824 ),
825 ),
826 );
827 });
828​
829 it.effect("delays automatic refresh when a cached remote snapshot is available", () => {
830 const state = {
831 currentLocalStatus: baseLocalStatus,
832 currentRemoteStatus: baseRemoteStatus,
833 localStatusCalls: 0,
834 remoteStatusCalls: 0,
835 localInvalidationCalls: 0,
836 remoteInvalidationCalls: 0,
837 };
838​
839 return Effect.gen(function* () {
840 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
841 yield* broadcaster.getStatus({ cwd: "/repo" });
842 const scope = yield* Scope.make();
843 const snapshotDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
844 yield* Stream.runForEach(
845 broadcaster.streamStatus(
846 { cwd: "/repo" },
847 { automaticRemoteRefreshInterval: Effect.succeed(Duration.minutes(1)) },
848 ),
849 (event) =>
850 event._tag === "snapshot"
851 ? Deferred.succeed(snapshotDeferred, event).pipe(Effect.ignore)
852 : Effect.void,
853 ).pipe(Effect.forkIn(scope));
854​
855 yield* Deferred.await(snapshotDeferred);
856 assert.equal(state.remoteStatusCalls, 1);
857 assert.equal(state.remoteInvalidationCalls, 0);
858​
859 yield* TestClock.adjust(Duration.seconds(59));
860 assert.equal(state.remoteStatusCalls, 1);
861​
862 yield* TestClock.adjust(Duration.seconds(1));
863 yield* Effect.yieldNow;
864 assert.equal(state.remoteStatusCalls, 2);
865 assert.equal(state.remoteInvalidationCalls, 1);
866​
867 yield* Scope.close(scope, Exit.void);
868 }).pipe(Effect.provide(Layer.merge(layerTestFor(state), TestClock.layer())));
869 });
870​
871 // A push from a terminal moves ahead; a PR merged on the host moves ahead-of-default.
872 it.effect.each([
873 ["a push", { ...baseRemoteStatus, aheadCount: 1, aheadOfDefaultCount: 0 }],
874 ["a merged pull request", { ...baseRemoteStatus, aheadOfDefaultCount: 2 }],
875 ] as const)("re-reads local status when a fetch reflects %s", ([, initialRemote]) => {
876 const state = {
877 currentLocalStatus: baseLocalStatus,
878 currentRemoteStatus: initialRemote as VcsStatusRemoteResult | null,
879 localStatusCalls: 0,
880 remoteStatusCalls: 0,
881 localInvalidationCalls: 0,
882 remoteInvalidationCalls: 0,
883 };
884​
885 return Effect.gen(function* () {
886 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
887 yield* broadcaster.getStatus({ cwd: "/repo" });
888 const scope = yield* Scope.make();
889 const snapshotDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
890 const localUpdatedDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
891 yield* Stream.runForEach(
892 broadcaster.streamStatus(
893 { cwd: "/repo" },
894 { automaticRemoteRefreshInterval: Effect.succeed(Duration.minutes(1)) },
895 ),
896 (event) =>
897 event._tag === "snapshot"
898 ? Deferred.succeed(snapshotDeferred, event).pipe(Effect.ignore)
899 : event._tag === "localUpdated"
900 ? Deferred.succeed(localUpdatedDeferred, event).pipe(Effect.ignore)
901 : Effect.void,
902 ).pipe(Effect.forkIn(scope));
903 yield* Deferred.await(snapshotDeferred);
904​
905 // The next fetch moves the base, so the Changes totals shrink.
906 const pushedLocal: VcsStatusLocalResult = {
907 ...baseLocalStatus,
908 branchChanges: { baseRef: "origin/main", insertions: 0, deletions: 0 },
909 };
910 state.currentLocalStatus = pushedLocal;
911 state.currentRemoteStatus = { ...baseRemoteStatus, aheadOfDefaultCount: 0 };
912 yield* TestClock.adjust(Duration.minutes(1));
913​
914 assert.deepStrictEqual(yield* Deferred.await(localUpdatedDeferred), {
915 _tag: "localUpdated",
916 local: pushedLocal,
917 } satisfies VcsStatusStreamEvent);
918 yield* Scope.close(scope, Exit.void);
919 }).pipe(Effect.provide(Layer.merge(layerTestFor(state), TestClock.layer())));
920 });
921​
922 it.effect("an explicit refresh reads local totals after the fetch", () => {
923 const state: Parameters<typeof layerTestFor>[0] = {
924 currentLocalStatus: baseLocalStatus,
925 currentRemoteStatus: baseRemoteStatus,
926 localStatusCalls: 0,
927 remoteStatusCalls: 0,
928 localInvalidationCalls: 0,
929 remoteInvalidationCalls: 0,
930 };
931​
932 return Effect.gen(function* () {
933 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
934 const fetchStarted = yield* Deferred.make<void>();
935 const finishFetch = yield* Deferred.make<void>();
936 state.beforeRemoteStatus = Deferred.succeed(fetchStarted, undefined).pipe(
937 Effect.andThen(Deferred.await(finishFetch)),
938 );
939 const refresh = yield* broadcaster.refreshStatus("/repo").pipe(Effect.forkScoped);
940 yield* Deferred.await(fetchStarted);
941​
942 // The fetch moves the base while it runs, so totals read before it ends would be stale.
943 const fetchedLocal: VcsStatusLocalResult = {
944 ...baseLocalStatus,
945 branchChanges: { baseRef: "origin/main", insertions: 0, deletions: 0 },
946 };
947 state.currentLocalStatus = fetchedLocal;
948 yield* Deferred.succeed(finishFetch, undefined);
949​
950 const status = yield* Fiber.join(refresh);
951 assert.deepStrictEqual(status.branchChanges, fetchedLocal.branchChanges);
952 }).pipe(Effect.provide(layerTestFor(state)));
953 });
954​
955 it("backs off remote refresh failures exponentially and honors larger configured intervals", () => {
956 assert.equal(
957 Duration.toMillis(VcsStatusBroadcaster.remoteRefreshFailureDelay(1, Duration.seconds(1))),
958 30_000,
959 );
960 assert.equal(
961 Duration.toMillis(VcsStatusBroadcaster.remoteRefreshFailureDelay(2, Duration.seconds(1))),
962 60_000,
963 );
964 assert.equal(
965 Duration.toMillis(VcsStatusBroadcaster.remoteRefreshFailureDelay(3, Duration.seconds(1))),
966 120_000,
967 );
968 assert.equal(
969 Duration.toMillis(VcsStatusBroadcaster.remoteRefreshFailureDelay(1, Duration.minutes(5))),
970 300_000,
971 );
972 assert.equal(
973 Duration.toMillis(VcsStatusBroadcaster.remoteRefreshFailureDelay(20, Duration.seconds(1))),
974 900_000,
975 );
976 });
977​
978 it("summarizes refresh causes without exposing nested failure details", () => {
979 const nestedCause = new Error("private nested failure detail");
980 const failure = new GitManagerError({
981 operation: "VcsStatusBroadcaster.remoteStatus",
982 cwd: "/private/user/workspace/repo",
983 detail: "private Git failure detail",
984 cause: nestedCause,
985 });
986 const cause = Cause.combine(Cause.fail(failure), Cause.die(new TypeError("private defect")));
987​
988 assert.deepStrictEqual(VcsStatusBroadcaster.remoteRefreshFailureDiagnostics(cause), {
989 reasonCount: 2,
990 failureCount: 1,
991 failureTags: ["GitManagerError"],
992 failureOperations: ["VcsStatusBroadcaster.remoteStatus"],
993 defectCount: 1,
994 defectTags: ["TypeError"],
995 interruptionCount: 0,
996 });
997 });
998​
999 it.effect("does not start automatic remote refreshes without foreground client demand", () => {
1000 const state = {
1001 currentLocalStatus: baseLocalStatus,
1002 currentRemoteStatus: baseRemoteStatus,
1003 localStatusCalls: 0,
1004 remoteStatusCalls: 0,
1005 localInvalidationCalls: 0,
1006 remoteInvalidationCalls: 0,
1007 };
1008 const layerTest = VcsStatusBroadcaster.layer.pipe(
1009 Layer.provideMerge(NodeServices.layer),
1010 Layer.provide(layerBackgroundPolicy(() => false)),
1011 Layer.provide(
1012 Layer.mock(GitWorkflowService.GitWorkflowService)({
1013 localStatus: () =>
1014 Effect.sync(() => {
1015 state.localStatusCalls += 1;
1016 return state.currentLocalStatus;
1017 }),
1018 remoteStatus: () =>
1019 Effect.sync(() => {
1020 state.remoteStatusCalls += 1;
1021 return state.currentRemoteStatus;
1022 }),
1023 invalidateLocalStatus: () =>
1024 Effect.sync(() => {
1025 state.localInvalidationCalls += 1;
1026 }),
1027 invalidateRemoteStatus: () =>
1028 Effect.sync(() => {
1029 state.remoteInvalidationCalls += 1;
1030 }),
1031 } satisfies Partial<GitWorkflowService.GitWorkflowService["Service"]>),
1032 ),
1033 );
1034​
1035 return Effect.gen(function* () {
1036 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
1037 const snapshot = yield* Stream.runHead(
1038 broadcaster.streamStatus(
1039 { cwd: "/repo" },
1040 { automaticRemoteRefreshInterval: Effect.succeed(Duration.seconds(1)) },
1041 ),
1042 );
1043​
1044 assert.isTrue(Option.isSome(snapshot));
1045 assert.equal(state.remoteStatusCalls, 0);
1046 assert.equal(state.remoteInvalidationCalls, 0);
1047 }).pipe(Effect.provide(layerTest));
1048 });
1049​
1050 it.effect("releases remote demand while passive observers remain", () => {
1051 const state = {
1052 currentLocalStatus: baseLocalStatus,
1053 currentRemoteStatus: baseRemoteStatus,
1054 localStatusCalls: 0,
1055 remoteStatusCalls: 0,
1056 localInvalidationCalls: 0,
1057 remoteInvalidationCalls: 0,
1058 };
1059 let remoteInterruptedDeferred: Deferred.Deferred<void, never> | null = null;
1060 let remoteStartedDeferred: Deferred.Deferred<void, never> | null = null;
1061 const layerTest = VcsStatusBroadcaster.layer.pipe(
1062 Layer.provideMerge(NodeServices.layer),
1063 Layer.provide(layerBackgroundPolicy(() => true)),
1064 Layer.provide(
1065 Layer.mock(GitWorkflowService.GitWorkflowService)({
1066 localStatus: () =>
1067 Effect.sync(() => {
1068 state.localStatusCalls += 1;
1069 return state.currentLocalStatus;
1070 }),
1071 remoteStatus: () =>
1072 Effect.sync(() => {
1073 state.remoteStatusCalls += 1;
1074 }).pipe(
1075 Effect.andThen(
1076 remoteStartedDeferred
1077 ? Deferred.succeed(remoteStartedDeferred, undefined).pipe(Effect.ignore)
1078 : Effect.void,
1079 ),
1080 Effect.andThen(Effect.never as Effect.Effect<VcsStatusRemoteResult | null, never>),
1081 Effect.onInterrupt(() =>
1082 remoteInterruptedDeferred
1083 ? Deferred.succeed(remoteInterruptedDeferred, undefined).pipe(Effect.ignore)
1084 : Effect.void,
1085 ),
1086 ),
1087 invalidateLocalStatus: () =>
1088 Effect.sync(() => {
1089 state.localInvalidationCalls += 1;
1090 }),
1091 invalidateRemoteStatus: () =>
1092 Effect.sync(() => {
1093 state.remoteInvalidationCalls += 1;
1094 }),
1095 } satisfies Partial<GitWorkflowService.GitWorkflowService["Service"]>),
1096 ),
1097 );
1098​
1099 return Effect.gen(function* () {
1100 const remoteInterrupted = yield* Deferred.make<void>();
1101 const remoteStarted = yield* Deferred.make<void>();
1102 remoteInterruptedDeferred = remoteInterrupted;
1103 remoteStartedDeferred = remoteStarted;
1104​
1105 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
1106 const firstSnapshot = yield* Deferred.make<VcsStatusStreamEvent>();
1107 const secondSnapshot = yield* Deferred.make<VcsStatusStreamEvent>();
1108 const firstScope = yield* Scope.make();
1109 const secondScope = yield* Scope.make();
1110 const passiveSnapshot = yield* Deferred.make<VcsStatusStreamEvent>();
1111 yield* Stream.runForEach(
1112 broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }),
1113 (event) =>
1114 event._tag === "snapshot"
1115 ? Deferred.succeed(passiveSnapshot, event).pipe(Effect.ignore)
1116 : Effect.void,
1117 ).pipe(Effect.forkScoped);
1118 yield* Deferred.await(passiveSnapshot);
1119 assert.equal(state.remoteStatusCalls, 0);
1120 yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) =>
1121 event._tag === "snapshot"
1122 ? Deferred.succeed(firstSnapshot, event).pipe(Effect.ignore)
1123 : Effect.void,
1124 ).pipe(Effect.forkIn(firstScope));
1125 yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) =>
1126 event._tag === "snapshot"
1127 ? Deferred.succeed(secondSnapshot, event).pipe(Effect.ignore)
1128 : Effect.void,
1129 ).pipe(Effect.forkIn(secondScope));
1130​
1131 yield* Deferred.await(firstSnapshot);
1132 yield* Deferred.await(secondSnapshot);
1133 yield* Deferred.await(remoteStarted);
1134​
1135 assert.equal(state.remoteStatusCalls, 1);
1136​
1137 yield* Scope.close(firstScope, Exit.void);
1138 assert.isTrue(Option.isNone(yield* Deferred.poll(remoteInterrupted)));
1139​
1140 yield* Scope.close(secondScope, Exit.void).pipe(Effect.forkScoped);
1141 yield* Deferred.await(remoteInterrupted);
1142 assert.isTrue(Option.isSome(yield* Deferred.poll(remoteInterrupted)));
1143 }).pipe(Effect.provide(layerTest));
1144 });
1145});