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