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 streamBranchChanges: Stream.Stream<{
209 readonly cwd: string;
210 readonly refName: string | null;
211 }>;
212 readonly getStatus: (
213 input: VcsStatusInput,
214 ) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
215 readonly refreshLocalStatus: (
216 cwd: string,
217 ) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;
218 readonly refreshStatus: (
219 cwd: string,
220 options?: { readonly localOnly?: boolean },
221 ) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
222 readonly refreshPullRequestStatus: (
223 cwd: string,
224 ) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
225 readonly streamStatus: (
226 input: VcsStatusSubscriptionInput,
227 ) => Stream.Stream<VcsStatusStreamEvent, GitManagerServiceError>;
228 }
229>()("t3/vcs/VcsStatusBroadcaster") {}
230
231function fingerprintStatusPart(status: unknown): string {
232 return JSON.stringify(status);
233}
234
235const normalizeCwd = (cwd: string) =>
236 Effect.service(FileSystem.FileSystem).pipe(
237 Effect.flatMap((fs) => fs.realPath(cwd)),
238 Effect.orElseSucceed(() => cwd),
239 );
240
241/** @public */
242export const make = Effect.gen(function* () {
243 const automaticFetchInterval = yield* VcsAutomaticFetchInterval;
244 const autoPullPolicy = yield* VcsAutoPullPolicy;
245 const workflow = yield* GitWorkflowService.GitWorkflowService;
246 const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
247 const fs = yield* FileSystem.FileSystem;
248 const changesPubSub = yield* Effect.acquireRelease(
249 PubSub.unbounded<VcsStatusChange>(),
250 (pubsub) => PubSub.shutdown(pubsub),
251 );
252 const branchChangesPubSub = yield* Effect.acquireRelease(
253 PubSub.unbounded<{ readonly cwd: string; readonly refName: string | null }>(),
254 (pubsub) => PubSub.shutdown(pubsub),
255 );
256 const broadcasterScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
257 Scope.close(scope, Exit.void),
258 );
259 const cacheRef = yield* Ref.make(new Map<string, CachedVcsStatus>());
260 // One permit per cwd for remote reads that write the cache. Without it a
261 // periodic poll that started before an agent creates a PR can finish after the
262 // turn-end refresh and overwrite the fresh PR with its stale `pr: null`.
263 const remoteWriteLocks = yield* KeyedLock.make<string>();
264 const withRemoteWriteLock = <A, E, R>(cwd: string, effect: Effect.Effect<A, E, R>) =>
265 remoteWriteLocks.withLock(cwd, effect);
266 const pollersRef = yield* SynchronizedRef.make(new Map<string, ActiveRemotePoller>());
267
268 const getCachedStatus = Effect.fn("VcsStatusBroadcaster.getCachedStatus")(function* (
269 cwd: string,
270 ) {
271 return yield* Ref.get(cacheRef).pipe(Effect.map((cache) => cache.get(cwd) ?? null));
272 });
273
274 const updateCachedLocalStatus = Effect.fn("VcsStatusBroadcaster.updateCachedLocalStatus")(
275 function* (cwd: string, local: VcsStatusLocalResult, options?: { publish?: boolean }) {
276 const nextLocal = { fingerprint: fingerprintStatusPart(local), value: local };
277 const [localChanged, branchChanged, remoteCleared] = yield* Ref.modify(cacheRef, (cache) => {
278 const previous = cache.get(cwd) ?? { local: null, remote: null };
279 const remote = previous.remote?.branch === local.refName ? previous.remote : null;
280 return [
281 [
282 previous.local?.fingerprint !== nextLocal.fingerprint,
283 previous.local?.value.refName !== local.refName,
284 previous.remote !== remote,
285 ],
286 new Map(cache).set(cwd, { local: nextLocal, remote }),
287 ] as const;
288 });
289 if (branchChanged && local.isRepo) {
290 yield* PubSub.publish(branchChangesPubSub, { cwd, refName: local.refName });
291 }
292 if (options?.publish && remoteCleared) {
293 yield* PubSub.publish(changesPubSub, {
294 cwd,
295 event: { _tag: "remoteUpdated", remote: null },
296 });
297 }
298 if (options?.publish && localChanged) {
299 yield* PubSub.publish(changesPubSub, {
300 cwd,
301 event: { _tag: "localUpdated", local },
302 });
303 }
304 return local;
305 },
306 );
307
308 const updateCachedRemoteStatus = Effect.fn("VcsStatusBroadcaster.updateCachedRemoteStatus")(
309 function* (cwd: string, remote: CachedRemoteStatus | null, options?: { publish?: boolean }) {
310 const [changed, value] = yield* Ref.modify(cacheRef, (cache) => {
311 const previous = cache.get(cwd) ?? { local: null, remote: null };
312 const next = remote?.branch === previous.local?.value.refName ? remote : null;
313 return [
314 [previous.remote?.fingerprint !== next?.fingerprint, next?.value ?? null],
315 new Map(cache).set(cwd, { ...previous, remote: next }),
316 ] as const;
317 });
318 if (options?.publish && changed) {
319 yield* PubSub.publish(changesPubSub, {
320 cwd,
321 event: { _tag: "remoteUpdated", remote: value },
322 });
323 }
324 return value;
325 },
326 );
327
328 const loadLocalStatus = Effect.fn("VcsStatusBroadcaster.loadLocalStatus")(function* (
329 cwd: string,
330 ) {
331 const local = yield* workflow.localStatus({ cwd });
332 return yield* updateCachedLocalStatus(cwd, local);
333 });
334
335 const getOrLoadLocalStatus = Effect.fn("VcsStatusBroadcaster.getOrLoadLocalStatus")(function* (
336 cwd: string,
337 ) {
338 const cached = yield* getCachedStatus(cwd);
339 if (cached?.local) {
340 const branch = yield* workflow.currentBranch(cwd);
341 if (branch === cached.local.value.refName) return cached.local.value;
342 return yield* refreshLocalStatusCore(cwd);
343 }
344 return yield* loadLocalStatus(cwd);
345 });
346
347 const getStatusParts = Effect.fn("VcsStatusBroadcaster.getStatusParts")(function* (cwd: string) {
348 const cached = yield* getCachedStatus(cwd);
349 if (cached?.local) {
350 return { local: cached.local.value, remote: cached.remote?.value ?? null };
351 }
352 return { local: yield* loadLocalStatus(cwd), remote: null };
353 });
354
355 const withFileSystem = Effect.provideService(FileSystem.FileSystem, fs);
356
357 const getStatus: VcsStatusBroadcaster["Service"]["getStatus"] = Effect.fn(
358 "VcsStatusBroadcaster.getStatus",
359 )(function* (input) {
360 const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
361 yield* getOrLoadLocalStatus(cwd);
362 const cached = yield* getCachedStatus(cwd);
363 if (cached?.local && cached.remote) {
364 return mergeGitStatusParts(cached.local.value, cached.remote.value);
365 }
366 return yield* withRemoteWriteLock(
367 cwd,
368 Effect.gen(function* () {
369 const latest = yield* getCachedStatus(cwd);
370 const refreshUpstream = !Duration.isZero(yield* automaticFetchInterval);
371 const remote = latest?.remote ?? (yield* readRemoteStatus(cwd, { refreshUpstream }));
372 yield* updateCachedRemoteStatus(cwd, remote);
373 const parts = yield* getStatusParts(cwd);
374 return mergeGitStatusParts(parts.local, parts.remote);
375 }),
376 );
377 });
378
379 // A refresh that started after a request saw every change that request could mean, so queued
380 // callers share it instead of each running git status again.
381 const localRefreshLocks = yield* KeyedLock.make<string>();
382 const localRefreshRequests = new Map<string, number>();
383 const localRefreshResults = new Map<
384 string,
385 { readonly startedAt: number; readonly local: VcsStatusLocalResult }
386 >();
387 const refreshLocalStatusCore = Effect.fn("VcsStatusBroadcaster.refreshLocalStatusCore")(
388 function* (cwd: string) {
389 const requestedAt = (localRefreshRequests.get(cwd) ?? 0) + 1;
390 localRefreshRequests.set(cwd, requestedAt);
391 return yield* localRefreshLocks.withLock(
392 cwd,
393 Effect.gen(function* () {
394 const shared = localRefreshResults.get(cwd);
395 if (shared !== undefined && shared.startedAt >= requestedAt) return shared.local;
396 const startedAt = localRefreshRequests.get(cwd) ?? requestedAt;
397 yield* workflow.invalidateLocalStatus(cwd);
398 const local = yield* workflow.localStatus({ cwd });
399 localRefreshResults.set(cwd, { startedAt, local });
400 return yield* updateCachedLocalStatus(cwd, local, { publish: true });
401 }),
402 );
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 readRemoteStatus = Effect.fn("VcsStatusBroadcaster.readRemoteStatus")(function* (
414 cwd: string,
415 options?: Parameters<GitWorkflowService.GitWorkflowService["Service"]["remoteStatus"]>[1],
416 ) {
417 const branch = yield* workflow.currentBranch(cwd);
418 // GitManager's remote TTL cache is keyed by cwd, not the checked-out branch.
419 yield* workflow.invalidateRemoteStatus(cwd);
420 const value = yield* workflow.remoteStatus({ cwd }, options);
421 const currentBranch = yield* workflow.currentBranch(cwd);
422 const cached = yield* getCachedStatus(cwd);
423 if (branch !== currentBranch || cached?.local?.value.refName !== currentBranch) {
424 yield* refreshLocalStatusCore(cwd);
425 }
426 return branch === currentBranch
427 ? { branch, value, fingerprint: fingerprintStatusPart(value) }
428 : null;
429 });
430
431 const maybeAutoPull = Effect.fn("VcsStatusBroadcaster.maybeAutoPull")(function* (
432 cwd: string,
433 remoteRead: CachedRemoteStatus | null,
434 policyCwds: ReadonlyArray<string>,
435 ) {
436 const remote = remoteRead?.value ?? null;
437 let pullAttempted = false;
438 return yield* Effect.gen(function* () {
439 const autoPullEnabled = (yield* Effect.forEach(policyCwds, autoPullPolicy.isEnabled, {
440 concurrency: "unbounded",
441 })).some(Boolean);
442 if (
443 remote === null ||
444 !remote.hasUpstream ||
445 remote.aheadCount > 0 ||
446 remote.behindCount <= 0 ||
447 !autoPullEnabled
448 ) {
449 return null;
450 }
451
452 yield* workflow.invalidateLocalStatus(cwd);
453 const local = yield* workflow.localStatus({ cwd });
454 if (
455 !local.isRepo ||
456 !local.isDefaultRef ||
457 local.hasWorkingTreeChanges ||
458 local.refName !== remoteRead?.branch
459 )
460 return null;
461
462 pullAttempted = true;
463 yield* workflow.pullCurrentBranch(cwd);
464 yield* workflow.invalidateStatus(cwd);
465 yield* refreshLocalStatusCore(cwd);
466 const refreshedRemote = yield* readRemoteStatus(cwd, { refreshUpstream: false });
467 yield* updateCachedRemoteStatus(cwd, refreshedRemote, { publish: true });
468 return yield* getStatusParts(cwd);
469 }).pipe(
470 Effect.catch((error) =>
471 Effect.gen(function* () {
472 yield* Effect.logWarning("Automatic project pull failed", {
473 cwdLength: cwd.length,
474 errorTag: error._tag,
475 });
476 if (!pullAttempted) return null;
477 // A pull or its follow-up reads can fail after local state has changed.
478 // Let a failed reconciliation reach the caller instead of publishing old status.
479 yield* refreshLocalStatusCore(cwd);
480 yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true });
481 return yield* getStatusParts(cwd);
482 }),
483 ),
484 );
485 });
486
487 const refreshRemoteStatus = Effect.fn("VcsStatusBroadcaster.refreshRemoteStatus")(function* (
488 cwd: string,
489 options?: {
490 readonly refreshUpstream?: boolean;
491 readonly policyCwds?: ReadonlyArray<string>;
492 },
493 ) {
494 return yield* withRemoteWriteLock(
495 cwd,
496 Effect.gen(function* () {
497 const remoteRead = yield* readRemoteStatus(cwd, options);
498 const pulled =
499 options?.refreshUpstream === false
500 ? null
501 : yield* maybeAutoPull(cwd, remoteRead, options?.policyCwds ?? [cwd]);
502 if (pulled !== null) return pulled.remote;
503 // Base refs and merge bases can move without changing divergence counts.
504 yield* refreshLocalStatusCore(cwd);
505 return yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true });
506 }),
507 );
508 });
509
510 const refreshStatus: VcsStatusBroadcaster["Service"]["refreshStatus"] = Effect.fn(
511 "VcsStatusBroadcaster.refreshStatus",
512 )(function* (rawCwd, options) {
513 const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
514 const previous = options?.localOnly ? yield* getCachedStatus(cwd) : null;
515 const local = yield* refreshLocalStatusCore(cwd);
516 if (options?.localOnly) {
517 return yield* withRemoteWriteLock(
518 cwd,
519 Effect.gen(function* () {
520 if (previous?.local?.value.refName !== local.refName || !previous?.remote) {
521 yield* workflow.invalidateRemoteStatus(cwd);
522 yield* updateCachedRemoteStatus(
523 cwd,
524 { branch: local.refName, fingerprint: fingerprintStatusPart(null), value: null },
525 { publish: true },
526 );
527 }
528 const parts = yield* getStatusParts(cwd);
529 return mergeGitStatusParts(parts.local, parts.remote);
530 }),
531 );
532 }
533 return yield* withRemoteWriteLock(
534 cwd,
535 Effect.gen(function* () {
536 const refreshUpstream = !Duration.isZero(yield* automaticFetchInterval);
537 // Bump the PR lookup epoch after earlier remote writers have finished.
538 yield* workflow.invalidateStatus(cwd);
539 const remoteRead = yield* readRemoteStatus(cwd, { refreshUpstream });
540 // Fetch can move the base used for local Changes totals.
541 yield* refreshLocalStatusCore(cwd);
542 // Without a fetch, the cached behind count cannot justify an automatic pull.
543 const pulled = refreshUpstream ? yield* maybeAutoPull(cwd, remoteRead, [rawCwd]) : null;
544 if (pulled !== null) return mergeGitStatusParts(pulled.local, pulled.remote);
545 yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true });
546 const parts = yield* getStatusParts(cwd);
547 return mergeGitStatusParts(parts.local, parts.remote);
548 }),
549 );
550 });
551
552 const refreshPullRequestStatus: VcsStatusBroadcaster["Service"]["refreshPullRequestStatus"] =
553 Effect.fn("VcsStatusBroadcaster.refreshPullRequestStatus")(function* (rawCwd) {
554 const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
555 return yield* withRemoteWriteLock(
556 cwd,
557 Effect.gen(function* () {
558 const cached = yield* getCachedStatus(cwd);
559 if (!cached?.local || cached.remote?.value === null) return null;
560 // Turn completion must update divergence even when background polling is paused.
561 const remoteRead = yield* readRemoteStatus(cwd, {
562 refreshUpstream: false,
563 refreshMissingPullRequest: true,
564 });
565 return yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true });
566 }),
567 );
568 });
569
570 // A subscription owns this loop; keep each poll's spans out of a never-ending parent span.
571 const makeRemoteRefreshLoop = Effect.fnUntraced(function* (
572 cwd: string,
573 demandCwdsRef: Ref.Ref<ReadonlyMap<string, number>>,
574 refreshImmediately: boolean,
575 ) {
576 const consecutiveFailuresRef = yield* Ref.make(0);
577 const needsInitialRefreshRef = yield* Ref.make(refreshImmediately);
578 const refreshRemoteStatusIfEnabled = Effect.gen(function* () {
579 const configuredInterval = yield* automaticFetchInterval;
580 const activeInterval = Duration.isZero(configuredInterval)
581 ? DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL
582 : configuredInterval;
583 const needsInitialRefresh = yield* Ref.get(needsInitialRefreshRef);
584 if (Duration.isZero(configuredInterval) && !needsInitialRefresh) {
585 return activeInterval;
586 }
587
588 const demandCwds = yield* Ref.get(demandCwdsRef);
589 const shouldRun =
590 needsInitialRefresh ||
591 (yield* Effect.forEach(
592 [...demandCwds.keys()],
593 (demandCwd) =>
594 backgroundPolicy.shouldRunScopeWork({
595 type: "vcs-status",
596 cwd: demandCwd,
597 }),
598 { concurrency: "unbounded" },
599 )).some(Boolean);
600 if (!shouldRun) {
601 return activeInterval;
602 }
603
604 const exit = yield* refreshRemoteStatus(cwd, {
605 refreshUpstream: !Duration.isZero(configuredInterval),
606 policyCwds: [...demandCwds.keys()],
607 }).pipe(Effect.exit);
608 if (Exit.isSuccess(exit)) {
609 yield* Ref.set(needsInitialRefreshRef, false);
610 yield* Ref.set(consecutiveFailuresRef, 0);
611 return activeInterval;
612 }
613
614 const interruptionReasons = exit.cause.reasons.filter(Cause.isInterruptReason);
615 if (interruptionReasons.length > 0) {
616 return yield* Effect.failCause(Cause.fromReasons<never>(interruptionReasons));
617 }
618
619 const consecutiveFailures = yield* Ref.updateAndGet(
620 consecutiveFailuresRef,
621 (count) => count + 1,
622 );
623 const nextDelay = remoteRefreshFailureDelay(consecutiveFailures, activeInterval);
624 yield* Effect.logWarning("VCS remote status refresh failed", {
625 cwdLength: cwd.length,
626 ...remoteRefreshFailureDiagnostics(exit.cause),
627 consecutiveFailures,
628 nextDelayMs: Duration.toMillis(nextDelay),
629 });
630 return nextDelay;
631 });
632
633 if (!refreshImmediately) {
634 const configuredInterval = yield* automaticFetchInterval;
635 yield* Effect.sleep(
636 Duration.isZero(configuredInterval)
637 ? DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL
638 : configuredInterval,
639 );
640 }
641
642 return yield* refreshRemoteStatusIfEnabled.pipe(
643 Effect.repeat(
644 Schedule.identity<Duration.Duration>().pipe(
645 Schedule.addDelay(({ output: delay }) => Effect.succeed(delay)),
646 ),
647 ),
648 Effect.asVoid,
649 );
650 });
651
652 const retainRemotePoller = Effect.fn("VcsStatusBroadcaster.retainRemotePoller")(function* (
653 cwd: string,
654 demandCwd: string,
655 refreshImmediately: boolean,
656 ) {
657 yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
658 const existing = activePollers.get(cwd);
659 if (existing) {
660 return Ref.update(existing.demandCwds, (demandCwds) => {
661 const next = new Map(demandCwds);
662 next.set(demandCwd, (next.get(demandCwd) ?? 0) + 1);
663 return next;
664 }).pipe(
665 Effect.map(() => {
666 const nextPollers = new Map(activePollers);
667 nextPollers.set(cwd, {
668 ...existing,
669 subscriberCount: existing.subscriberCount + 1,
670 });
671 return [undefined, nextPollers] as const;
672 }),
673 );
674 }
675
676 return Ref.make<ReadonlyMap<string, number>>(new Map([[demandCwd, 1]])).pipe(
677 Effect.flatMap((demandCwds) =>
678 makeRemoteRefreshLoop(cwd, demandCwds, refreshImmediately).pipe(
679 Effect.forkIn(broadcasterScope),
680 Effect.map((fiber) => {
681 const nextPollers = new Map(activePollers);
682 nextPollers.set(cwd, {
683 fiber,
684 subscriberCount: 1,
685 demandCwds,
686 });
687 return [undefined, nextPollers] as const;
688 }),
689 ),
690 ),
691 );
692 });
693 });
694
695 const releaseRemotePoller = Effect.fn("VcsStatusBroadcaster.releaseRemotePoller")(function* (
696 cwd: string,
697 demandCwd: string,
698 ) {
699 const pollerToInterrupt = yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
700 const existing = activePollers.get(cwd);
701 if (!existing) {
702 return Effect.succeed([null, activePollers] as const);
703 }
704
705 if (existing.subscriberCount > 1) {
706 return Ref.update(existing.demandCwds, (demandCwds) => {
707 const nextDemandCwds = new Map(demandCwds);
708 const count = nextDemandCwds.get(demandCwd) ?? 0;
709 if (count <= 1) {
710 nextDemandCwds.delete(demandCwd);
711 } else {
712 nextDemandCwds.set(demandCwd, count - 1);
713 }
714 return nextDemandCwds;
715 }).pipe(
716 Effect.as([
717 null,
718 new Map(activePollers).set(cwd, {
719 ...existing,
720 subscriberCount: existing.subscriberCount - 1,
721 }),
722 ] as const),
723 );
724 }
725
726 return Effect.succeed([
727 existing.fiber,
728 new Map([...activePollers].filter(([activeCwd]) => activeCwd !== cwd)),
729 ] as const);
730 });
731
732 if (pollerToInterrupt) {
733 yield* Fiber.interrupt(pollerToInterrupt).pipe(Effect.ignore);
734 }
735 });
736
737 const streamStatus: VcsStatusBroadcaster["Service"]["streamStatus"] = (input) =>
738 Stream.unwrap(
739 Effect.gen(function* () {
740 const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
741 const subscription = yield* PubSub.subscribe(changesPubSub);
742 const initialLocal = yield* getOrLoadLocalStatus(cwd);
743 const cachedStatus = yield* getCachedStatus(cwd);
744 const initialRemote = cachedStatus?.remote?.value ?? null;
745 if (input.includeRemote !== false) {
746 yield* retainRemotePoller(
747 cwd,
748 input.cwd,
749 cachedStatus?.remote === null || cachedStatus?.remote === undefined,
750 );
751 }
752 const release =
753 input.includeRemote === false
754 ? Effect.void
755 : releaseRemotePoller(cwd, input.cwd).pipe(Effect.ignore, Effect.asVoid);
756
757 return Stream.concat(
758 Stream.make({
759 _tag: "snapshot" as const,
760 local: initialLocal,
761 remote: initialRemote,
762 }),
763 Stream.fromSubscription(subscription).pipe(
764 Stream.filter((event) => event.cwd === cwd),
765 Stream.map((event) => event.event),
766 ),
767 ).pipe(Stream.ensuring(release));
768 }),
769 );
770
771 return VcsStatusBroadcaster.of({
772 streamBranchChanges: Stream.fromPubSub(branchChangesPubSub),
773 getStatus,
774 refreshLocalStatus,
775 refreshStatus,
776 refreshPullRequestStatus,
777 streamStatus,
778 });
779});
780
781export const layer = Layer.effect(VcsStatusBroadcaster, make);