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 Stream from "effect/Stream";
14import * as SynchronizedRef from "effect/SynchronizedRef";
15import type {
16 GitManagerServiceError,
17 VcsStatusInput,
18 VcsStatusLocalResult,
19 VcsStatusRemoteResult,
20 VcsStatusResult,
21 VcsStatusStreamEvent,
22} from "@t3tools/contracts";
23import { mergeGitStatusParts } from "@t3tools/shared/git";
24import * as KeyedLock from "@t3tools/shared/KeyedLock";
25import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
26
27import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
28import * as GitWorkflowService from "../git/GitWorkflowService.ts";
29import * as ProjectStore from "../orchestration-v2/ProjectStore.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 layerAutoPullPolicy = Layer.effect(
153 VcsAutoPullPolicy,
154 Effect.gen(function* () {
155 const projects = yield* ProjectStore.ProjectStoreV2;
156 const serverSettings = yield* ServerSettings.ServerSettingsService;
157 return {
158 isEnabled: Effect.fn("VcsAutoPullPolicy.isEnabled")(
159 function* (cwd: string) {
160 const project = yield* projects.findActiveByWorkspaceRoot(cwd);
161 if (project._tag === "None") return false;
162 const settings = yield* serverSettings.getSettings;
163 return resolveProjectSettings(settings, project.value.projectId).settings.defaultAutoPull;
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
220/** @public Service construction is part of the canonical Effect module API. */
221export const make = Effect.gen(function* () {
222 const autoPullPolicy = yield* VcsAutoPullPolicy;
223 const workflow = yield* GitWorkflowService.GitWorkflowService;
224 const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
225 const fs = yield* FileSystem.FileSystem;
226 const changesPubSub = yield* Effect.acquireRelease(
227 PubSub.unbounded<VcsStatusChange>(),
228 (pubsub) => PubSub.shutdown(pubsub),
229 );
230 const broadcasterScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
231 Scope.close(scope, Exit.void),
232 );
233 const cacheRef = yield* Ref.make(new Map<string, CachedVcsStatus>());
234 // One permit per cwd for remote reads that write the cache. Without it a
235 // periodic poll that started before `gh pr create` can finish after the
236 // turn-end refresh and overwrite the fresh PR with its stale `pr: null`.
237 const remoteWriteLocks = yield* KeyedLock.make<string>();
238 const withRemoteWriteLock = <A, E, R>(cwd: string, effect: Effect.Effect<A, E, R>) =>
239 remoteWriteLocks.withLock(cwd, effect);
240 const pollersRef = yield* SynchronizedRef.make(new Map<string, ActiveRemotePoller>());
241
242 const getCachedStatus = Effect.fn("VcsStatusBroadcaster.getCachedStatus")(function* (
243 cwd: string,
244 ) {
245 return yield* Ref.get(cacheRef).pipe(Effect.map((cache) => cache.get(cwd) ?? null));
246 });
247
248 const updateCachedLocalStatus = Effect.fn("VcsStatusBroadcaster.updateCachedLocalStatus")(
249 function* (cwd: string, local: VcsStatusLocalResult, options?: { publish?: boolean }) {
250 const nextLocal = {
251 fingerprint: fingerprintStatusPart(local),
252 value: local,
253 } satisfies CachedValue<VcsStatusLocalResult>;
254 const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
255 const previous = cache.get(cwd) ?? { local: null, remote: null };
256 const nextCache = new Map(cache);
257 nextCache.set(cwd, {
258 ...previous,
259 local: nextLocal,
260 });
261 return [previous.local?.fingerprint !== nextLocal.fingerprint, nextCache] as const;
262 });
263
264 if (options?.publish && shouldPublish) {
265 yield* PubSub.publish(changesPubSub, {
266 cwd,
267 event: {
268 _tag: "localUpdated",
269 local,
270 },
271 });
272 }
273
274 return local;
275 },
276 );
277
278 const updateCachedRemoteStatus = Effect.fn("VcsStatusBroadcaster.updateCachedRemoteStatus")(
279 function* (cwd: string, remote: VcsStatusRemoteResult | null, options?: { publish?: boolean }) {
280 const nextRemote = {
281 fingerprint: fingerprintStatusPart(remote),
282 value: remote,
283 } satisfies CachedValue<VcsStatusRemoteResult | null>;
284 const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
285 const previous = cache.get(cwd) ?? { local: null, remote: null };
286 const nextCache = new Map(cache);
287 nextCache.set(cwd, {
288 ...previous,
289 remote: nextRemote,
290 });
291 return [previous.remote?.fingerprint !== nextRemote.fingerprint, nextCache] as const;
292 });
293
294 if (options?.publish && shouldPublish) {
295 yield* PubSub.publish(changesPubSub, {
296 cwd,
297 event: {
298 _tag: "remoteUpdated",
299 remote,
300 },
301 });
302 }
303
304 return remote;
305 },
306 );
307
308 const updateCachedStatus = Effect.fn("VcsStatusBroadcaster.updateCachedStatus")(function* (
309 cwd: string,
310 local: VcsStatusLocalResult,
311 remote: VcsStatusRemoteResult | null,
312 options?: { publish?: boolean },
313 ) {
314 const nextLocal = {
315 fingerprint: fingerprintStatusPart(local),
316 value: local,
317 } satisfies CachedValue<VcsStatusLocalResult>;
318 const nextRemote = {
319 fingerprint: fingerprintStatusPart(remote),
320 value: remote,
321 } satisfies CachedValue<VcsStatusRemoteResult | null>;
322 const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
323 const previous = cache.get(cwd) ?? { local: null, remote: null };
324 const nextCache = new Map(cache);
325 nextCache.set(cwd, {
326 local: nextLocal,
327 remote: nextRemote,
328 });
329 return [
330 previous.local?.fingerprint !== nextLocal.fingerprint ||
331 previous.remote?.fingerprint !== nextRemote.fingerprint,
332 nextCache,
333 ] as const;
334 });
335
336 if (options?.publish && shouldPublish) {
337 yield* PubSub.publish(changesPubSub, {
338 cwd,
339 event: {
340 _tag: "snapshot",
341 local,
342 remote,
343 },
344 });
345 }
346
347 return mergeGitStatusParts(local, remote);
348 });
349
350 const loadLocalStatus = Effect.fn("VcsStatusBroadcaster.loadLocalStatus")(function* (
351 cwd: string,
352 ) {
353 const local = yield* workflow.localStatus({ cwd });
354 return yield* updateCachedLocalStatus(cwd, local);
355 });
356
357 const getOrLoadLocalStatus = Effect.fn("VcsStatusBroadcaster.getOrLoadLocalStatus")(function* (
358 cwd: string,
359 ) {
360 const cached = yield* getCachedStatus(cwd);
361 if (cached?.local) {
362 return cached.local.value;
363 }
364 return yield* loadLocalStatus(cwd);
365 });
366
367 const withFileSystem = Effect.provideService(FileSystem.FileSystem, fs);
368
369 const getStatus: VcsStatusBroadcaster["Service"]["getStatus"] = Effect.fn(
370 "VcsStatusBroadcaster.getStatus",
371 )(function* (input) {
372 const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
373 const cached = yield* getCachedStatus(cwd);
374 if (cached?.local && cached.remote) {
375 return mergeGitStatusParts(cached.local.value, cached.remote.value);
376 }
377 return yield* withRemoteWriteLock(
378 cwd,
379 Effect.gen(function* () {
380 const latest = yield* getCachedStatus(cwd);
381 const [local, remote] = yield* Effect.all(
382 [
383 latest?.local ? Effect.succeed(latest.local.value) : workflow.localStatus({ cwd }),
384 latest?.remote ? Effect.succeed(latest.remote.value) : workflow.remoteStatus({ cwd }),
385 ],
386 { concurrency: "unbounded" },
387 );
388 return yield* updateCachedStatus(cwd, local, remote);
389 }),
390 );
391 });
392
393 const refreshLocalStatusCore = Effect.fn("VcsStatusBroadcaster.refreshLocalStatusCore")(
394 function* (cwd: string) {
395 yield* workflow.invalidateLocalStatus(cwd);
396 const local = yield* workflow.localStatus({ cwd });
397 return yield* updateCachedLocalStatus(cwd, local, { publish: true });
398 },
399 );
400
401 const refreshLocalStatus: VcsStatusBroadcaster["Service"]["refreshLocalStatus"] = Effect.fn(
402 "VcsStatusBroadcaster.refreshLocalStatus",
403 )(function* (rawCwd) {
404 const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
405 return yield* refreshLocalStatusCore(cwd);
406 });
407
408 const maybeAutoPull = Effect.fn("VcsStatusBroadcaster.maybeAutoPull")(function* (
409 cwd: string,
410 remote: VcsStatusRemoteResult | null,
411 policyCwds: ReadonlyArray<string>,
412 ) {
413 return yield* Effect.gen(function* () {
414 const autoPullEnabled = (yield* Effect.forEach(policyCwds, autoPullPolicy.isEnabled, {
415 concurrency: "unbounded",
416 })).some(Boolean);
417 if (
418 remote === null ||
419 !remote.hasUpstream ||
420 remote.aheadCount > 0 ||
421 remote.behindCount <= 0 ||
422 !autoPullEnabled
423 ) {
424 return null;
425 }
426
427 yield* workflow.invalidateLocalStatus(cwd);
428 const local = yield* workflow.localStatus({ cwd });
429 if (!local.isRepo || !local.isDefaultRef || local.hasWorkingTreeChanges) return null;
430
431 yield* workflow.pullCurrentBranch(cwd);
432 yield* workflow.invalidateStatus(cwd);
433 const [refreshedLocal, refreshedRemote] = yield* Effect.all(
434 [workflow.localStatus({ cwd }), workflow.remoteStatus({ cwd }, { refreshUpstream: false })],
435 { concurrency: "unbounded" },
436 );
437 yield* updateCachedStatus(cwd, refreshedLocal, refreshedRemote, { publish: true });
438 return { local: refreshedLocal, remote: refreshedRemote };
439 }).pipe(
440 Effect.catch(() =>
441 Effect.logWarning("Automatic project pull failed", { cwd }).pipe(Effect.as(null)),
442 ),
443 );
444 });
445
446 const refreshRemoteStatus = Effect.fn("VcsStatusBroadcaster.refreshRemoteStatus")(function* (
447 cwd: string,
448 options?: {
449 readonly refreshUpstream?: boolean;
450 readonly policyCwds?: ReadonlyArray<string>;
451 },
452 ) {
453 return yield* withRemoteWriteLock(
454 cwd,
455 Effect.gen(function* () {
456 if (options?.refreshUpstream !== false) {
457 yield* workflow.invalidateRemoteStatus(cwd);
458 }
459 const previousRemote = (yield* getCachedStatus(cwd))?.remote?.value;
460 const remote = yield* workflow.remoteStatus({ cwd }, options);
461 const pulled = yield* maybeAutoPull(cwd, remote, options?.policyCwds ?? [cwd]);
462 if (pulled !== null) return pulled.remote;
463 // Local status holds the Changes totals, which compare against remote refs. A fetch can
464 // move them with no local trigger (a push from a terminal, a PR merged on the host), so
465 // re-read local status on the first fetch and whenever divergence moves.
466 if (
467 remote &&
468 (!previousRemote ||
469 previousRemote.aheadCount !== remote.aheadCount ||
470 previousRemote.behindCount !== remote.behindCount ||
471 previousRemote.aheadOfDefaultCount !== remote.aheadOfDefaultCount)
472 ) {
473 yield* refreshLocalStatusCore(cwd);
474 }
475 return yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
476 }),
477 );
478 });
479
480 const refreshStatus: VcsStatusBroadcaster["Service"]["refreshStatus"] = Effect.fn(
481 "VcsStatusBroadcaster.refreshStatus",
482 )(function* (rawCwd) {
483 const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
484 // invalidateStatus (not the two partial invalidations) so an explicit
485 // refresh also bypasses GitManager's slow PR-lookup cache.
486 return yield* withRemoteWriteLock(
487 cwd,
488 Effect.gen(function* () {
489 yield* workflow.invalidateStatus(cwd);
490 // Local after remote: the fetch can move the base that the Changes totals compare with.
491 const remote = yield* workflow.remoteStatus({ cwd });
492 const local = yield* workflow.localStatus({ cwd });
493 const pulled = yield* maybeAutoPull(cwd, remote, [rawCwd]);
494 if (pulled !== null) return mergeGitStatusParts(pulled.local, pulled.remote);
495 return yield* updateCachedStatus(cwd, local, remote, { publish: true });
496 }),
497 );
498 });
499
500 const refreshPullRequestStatus: VcsStatusBroadcaster["Service"]["refreshPullRequestStatus"] =
501 Effect.fn("VcsStatusBroadcaster.refreshPullRequestStatus")(function* (rawCwd) {
502 const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
503 return yield* withRemoteWriteLock(
504 cwd,
505 Effect.gen(function* () {
506 const cached = yield* getCachedStatus(cwd);
507 if (cached?.remote?.value == null) return null;
508 const poller = (yield* SynchronizedRef.get(pollersRef)).get(cwd);
509 const demandCwds = poller ? [...(yield* Ref.get(poller.demandCwds)).keys()] : [rawCwd];
510 const shouldRefresh = (yield* Effect.forEach(
511 demandCwds,
512 (demandCwd) =>
513 backgroundPolicy.shouldRunScopeWork({ type: "vcs-status", cwd: demandCwd }),
514 { concurrency: "unbounded" },
515 )).some(Boolean);
516 if (!shouldRefresh) return null;
517 // Resolve the checked-out branch again. A cached PR can belong to
518 // the previous branch after an agent checks out another branch.
519 const remote = yield* workflow.remoteStatus(
520 { cwd },
521 { refreshUpstream: false, refreshMissingPullRequest: true },
522 );
523 return yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
524 }),
525 );
526 });
527
528 const makeRemoteRefreshLoop = (
529 cwd: string,
530 demandCwdsRef: Ref.Ref<ReadonlyMap<string, number>>,
531 automaticRemoteRefreshInterval: Effect.Effect<Duration.Duration, never>,
532 refreshImmediately: boolean,
533 ) => {
534 return Effect.gen(function* () {
535 const consecutiveFailuresRef = yield* Ref.make(0);
536 const needsInitialRefreshRef = yield* Ref.make(refreshImmediately);
537 const refreshRemoteStatusIfEnabled = Effect.gen(function* () {
538 const configuredInterval = yield* automaticRemoteRefreshInterval;
539 const activeInterval = Duration.isZero(configuredInterval)
540 ? DEFAULT_VCS_STATUS_REFRESH_INTERVAL
541 : configuredInterval;
542 const needsInitialRefresh = yield* Ref.get(needsInitialRefreshRef);
543 if (Duration.isZero(configuredInterval) && !needsInitialRefresh) {
544 return activeInterval;
545 }
546
547 const demandCwds = yield* Ref.get(demandCwdsRef);
548 const shouldRun =
549 needsInitialRefresh ||
550 (yield* Effect.forEach(
551 [...demandCwds.keys()],
552 (demandCwd) =>
553 backgroundPolicy.shouldRunScopeWork({
554 type: "vcs-status",
555 cwd: demandCwd,
556 }),
557 { concurrency: "unbounded" },
558 )).some(Boolean);
559 if (!shouldRun) {
560 return activeInterval;
561 }
562
563 const exit = yield* refreshRemoteStatus(cwd, {
564 refreshUpstream: !Duration.isZero(configuredInterval),
565 policyCwds: [...demandCwds.keys()],
566 }).pipe(Effect.exit);
567 if (Exit.isSuccess(exit)) {
568 yield* Ref.set(needsInitialRefreshRef, false);
569 yield* Ref.set(consecutiveFailuresRef, 0);
570 return activeInterval;
571 }
572
573 const interruptionReasons = exit.cause.reasons.filter(Cause.isInterruptReason);
574 if (interruptionReasons.length > 0) {
575 return yield* Effect.failCause(Cause.fromReasons<never>(interruptionReasons));
576 }
577
578 const consecutiveFailures = yield* Ref.updateAndGet(
579 consecutiveFailuresRef,
580 (count) => count + 1,
581 );
582 const nextDelay = remoteRefreshFailureDelay(consecutiveFailures, activeInterval);
583 yield* Effect.logWarning("VCS remote status refresh failed", {
584 cwdLength: cwd.length,
585 ...remoteRefreshFailureDiagnostics(exit.cause),
586 consecutiveFailures,
587 nextDelayMs: Duration.toMillis(nextDelay),
588 });
589 return nextDelay;
590 });
591
592 if (!refreshImmediately) {
593 const configuredInterval = yield* automaticRemoteRefreshInterval;
594 yield* Effect.sleep(
595 Duration.isZero(configuredInterval)
596 ? DEFAULT_VCS_STATUS_REFRESH_INTERVAL
597 : configuredInterval,
598 );
599 }
600
601 return yield* refreshRemoteStatusIfEnabled.pipe(
602 Effect.repeat(
603 Schedule.identity<Duration.Duration>().pipe(
604 Schedule.addDelay(({ output: delay }) => Effect.succeed(delay)),
605 ),
606 ),
607 Effect.asVoid,
608 );
609 });
610 };
611
612 const retainRemotePoller = Effect.fn("VcsStatusBroadcaster.retainRemotePoller")(function* (
613 cwd: string,
614 demandCwd: string,
615 automaticRemoteRefreshInterval: Effect.Effect<Duration.Duration, never>,
616 refreshImmediately: boolean,
617 ) {
618 yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
619 const existing = activePollers.get(cwd);
620 if (existing) {
621 return Ref.update(existing.demandCwds, (demandCwds) => {
622 const next = new Map(demandCwds);
623 next.set(demandCwd, (next.get(demandCwd) ?? 0) + 1);
624 return next;
625 }).pipe(
626 Effect.map(() => {
627 const nextPollers = new Map(activePollers);
628 nextPollers.set(cwd, {
629 ...existing,
630 subscriberCount: existing.subscriberCount + 1,
631 });
632 return [undefined, nextPollers] as const;
633 }),
634 );
635 }
636
637 return Ref.make<ReadonlyMap<string, number>>(new Map([[demandCwd, 1]])).pipe(
638 Effect.flatMap((demandCwds) =>
639 makeRemoteRefreshLoop(
640 cwd,
641 demandCwds,
642 automaticRemoteRefreshInterval,
643 refreshImmediately,
644 ).pipe(
645 Effect.forkIn(broadcasterScope),
646 Effect.map((fiber) => {
647 const nextPollers = new Map(activePollers);
648 nextPollers.set(cwd, {
649 fiber,
650 subscriberCount: 1,
651 demandCwds,
652 });
653 return [undefined, nextPollers] as const;
654 }),
655 ),
656 ),
657 );
658 });
659 });
660
661 const releaseRemotePoller = Effect.fn("VcsStatusBroadcaster.releaseRemotePoller")(function* (
662 cwd: string,
663 demandCwd: string,
664 ) {
665 const pollerToInterrupt = yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
666 const existing = activePollers.get(cwd);
667 if (!existing) {
668 return Effect.succeed([null, activePollers] as const);
669 }
670
671 if (existing.subscriberCount > 1) {
672 return Ref.update(existing.demandCwds, (demandCwds) => {
673 const nextDemandCwds = new Map(demandCwds);
674 const count = nextDemandCwds.get(demandCwd) ?? 0;
675 if (count <= 1) {
676 nextDemandCwds.delete(demandCwd);
677 } else {
678 nextDemandCwds.set(demandCwd, count - 1);
679 }
680 return nextDemandCwds;
681 }).pipe(
682 Effect.as([
683 null,
684 new Map(activePollers).set(cwd, {
685 ...existing,
686 subscriberCount: existing.subscriberCount - 1,
687 }),
688 ] as const),
689 );
690 }
691
692 return Effect.succeed([
693 existing.fiber,
694 new Map([...activePollers].filter(([activeCwd]) => activeCwd !== cwd)),
695 ] as const);
696 });
697
698 if (pollerToInterrupt) {
699 yield* Fiber.interrupt(pollerToInterrupt).pipe(Effect.ignore);
700 }
701 });
702
703 const streamStatus: VcsStatusBroadcaster["Service"]["streamStatus"] = (input, options) =>
704 Stream.unwrap(
705 Effect.gen(function* () {
706 const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
707 const subscription = yield* PubSub.subscribe(changesPubSub);
708 const initialLocal = yield* getOrLoadLocalStatus(cwd);
709 const cachedStatus = yield* getCachedStatus(cwd);
710 const initialRemote = cachedStatus?.remote?.value ?? null;
711 yield* retainRemotePoller(
712 cwd,
713 input.cwd,
714 options?.automaticRemoteRefreshInterval ??
715 Effect.succeed(DEFAULT_VCS_STATUS_REFRESH_INTERVAL),
716 cachedStatus?.remote === null || cachedStatus?.remote === undefined,
717 );
718
719 const release = releaseRemotePoller(cwd, input.cwd).pipe(Effect.ignore, Effect.asVoid);
720
721 return Stream.concat(
722 Stream.make({
723 _tag: "snapshot" as const,
724 local: initialLocal,
725 remote: initialRemote,
726 }),
727 Stream.fromSubscription(subscription).pipe(
728 Stream.filter((event) => event.cwd === cwd),
729 Stream.map((event) => event.event),
730 ),
731 ).pipe(Stream.ensuring(release));
732 }),
733 );
734
735 return VcsStatusBroadcaster.of({
736 getStatus,
737 refreshLocalStatus,
738 refreshStatus,
739 refreshPullRequestStatus,
740 streamStatus,
741 });
742});
743
744export const layer = Layer.effect(VcsStatusBroadcaster, make);