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

VcsStatusBroadcaster.test.ts

716 lines26.9 KB

1import { SourceControlProviderKind } from "@t3tools/contracts";
2import { assert, it, describe } from "@effect/vitest";
3import * as NodeServices from "@effect/platform-node/NodeServices";
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 Option from "effect/Option";
13import * as Path from "effect/Path";
14import * as Scope from "effect/Scope";
15import * as Stream from "effect/Stream";
16import * as TestClock from "effect/testing/TestClock";
17import type {
18 BackgroundScope,
19 VcsStatusLocalResult,
20 VcsStatusRemoteResult,
21 VcsStatusResult,
22 VcsStatusStreamEvent,
23} from "@t3tools/contracts";
24import { GitManagerError } from "@t3tools/contracts";
25​
26import * as VcsStatusBroadcaster from "./VcsStatusBroadcaster.ts";
27import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
28import * as GitWorkflowService from "../git/GitWorkflowService.ts";
29import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
30​
31const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
32​
33const baseLocalStatus: VcsStatusLocalResult = {
34 isRepo: true,
35 sourceControlProvider: {
36 kind: SourceControlProviderKind.make("github"),
37 name: "GitHub",
38 baseUrl: "https://github.com",
39 },
40 hasPrimaryRemote: true,
41 isDefaultRef: false,
42 refName: "feature/status-broadcast",
43 hasWorkingTreeChanges: false,
44 workingTree: { files: [], insertions: 0, deletions: 0 },
45};
46​
47const baseRemoteStatus: VcsStatusRemoteResult = {
48 hasUpstream: true,
49 aheadCount: 0,
50 behindCount: 0,
51 pr: null,
52};
53​
54const remoteStatusWithPr: VcsStatusRemoteResult = {
55 ...baseRemoteStatus,
56 pr: {
57 number: 2978,
58 title: "[codex] Rewrite client connection architecture",
59 url: "https://github.com/pingdotgg/t3code/pull/2978",
60 baseRef: "main",
61 headRef: "codex/connection-state-audit",
62 state: "open",
63 },
64};
65​
66const baseStatus: VcsStatusResult = {
67 ...baseLocalStatus,
68 ...baseRemoteStatus,
69};
70​
71function layerTestFor(state: {
72 currentLocalStatus: VcsStatusLocalResult;
73 currentRemoteStatus: VcsStatusRemoteResult | null;
74 localStatusCalls: number;
75 remoteStatusCalls: number;
76 localInvalidationCalls: number;
77 remoteInvalidationCalls: number;
78 remoteStatusRefreshUpstreamValues?: Array<boolean | undefined>;
79 backgroundWorkEnabled?: boolean;
80 automaticFetchInterval?: Effect.Effect<Duration.Duration>;
81 beforeRemoteStatus?: Effect.Effect<void>;
82}) {
83 return VcsStatusBroadcaster.layer.pipe(
84 Layer.provideMerge(NodeServices.layer),
85 Layer.provide(layerBackgroundPolicy(() => state.backgroundWorkEnabled !== false)),
86 Layer.provide(
87 Layer.succeed(
88 VcsStatusBroadcaster.VcsAutomaticFetchInterval,
89 state.automaticFetchInterval ?? Effect.succeed(Duration.seconds(30)),
90 ),
91 ),
92 Layer.provide(
93 Layer.mock(GitWorkflowService.GitWorkflowService)({
94 localStatus: () =>
95 Effect.sync(() => {
96 state.localStatusCalls += 1;
97 return state.currentLocalStatus;
98 }),
99 remoteStatus: (_input, options) =>
100 Effect.suspend(() => state.beforeRemoteStatus ?? Effect.void).pipe(
101 Effect.andThen(
102 Effect.sync(() => {
103 state.remoteStatusCalls += 1;
104 state.remoteStatusRefreshUpstreamValues?.push(options?.refreshUpstream);
105 return state.currentRemoteStatus;
106 }),
107 ),
108 ),
109 invalidateLocalStatus: () =>
110 Effect.sync(() => {
111 state.localInvalidationCalls += 1;
112 }),
113 invalidateRemoteStatus: () =>
114 Effect.sync(() => {
115 state.remoteInvalidationCalls += 1;
116 }),
117 invalidateStatus: () =>
118 Effect.sync(() => {
119 state.localInvalidationCalls += 1;
120 state.remoteInvalidationCalls += 1;
121 }),
122 }),
123 ),
124 );
126​
127function layerBackgroundPolicy(shouldRunScopeWork: (scope: BackgroundScope) => boolean) {
128 return Layer.mock(BackgroundPolicy.BackgroundPolicy)({
129 reportClientActivity: () => Effect.void,
130 removeRpcClient: () => Effect.void,
131 reportHostPowerState: () => Effect.void,
132 snapshot: Effect.succeed({
133 hostPower: {
134 source: "unknown",
135 idle: "unknown",
136 idleSeconds: null,
137 locked: "unknown",
138 suspended: false,
139 onBattery: "unknown",
140 lowPowerMode: "unknown",
141 thermalState: "unknown",
142 stale: true,
143 updatedAt: TEST_EPOCH,
144 },
145 leases: [],
146 activeForegroundLeaseCount: 0,
147 activeScopeKeys: [],
148 shouldRunOpportunisticWork: false,
149 updatedAt: TEST_EPOCH,
150 }),
151 streamChanges: Stream.empty,
152 hasDemand: () => Effect.succeed(true),
153 shouldRunScopeWork: (scope) => Effect.sync(() => shouldRunScopeWork(scope)),
154 shouldRunOpportunisticWork: Effect.succeed(true),
155 });
157​
158describe("VcsStatusBroadcaster", () => {
159 it.effect("publishes a terminal branch switch without reading remote status", () => {
160 const state = {
161 currentLocalStatus: baseLocalStatus,
162 currentRemoteStatus: remoteStatusWithPr,
163 localStatusCalls: 0,
164 remoteStatusCalls: 0,
165 localInvalidationCalls: 0,
166 remoteInvalidationCalls: 0,
167 };
168​
169 return Effect.gen(function* () {
170 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
171 yield* broadcaster.getStatus({ cwd: "/repo" });
172 const subscribed = yield* Deferred.make<void>();
173 const events = yield* broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }).pipe(
174 Stream.tap((event) =>
175 event._tag === "snapshot" ? Deferred.succeed(subscribed, undefined) : Effect.void,
176 ),
177 Stream.take(2),
178 Stream.runCollect,
179 Effect.forkScoped,
180 );
181 yield* Deferred.await(subscribed);
182​
183 state.currentLocalStatus = { ...baseLocalStatus, refName: "main" };
184 const refreshed = yield* broadcaster.refreshStatus("/repo", { localOnly: true });
185 assert.equal(refreshed.refName, "main");
186 assert.isNull(refreshed.pr);
187 assert.equal(state.localInvalidationCalls, 1);
188 assert.equal(state.remoteStatusCalls, 1);
189 assert.equal(state.remoteInvalidationCalls, 1);
190 assert.deepStrictEqual((yield* Fiber.join(events))[1], {
191 _tag: "snapshot",
192 local: state.currentLocalStatus,
193 remote: null,
194 });
195 assert.isNull((yield* broadcaster.getStatus({ cwd: "/repo" })).pr);
196 const snapshot = yield* broadcaster
197 .streamStatus({ cwd: "/repo", includeRemote: false })
198 .pipe(Stream.take(1), Stream.runCollect);
199 assert.deepStrictEqual(snapshot[0], {
200 _tag: "snapshot",
201 local: state.currentLocalStatus,
202 remote: null,
203 });
204 }).pipe(Effect.provide(layerTestFor(state)));
205 });
206​
207 it.effect(
208 "preserves cached remote status when a local-only refresh stays on the same branch",
209 () => {
210 const state = {
211 currentLocalStatus: baseLocalStatus,
212 currentRemoteStatus: { ...remoteStatusWithPr, aheadCount: 2, behindCount: 3 },
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 const initial = yield* broadcaster.getStatus({ cwd: "/repo" });
222 const refreshed = yield* broadcaster.refreshStatus("/repo", { localOnly: true });
223 assert.deepStrictEqual(refreshed, initial);
224 assert.deepStrictEqual(yield* broadcaster.getStatus({ cwd: "/repo" }), refreshed);
225 assert.equal(state.localInvalidationCalls, 1);
226 assert.equal(state.remoteInvalidationCalls, 0);
227 assert.equal(state.remoteStatusCalls, 1);
228 }).pipe(Effect.provide(layerTestFor(state)));
229 },
230 );
231​
232 it.effect("clears the previous branch's remote status after an in-flight PR refresh", () => {
233 const remoteReadStarted = Deferred.makeUnsafe<void>();
234 const releaseRemoteRead = Deferred.makeUnsafe<void>();
235 const state = {
236 currentLocalStatus: baseLocalStatus,
237 currentRemoteStatus: remoteStatusWithPr,
238 localStatusCalls: 0,
239 remoteStatusCalls: 0,
240 localInvalidationCalls: 0,
241 remoteInvalidationCalls: 0,
242 beforeRemoteStatus: Effect.void,
243 };
244​
245 return Effect.gen(function* () {
246 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
247 yield* broadcaster.getStatus({ cwd: "/repo" });
248 state.beforeRemoteStatus = Deferred.succeed(remoteReadStarted, undefined).pipe(
249 Effect.andThen(Deferred.await(releaseRemoteRead)),
250 );
251 const remoteRefresh = yield* broadcaster
252 .refreshPullRequestStatus("/repo")
253 .pipe(Effect.forkScoped);
254 yield* Deferred.await(remoteReadStarted);
255 state.currentLocalStatus = { ...baseLocalStatus, refName: "main" };
256 const localRefresh = yield* broadcaster
257 .refreshStatus("/repo", { localOnly: true })
258 .pipe(Effect.forkScoped);
259 yield* Deferred.succeed(releaseRemoteRead, undefined);
260 yield* Fiber.join(remoteRefresh);
261 yield* Fiber.join(localRefresh);
262​
263 const status = yield* broadcaster.getStatus({ cwd: "/repo" });
264 assert.equal(status.refName, "main");
265 assert.isNull(status.pr);
266 assert.equal(status.aheadCount, 0);
267 assert.equal(status.behindCount, 0);
268 assert.equal(state.remoteStatusCalls, 2);
269 }).pipe(Effect.provide(layerTestFor(state)));
270 });
271​
272 it.effect.skipIf(!symlinksSupported)(
273 "automatically pulls an enabled clean default branch when status detects it is behind",
274 () => {
275 let remoteStatus: VcsStatusRemoteResult = { ...baseRemoteStatus, behindCount: 2 };
276 let pullCalls = 0;
277 let configuredWorkspaceRoot = "";
278 const localStatus: VcsStatusLocalResult = {
279 ...baseLocalStatus,
280 isDefaultRef: true,
281 refName: "main",
282 };
283 const layerTest = VcsStatusBroadcaster.layer.pipe(
284 Layer.provideMerge(NodeServices.layer),
285 Layer.provide(layerBackgroundPolicy(() => true)),
286 Layer.provide(
287 Layer.succeed(VcsStatusBroadcaster.VcsAutoPullPolicy, {
288 isEnabled: (cwd) => Effect.succeed(cwd === configuredWorkspaceRoot),
289 }),
290 ),
291 Layer.provide(
292 Layer.mock(GitWorkflowService.GitWorkflowService)({
293 localStatus: () => Effect.succeed(localStatus),
294 remoteStatus: () => Effect.succeed(remoteStatus),
295 invalidateLocalStatus: () => Effect.void,
296 invalidateRemoteStatus: () => Effect.void,
297 invalidateStatus: () => Effect.void,
298 pullCurrentBranch: () =>
299 Effect.sync(() => {
300 pullCalls += 1;
301 remoteStatus = { ...remoteStatus, behindCount: 0 };
302 return {
303 status: "pulled" as const,
304 refName: "main",
305 upstreamRef: "origin/main",
306 };
307 }),
308 }),
309 ),
310 );
311​
312 return Effect.gen(function* () {
313 const fileSystem = yield* FileSystem.FileSystem;
314 const path = yield* Path.Path;
315 const realDir = yield* fileSystem.makeTempDirectoryScoped({
316 prefix: "t3-vcs-auto-pull-real-",
317 });
318 const linkParent = yield* fileSystem.makeTempDirectoryScoped({
319 prefix: "t3-vcs-auto-pull-link-",
320 });
321 configuredWorkspaceRoot = path.join(linkParent, "repo-link");
322 yield* fileSystem.symlink(realDir, configuredWorkspaceRoot);
323​
324 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
325 const status = yield* broadcaster.refreshStatus(configuredWorkspaceRoot);
326​
327 assert.equal(pullCalls, 1);
328 assert.equal(status.behindCount, 0);
329 }).pipe(Effect.provide(layerTest));
330 },
331 );
332​
333 it.effect("refreshes a loaded cwd without reusing a previous branch's PR", () => {
334 const state = {
335 currentLocalStatus: baseLocalStatus,
336 currentRemoteStatus: baseRemoteStatus,
337 localStatusCalls: 0,
338 remoteStatusCalls: 0,
339 localInvalidationCalls: 0,
340 remoteInvalidationCalls: 0,
341 };
342​
343 return Effect.gen(function* () {
344 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
345​
346 assert.isNull(yield* broadcaster.refreshPullRequestStatus("/repo"));
347 assert.equal(state.remoteStatusCalls, 0);
348​
349 yield* broadcaster.getStatus({ cwd: "/repo" });
350 assert.equal(state.remoteStatusCalls, 1);
351​
352 state.currentRemoteStatus = remoteStatusWithPr;
353 const refreshed = yield* broadcaster.refreshPullRequestStatus("/repo");
354 assert.deepStrictEqual(refreshed, remoteStatusWithPr);
355 assert.equal(state.remoteStatusCalls, 2);
356 assert.equal(state.remoteInvalidationCalls, 0);
357​
358 state.currentLocalStatus = { ...baseLocalStatus, refName: "feature/next" };
359 state.currentRemoteStatus = baseRemoteStatus;
360 yield* broadcaster.refreshLocalStatus("/repo");
361 const refreshedBranch = yield* broadcaster.refreshPullRequestStatus("/repo");
362 assert.deepStrictEqual(refreshedBranch, baseRemoteStatus);
363 assert.equal(state.remoteStatusCalls, 3);
364 }).pipe(Effect.provide(layerTestFor(state)));
365 });
366​
367 it.effect("a poll that started before the turn-end refresh cannot overwrite its PR", () => {
368 const releaseFirstPoll = Deferred.makeUnsafe<void>();
369 const firstPollStarted = Deferred.makeUnsafe<void>();
370 let remoteReads = 0;
371 const layer = VcsStatusBroadcaster.layer.pipe(
372 Layer.provideMerge(NodeServices.layer),
373 Layer.provide(layerBackgroundPolicy(() => true)),
374 Layer.provide(
375 Layer.mock(GitWorkflowService.GitWorkflowService)({
376 localStatus: () => Effect.succeed(baseLocalStatus),
377 remoteStatus: () =>
378 Effect.gen(function* () {
379 remoteReads += 1;
380 if (remoteReads === 2) {
381 yield* Deferred.succeed(firstPollStarted, undefined);
382 yield* Deferred.await(releaseFirstPoll);
383 return baseRemoteStatus;
384 }
385 return remoteReads === 1 ? baseRemoteStatus : remoteStatusWithPr;
386 }),
387 invalidateLocalStatus: () => Effect.void,
388 invalidateRemoteStatus: () => Effect.void,
389 invalidateStatus: () => Effect.void,
390 }),
391 ),
392 );
393​
394 return Effect.gen(function* () {
395 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
396 yield* broadcaster.getStatus({ cwd: "/repo" });
397​
398 const poll = yield* broadcaster.refreshStatus("/repo").pipe(Effect.forkScoped);
399 yield* Deferred.await(firstPollStarted);
400 const refresh = yield* broadcaster.refreshPullRequestStatus("/repo").pipe(Effect.forkScoped);
401 yield* Deferred.succeed(releaseFirstPoll, undefined);
402 yield* Fiber.join(poll);
403 const refreshed = yield* Fiber.join(refresh);
404​
405 assert.deepStrictEqual(refreshed, remoteStatusWithPr);
406 const final = yield* broadcaster.getStatus({ cwd: "/repo" });
407 assert.deepStrictEqual(final.pr, remoteStatusWithPr.pr);
408 }).pipe(Effect.provide(layer), Effect.scoped);
409 });
410​
411 it.effect("an initial status read cannot overwrite an explicit refresh", () => {
412 const firstReadStarted = Deferred.makeUnsafe<void>();
413 const releaseFirstRead = Deferred.makeUnsafe<void>();
414 let remoteReads = 0;
415 const layer = VcsStatusBroadcaster.layer.pipe(
416 Layer.provide(FileSystem.layerNoop({ realPath: (path) => Effect.succeed(path) })),
417 Layer.provideMerge(NodeServices.layer),
418 Layer.provide(layerBackgroundPolicy(() => true)),
419 Layer.provide(
420 Layer.mock(GitWorkflowService.GitWorkflowService)({
421 localStatus: () => Effect.succeed(baseLocalStatus),
422 remoteStatus: () =>
423 Effect.gen(function* () {
424 remoteReads += 1;
425 if (remoteReads === 1) {
426 yield* Deferred.succeed(firstReadStarted, undefined);
427 yield* Deferred.await(releaseFirstRead);
428 return baseRemoteStatus;
429 }
430 return remoteStatusWithPr;
431 }),
432 invalidateStatus: () => Effect.void,
433 }),
434 ),
435 );
436 return Effect.gen(function* () {
437 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
438 const initial = yield* broadcaster.getStatus({ cwd: "/repo" }).pipe(Effect.forkScoped);
439 yield* Deferred.await(firstReadStarted);
440 const refresh = yield* broadcaster.refreshStatus("/repo").pipe(Effect.forkScoped);
441 yield* TestClock.adjust(Duration.zero);
442 yield* Deferred.succeed(releaseFirstRead, undefined);
443 yield* Fiber.join(initial);
444 yield* Fiber.join(refresh);
445 assert.deepStrictEqual(
446 (yield* broadcaster.getStatus({ cwd: "/repo" })).pr,
447 remoteStatusWithPr.pr,
448 );
449 }).pipe(Effect.provide(layer), Effect.scoped);
450 });
451​
452 it.effect("keeps the cached snapshot unchanged when a refresh branch fails", () => {
453 const state = {
454 currentLocalStatus: baseLocalStatus,
455 currentRemoteStatus: baseRemoteStatus,
456 localStatusCalls: 0,
457 remoteStatusCalls: 0,
458 localInvalidationCalls: 0,
459 remoteInvalidationCalls: 0,
460 failRemoteStatus: false,
461 };
462 const layerTest = VcsStatusBroadcaster.layer.pipe(
463 Layer.provideMerge(NodeServices.layer),
464 Layer.provide(layerBackgroundPolicy(() => true)),
465 Layer.provide(
466 Layer.mock(GitWorkflowService.GitWorkflowService)({
467 localStatus: () =>
468 Effect.sync(() => {
469 state.localStatusCalls += 1;
470 return state.currentLocalStatus;
471 }),
472 remoteStatus: () =>
473 Effect.suspend(() => {
474 state.remoteStatusCalls += 1;
475 return state.failRemoteStatus
476 ? Effect.fail(
477 new GitManagerError({
478 operation: "VcsStatusBroadcaster.test",
479 cwd: "/repo",
480 detail: "remote status failed",
481 }),
482 )
483 : Effect.succeed(state.currentRemoteStatus);
484 }),
485 invalidateLocalStatus: () =>
486 Effect.sync(() => {
487 state.localInvalidationCalls += 1;
488 }),
489 invalidateRemoteStatus: () =>
490 Effect.sync(() => {
491 state.remoteInvalidationCalls += 1;
492 }),
493 invalidateStatus: () =>
494 Effect.sync(() => {
495 state.localInvalidationCalls += 1;
496 state.remoteInvalidationCalls += 1;
497 }),
498 }),
499 ),
500 );
501​
502 return Effect.gen(function* () {
503 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
504 yield* broadcaster.getStatus({ cwd: "/repo" });
505​
506 state.currentLocalStatus = {
507 ...baseLocalStatus,
508 refName: "feature/partial-refresh",
509 };
510 state.currentRemoteStatus = {
511 ...baseRemoteStatus,
512 aheadCount: 3,
513 };
514 state.failRemoteStatus = true;
515​
516 const refreshExit = yield* broadcaster.refreshStatus("/repo").pipe(Effect.exit);
517 const cached = yield* broadcaster.getStatus({ cwd: "/repo" });
518​
519 assert.isTrue(Exit.isFailure(refreshExit));
520 assert.deepStrictEqual(cached, baseStatus);
521 }).pipe(Effect.provide(layerTest));
522 });
523​
524 it.effect.skipIf(!symlinksSupported)(
525 "normalizes symlinked CWDs before cache lookup and workflow calls",
526 () => {
527 const seenCwds: string[] = [];
528 const state = {
529 currentLocalStatus: baseLocalStatus,
530 currentRemoteStatus: baseRemoteStatus,
531 localStatusCalls: 0,
532 remoteStatusCalls: 0,
533 localInvalidationCalls: 0,
534 remoteInvalidationCalls: 0,
535 };
536 const layerTest = VcsStatusBroadcaster.layer.pipe(
537 Layer.provideMerge(NodeServices.layer),
538 Layer.provide(layerBackgroundPolicy(() => true)),
539 Layer.provide(
540 Layer.mock(GitWorkflowService.GitWorkflowService)({
541 localStatus: (input) =>
542 Effect.sync(() => {
543 seenCwds.push(input.cwd);
544 state.localStatusCalls += 1;
545 return state.currentLocalStatus;
546 }),
547 remoteStatus: (input) =>
548 Effect.sync(() => {
549 seenCwds.push(input.cwd);
550 state.remoteStatusCalls += 1;
551 return state.currentRemoteStatus;
552 }),
553 invalidateLocalStatus: () =>
554 Effect.sync(() => {
555 state.localInvalidationCalls += 1;
556 }),
557 invalidateRemoteStatus: () =>
558 Effect.sync(() => {
559 state.remoteInvalidationCalls += 1;
560 }),
561 } satisfies Partial<GitWorkflowService.GitWorkflowService["Service"]>),
562 ),
563 );
564​
565 return Effect.gen(function* () {
566 const fileSystem = yield* FileSystem.FileSystem;
567 const path = yield* Path.Path;
568 const realDir = yield* fileSystem.makeTempDirectoryScoped({
569 prefix: "t3-vcs-status-real-",
570 });
571 const linkParent = yield* fileSystem.makeTempDirectoryScoped({
572 prefix: "t3-vcs-status-link-",
573 });
574 const linkDir = path.join(linkParent, "repo-link");
575 yield* fileSystem.symlink(realDir, linkDir);
576 const realPath = yield* fileSystem.realPath(realDir);
577​
578 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
579 yield* broadcaster.getStatus({ cwd: linkDir });
580 yield* broadcaster.getStatus({ cwd: realDir });
581​
582 assert.deepStrictEqual(seenCwds, [realPath, realPath]);
583 assert.equal(state.localStatusCalls, 1);
584 assert.equal(state.remoteStatusCalls, 1);
585 }).pipe(Effect.provide(layerTest));
586 },
587 );
588​
589 it.effect("an explicit refresh reads local totals after the fetch", () => {
590 const state: Parameters<typeof layerTestFor>[0] = {
591 currentLocalStatus: baseLocalStatus,
592 currentRemoteStatus: baseRemoteStatus,
593 localStatusCalls: 0,
594 remoteStatusCalls: 0,
595 localInvalidationCalls: 0,
596 remoteInvalidationCalls: 0,
597 };
598​
599 return Effect.gen(function* () {
600 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
601 const fetchStarted = yield* Deferred.make<void>();
602 const finishFetch = yield* Deferred.make<void>();
603 state.beforeRemoteStatus = Deferred.succeed(fetchStarted, undefined).pipe(
604 Effect.andThen(Deferred.await(finishFetch)),
605 );
606 const refresh = yield* broadcaster.refreshStatus("/repo").pipe(Effect.forkScoped);
607 yield* Deferred.await(fetchStarted);
608​
609 const fetchedLocal: VcsStatusLocalResult = {
610 ...baseLocalStatus,
611 branchChanges: { baseRef: "origin/main", insertions: 0, deletions: 0 },
612 };
613 state.currentLocalStatus = fetchedLocal;
614 yield* Deferred.succeed(finishFetch, undefined);
615​
616 const status = yield* Fiber.join(refresh);
617 assert.deepStrictEqual(status.branchChanges, fetchedLocal.branchChanges);
618 }).pipe(Effect.provide(layerTestFor(state)));
619 });
620​
621 it.effect("releases remote demand while passive observers remain", () => {
622 const state = {
623 currentLocalStatus: baseLocalStatus,
624 currentRemoteStatus: baseRemoteStatus,
625 localStatusCalls: 0,
626 remoteStatusCalls: 0,
627 localInvalidationCalls: 0,
628 remoteInvalidationCalls: 0,
629 };
630 let remoteInterruptedDeferred: Deferred.Deferred<void, never> | null = null;
631 let remoteStartedDeferred: Deferred.Deferred<void, never> | null = null;
632 const layerTest = VcsStatusBroadcaster.layer.pipe(
633 Layer.provideMerge(NodeServices.layer),
634 Layer.provide(layerBackgroundPolicy(() => true)),
635 Layer.provide(
636 Layer.mock(GitWorkflowService.GitWorkflowService)({
637 localStatus: () =>
638 Effect.sync(() => {
639 state.localStatusCalls += 1;
640 return state.currentLocalStatus;
641 }),
642 remoteStatus: () =>
643 Effect.sync(() => {
644 state.remoteStatusCalls += 1;
645 }).pipe(
646 Effect.andThen(
647 remoteStartedDeferred
648 ? Deferred.succeed(remoteStartedDeferred, undefined).pipe(Effect.ignore)
649 : Effect.void,
650 ),
651 Effect.andThen(Effect.never as Effect.Effect<VcsStatusRemoteResult | null, never>),
652 Effect.onInterrupt(() =>
653 remoteInterruptedDeferred
654 ? Deferred.succeed(remoteInterruptedDeferred, undefined).pipe(Effect.ignore)
655 : Effect.void,
656 ),
657 ),
658 invalidateLocalStatus: () =>
659 Effect.sync(() => {
660 state.localInvalidationCalls += 1;
661 }),
662 invalidateRemoteStatus: () =>
663 Effect.sync(() => {
664 state.remoteInvalidationCalls += 1;
665 }),
666 } satisfies Partial<GitWorkflowService.GitWorkflowService["Service"]>),
667 ),
668 );
669​
670 return Effect.gen(function* () {
671 const remoteInterrupted = yield* Deferred.make<void>();
672 const remoteStarted = yield* Deferred.make<void>();
673 remoteInterruptedDeferred = remoteInterrupted;
674 remoteStartedDeferred = remoteStarted;
675​
676 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
677 const firstSnapshot = yield* Deferred.make<VcsStatusStreamEvent>();
678 const secondSnapshot = yield* Deferred.make<VcsStatusStreamEvent>();
679 const firstScope = yield* Scope.make();
680 const secondScope = yield* Scope.make();
681 const passiveSnapshot = yield* Deferred.make<VcsStatusStreamEvent>();
682 yield* Stream.runForEach(
683 broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }),
684 (event) =>
685 event._tag === "snapshot"
686 ? Deferred.succeed(passiveSnapshot, event).pipe(Effect.ignore)
687 : Effect.void,
688 ).pipe(Effect.forkScoped);
689 yield* Deferred.await(passiveSnapshot);
690 assert.equal(state.remoteStatusCalls, 0);
691 yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) =>
692 event._tag === "snapshot"
693 ? Deferred.succeed(firstSnapshot, event).pipe(Effect.ignore)
694 : Effect.void,
695 ).pipe(Effect.forkIn(firstScope));
696 yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) =>
697 event._tag === "snapshot"
698 ? Deferred.succeed(secondSnapshot, event).pipe(Effect.ignore)
699 : Effect.void,
700 ).pipe(Effect.forkIn(secondScope));
701​
702 yield* Deferred.await(firstSnapshot);
703 yield* Deferred.await(secondSnapshot);
704 yield* Deferred.await(remoteStarted);
705​
706 assert.equal(state.remoteStatusCalls, 1);
707​
708 yield* Scope.close(firstScope, Exit.void);
709 assert.isTrue(Option.isNone(yield* Deferred.poll(remoteInterrupted)));
710​
711 yield* Scope.close(secondScope, Exit.void).pipe(Effect.forkScoped);
712 yield* Deferred.await(remoteInterrupted);
713 assert.isTrue(Option.isSome(yield* Deferred.poll(remoteInterrupted)));
714 }).pipe(Effect.provide(layerTest));
715 });
716});