Open History to see the last commit
1import * as Cause from "effect/Cause";
2import * as Context from "effect/Context";
3import * as Duration from "effect/Duration";
4import * as Effect from "effect/Effect";
5import * as Exit from "effect/Exit";
6import * as Fiber from "effect/Fiber";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as PubSub from "effect/PubSub";
10import * as Ref from "effect/Ref";
11import * as Schedule from "effect/Schedule";
12import * as Scope from "effect/Scope";
13import * as Semaphore from "effect/Semaphore";
14import * as Stream from "effect/Stream";
15import * as SynchronizedRef from "effect/SynchronizedRef";
16import type {
17 GitManagerServiceError,
18 VcsStatusInput,
19 VcsStatusLocalResult,
20 VcsStatusRemoteResult,
21 VcsStatusResult,
22 VcsStatusStreamEvent,
23} from "@t3tools/contracts";
24import { mergeGitStatusParts } from "@t3tools/shared/git";
25
26import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
27import * as GitWorkflowService from "../git/GitWorkflowService.ts";
28import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
29
30const DEFAULT_VCS_STATUS_REFRESH_INTERVAL = Duration.seconds(30);
31const VCS_STATUS_REFRESH_FAILURE_BASE_DELAY = Duration.seconds(30);
32const VCS_STATUS_REFRESH_FAILURE_MAX_DELAY = Duration.minutes(15);
33const MAX_FAILURE_DIAGNOSTIC_VALUES = 8;
34const MAX_FAILURE_DIAGNOSTIC_VALUE_LENGTH = 128;
35
36function boundedDiagnosticValue(value: string): string {
37 return value.slice(0, MAX_FAILURE_DIAGNOSTIC_VALUE_LENGTH);
38}
39
40function diagnosticValueTag(value: unknown): string {
41 try {
42 if (
43 typeof value === "object" &&
44 value !== null &&
45 "_tag" in value &&
46 typeof value._tag === "string"
47 ) {
48 return boundedDiagnosticValue(value._tag);
49 }
50 if (value instanceof Error) {
51 return boundedDiagnosticValue(value.name);
52 }
53 return typeof value;
54 } catch {
55 return "Uninspectable";
56 }
57}
58
59function diagnosticFailureOperation(value: unknown): string | undefined {
60 try {
61 if (
62 typeof value === "object" &&
63 value !== null &&
64 "operation" in value &&
65 typeof value.operation === "string"
66 ) {
67 return boundedDiagnosticValue(value.operation);
68 }
69 } catch {
70 return undefined;
71 }
72 return undefined;
73}
74
75function addUniqueDiagnosticValue(values: Array<string>, value: string | undefined): void {
76 if (
77 value !== undefined &&
78 values.length < MAX_FAILURE_DIAGNOSTIC_VALUES &&
79 !values.includes(value)
80 ) {
81 values.push(value);
82 }
83}
84
85export function remoteRefreshFailureDiagnostics(cause: Cause.Cause<unknown>) {
86 const failureTags: Array<string> = [];
87 const failureOperations: Array<string> = [];
88 const defectTags: Array<string> = [];
89 let failureCount = 0;
90 let defectCount = 0;
91 let interruptionCount = 0;
92
93 for (const reason of cause.reasons) {
94 if (Cause.isFailReason(reason)) {
95 failureCount += 1;
96 addUniqueDiagnosticValue(failureTags, diagnosticValueTag(reason.error));
97 addUniqueDiagnosticValue(failureOperations, diagnosticFailureOperation(reason.error));
98 continue;
99 }
100 if (Cause.isDieReason(reason)) {
101 defectCount += 1;
102 addUniqueDiagnosticValue(defectTags, diagnosticValueTag(reason.defect));
103 continue;
104 }
105 interruptionCount += 1;
106 }
107
108 return {
109 reasonCount: cause.reasons.length,
110 failureCount,
111 failureTags,
112 failureOperations,
113 defectCount,
114 defectTags,
115 interruptionCount,
116 };
117}
118
119interface VcsStatusChange {
120 readonly cwd: string;
121 readonly event: VcsStatusStreamEvent;
122}
123
124interface CachedValue<T> {
125 readonly fingerprint: string;
126 readonly value: T;
127}
128
129interface CachedVcsStatus {
130 readonly local: CachedValue<VcsStatusLocalResult> | null;
131 readonly remote: CachedValue<VcsStatusRemoteResult | null> | null;
132}
133
134interface ActiveRemotePoller {
135 readonly fiber: Fiber.Fiber<void, never>;
136 readonly subscriberCount: number;
137 readonly demandCwds: Ref.Ref<ReadonlyMap<string, number>>;
138}
139
140interface StreamStatusOptions {
141 readonly automaticRemoteRefreshInterval?: Effect.Effect<Duration.Duration, never>;
142}
143
144export class VcsAutoPullPolicy extends Context.Reference<{
145 readonly isEnabled: (cwd: string) => Effect.Effect<boolean, never>;
146}>("t3/vcs/VcsAutoPullPolicy", {
147 defaultValue: () => ({ isEnabled: () => Effect.succeed(false) }),
148}) {}
149
150export const autoPullPolicyLayer = Layer.effect(
151 VcsAutoPullPolicy,
152 Effect.gen(function* () {
153 const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
154 return {
155 isEnabled: (cwd: string) =>
156 snapshots.getActiveProjectByWorkspaceRoot(cwd).pipe(
157 Effect.map((project) => project._tag === "Some" && project.value.autoPull === true),
158 Effect.orElseSucceed(() => false),
159 ),
160 };
161 }),
162);
163
164export function remoteRefreshFailureDelay(
165 consecutiveFailures: number,
166 configuredInterval: Duration.Duration,
167) {
168 const exponent = Math.max(0, consecutiveFailures - 1);
169 const backoffMs =
170 Duration.toMillis(VCS_STATUS_REFRESH_FAILURE_BASE_DELAY) * Math.pow(2, exponent);
171 const cappedBackoff = Duration.min(
172 Duration.millis(backoffMs),
173 VCS_STATUS_REFRESH_FAILURE_MAX_DELAY,
174 );
175 return Duration.max(configuredInterval, cappedBackoff);
176}
177
178export class VcsStatusBroadcaster extends Context.Service<
179 VcsStatusBroadcaster,
180 {
181 readonly getStatus: (
182 input: VcsStatusInput,
183 ) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
184 readonly refreshLocalStatus: (
185 cwd: string,
186 ) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;
187 readonly refreshStatus: (cwd: string) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
188 /**
189 * Refresh a loaded cwd after a turn if background policy allows it.
190 * GitManager retries missing PRs for the current branch and keeps known
191 * PRs and failed lookup backoff cached. This does not fetch Git remotes.
192 */
193 readonly refreshPullRequestStatus: (
194 cwd: string,
195 ) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
196 readonly streamStatus: (
197 input: VcsStatusInput,
198 options?: StreamStatusOptions,
199 ) => Stream.Stream<VcsStatusStreamEvent, GitManagerServiceError>;
200 }
201>()("t3/vcs/VcsStatusBroadcaster") {}
202
203function fingerprintStatusPart(status: unknown): string {
204 return JSON.stringify(status);
205}
206
207const normalizeCwd = (cwd: string) =>
208 Effect.service(FileSystem.FileSystem).pipe(
209 Effect.flatMap((fs) => fs.realPath(cwd)),
210 Effect.orElseSucceed(() => cwd),
211 );
212
213export const make = Effect.gen(function* () {
214 const autoPullPolicy = yield* VcsAutoPullPolicy;
215 const workflow = yield* GitWorkflowService.GitWorkflowService;
216 const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
217 const fs = yield* FileSystem.FileSystem;
218 const changesPubSub = yield* Effect.acquireRelease(
219 PubSub.unbounded<VcsStatusChange>(),
220 (pubsub) => PubSub.shutdown(pubsub),
221 );
222 const broadcasterScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
223 Scope.close(scope, Exit.void),
224 );
225 const cacheRef = yield* Ref.make(new Map<string, CachedVcsStatus>());
226 // One permit per cwd for remote reads that write the cache. Without it a
227 // periodic poll that started before `gh pr create` can finish after the
228 // turn-end refresh and overwrite the fresh PR with its stale `pr: null`.
229 const remoteWriteLocks = new Map<string, Semaphore.Semaphore>();
230 const withRemoteWriteLock = <A, E, R>(cwd: string, effect: Effect.Effect<A, E, R>) => {
231 let lock = remoteWriteLocks.get(cwd);
232 if (lock === undefined) {
233 lock = Semaphore.makeUnsafe(1);
234 remoteWriteLocks.set(cwd, lock);
235 }
236 return lock.withPermits(1)(effect);
237 };
238 const pollersRef = yield* SynchronizedRef.make(new Map<string, ActiveRemotePoller>());
239
240 const getCachedStatus = Effect.fn("VcsStatusBroadcaster.getCachedStatus")(function* (
241 cwd: string,
242 ) {
243 return yield* Ref.get(cacheRef).pipe(Effect.map((cache) => cache.get(cwd) ?? null));
244 });
245
246 const updateCachedLocalStatus = Effect.fn("VcsStatusBroadcaster.updateCachedLocalStatus")(
247 function* (cwd: string, local: VcsStatusLocalResult, options?: { publish?: boolean }) {
248 const nextLocal = {
249 fingerprint: fingerprintStatusPart(local),
250 value: local,
251 } satisfies CachedValue<VcsStatusLocalResult>;
252 const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
253 const previous = cache.get(cwd) ?? { local: null, remote: null };
254 const nextCache = new Map(cache);
255 nextCache.set(cwd, {
256 ...previous,
257 local: nextLocal,
258 });
259 return [previous.local?.fingerprint !== nextLocal.fingerprint, nextCache] as const;
260 });
261
262 if (options?.publish && shouldPublish) {
263 yield* PubSub.publish(changesPubSub, {
264 cwd,
265 event: {
266 _tag: "localUpdated",
267 local,
268 },
269 });
270 }
271
272 return local;
273 },
274 );
275
276 const updateCachedRemoteStatus = Effect.fn("VcsStatusBroadcaster.updateCachedRemoteStatus")(
277 function* (cwd: string, remote: VcsStatusRemoteResult | null, options?: { publish?: boolean }) {
278 const nextRemote = {
279 fingerprint: fingerprintStatusPart(remote),
280 value: remote,
281 } satisfies CachedValue<VcsStatusRemoteResult | null>;
282 const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
283 const previous = cache.get(cwd) ?? { local: null, remote: null };
284 const nextCache = new Map(cache);
285 nextCache.set(cwd, {
286 ...previous,
287 remote: nextRemote,
288 });
289 return [previous.remote?.fingerprint !== nextRemote.fingerprint, nextCache] as const;
290 });
291
292 if (options?.publish && shouldPublish) {
293 yield* PubSub.publish(changesPubSub, {
294 cwd,
295 event: {
296 _tag: "remoteUpdated",
297 remote,
298 },
299 });
300 }
301
302 return remote;
303 },
304 );
305
306 const updateCachedStatus = Effect.fn("VcsStatusBroadcaster.updateCachedStatus")(function* (
307 cwd: string,
308 local: VcsStatusLocalResult,
309 remote: VcsStatusRemoteResult | null,
310 options?: { publish?: boolean },
311 ) {
312 const nextLocal = {
313 fingerprint: fingerprintStatusPart(local),
314 value: local,
315 } satisfies CachedValue<VcsStatusLocalResult>;
316 const nextRemote = {
317 fingerprint: fingerprintStatusPart(remote),
318 value: remote,
319 } satisfies CachedValue<VcsStatusRemoteResult | null>;
320 const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
321 const previous = cache.get(cwd) ?? { local: null, remote: null };
322 const nextCache = new Map(cache);
323 nextCache.set(cwd, {
324 local: nextLocal,
325 remote: nextRemote,
326 });
327 return [
328 previous.local?.fingerprint !== nextLocal.fingerprint ||
329 previous.remote?.fingerprint !== nextRemote.fingerprint,
330 nextCache,
331 ] as const;
332 });
333
334 if (options?.publish && shouldPublish) {
335 yield* PubSub.publish(changesPubSub, {
336 cwd,
337 event: {
338 _tag: "snapshot",
339 local,
340 remote,
341 },
342 });
343 }
344
345 return mergeGitStatusParts(local, remote);
346 });
347
348 const loadLocalStatus = Effect.fn("VcsStatusBroadcaster.loadLocalStatus")(function* (
349 cwd: string,
350 ) {
351 const local = yield* workflow.localStatus({ cwd });
352 return yield* updateCachedLocalStatus(cwd, local);
353 });
354
355 const getOrLoadLocalStatus = Effect.fn("VcsStatusBroadcaster.getOrLoadLocalStatus")(function* (
356 cwd: string,
357 ) {
358 const cached = yield* getCachedStatus(cwd);
359 if (cached?.local) {
360 return cached.local.value;
361 }
362 return yield* loadLocalStatus(cwd);
363 });
364
365 const withFileSystem = Effect.provideService(FileSystem.FileSystem, fs);
366
367 const getStatus: VcsStatusBroadcaster["Service"]["getStatus"] = Effect.fn(
368 "VcsStatusBroadcaster.getStatus",
369 )(function* (input) {
370 const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
371 const cached = yield* getCachedStatus(cwd);
372 if (cached?.local && cached.remote) {
373 return mergeGitStatusParts(cached.local.value, cached.remote.value);
374 }
375 return yield* withRemoteWriteLock(
376 cwd,
377 Effect.gen(function* () {
378 const latest = yield* getCachedStatus(cwd);
379 const [local, remote] = yield* Effect.all(
380 [
381 latest?.local ? Effect.succeed(latest.local.value) : workflow.localStatus({ cwd }),
382 latest?.remote ? Effect.succeed(latest.remote.value) : workflow.remoteStatus({ cwd }),
383 ],
384 { concurrency: "unbounded" },
385 );
386 return yield* updateCachedStatus(cwd, local, remote);
387 }),
388 );
389 });
390
391 const refreshLocalStatusCore = Effect.fn("VcsStatusBroadcaster.refreshLocalStatusCore")(
392 function* (cwd: string) {
393 yield* workflow.invalidateLocalStatus(cwd);
394 const local = yield* workflow.localStatus({ cwd });
395 return yield* updateCachedLocalStatus(cwd, local, { publish: true });
396 },
397 );
398
399 const refreshLocalStatus: VcsStatusBroadcaster["Service"]["refreshLocalStatus"] = Effect.fn(
400 "VcsStatusBroadcaster.refreshLocalStatus",
401 )(function* (rawCwd) {
402 const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
403 return yield* refreshLocalStatusCore(cwd);
404 });
405
406 const maybeAutoPull = Effect.fn("VcsStatusBroadcaster.maybeAutoPull")(function* (
407 cwd: string,
408 remote: VcsStatusRemoteResult | null,
409 policyCwds: ReadonlyArray<string>,
410 ) {
411 return yield* Effect.gen(function* () {
412 const autoPullEnabled = (yield* Effect.forEach(policyCwds, autoPullPolicy.isEnabled, {
413 concurrency: "unbounded",
414 })).some(Boolean);
415 if (
416 remote === null ||
417 !remote.hasUpstream ||
418 remote.aheadCount > 0 ||
419 remote.behindCount <= 0 ||
420 !autoPullEnabled
421 ) {
422 return null;
423 }
424
425 yield* workflow.invalidateLocalStatus(cwd);
426 const local = yield* workflow.localStatus({ cwd });
427 if (!local.isRepo || !local.isDefaultRef || local.hasWorkingTreeChanges) return null;
428
429 yield* workflow.pullCurrentBranch(cwd);
430 yield* workflow.invalidateStatus(cwd);
431 const [refreshedLocal, refreshedRemote] = yield* Effect.all(
432 [workflow.localStatus({ cwd }), workflow.remoteStatus({ cwd }, { refreshUpstream: false })],
433 { concurrency: "unbounded" },
434 );
435 yield* updateCachedStatus(cwd, refreshedLocal, refreshedRemote, { publish: true });
436 return { local: refreshedLocal, remote: refreshedRemote };
437 }).pipe(
438 Effect.catch(() =>
439 Effect.logWarning("Automatic project pull failed", { cwd }).pipe(Effect.as(null)),
440 ),
441 );
442 });
443
444 const refreshRemoteStatus = Effect.fn("VcsStatusBroadcaster.refreshRemoteStatus")(function* (
445 cwd: string,
446 options?: {
447 readonly refreshUpstream?: boolean;
448 readonly policyCwds?: ReadonlyArray<string>;
449 },
450 ) {
451 return yield* withRemoteWriteLock(
452 cwd,
453 Effect.gen(function* () {
454 if (options?.refreshUpstream !== false) {
455 yield* workflow.invalidateRemoteStatus(cwd);
456 }
457 const remote = yield* workflow.remoteStatus({ cwd }, options);
458 const pulled = yield* maybeAutoPull(cwd, remote, options?.policyCwds ?? [cwd]);
459 if (pulled !== null) return pulled.remote;
460 return yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
461 }),
462 );
463 });
464
465 const refreshStatus: VcsStatusBroadcaster["Service"]["refreshStatus"] = Effect.fn(
466 "VcsStatusBroadcaster.refreshStatus",
467 )(function* (rawCwd) {
468 const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
469 // invalidateStatus (not the two partial invalidations) so an explicit
470 // refresh also bypasses GitManager's slow PR-lookup cache.
471 return yield* withRemoteWriteLock(
472 cwd,
473 Effect.gen(function* () {
474 yield* workflow.invalidateStatus(cwd);
475 const [local, remote] = yield* Effect.all(
476 [workflow.localStatus({ cwd }), workflow.remoteStatus({ cwd })],
477 { concurrency: "unbounded" },
478 );
479 const pulled = yield* maybeAutoPull(cwd, remote, [rawCwd]);
480 if (pulled !== null) return mergeGitStatusParts(pulled.local, pulled.remote);
481 return yield* updateCachedStatus(cwd, local, remote, { publish: true });
482 }),
483 );
484 });
485
486 const refreshPullRequestStatus: VcsStatusBroadcaster["Service"]["refreshPullRequestStatus"] =
487 Effect.fn("VcsStatusBroadcaster.refreshPullRequestStatus")(function* (rawCwd) {
488 const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
489 return yield* withRemoteWriteLock(
490 cwd,
491 Effect.gen(function* () {
492 const cached = yield* getCachedStatus(cwd);
493 if (cached?.remote?.value == null) return null;
494 const poller = (yield* SynchronizedRef.get(pollersRef)).get(cwd);
495 const demandCwds = poller ? [...(yield* Ref.get(poller.demandCwds)).keys()] : [rawCwd];
496 const shouldRefresh = (yield* Effect.forEach(
497 demandCwds,
498 (demandCwd) =>
499 backgroundPolicy.shouldRunScopeWork({ type: "vcs-status", cwd: demandCwd }),
500 { concurrency: "unbounded" },
501 )).some(Boolean);
502 if (!shouldRefresh) return null;
503 // Resolve the checked-out branch again. A cached PR can belong to
504 // the previous branch after an agent checks out another branch.
505 const remote = yield* workflow.remoteStatus(
506 { cwd },
507 { refreshUpstream: false, refreshMissingPullRequest: true },
508 );
509 return yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
510 }),
511 );
512 });
513
514 const makeRemoteRefreshLoop = (
515 cwd: string,
516 demandCwdsRef: Ref.Ref<ReadonlyMap<string, number>>,
517 automaticRemoteRefreshInterval: Effect.Effect<Duration.Duration, never>,
518 refreshImmediately: boolean,
519 ) => {
520 return Effect.gen(function* () {
521 const consecutiveFailuresRef = yield* Ref.make(0);
522 const needsInitialRefreshRef = yield* Ref.make(refreshImmediately);
523 const refreshRemoteStatusIfEnabled = Effect.gen(function* () {
524 const configuredInterval = yield* automaticRemoteRefreshInterval;
525 const activeInterval = Duration.isZero(configuredInterval)
526 ? DEFAULT_VCS_STATUS_REFRESH_INTERVAL
527 : configuredInterval;
528 const needsInitialRefresh = yield* Ref.get(needsInitialRefreshRef);
529 if (Duration.isZero(configuredInterval) && !needsInitialRefresh) {
530 return activeInterval;
531 }
532
533 const demandCwds = yield* Ref.get(demandCwdsRef);
534 const shouldRun =
535 needsInitialRefresh ||
536 (yield* Effect.all(
537 [...demandCwds.keys()].map((demandCwd) =>
538 backgroundPolicy.shouldRunScopeWork({
539 type: "vcs-status",
540 cwd: demandCwd,
541 }),
542 ),
543 { concurrency: "unbounded" },
544 )).some(Boolean);
545 if (!shouldRun) {
546 return activeInterval;
547 }
548
549 const exit = yield* refreshRemoteStatus(cwd, {
550 refreshUpstream: !Duration.isZero(configuredInterval),
551 policyCwds: [...demandCwds.keys()],
552 }).pipe(Effect.exit);
553 if (Exit.isSuccess(exit)) {
554 yield* Ref.set(needsInitialRefreshRef, false);
555 yield* Ref.set(consecutiveFailuresRef, 0);
556 return activeInterval;
557 }
558
559 const interruptionReasons = exit.cause.reasons.filter(Cause.isInterruptReason);
560 if (interruptionReasons.length > 0) {
561 return yield* Effect.failCause(Cause.fromReasons<never>(interruptionReasons));
562 }
563
564 const consecutiveFailures = yield* Ref.updateAndGet(
565 consecutiveFailuresRef,
566 (count) => count + 1,
567 );
568 const nextDelay = remoteRefreshFailureDelay(consecutiveFailures, activeInterval);
569 yield* Effect.logWarning("VCS remote status refresh failed", {
570 cwdLength: cwd.length,
571 ...remoteRefreshFailureDiagnostics(exit.cause),
572 consecutiveFailures,
573 nextDelayMs: Duration.toMillis(nextDelay),
574 });
575 return nextDelay;
576 });
577
578 if (!refreshImmediately) {
579 const configuredInterval = yield* automaticRemoteRefreshInterval;
580 yield* Effect.sleep(
581 Duration.isZero(configuredInterval)
582 ? DEFAULT_VCS_STATUS_REFRESH_INTERVAL
583 : configuredInterval,
584 );
585 }
586
587 return yield* refreshRemoteStatusIfEnabled.pipe(
588 Effect.repeat(
589 Schedule.identity<Duration.Duration>().pipe(
590 Schedule.addDelay(({ output: delay }) => Effect.succeed(delay)),
591 ),
592 ),
593 Effect.asVoid,
594 );
595 });
596 };
597
598 const retainRemotePoller = Effect.fn("VcsStatusBroadcaster.retainRemotePoller")(function* (
599 cwd: string,
600 demandCwd: string,
601 automaticRemoteRefreshInterval: Effect.Effect<Duration.Duration, never>,
602 refreshImmediately: boolean,
603 ) {
604 yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
605 const existing = activePollers.get(cwd);
606 if (existing) {
607 return Ref.update(existing.demandCwds, (demandCwds) => {
608 const next = new Map(demandCwds);
609 next.set(demandCwd, (next.get(demandCwd) ?? 0) + 1);
610 return next;
611 }).pipe(
612 Effect.map(() => {
613 const nextPollers = new Map(activePollers);
614 nextPollers.set(cwd, {
615 ...existing,
616 subscriberCount: existing.subscriberCount + 1,
617 });
618 return [undefined, nextPollers] as const;
619 }),
620 );
621 }
622
623 return Ref.make<ReadonlyMap<string, number>>(new Map([[demandCwd, 1]])).pipe(
624 Effect.flatMap((demandCwds) =>
625 makeRemoteRefreshLoop(
626 cwd,
627 demandCwds,
628 automaticRemoteRefreshInterval,
629 refreshImmediately,
630 ).pipe(
631 Effect.forkIn(broadcasterScope),
632 Effect.map((fiber) => {
633 const nextPollers = new Map(activePollers);
634 nextPollers.set(cwd, {
635 fiber,
636 subscriberCount: 1,
637 demandCwds,
638 });
639 return [undefined, nextPollers] as const;
640 }),
641 ),
642 ),
643 );
644 });
645 });
646
647 const releaseRemotePoller = Effect.fn("VcsStatusBroadcaster.releaseRemotePoller")(function* (
648 cwd: string,
649 demandCwd: string,
650 ) {
651 const pollerToInterrupt = yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
652 const existing = activePollers.get(cwd);
653 if (!existing) {
654 return Effect.succeed([null, activePollers] as const);
655 }
656
657 if (existing.subscriberCount > 1) {
658 return Ref.update(existing.demandCwds, (demandCwds) => {
659 const nextDemandCwds = new Map(demandCwds);
660 const count = nextDemandCwds.get(demandCwd) ?? 0;
661 if (count <= 1) {
662 nextDemandCwds.delete(demandCwd);
663 } else {
664 nextDemandCwds.set(demandCwd, count - 1);
665 }
666 return nextDemandCwds;
667 }).pipe(
668 Effect.as([
669 null,
670 new Map(activePollers).set(cwd, {
671 ...existing,
672 subscriberCount: existing.subscriberCount - 1,
673 }),
674 ] as const),
675 );
676 }
677
678 return Effect.succeed([
679 existing.fiber,
680 new Map([...activePollers].filter(([activeCwd]) => activeCwd !== cwd)),
681 ] as const);
682 });
683
684 if (pollerToInterrupt) {
685 yield* Fiber.interrupt(pollerToInterrupt).pipe(Effect.ignore);
686 }
687 });
688
689 const streamStatus: VcsStatusBroadcaster["Service"]["streamStatus"] = (input, options) =>
690 Stream.unwrap(
691 Effect.gen(function* () {
692 const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
693 const subscription = yield* PubSub.subscribe(changesPubSub);
694 const initialLocal = yield* getOrLoadLocalStatus(cwd);
695 const cachedStatus = yield* getCachedStatus(cwd);
696 const initialRemote = cachedStatus?.remote?.value ?? null;
697 yield* retainRemotePoller(
698 cwd,
699 input.cwd,
700 options?.automaticRemoteRefreshInterval ??
701 Effect.succeed(DEFAULT_VCS_STATUS_REFRESH_INTERVAL),
702 cachedStatus?.remote === null || cachedStatus?.remote === undefined,
703 );
704
705 const release = releaseRemotePoller(cwd, input.cwd).pipe(Effect.ignore, Effect.asVoid);
706
707 return Stream.concat(
708 Stream.make({
709 _tag: "snapshot" as const,
710 local: initialLocal,
711 remote: initialRemote,
712 }),
713 Stream.fromSubscription(subscription).pipe(
714 Stream.filter((event) => event.cwd === cwd),
715 Stream.map((event) => event.event),
716 ),
717 ).pipe(Stream.ensuring(release));
718 }),
719 );
720
721 return VcsStatusBroadcaster.of({
722 getStatus,
723 refreshLocalStatus,
724 refreshStatus,
725 refreshPullRequestStatus,
726 streamStatus,
727 });
728});
729
730export const layer = Layer.effect(VcsStatusBroadcaster, make);