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