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

VcsStatusBroadcaster.test.ts

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