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