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